Django queryset If statement never evaluates to true?

Question: I have a simple update view.  That reads the POST request from a previous view.  This part works great.
owner = ADMirror.objects.get (employeentname=request.POST.get('userpost'))

I have a query set defined as:
currentlevel = QVReportAccess.objects.filter(ntname = 'owner.employeentname, active = 1).values('sr_datareduce_summary_code')

which the print looks like:
<QuerySet [{'sr_datareduce_summary_code': 'Z07126'}, {'sr_datareduce_summary_code': 'Z07126'}, {'sr_datareduce_summary_c
ode': 'Z07126'}, {'sr_datareduce_summary_code': 'Z07126'}, {'sr_datareduce_summary_code': 'Z07126'}, {'sr_datareduce_sum
mary_code': 'Z07126'}, {'sr_datareduce_summary_code': 'Z07126'}, {'sr_datareduce_summary_code': 'Z07126'}, {'sr_dataredu
ce_summary_code': 'Z07126'}, {'sr_datareduce_summary_code': 'Z07126'}, {'sr_datareduce_summary_code': 'Z07126'}, {'sr_da
tareduce_summary_code': 'Z07126'}, {'sr_datareduce_summary_code': 'Z07126'}, {'sr_datareduce_summary_code': 'Z07126'}, {
'sr_datareduce_summary_code': 'Z07126'}, {'sr_datareduce_summary_code': 'Z07126'}, {'sr_datareduce_summary_code': 'Z0712
6'}, {'sr_datareduce_summary_code': 'Z07126'}, {'sr_datareduce_summary_code': 'Z07126'}, {'sr_datareduce_summary_code':
'Z07126'}, '...(remaining elements truncated)...']>

The query set will have duplicates for the sr_datareduce_summary_code because they are at individual program levels in the model.
I then have the following if statement to give a yes if true and no if false, but even though the queryset contains Z07126 my if statement never evaluates to true.  Why is this and how can I get it to work correctly?
if QVReportAccess.objects.filter(ntname = owner.employeentname, active = 1).values_list('sr_datareduce_summary_code') == "Z07126":
    appaccess = 'yes'
else:
    appaccess = 'no'

print(appaccess)

Comment: You're comparing a list to a string, that'll never be true
Comment: It looks like you're comparing a list of tuples (from `values_list()`) to a string.
Comment: How can I compare the values of the list to a string?
Comment: this is a values list, which means it contains many items, so which field would you want to compare to `Z07126`?
Answer: You're comparing a list to a string, that'll never be true
Either you just need to check if that code exists in the filter
if QVReportAccess.objects.filter(ntname = owner.employeentname, active = 1, sr_datareduce_summary_code= "Z07126").exists():

or if you need to keep the values_list, assign it to a variable and use in with values_list('sr_datareduce_summary_code', flat=True)
if 'Z07126' in my_query_list:

Comment: This helps me out as well Sayse.  Thank you.
Answer: Or you can just loop the filtered Queryset:
for obj in QVReportAccess.objects.filter(
    ntname=owner.employeentname,
    active=1,
    sr_datareduce_summary_code="Z07126"):

    # do something with obj
    print(obj.sr_datareduce_summary_code)

Answer: queryset = QVReportAccess.objects.filter(ntname=owner.employeentname, active=1).values_list('sr_datareduce_summary_code', flat=True)

if queryset.exists() and str(queryset[0]) == "Z07126":
    appaccess = 'yes'
else:
    appaccess = 'no'

print(appaccess)

so filter()  basically return a queryset and not an object, it might also be blank, best way to check if queryset is empty or not is to use exists()
values_list() returns tuples when iterated over. Each tuple contains the value from the respective field passed into it.
If you only pass in a single field, you can also pass in the flat parameter. If True, this will mean the returned results are single values, rather than one-tuples. Example when you don't pass flat=True:
>>> Entry.objects.values_list('id').order_by('id')
[(1,), (2,), (3,), ...]

when you pass flat=True:
>>> Entry.objects.values_list('id', flat=True).order_by('id')
[1, 2, 3, ...]

I hope you get the idea for solving your problem.
Comment: Thank you for this explanation Sumeet.  We'll thought out and you've made my problem clear as day.


Access tomcat from outside LAN

Question: Hi I'm developing a web app in eclipse and using a tomcat server (6.0) integrated with the IDE.
I'm perfectly able to access the webapp from localhost or another computer in the LAN (http://192.168.0.2:8080/ works fine) and using https://www.grc.com/x/portprobe=8080 I can see that the router and my firewall work fine and the port is open. But still I can't access the from the URL I've created with dyndns. It just timeouts. Doesn't work using directly my IP from whatsmyip, so is not a problem of dyndns
Anyone can help me access tomcat from outside LAN?
Thanks
Answer: Are you trying to test this access to your "dyndns" URL from a computer on the LAN? The hostname in that URL is going to resolve to your public IP address, and it may be that your firewall / router doesn't support "hairpin NAT-- that is, having a request coming in from the LAN-side interface that needs to be routed back to the LAN-side interface.
If, indeed, you're trying to access it from off-site and it's not working then you probably need to check a few thngs:

Is the Tomcat server able to access the Internet itself? (i.e. is its default-gateway set properly) If not, then rectify that problem first.
When you attempt to source a connection from the Internet to the Tomcat server do you see the packets ever make it to the Tomcat server? (You don't mention your OS, but you should get familiar with the built-in packet sniffing tools in your OS. I "reach for the sniffer" earlier than most admins, but my philosophy is something like "If I have a tool that will let me see what's going on down on the wire then I'm going to use it.) If the Tomcat server is a Linux box, fire up tcpdump with a command-line like "tcpdump port 8080" (assuming that the box has a single interface-- you'll need to specify the interface number of not) and watch for your TCP SYN's coming in from the Internet. If it's a Windows machine, install the built-in Network Monitor or Wireshark and run a quick sniff. If you can establish early that your firewall/router is getting the packets to you then you won't end up fighting for hours only to find out that the port-foward there is the issue.
Comment: you were right, the problem was my router not supporting hairpin NAT
thanks a lot
Comment: Yes. The problem is with my gateway setting. Thank you.
Comment: Glad I could help.

Access tomcat from outside LAN


Internationalization on serverless backend (AWS)

Question: I'm building a serverless node.js web app on AWS (using Serverless Framework) and trying to implement internationalization on the backend (API Gateway/Lambda/DynamoDB).
For front-end(React), I use redux to store the selected language and react-intl to switch multiple languages. For the backend, what's the best way to implement internationalization?
Here are two ways I can think of, but there must be better ones.
A. Translate on the backend (Get language from path parameter)
path: {language}/validate

validate.js
export function main(event, context, callback) {
    const language = event.pathParameters.language;
    const data = JSON.parse(event.body);
    callback(null, validate(language, data));
}

This way, I need to pass the language as a function parameter to everywhere, which is not desirable.
B. Translate on front-end (i18n, react-intl)
backend hello.js response
{
    id: "samplePage.message.hello",
    defaultMessage: `Hello, ${name}`,
    values: { name }
}

frontend hello.js
<FormattedMessage {...response} />

ja.json (translation file for i18n)
{
    "samplePage.message.hello": "こんにちは、{name}。",
}

This way, it looks like everything works fine without any trouble, but am I missing anything?
Comment: @user234461 I know Stackoverflow is an English site, but why should I not ask a question about internationalization? Many companies in english native countries provide services in multiple languages, and they also need to think about internationalization.
Comment: Because AWS is bad
Answer: We do the same as you suggest in B)...basically we have our backend on AWS lambda and access data from dynamodb.
All our translation happens in the frontend. Only difference we use i18next (more specific react-i18next but makes no difference if this or react-intl -> just offers a little more backends, caching, language detection,... https://www.i18next.com/).
If you like to learn more or see it in action checkout https://locize.com (or directly try it at https://www.locize.io/ 14d free trial) while the app currently only is available in english all the texts comes in via xhr loading and get applied on runtime (i18n).
If interested in how we use serverless at locize.com see following slides from a speech we gave last year: https://blog.locize.com/2017-06-22-how-locize-leverages-serverless/
Last but not least...if you like to get most out of your ICU messages and validation, syntax highlighting and proper plural conversion and machine translation by not destroying the icu dsl during MT -> Just give our service a try...it comes with 14d free trial.


On the Example of Vector-Valued Integrals

Question: Let $p>1$. I am looking for a sequence $(f_{n}(x))$ such that
\begin{align*}
\left(\sum_{n}|f_{n}(x)|^{2}\right)^{1/2}&\notin L^{p}(\mathbb{R}^{N}),\\
\sum_{n}a_{n}f_{n}(x)&\in L^{p}(\mathbb{R}^{N}),~~~~\text{for any}~(a_{n})\in l^{2}~\text{with}~\|(a_{n})\|_{l^{2}}\leq 1
\end{align*}
so that
\begin{align*}
\sup_{\|(a_{n})\|_{l^{2}}\leq 1}\left\|\sum_{n}a_{n}f_{n}(x)\right\|_{L^{p}(\mathbb{R}^{N})}<\infty.
\end{align*}
The tricky thing is that, the space $l^{2}$ is self-dual, but when we treat it as the inner one but taking $L^{p}$ integral as outer one, the situation is different.
I also think about the Khintchine inequality, but this does not help.
Any suggestion?
Answer: Assuming that $1<p<2$:
Let $(S_{n})$ be a sequence of disjoint sets in $\mathbb{R}^{N}$ such that the volume $|S_{n}|=1$.
Let $f_{n}=(1/n^{1/p})\chi_{S_{n}}$, we compute that
\begin{align*}
\int_{\mathbb{R}^{N}}\left(\sum_{n}|f_{n}(x)|^{2}\right)^{p/2}dx&=\sum_{n}\int_{S_{n}}f_{n}(x)^{p}dx\\
&=\sum_{n}\dfrac{1}{n}\\
&=\infty.
\end{align*}
On the other hand, for any $(a_{n})\in l^{2}$ such that $\|(a_{n})\|_{l^{2}}\leq 1$, we compute that
\begin{align*}
\int_{\mathbb{R}^{N}}\left|\sum_{n}a_{n}f_{n}(x)\right|^{p}dx&=\sum_{n}\int_{S_{n}}|a_{n}|^{p}\cdot\dfrac{1}{n}dx\\
&=\sum_{n}|a_{n}|^{p}\cdot\dfrac{1}{n}\\
&\leq\left(\sum_{n}|a_{n}|^{2}\right)^{p/2}\left(\sum_{n}\dfrac{1}{n^{r}}\right)^{1/r}\\
&\leq\left(\sum_{n}\dfrac{1}{n^{r}}\right)^{1/r},
\end{align*}
where $1/(2/p)+1/r=1$.
Now assuming that $p\geq 2$:
Note that $\|(a_{n})\|_{l^{2}}\leq 1$ implies that $|a_{n}|\leq 1$ for each $n=1,2,...$ and hence
\begin{align*}
\int_{\mathbb{R}^{N}}\left|\sum_{n}a_{n}f_{n}(x)\right|^{p}dx&=\sum_{n}|a_{n}|^{p}\cdot\dfrac{1}{n}\\
&\leq\sum_{n}|a_{n}|^{2}\\
&\leq 1.
\end{align*}


java SimpleDateFormat

Question: in Java, how to parse a date string that contains a letter that does not represent a pattern?

"2007-11-02T14:46:03+01:00"

String date ="2007-11-02T14:46:03+01:00";
String format = "yyyy-MM-ddTHH:mm:ssz";
new SimpleDateFormat(format).parse(date);

Exception in thread "main" java.lang.IllegalArgumentException: Illegal pattern character 'T'
    at java.text.SimpleDateFormat.compile(SimpleDateFormat.java:769)
    at java.text.SimpleDateFormat.initialize(SimpleDateFormat.java:576)
    at java.text.SimpleDateFormat.(SimpleDateFormat.java:501)
    at java.text.SimpleDateFormat.(SimpleDateFormat.java:476)
Comment: Note that the question about parsing ISO 8601 dates is a frequently asked and answered question. Search for "Java ISO 8601 date" or something similar and you'll find many answers.
Comment: For anyone reading this question today or tomorrow I recommend you don't use `SimpleDateFormat`. That class is notoriously troublesome and long outdated. Instead just use `OffsetDateTime` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/).
Comment: For example: http://stackoverflow.com/questions/6279647/converting-a-string-to-date-almost-done/6280206#6280206
Answer: You can try
String format = "yyyy-MM-dd'T'HH:mm:ssz";

Reference : from Javadoc

Text can be quoted using single quotes
  (') to avoid interpretation.
Comment: It works only if the string contains 'GMT'. Just like this : String date ="2007-11-02T14:46:03GMT+01:00";
Comment: @Hendra that is true or it has to be `String date ="2007-11-02T14:46:03+0100";` `SimpleDateTime` is is pretty limited in such situations an I guess if you(OP) don't have much control over the input, using libraries such as joda time would work out best.
Answer: The time you're trying to parse appears to be in ISO 8601 format. SimpleDateFormat unfortunately doesn't support all the same timezone specifiers as ISO 8601. If you want to be able to properly handle all the forms specified in the ISO, the best thing to do is use Joda time.
This example is straight out of the user guide:
DateTime dt = new DateTime("2004-12-13T21:39:45.618-08:00");

Comment: @user - you're right, the ISO version doesn't like colons. Good news is you can pass the version with colons straight to the `DateTime` constructor.
Comment: this doesn't work, +01:00 needs to be +0100 for joda to work.
Answer: No formatter needed
It's time to post the modern answer, the answer that uses java.time, the modern Java date and time API. Your format is ISO 8601, and the classes of java.time generally parse the most common ISO 8601 variants as their default, that is, without any explicit formatter.
    String date ="2007-11-02T14:46:03+01:00";
    OffsetDateTime dateTime = OffsetDateTime.parse(date);
    System.out.println(dateTime);

Output is:

2007-11-02T14:46:03+01:00

Yes, java.time also gives ISO 8601 format back from the toString methods, implicitly called when we print an object.
Enclose literal letters in single quotes
To answer the question as asked, you may enclose letters in single quotes to make DateTimeFormatter take them as literal letters rather than format specifiers. There would be no point whatsoever in doing the following in real code, but for the sake of demonstration:
    DateTimeFormatter isoFormatter
            = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssXXX");
    String date ="2007-11-02T14:46:03+01:00";
    OffsetDateTime dateTime = OffsetDateTime.parse(date, isoFormatter);

The result is the same as before.
Link
Oracle tutorial: Date Time explaining how to use java.time.
Answer: String testDate = "2007-11-02T14:46:03+01:00";
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz");
Date date = formatter.parse(testDate);
System.out.println(date);

You can try similar to the above
You can use following link for reference
Answer: If you don't care about the time zone, you can use this method.
  public static Date convertToDate(String strDate) throws ParseException {
    Date date = null;
    if (strDate != null) {
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
      date = sdf.parse(strDate);
    }
    return date;
  }

I don't know if it's still useful for you, but I encounter with the same problem now, and after a little I come up with this.
Comment: You need to care about the UTC offset or you will get incorrect results (more often than not).
Answer: Below format code works for me !
But the code converts the date : 20220722 to date : 22-July-2022
where tradeDate = 20220722
Comment: Thanks for wanting to contribute. One, this is not what was asked. The question was about a datetime string having a `T` in it. Two, no one should use the old and very troublesome `SimpleDateFormat` class nor its friend the `Date` class. java.time, the modern Java date and time API, parses both your string and the one from the question without the programmer needing to fiddle with a format pattern string. See my answer.

java SimpleDateFormat


How to add a dynamic weather ticker to the webpage

Question: All Weather Tickers I found are static and if the user wants to select a zip code it links you to a different page.
Do you know any weather ticker that just gets the new info  in the same page?
Answer: RICO has an AJAX weather widget that seems to be along the lines of what you want.
Answer: It's possible to do this yourself - you can generally get this data from the National Weather Service's METARs.  Here's the METAR for the Rochester, NY airport. They're available in all sorts of ways (XML, FTP), and there are lots of parsers out there.


VS Community 2015 - No Windows Phone Emulator Installed

Question: I get the following error when trying to build (Debug > Windows Phone > Device) the default Cordova TypeScript project :
No Windows Phone 8 emulators installed.  Please install Visual Studio 2013 with Windows Phone 8 tools selected to install the emulators

Note: I was using the release candiate of Visual Studio 2015 and just installed the trial version of Visual Studio Community 2015.
Installing Visual Studio 2013 Windows Phone 8 tools can't be the correct solution.
Comment: I found my problem.  In previous versions of VS2015 I could debug on my USB connected phones/devices using Debug > Windows Phone 8 > Device. With the current version (community 2015 rtm) I need to use Debug > Windows Phone (Universal) > Device. Tested and confirmed
Comment: Are you on Windows 7 or 8?
Comment: I'm on Windows 8.1.  Unfortunately, I'm thinking a clean install is the real solution as it's worked for previous version of VS2015.
Comment: @DeanB_Develop agree. I think you need a clean install.
Comment: Uninstalled VS2015 Community, reinstalled and tried rebuilding.  Same error appears when trying to Debug > Windows Phone 8 > Device.  The same error occurs when using Debug > Windows Phone 8 > Emulators
Comment: I don't see why you accepted Subhag Oak's answer he totally missed you point.  Thanks for your solution though.  It worked.
Comment: @pdschuller Subhag Oak is right in that you need VS 2013 installed to deploy to a Windows phones for testing.

My solutions was to use Windows Phone (universal) as the solutions platform when testing APPS on Windows 8.1 and windows 10. Now I can test apps on Windows devices without the Visual Studio 2013 install.
Answer: I've downloaded and installed wpsdkv80_enu1.iso from http://www.microsoft.com/en-us/download/details.aspx?id=35471. It is Windows Phone SDK 8.0 and Emulator and it's working fine with Visual Studio 2015 Community
If you want to only test universal apps, you don't need to download WP SDK 8.0.
You can debug universal apps directly from VS by switching platform to Windows Phone(universal) and choose Windows 8.1 Emulator. But it expects Emulators for Windows Phone 8.1 to be installed.

If didn't installed Emulators for Windows Phone 8.1 you can do so in Program and Features -> Visual Studio 2015 -> Change.
Comment: Just wanted to say that you won't see 8.1 emulators if you have this.   I changed 10.0 -> 8.1 and the emulator options popped.
Answer: Thanks for upgrading to the RTM VS 2015. Unfortunately, you do require VS2013 for Windows 8 emulators to be installed. They aren't available on VS 2015 or there is no stand-alone installer for the emulators. But you should be able to deploy your Windows 8 application on Windows 8.1 emulators, if that helps.
Comment: @frodeborli, I updated the Camera plugin (CameraProxy.js) to work with Windows Phone 8.1 using PickSingleFileAndContinue. I haven't submitted fixes to the official repo yet, but you can find the code here: https://github.com/Mikejo5001/mobile-services-samples/tree/master/CordovaUploadImages
Comment: The problem with Windows 8.1 is that the PickSingleFileAsync-method is deprecated, in favor of PickSingleFileAndContinue. Since this method is "difficult" for Cordova use (requires saving the app state), Cordova must use a custom camera instead of the one provided by the OS. I'm willing to sacrifice 512 MB devices (for which this API change was made), but that does not help because the PickSingleFileAsync-method isn't available anyway. I'm only hoping Windows 10 Phone is able to run the Android version of my app. :-(
Comment: Did anybody tried to install emulators Windows Phone 8.1 Emulators from https://dev.windows.com/en-us/develop/download-phone-sdk ?
Comment: But the emulators *are* installed by VS2015 setup, and I have them installed! Yet the VS2015 Update 3 IDE does not find them... :(
Answer: Correct me if I'm wrong:

The Windows Phone 8.1 emulators provided by VS2015 are only good
for testing Universal Windows apps (APPX) and nothing else.
Windows Phone 8.1
legacy apps (XAP) can only be emulated by installing the Windows Phone 8.1 Updated Emulators separately.

You won' find this piece of information anywhere on the MS reference sites.


As validações feitas no set, não estão funcionando. C#

Question: Estou treinando POO, e num exercicio com herança, fiz os Gets e Sets, e nos sets eu fiz algumas validações nos atributos, porem quando instanciei o objeto e passei os parametros, nao mostrava mensagem de erro, nesse caso por exemplo, "Se o id for <=0 dar um erro, ai passei como parametro um numero negativo, porem ele imprime o valor normal e nao da nenhuma mensagem de erro.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    public class Item
    {
        private int id;
        private string descricao;
        private string genero;
        private string autor;
        private int dataLancamento;

        public Item(int id, string descricao, string genero, string autor, int dataLancamento)
        {
            this.id = id;
            this.descricao = descricao;
            this.genero = genero;
            this.autor = autor;
            this.dataLancamento = dataLancamento;
        }

        public int ID
        {
            get { return id; }

            set
            {
                if (id <= 0)
                {
                    throw new ArgumentException("O ID informado é inválido");
                }
                id = value;
            }
        }

        public string Descricao
        {
            get { return descricao; }

            set
            {
                if (descricao == null)
                {
                    throw new ArgumentException("A Descrição informada é inválida");
                }
                descricao = value;
            }
        }

        public string Genero
        {
            get { return genero; }
            set
            {
                if (genero == null)
                {
                    throw new ArgumentException("O genêro informado é inválido");
                }
                genero = value;
            }
        }

        public string Autor
        {
            get { return autor; }
            set
            {
                if (autor == null)
                {
                    throw new ArgumentException("Autor informado é inválido");
                }
                autor = value;
            }
        }

        public int DataLancamento
        {
            get { return dataLancamento; }
            set
            {
                if (dataLancamento <= 0 )
                {
                    throw new ArgumentException(" O Dia informado é inválido");
                }
                dataLancamento = value;
            }
        }

        public class CD : Item
        {
            private string idioma;

            public CD(int id, string descricao, string genero, string autor, int dataLancamento, string idioma) : base(id, descricao, genero, autor, dataLancamento)
            {
                this.idioma = idioma;
            }

            public string Idioma
            {
                get { return idioma; }
                set
                {
                    if (idioma == null)
                    {
                        throw new ArgumentException("O Idioma informado é inválido");
                    }
                    idioma = value;
                }

            }

            public void mensagem()
            {
                Console.WriteLine("ID: " + ID);
                Console.WriteLine("Descrição: " + Descricao);
                Console.WriteLine("Genero: " + Genero);
                Console.WriteLine("Autor: " + Autor);
                Console.WriteLine("Idioma CD: " + idioma);

            }

        }

    }

    internal class Program
    {
        static void Main(string[] args)
        {
            CD cd = new CD(-1587, "Teste", "", "Teste", 1002, "Portugês");

            cd.mensagem();
            Console.ReadLine();
        }
    }
}

Comment: Veja se ajuda [Como funcionam as propriedades no C#?](https://pt.stackoverflow.com/q/156804/137387)
Comment: Você tá validando pelo backing field sendo que ele ainda não foi atualizado... Se trocar as validações pra usar o `value` vai funcionar.
Comment: opa, perdão, não consegui entender
Answer: Cara acredito que você esteja fazendo de forma errônea da prop ID, pois Você está validando o valor id ao invés do valor value
dentro do seu set tenta fazer:
if (value <= 0)
{
    throw new ArgumentException("O ID informado é inválido");
}
id = value;

Não sei se ajudaria, mas tenta ai :)
Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


establish counts of elements of pandas dataframe

Question: Currently working to implement some fuzzy matching logic to group together emails with similar patterns and I need to improve the efficiency of part of the code but not sure what the best path forward is. I use a package to output a pandas dataframe that looks like this:

I redacted the data, but it's just four columns with an ID #, the email associated with a given ID, a group ID number that identifies the cluster a given email falls into, and then the group rep which is the most mathematically central email of a given cluster.
What I want to do is count the number of occurrences of each distinct element in the group rep column and create a new dataframe that's just two columns with one column having the group rep email and then the second column having the corresponding count of that group rep in the original dataframe. It should look something like this:

As of now, I'm converting my group reps to a list and then using a for-loop to create a list of  tuples(I think?) with each tuple containing a centroid email group identifiers and the number of times that identifier occurs in the original df (aka the number of emails in the original data that belong to that centroid email's group). The code looks like this:
groups = list(df['group rep'].unique())

# preparing list of tuples with group count
req_groups = []

for g in groups:
  count = (g, df['group rep'].value_counts()[g])
  #print(count)
  req_groups.append(count)

print(req_groups)

Unfortunately, this operation takes far too long. I'm sure there's a better solution, but could definitely use some help finding a path forward. Thanks in advance for your help!
Answer: You can use df.groupby('group rep').count().
Answer: Let's consider the following dataframe :
                   email
0      firstname.lastname@example.com
1        firstname.lastname@example.com
2  email@example.com
3       firstname.lastname@example.com
4         email@example.com
5        email@example.com
6  firstname.lastname@example.com

Proposed script
import pandas as pd
import operator

m = {'email':['firstname.lastname@example.com','firstname.lastname@example.com','firstname.lastname@example.com','firstname.lastname@example.com',
                 'email@example.com','email@example.com','email@example.com']}
df = pd.DataFrame(m)
counter = pd.DataFrame.from_dict({c: [operator.countOf(df['email'], c)] for c in df['email'].unique()})

cnt_df = counter.T.rename(columns={0:'count'})

print(cnt_df)

Result
                       count
email@example.com          1
email@example.com            2
email@example.com      2
firstname.lastname@example.com           1
email@example.com             1

Comment: https://stackoverflow.com/questions/75264807/how-can-i-count-instances-of-a-string-in-a-dataframe-column-of-lists-that-matche/75275267#75275267


Is Groovy 3.0.5 incompatible with Mockito 3.6.28 ? Mocks are not usable

Question: I am currently trying to move from Junit 4 Mockito 3.2.4 in order (mainly), to benefit from mockStatic and get rid of PowerMock
Migration went surprisingly well until I arrived at the test mocking static methods. Groovy 2.4.6, which is currently in used, does not support method reference operator ::
I am now trying to migrate to Groovy 3.0.5 and I have an issue opening mocks. Here is a simple code that reflect the issue:
class Article {
    Article() {
    }

    String getName() {
        return "toto"
    }

}

class ArticleManager {

    private Article article
    ArticleManager(Article article) {
        this.article = article
    }

    static int getArticleCount() {
        return 5
    }

    Article getArticleAt(int index) {
        return article
    }

}

import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.mockito.Mock
import org.mockito.MockitoAnnotations

import static org.mockito.Mockito.any
import static org.mockito.Mockito.when

class MockTest {

    private AutoCloseable closeable
    Article article

    @Mock
    private ArticleManager manager

    @BeforeEach
    void setup() {
        article = new Article()
        closeable = MockitoAnnotations.openMocks(this)
    }

    @AfterEach
    void releaseMocks() throws Exception {
        closeable.close()
    }

    @Test
    void testGroovy() {

        assert article.getName() == "toto"

        assert manager != null

        assert manager.getArticleAt(0) == null
        when(manager.getArticleAt(any(Integer.class))).thenReturn(article)
        assert manager.getArticleAt(0) == article
    }
}

Running this test with groovy 2.4.6 => OK
Running this test with a Java equivalent of code (no groovy) => OK
Running this test with groovy 3.0.5 =>

manager.getArticleAt(0) - > java.lang.NullPointerException
when(manager.getArticleAt(any(Integer.class))).thenReturn(article) -> Method threw 'org.mockito.exceptions.misusing.InvalidUseOfMatchersException' exception.
manager is not null, it's an ArticleManager$MockitoMocks$

I am doing something wrong here or is there an incompatibility of some sort ?
Thank you very much
Comment: In older groovy versions you can often use `.&` instead of `::`
Comment: That seems to work but now I have the following error: The used `MockMaker SubclassByteBuddyMockMaker does not support the creation of static mocks Mockito's inline mock maker supports static mocks based on the Instrumentation API.`
I googled it and it seems I should use mockito-inline instead of mockito-core. But when I do that, I have the exact same problem that described in my original post
Comment: I think the NPE is the age old metaclass problem. You can try when(manager.getMetaClass()).thenCallRealMethod() or add "answer=Answers.CALL_REAL_METHOD" to the mock annotation. There once was a compatibility mockito plugin that fixed this under the hood.
Comment: As for the matcher, I think anyInt() is what you're looking for.
Comment: Thank you I will investigate this as soon as Monday. But why would I want my mock to call the real method ? I do that only on a case to case basis
Answer: I've encountered the same thing in my project. I think it's indeed the "age old metaclass problem", aka mockito/mockito#72, and I think it's occurring again with Groovy 3.0 because the internal methods are no longer marked synthetic. I have reported mockito/mockito#2204 about this.
EDIT 2021-02-15: I submitted a pull request to fix this. It has been accepted and released, so please try again with Mockito v3.7.18.
Comment: so from what you are saying it's a bug that should be fixed ?
Comment: Yes, and in fact my pull request to fix it was accepted and released this morning. So please try your tests with Mockito v3.7.18. https://github.com/mockito/mockito/releases/tag/v3.7.18


Create imagefield with maximum number of values programmatically

Question: I've created an imagefield in my own module, like this:
$form['heading_img'] = array(
    '#type' => 'media',
    '#title' => t('Heading image'),
    '#default_value' => isset($content['settings']['heading_img']) ? $content['settings']['heading_img'] : '',
    '#theme' => 'media_widget',
    '#media_options' => array(
      'global' => array(
        'types' => array('image'),
        'schemes' => array(
          'public' => 'public',
        ),
        'file_extensions' => 'png gif jpg jpeg',
        'min_resolution' => '1920x550',
        'max_filesize' => '750 KB',
        'uri_scheme' => 'public',
      ),
    ),
);

Sometimes I need more heading images. Is it possible to make this field unlimited?
So you could click on a button: Add an other image. Something like this.
Answer: When scanning though the field definition of the media fields, you'll notice the multiselect property on line 118. Which gets the value of $multiselect from line 103:
$multiselect = ($field['cardinality'] > 1 || $field['cardinality'] == FIELD_CARDINALITY_UNLIMITED);

So in your definition you could try adding this multiselect property with an integer value (eg. 5 to allow 0-5 images), or FIELD_CARDINALITY_UNLIMITED.
$form['heading_img'] = array(
    '#type' => 'media',
    '#title' => t('Heading image'),
    '#default_value' => isset($content['settings']['heading_img']) ? $content['settings']['heading_img'] : '',
    '#theme' => 'media_widget',
    '#media_options' => array(
      'global' => array(
        'types' => array('image'),
        'schemes' => array(
          'public' => 'public',
        ),
        'file_extensions' => 'png gif jpg jpeg',
        'min_resolution' => '1920x550',
        'max_filesize' => '750 KB',
        'uri_scheme' => 'public',
        'multiselect' => FIELD_CARDINALITY_UNLIMITED
      ),
    ),
);

Comment: I saw this, but this is only for uploading images. I can't select multiple images in a specific field, just one image.
Comment: Then you must create multiple form fields with the same definition. So you'll end up with `$form['heading_img'], $form['heading_img2'], $form['heading_img3']` and so on. You can do this hardcoded, or using AJAX (see the [ajax_example](http://cgit.drupalcode.org/examples/tree/ajax_example?h=7.x-1.x) in the [examples project](http://drupal.org/project/examples)). But wouldn't it be easier to create a content type or an [entityform](https://www.drupal.org/project/entityform) for this?
Comment: This is a part of a custom module, I can't create a content type or entityform for this.


Form a Committee Of 10 Senators

Question: The problem I'm working on reads: "How many different committees of 10 Senators can be formed if the two Senators from the same state, (50 States in All) are considered identical?"
This is the answer I got but I'm almost sure it's wrong:
$e_{1-50}=(1+x+x^2)$
$g(x)=(1+x+x^2)^{50}$
$(1+x+x^2)^{50}=\frac{(1-x^3)^{50}}{(1-x)^{50}}$
$=(1-x^3)^{50}*\frac{1}{(1-x)^{50}}$
$(1-x^3)^{50}=(1+(-1)(x^3 ))^{50}$
$=(1-C(50,1) x^3+C(50,2) x^6-C(50,3) x^9+⋯)$
$\frac{1}{(1-x)^{50}} =(1+C(50,1)x+C(51,2) x^2+⋯+C(59,10) x^{10}+⋯)$
$g(x)=(1-C(50,1) x^3+C(50,2) x^6-C(50,3) x^9+⋯)
   *(1+C(50,1)x+C(51,2) x^2+⋯+C(59,10) x^{10}+⋯)$
$a_{r}=C(59,10)-C(50,1)*C(56,7)+C(50,2)*C(53,4)-C(50,3)*C(50,1)=51,590,216,930$
I'm wondering where I went wrong. Any help would be greatly appreciated!
Comment: The way the question is phrased makes me think that there's still a pool of 100 senators, but a combination that contains 9 senators `California 1` is the same as a combination with the same 9 senators and `California 2` (as opposed to making combinations of 50 senators from different states). This would allow for combinations such as `CA1, CA2, OH1, OH2, DE1, DE2, MI1, MI2, AK1, AK2`
Answer: We can count this by considering the number of states $i$ that contribute two senators:
$$
\sum_{i=0}^{5}\binom{50}{i}\binom{50-i}{10-2i}=51590216930.
$$
Comment: So my answer was right?
Comment: It seems so. Although your math seems hard to read. Why not use the Tex mode to make it more readable (enclose in $, use \binom instead of C)?
Comment: I fixed it, thanks for the tip.
Comment: Your answer, and your method, are correct (not an approximation).
Answer: i think i might have a solution.  you have at least $5$ states and at most $10$ with the $2$ senators in each state considered identical.  if it is $5$ states there are none left to choose otherwise there are $2,4,6,8,10$ states selected that have $1$ senator chosen.
${5\choose 0}{50\choose 5}+{6\choose 2}{50\choose 6}+{7\choose 4}{50\choose 7}+{8\choose 6}{50\choose 8}+{9\choose 8}{50\choose 9}+{10\choose 10}{50\choose 10}$
Comment: This seems to get the same answer as I came up with. I am supposed to be using generating functions.
Answer: I wonder at the interpretation of the question.
If there were 50 pairs of counters of different colors, I can understand,
but how can you have a committee with identical people ?
I would think the answer is simply $\dbinom{50}{10}$
Remarks
Since you were asked to use a G.F. your interpretation and that of others must be right, but I am mystified why the questioner had to insert  "the two Senators from the same state, (50 States in All) are considered identical"
Comment: That doesn't allow for you to have two senators from the same state in the committee.
Comment: That's exactly the point. "...two Senators from the same state, (50 States in All) are considered identical." How can you have a committee with identical *people* ?

Form a Committee Of 10 Senators


Drupal 7 CKEditor while replacing from textarea media files are not rendering

Question: I'm working with Drupal 7 + WYSIWYG module + CKEditor + Field Collection.
My issue is, CKEditor is not rendering the media files which is included through media browser.
Steps to reproduce:

Create field collection field with unlimited occurrence.
Add some text and audio/video/document file using media browser with media teaser setting.
Now click "Add another item" button.

That's it now new field will be added, but the previous field will only have the text you entered, the media will be gone.
When I debugged the field, I found the values in hidden textarea. When CKEditor tries to render the values, media elements are not rendering.

Answer: After a long research I found one solution from here.
The patch they provided works for me.
https://www.drupal.org/files/issues/interdiff_8413.txt
I will leave this question open, so that others can get some help from this.


Keeping 2 x Versions of Xcode on Mac

Question: I was rooting around for the answer on StackOverflow to the question above, as I had recently updated to Mac Sierra and by doing so Xcode 7 updated to 8 automatically. I couldn't find the answer to what I wanted, so I decided to share my findings.
Of course I'm not quite ready to invest the time just yet in Swift 3.0 so I wanted to know how to keep two instances of Xcode on my machine for the time being.
Therefore below is how I went about doing this...
Comment: There are already [plenty of existing questions](http://stackoverflow.com/search?q=Xcode+install+two+versions) on this topic. No need for another.
Comment: Really? I didn't come across any when I searched for this exact solution
Answer:
Login to Apple Developer Downloads and find Xcode 7.3.1 or equivalent version of what you want to maintain on your machine.
Download the file and double click on it to open the installer
DON'T drag it across to Applications just yet
Instead, open a Finder Window and drag it to Desktop/Downloads, to install it there
Control-click on the Xcode file to "Get Info"
Under Name & Extension, in the text field, change this from Xcode.app to Xcode7.app (or equivalent naming convention)
Drag this renamed file into Applications
Restart Mac
Open Xcode7 (or new & renamed application)
Voila! 2 x instances of Xcode on your Mac (Xcode proper & Xcode7)

I gather you should never open both apps at the same time. However here is a solution that really does help you if you are still currently developing in two apps or environments on different versions of Swift. Hope this helps.

Keeping 2 x Versions of Xcode on Mac


Separate DateTime column from Database into two separate columns of RadGrid

Question: How can I split "DateTime" column from database, which has the format
yyyy-mm-dd 00:00:00.000, into two separate columns of a RadGrid?
i.e., in Date column of RadGrid, Date should display from database DateTime column.
And in Time column of RadGrid, Time should display from database DateTime column.
Answer: You can bind the very same field to two different bound columns (or whatever the column types you've used).
<telerik:GridBoundColumn
   DataField="YourDateField"
   UniqueName="CDate"
   HeaderText="Date"
   DataType="System.DateTime" DataFormatString="{0:yyyy-MM-dd}">
</telerik:GridBoundColumn>
<telerik:GridBoundColumn
   DataField="YourDateField"
   UniqueName="CTime"
   HeaderText="Time"
   DataType="System.DateTime" DataFormatString="{0:HH:mm:ss}">
</telerik:GridBoundColumn>

Edit:
I think use of IEnumerable<T> is the best approach to solve number of issues including data formatting and checking empty fields.
public class MyModel
{
  public string UpdateDate {get;set;}
  public string UpdateTime {get;set;}
 //and add other properties which you need to be a part of grid
}

Write code to populate the IEnumerable<MyModel> data-source which will be used by the grid.
var list = new List<MyModel>();

// Read one by one row/result from database and set value to
// an instance of MyModel

/* read/fetch row from database */
.....
var dbRow = /* fetch a row */
var model = new MyModel{ UpdateTime = "", UpdateDate=""};
if( dbRow.UpdateDateTime !=null )
 {
   model.UpdateDate = dbRow.UpdateDateTime.ToString("yyyy-MM-dd");
   model.UpdateTime = dbRow.UpdateDateTime.ToString("HH:mm:ss");
 }
list.Add( model );
...
...

and finally bind the list data source to your Grid control.
SO Thread - How Handle Null Values(In Columns) In Telerik RadGrid?
Update suggested by OP
Below code is also working fine to check the null/default values before display it into RadGrid:
protected void GridReport_ItemDataBound(object sender, GridItemEventArgs e)
    {
        if (e.Item is GridDataItem)
        {
            GridDataItem item = (GridDataItem)e.Item;

            if (item["ScanDate"].Text == "01/01/1900")
            {
                item["ScanDate"].Text = "";
            }

            if(item["ScanTime"].Text == "00:00:00 AM")
            {
                item["ScanTime"].Text = "";
            }
        }
   }

Comment: Thank you both of you for the help. I too added my solution to the post above and its working fine.
Comment: I get below error:

`Multiple controls with the same ID 'FilterTextBox_UpdateDateTime' were found. FindControl requires that controls have unique IDs.`
Please reply what shall I change in my code ?
Comment: @user3196511 I think you've to set different value for `UniqueName`.
Comment: Thank you for the reply. Its working fine now after changing the `UniqueName`. 1 more thing I want to ask that If some records do not have DateTime in Database table, then in RadGrid, its showing `01/01/1900` for Date and `00:00:00' for Time. Please let me know how show empty/blank cell in place of the default date time coming for few columns ? Please reply
Comment: In Item_databound event, check for empty fields using `if` condition and if it empty, then make it to display your own text. @user3196511
Comment: @Balaji: Thank you for the reply. Can you please let me know how to check for empty fields for 2 separate date and time columns of Grid, in which data is coming from 1 "DateTime" column of Database table ? Please reply


Net forehand with topspin to high balls: how to practise them?

Question: I want to improve my forehand near the net. I hit ball to a wall with a specific target but the rebound is so fast that it is not really equivalent to high ball shots. How do you train forehand near the net?
Example

Topspin forehand like the Federer below near the net.
Answer: Get a basket of balls, go out to the court, and just practice them. Give the ball a high bounce. Set a specific target to hit, like try hitting the corner sides of the service lines.


Drupal Rest services "access denied user anonymous"

Question: I have created a custom service where I am passing parameters and retrieving result from another file.
So to test it I tried on Postman and I put URL with sitename/endpoint/resource and passed parameters in key value.
When I submit I get an error as access denied user anonymous.
I have return my custom services under hook_services_resources() function
function mymodule_services_resources() {
 $api = array(
  'blog' => array(
    'actions' => array(
     'math' => array(
      'help' => 'Retrieves posted blogs',
      'file' => array('type' => 'inc', 'module' => 'MYMODULE', 'name' => 'mymodule'),

      'callback' => 'mymodule_blog_retrieve',
      'access arguments' => array('services_access_menu'),

      'access arguments append' => TRUE,
      'args' => array(
        array(
          'name' => 'var1',
          'type' => 'string',
          'description' => 'variable 1',
          'source' => array('data' => 'var1'),
          'default' => '0',
        ),
        array(
          'name' => 'var2',
          'type' => 'string',
          'description' => 'variable 2',
          'source' => array('data' => 'var2'),
          'default' => '0',
        ),
      ),
    ),
  ),
),

 );
  return $api;
}

and inc file just takes parameters var1 and var2 and adds it and returns the sum.
Please help me finding out where i have done mistakes.
Answer: Here is running code with access callback function:

function mymodule_services_resources() {
 $api = array(
  'blog' => array(
    'actions' => array(
     'math' => array(
      'help' => 'Retrieves posted blogs',
      'file' => array('type' => 'inc', 'module' => 'MYMODULE', 'name' => 'mymodule'),
      'callback' => 'mymodule_blog_retrieve',
      'access arguments' => array('views'),
      'access callback' => '_blog_access_provide_access',
      'access arguments append' => TRUE,
      'args' => array(
        array(
          'name' => 'var1',
          'type' => 'string',
          'description' => 'variable 1',
          'source' => array('data' => 'var1'),
          'default' => '0',
        ),
        array(
          'name' => 'var2',
          'type' => 'string',
          'description' => 'variable 2',
          'source' => array('data' => 'var2'),
          'default' => '0',
        ),
      ),
    ),
  ),
),

 );
  return $api;
}

/** * Access callback */
function _blog_access_provide_access() {
  return TRUE;
}

I hope this would help you.
Answer: Two suggestions on that.

Try removing 'access arguments append' => TRUE and clear cache. It
can interfere with the user_access check.
Depending on your authentication method, you may need to set the
correct X-CSRF-Token authentication token in the request. See
Problems with Services and CSRF token
Comment: i was working on User View type so had access permissions set at views level not just service module level


Windows Server 2003 : Unable to load

Question: I had a physical server installed windows server 2003, it appear to be unable to load into windows, I tried diagnose it from Boot Disk Utilities and notice all the results return was failed.
Is that mean anything? and how can I solve if unable to load the windows?
I believe this is quite a common issue of server failure, please help.
Thank you in advanced.
Comment: Does it give an error message?
Comment: Have you tried booting into Safe Mode?
Answer: Sounds like your drive is toast to me - in which case, you're out of luck.
That said, could provide some more information such as what hardware you're using, what error messages are appearing and what the output from the Boot Disk Utilities was.
Answer: A couple of possible Solutions for Blue Screen after the boot menu :
RAID Failure - It could be that if you have a RAID 1 setup then the RAID has failed.  It is possible that windows is trying to boot from the failed drive.  Try booting from each drive seperately and see if one is working correctly.
Other Hardware Failure - We have a number of servers that will not allow windows to boot if they have a fan failure - windows will report that it has shut down to protect the system from damage.

Windows Server 2003 : Unable to load


The line that goes through the point (0, 3/2 ) and is orthogonal to a tangent line to the part of parabola y =x^2 with x > 0 is y = ax + 3/2.

Question:

Find  the slope $a$ which is in $y=ax+3/2$
Find the $x$-coordinate of the intersection of the two lines.
Comment: What is your effort so far?
Comment: I found that a= -1/2 and x coordinate (1,1).  I have solved for an hour. I need easy way.step by step
Comment: $y=ax+\frac{3}{2}$ is the given tangent line to $y=x^2$ for $x>0$?
Comment: y=ax +3/2 is the given normal line to y=x^2 for x>0
Comment: For someone to give you a method that you'll understand, you need to tell us more about what it is that you know how to use: Can you use calculus to find tangents and normals? Do you know about pole-polar relationships? Are you familiar with homogeneous coordinates? I could, for instance write up a method that determines $x$ by finding when a certain matrix determinant vanishes, but if you're not familiar with the methods that lead to it, it's not going to be of much use to you.
Comment: My level is pre-calculus. Firtsly ,I drew a graph and found point of intersection of normal line and tangent line on parabola. Then found slope of tangent line which is 2. Lastly,found slope of normal line -1/2. Coefficient " a " in y=ax+ 3/2 is slope. Answer (1,1).   m=a=-1/2
Answer: Hint: Solve the equation $$x^2-ax-\frac{3}{2}=0$$ and set the discriminant equal to zero and determine the variable $a$.
Answer: Step by step approach (as requested in comment to question):
Call the $x$-coordinate of the intersection of the tangent and normal lines $x_0$.
The $y$-coordinate is then $y_0=x_0^2$.
Call $m$ the slope of the tangent line to $y=x^2$ at $x_0$.  What is $m$ in terms of $x_0$?
What is the slope of the normal line at $x_0$?  [Hint:  it is perpendicular to the tangent line.]
What is the $y$-intercept of the normal line at $x_0$?  [Hint:  you just found its slope, and $(x_0,x_0^2)$ is a point on it.]
Given that the $y$-intercept of the normal line is $\dfrac32$ and $x_0>0$, what is $x_0$?
Above you got the slope of the normal line at $x_0$ in terms of $x_0$; this is $a$.
Here is how I picture it, with the parabola in red, the tangent line in blue, and the normal line in green:
Comment: As I understand from your steps equation will be ➡ 2x=(x^2-3/2)/x-0 Then answer will be uncorrect!
Comment: equation for what?  that's not what I got; please report your answers to each step


How to redirect my content type form after submitting in module

Question: How to redirect my content type form after submitting in module.
Code:
function message_proposal_form_alter( & $form, & $form_state, $form_id) {
  if ($form['#id'] == "article-node-form") {
    $form['submit'][] = 'my_callback_function';

  }
}

And
function my_callback_function($form, $form_state) {
  unset($_GET['destination']);
  $form_state['redirect'] = 'node/add/article';
}

Comment: You tried and?.. What was the effect? "is not redirected" is pretty vague. Is function called at all? Some kind of PHP error happens? HTTP 500? Any redirection http headers sent or not?
Answer: You can use Node Save Redirect module.

This module provides a method of specifying a location to take the user after saving a piece of content.
  A set of radios buttons are added to the submission vertical tab on the content type edit form.

The available options are:
Default - Default behaviour
Return to Edit page after saving
Return to content overview page (assuming the user has access permissions
Re-redirect to another location. (any valid drupal path)
Or you may try to add submit function to 'Save' button
function mymodule_form_alter (&$form, &$form_state, $form_id) {
  if ($form_id == 'my_node_form_id') {
    $form['actions']['submit']['#submit'][] = 'mymodule_node_form_redirect_submit';
  }
}

function mymodule_node_form_redirect_submit ($form, &$form_state) {
  $form_state['redirect'] = 'node/add/article';
}

Comment: Thank you. But I would like to do using custom module.


How to display data without html on ajax call?

Question: How to display only content on ajax hit without html markup?
what i am trying to do i have to show data on button click in profile dashboard(custom page) ,for this i have created controller file .
class OutstandingPaymentPending extends ControllerBase {
  // callback for learning portal access
  public function GetPendingPayment() {
    /* TO DO
     * Making api dynamic via configuration
     */
    global $base_url;
    $user_id = \Drupal::currentUser()->id();
    $psid = '';
    $psid_request = \Drupal::request()->get('ds');
    if (!empty($psid_request)) {
      $psid = $psid_request;
    }
    else {
      $psid = get_psid_by_user_id($user_id);
    }
    // Get outstanding data from api
    $url = OUT_STANDING_API . '?PSID=' . $psid;
    //$url = OUT_STANDING_API . '?PSID=00002449846';
    $access_token = API_ACCESS_TOKEN;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('AccessToken:' . $access_token));
    $response = curl_exec($ch);
    $err = curl_error($ch);
    curl_close($ch);
    $rows = array();
    $result = json_decode($response);

    $result = trim($result, '"');
    if (trim($result) == 'No data found') {
      $rows = array();
    } else {
        $outstanding_result = json_decode($result);
         $course_count = 1;
        $rows = [];
        if (!empty($outstanding_result)) {
        foreach ($outstanding_result as $key => $value) {
          //if ($outstanding_result->ResponseCode != 401) {
          $rows[] = array('course_name' => $outstanding_result[$key]->CRSNAME,
            'course_validity' => $outstanding_result[$key]->VALIDITY,
            'course_type' => $outstanding_result[$key]->COURSETYPE,
            'course_installment_date' => $outstanding_result[$key]->INSTDT,
            'course_total_outstanding' => $outstanding_result[$key]->TOTALOUTSTANDINSTAMT,
          );
          //}
        }
      }
    }

    return array(
      '#theme' => 'pending_installment_template',
      '#installment' => $rows
    );
  }
  }

My ajax code is:
//ajax for showing installment payment pending block on click
$(document).on('click', '#gettoptracks', function (e) {
    e.preventDefault();
    $.ajax({
        url: "/outstanding-payment-left",
        context: document.body,
        success: function (data) {
            $("#show-pending-payment").html(data);

        }
    });
    // your statements;
});

On clicking ajax based button its rendering entire page along with data with all html, so js files and css rendering two times in same page .
how i can show only data instead of entire page html which is rendering on page.html.twig?
Comment: You should be returning a Response object in that case, not the Drupal default. Which means you need to render this first, and then return that string in a Response object.
Answer: I have done this in a custom controller before. You don't want to return a render array, because Drupal will take the default action.
Instead, you want to render it to HTML (string) and return that back. Something like this:
$rendered = $this->renderer->renderRoot($build_array);
$response = new Response();
$response->setContent($rendered);
return $response;

As far as the Javascript, here is a generic example using fetch (in a twig file):

You also likely don't want to cache the render array either. You can also greatly simplify the API fetch code by using Guzzle (Client) instead of curl.
Comment: thanks a tonn great explanation,learnt new thing from you


Netgear FVS336G: appropriate solution for today's small businesses?

Question: I've been looking into a routers to facilitate a vpn solution for a small business. While the Netgear FVS336G looks good on paper, it appears to have some fairly crippling setbacks that drag down what appears to be some great hardware.
First off, the unit has been around for a couple years now, perhaps before 64-bit operating systems were as common as they are now, and complaints are everywhere that claim that SSL or IPsec (or both) VPN connections will not work with 64-bit operating systems. However, most of these claims mention only Vista, which makes me think that these problems could have potentially been solved since then.
Unfortunately though, Netgear's support forums seem to be incredibly private, and policed by some troll named jmizuguchi who just closes down public posts in order to marshal them into the private ones. Danger, will robinson.
Apparently their firmware upgrade process is a nightmare too, but that's beside the point.
My question is this: has anyone configured one a Netgear FVS336G to operate in a server 2008 (or R2)/windows 7 64-bit network? If so, is it possible to use the microsoft vpn client or are third party clients still required?
If this thing has just failed the test of time, is there a feature-comparable unit that I've missed, at anywhere near the same price range?
Thanks!
Answer: Quoting a NetOp, "nobody ever got fired for buying Cisco equipment"; because it works, it's widely supported, and an ASA5505 isn't that expensive (even for a small business).
Comment: Cisco ends up being the solution. Oh well, maybe netgear will figure out their problems one day.
Answer: I Second the the Cisco ASA5505 also look at the Juniper J2320. They are not that expensive at all when you look at the big picture. The netgear stuff is more of a lightwight "home office" product. It works most of the time but is a pain in the butt to configure and support is poor to say the least.
Answer: Although I'd agree with the higher quality Cisco equipment, if price is a big concern you could consider a software router such as Vyatta.  It claims to allow for most (if not all) router features, including VPN, and even has a free version.  It's a project I actually have coming up this week and next, so I can't really say much about it yet, but it's worth a look if you're still considering at all your options.
Answer: Old question, but to answer part of the OP's question, yes we've setup W2K8 and Win7 64 bit VPN with the FVS336G. HOWEVER, that setup was with the W2K8R2 acting as the VPN server with the appropriate ports forwarded in the router/firewall. We didn't even try to get the VPN working direct to the router.


Generating Gradle-like Test Reports from Maven

Question: I've worked with multiple Gradle projects that generate reports in the format pictured below. I like this format: it presents the information I require in a concise and intuitive format.
Question: Is it possible to generate reports in an identical format from Maven?
Answer: Likely Maven Surefire Report plugin does want you want. Also you may find useful the following SO question Is there a decent HTML Junit report plugin for Maven?
Comment: Thanks for the reply. Is it possible to tweak the plugin to include the STDIO and STDERR output corresponding to each test?
Comment: Well, I can't find such a possibility. But output can be preserved with [redirectTestOutputToFile](http://maven.apache.org/surefire/maven-surefire-plugin/test-mojo.html#redirectTestOutputToFile) option of Surefire plugin


how to present a question that each variable have 3 possible values in propositional logic

Question: the question is we have 8 houses, their positions are
<code>                                    A  B  C  D

                                    E  F  G  H
</code>
and each house can choose one wi-fi channel from three, and the neighbor (like A and B are neighbors, A and E are, but A and F are not) cannot use the same channel due to interference, use propositional logic to see if there is a solution.
If the question is each house chooses from 2 channels, then I can simply use 8 variables to be True / False to represent the 2 channels, but how should I do with 3 channels?
Comment: How about variables $A_1,A_2,A_3,B_1,B_2,B_3,...$?
Comment: This is my understanding, not sure if it makes sense: use A1 to represent if house A chooses channel 1, it's a True/False variable, and then use AB represents "house A choose different channel with house B", in propositional logic, it's very long: ((A1 and not A2 and not A3) and (not B1 and B2 and not B3)) or () or () or () or () or ()), means the six posssible ways. so this question is "AB and BC and CD and EF and FG and GH and AE and BF and CG and DF". Can you please have a look with my solution?
Comment: sorry, I don't understand, can you explain it? how should I write the propositional logic formula?
Comment: $A_1$ means "house A uses channel 1", and so on. You'll need propositions for each house to express the requirement that each house uses exactly one of the three channels, and propositions for each pair of neighboring houses to express the no-interference requirement. (There are multiple ways to do it - maybe give it a try and update the question if you get stuck.)
Comment: Yes, that works! You might be able to make it shorter by separating the "exactly one channel per house" requirements (e.g. $(A_1\land \lnot A_2\land\lnot A_3)\lor(\lnot A_1\land A_2\land\lnot A_3)\lor(\lnot A_1\land\lnot A_2\land A_3)$) from the "no neighbor interference" requirements (e.g. $\lnot (A_1\land B_1)$).
Answer: You could translate the following MiniZinc model to propositional logic:
<code>set of int: Channels = 1..3;
set of int: Rows = 1..2;
set of int: Cols = 1..4;

array[Rows, Cols] of var Channels: x;

constraint forall(c in Cols) (x[1,c] != x[2,c]);

constraint forall(r in Rows, c in 1..3) (x[r, c] != x[r, c+1]);

%  break symmetries by fixing the first two channels
constraint x[1,1] == 1;
constraint x[1,2] == 2;
</code>
Due to the symmetry breaking constraints, it results in $27$ solutions.
Without them, there are $27*6=162$ solutions.
Example solution:
<code> 1, 2, 3, 1
 2, 3, 1, 2
</code>


Swift cannot import SwiftyJSON and Alamofire by cocoapods on Xcode 8

Question: I need use SwiftyJSON and Alamofire in my Swift project, so I use cocoapods.
My podfile is :
platform :ios, '9.0'
target 'SwiftSalt' do
    use_frameworks!
    pod 'SwiftyJSON'
    pod 'Alamofire', '~> 4.0'
end
post_install do |installer|
    installer.pods_project.targets.each do |target|
        target.build_configurations.each do |config|
            config.build_settings['SWIFT_VERSION'] = '3.0'
        end
    end
end

Also, I did add a USER_HEADER_SEARCH_PATHS , $(PODS_ROOT)/**.
But, it still didn't work. It says "No such module 'SwiftyJSON'". What does module mean?
Answer: Change config.build_settings to swift 2.3. Because swiftyJSON is still on swift 2.3
 post_install do |installer|
installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
        config.build_settings['SWIFT_VERSION'] = '2.3'
    end
end

end
Comment: where can i find it?
Comment: Alamofire support Swift 3.0, should I seperate them?
Comment: Yeah SwiftyJSON not supported to 3.0. Yeah try it :)
Comment: SWIFTYjson has 3.0 branch, try to install that pod
Comment: I mean if I wrote 3.0, both would be 3.0. If I wrote 2.3, both would be 2.3. I don't know how to separate them. I don't know the cocoapods grammar.
Comment: just use my answer, alamofire supports 2.3. I also don't know how to separate :(
Comment: I do use your podfile, but still lots of errors in alamofire. Don't know why.
Comment: Did you update your cocoapods ?, don't use , '~> 4.0' in alamorfire
Comment: And how can I switch the version among SwiftyJSON's two branches. The two branches are master and swift3. And I think SwiftyJSON Swift 3.0 version is unstable.
Comment: Then just use 2.3 of both cocoapods
Answer: Used the following podfile to install the Swift 3 branch of SwiftyJSON, and it worked on the project:
  platform :ios, '10.0'

  project '/Users/You/yourproject.xcodeproj'

  target 'yourproject' do
  use_frameworks!
  pod 'SwiftyJSON', :git => 'https://github.com/appsailor/SwiftyJSON.git', :branch => 'swift3'
  end

  post_install do |installer|
     installer.pods_project.targets.each do |target|
        target.build_configurations.each do |config|
           config.build_settings['SWIFT_VERSION'] = '3.0'
           end
      end
  end

Answer: pod 'Alamofire', '~> 4.0'
pod 'SwiftyJSON', :git => 'https://github.com/appsailor/SwiftyJSON.git', :branch => 'swift3'


Define Javascript Variable With Contents of URL

Question: I have found a geocoder website that will give me some data that I need as a variable in my javascript code: http://geocoder.us/service/csv/geocode?zip=95472. the website returns only the content: 38.393314, -122.83666, Sebastopol, CA, 95472. I need pull this information from the website and put it into a string.
abc = "38.393314, -122.83666, Sebastopol, CA, 95472"
How can I accomplish this?
Comment: exact duplicate of [Reading external plain text content into string](http://stackoverflow.com/questions/10312561/reading-external-plain-text-content-into-string)
Answer: You can use AJAX:
<code>var req = new XMLHttpRequest(); //Create an AJAX object
req.open('GET','http://geocoder.us/service/csv/geocode?zip=95472',true); //Location and method
req.send(); //Send
req.onreadystatechange = function() { //When it's ready
    if (this.readyState === 4) { //... which is code 4
        console.log(this.responseText); //Then you have the responseText
    }
}
</code>
This only works when the request is from the same domain, tho (for security purposes). If you want it to work on any domain, you'll have to use a proxy.
Comment: This might not work because of cross-domain restrictions
Answer: You should use Javascript to make an ajax request to that URL and it will return the information you want in a format you specify, usually JSON. Depending on what Javascript libraries you are/aren't using, there's different ways you could do that -- probably the most common would be to use jQuery to make your request. Here's info on that API:
https://api.jquery.com/jQuery.get/
Comment: While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference.  Link-only answers can become invalid if the linked page changes.
Comment: Point taken. Thanks for the tip! I'll add relevant info.


In ActionScript, fill stage with external SWF

Question: EDIT: I have since solved this problem by simply reworking my MXML-based app and using the SWFLoader component to get the desired effect, without any reloading necessary. This question is therefore no longer an issue for me, but I leave it open for reference.

In MXML, I can get the desired effect easily:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
  layout="absolute">
  <mx:SWFLoader width="100%" height="100%"
    source="3298.swf"/>
</mx:Application>

It looks like this:
(external SWF fills stage) http://www.ubuntu-pics.de/bild/40036/screenshot_028_MSd0UZ.png
I'm new at ActionScript, though, so I can't quite figure out how to duplicate this without MXML. Here's the relevant class:
package {
  import flash.net.URLRequest;
  import flash.display.DisplayObject;
  import flash.display.Loader;
  import flash.events.Event;

  public class Asset extends Loader {
    public var id:int;
    private var preview:Preview;
    private var swfContent:DisplayObject;
    public var zone:int;

    public function Asset(data:Object) {
      id = data.id;
      zone = data.zone;
    }

    public function loadInto(previewToSet:Preview):void {
      preview = previewToSet;
      var request:URLRequest = new URLRequest(url);
      contentLoaderInfo.addEventListener(Event.COMPLETE, onCompleteHandler);
      load(request);
    }

    private function onCompleteHandler(loadEvent:Event):void {
      swfContent = loadEvent.currentTarget.content;
      swfContent.scaleX = 1;
      swfContent.scaleY = 1;
      preview.addChild(swfContent);
    }

    private function get url():String {
      return id + ".swf";
    }
  }
}

In the loadInto function I give the Asset a sprite to live on, and it starts to load. I can get pretty close by setting scaleX and scaleY each to 1, but I can't quite figure out why it's not at the top, and why the SWF is just a bit to large.
(external swf slightly off) http://www.ubuntu-pics.de/bild/40040/screenshot_029_4pHKNI.png
How can I duplicate MXML's 100% height and width in pure ActionScript? Is it doable? If not, I have a fallback app in pure MXML, but my implementation there involves loading the SWFs every time I want to add or remove any one of them... it's not perfect. So I'd prefer this type of implementation if I can just figure out the sizing issue.
Thanks!
Comment: Note to world: currently playing with the thought of just using the MX SWFLoader component in the ActionScript itself. Not sure why that didn't occur to me at first.
Answer: Use the resize event from the stage object and each time the resize event is fired resize the content according to that:
stage.addEventListener(Event.RESIZE, onResize);

public function onResize(e:Event):void{
 swfContent.width=stage.stageWidth;
 swfContent.height=stage.stageHeight;
}

Answer: try adding
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;

to the start of your class then size and place the loaded image to
loadedimage.x = loadedimage.y = 0;
loadedimage.width = stage.stageWidth;
loadedimage.height = stage.stageHeight;

Comment: This gets me closer: http://www.ubuntu-pics.de/bild/40045/screenshot_030_P8eB2D.png - I think there may be something sneaky going on with the SWF (I'm not the original author), since I remember on decompiling it that there was actual data stored in it instead of just a shape. I'll go back and see if I can find anything more useful there.
Comment: Nah, nothing particularly odd about the SWF that I can pick out. Hmm.
Answer: This sound like the anchor point of your swf is not precisely in it's corner. Try offsetting the x and y position in your code, or, even better, modifying the swf to have the anchor point in the corner ?


With which strings would I have an easier time bending/sliding/vibrato on acoustic guitar?

Question: I have been playing acoustic guitar on a standard Yamaha for several months.  As the title suggests, I'm looking to restring it so that I have an easier time bending and sliding!
Could you recommend any strings/techniques for this? I've read that buying thinner strings and/or tuning down can help a lot, but would you mind highlighting any other advantages/disadvantages that I may have missed?
Answer: Bending and sliding are two different things.
For slides, by which I'm assuming you're talking about sliding a note up and down a string with your finger and not a glass or metal "slide", you want to be able to move the note without generating too much of the annoying string noise you can get. For that, using coated strings to lubricate the sliding a little would be good. As a technique, it isn't a technique I use that much.
If you are talking slide in the "slide guitar" sense, you want higher action and reasonably heavy strings, but unlike with electric guitar, you might not need higher than you have already.
For bending, you hit a problem. For volume's sake, you want thicker strings and higher tension. For bending sake, you want thinner strings with lower tension. If you're plugging in an electro-acoustic guitar (piezo bridge or the like) then electricity has fixed that balance issue for you. If not, start developing hand strength and be resigned that you won't get great slinky Buddy Guy bends on an acoustic without the tone sounding weak and the sustain going away.
Comment: Thank you for the response - I wasn't talking about slide guitar - but that's my fault for not making that clear. I didn't consider the possibility of an electro-acoustic guitar - is it possible/practical to install an amp on my current guitar? Or do you really need to just buy a new electro-acoustic? Again, sorry for the vague questions and lack of information - but I am clueless here!
Comment: I didn't think you wanted slide, but there was enough ambiguity that I felt I should cover it.

There are magnetic soundhole pickups which are fairly easy to install and sound pretty good, so you don't have to get a new instrument.
Answer: For increased bending you have three solutions:

Change to nylon strings - this will cause all sorts of changes in the setup of your guitar, and will sound very different, but you will be able to bend much higher
Downtune the guitar - lower tension = easier bending
Improve your bending technique. I can get 5 or 6 semitones on the 7 th fret on my G-string, but to do that I use three fingers and I pivot around the side of my first finger by rotating my wrist, not by extending my fingers!

For improved sliding using the fingers:

Once your callouses develop, you will be able to slide rapidly without problems
Coated strings, such as Elixirs, make sliding much easier, as does use of Fast Fret to coat steel strings before you play
Part of the art of sliding is deciding on the speed profile you want. Certain speed profiles maximise the squeak from the winding, and others minimise it, so practice different types of slide.

For sliding using a metal or glass slide:

You want higher tension, so the slide doesn't push the strings out of tune too easily
You also want a higher action, as you don't want the string to touch the frets
Comment: Many thanks for the response - I've heard positive things about Elixir strings in the past. Would you recommend anything in particular within the Elixir range - perhaps something coated and thin as VarLogRant mentioned above - given that I am willing to give up sound quality? I apologise for the vague questions and lack of information - but I am rather clueless on this matter.
Comment: I generally use Elixir .009's on my faster electric guitars but the noise would be extremely thin on an acoustic. As @VarLogRant mentioned, a pickup would help - see http://www.seymourduncan.com/acoustic/how-to-choose-an-acoustic-pickup.php for examples.
Comment: We've covered the ups and downs of using electric strings on acoustic guitars ( http://music.stackexchange.com/questions/3570/why-shouldnt-i-put-electric-guitar-strings-on-my-acoustic-guitar ). You want SOME mass to drive the string, so I wouldn't go much lighter than .010s for the strings. Beyond that, it makes more sense to just go electric.
Comment: IME, Fast Fret and coated strings make it harder to bend as things are slippery...  Tuning down to Eb or D would probably be the better idea for bending.  Sliding is a different story.  Choose your poison! :)
Comment: interesting - I have never noticed fast fret or coatings  doing anything to affect bending. Your fingers don't really slip off strings when pushing sideways...
Comment: @DrMayhem: It happens for me...  Especially with a brand new fast fret application.  The strings slip from under my fingers in all cases.  I've been playing for about 32 years and have tried FF several times since it was first created.
Comment: I'm guessing it must be the type of guitar neck or playing style then. Having been a guitar player for a little over 25 years I play very much in a blues rock style, so bends are a key part of what I do.
Answer: This looks like a good spot to mention flatwounds (again and again). You can slip and slide with no squeeks! <rant> All that extra top-end is just noise harmonics anyway, siphoning energy from the fundamental </rant>
On an acoustic, you can go a little-bit lighter on the gauge without too much loss of power. 12s are the "standard" for dreadnought acoustics, but 11s would give significantly more flexibility. |12-11|/12 = 1/12 = 0.0833333% change (scaling factors out). As VarLogRant says, I wouldn't go lighter than .010s: you'd lose too much power and presence.
Answer: I personally have found the best strings for bending or slide on acoustic guitar. I have a twelve string acoustic but if I just put in the lighter strings rather than the second that's slightly heavier gage string for each string they bend and slide really well okay my electric guitar blends easier but the sound is fantastic and I can get just as good bend and slide effect's but I do put them on a twelve string .I Use Martin 12 strings E .012 to E .054 they stay in tune really well to .


How to pass variable in PHP using include?

Question: I have one page where i need to send some results to another PHP file.
include("test.php");
but i want to pass variable (var) also so that which can be processed by test.php using $_GET['var'] command. How is it possible in PHP?
Comment: retrieve your $var before including test.php, it will have access to everything declared before its inclusion.
Comment: It is possible by reading the documentation http://php.net/manual/en/function.include.php
Comment: I am new to php. Can u pls send me one example doing the same.
Answer: $var1="hello";
include ("test.php");
the test file contains below code
echo $var1." world";


NSFetchRequest predicate inconsistency iOS (NSFetchedResultsController) vs Mac (NSArrayController)

Question: An inconsistency exists between NSFetchedResultsController on iOS and NSArrayController on Mac when using an NSFetchRequest with a predicate containing an attribute that is defined by the object class and not part of the entity attributes.
Consider a managed object entity Foo implemented by class Foo.  Foo contains a property BOOL isFoo that is implemented by class Foo but is not backed by an attribute (ie. not part of the schema for entity Foo).  Now using isFoo as a condition in a predicate for NSArrayController works just fine.  One would assume this means that the predicate is applied to the object after it has been fetched, hence hitting the object class.  However, on iOS, use of the same predicate causes an NSInvalidArgumentException of isFoo not found.  On iOS, the predicate appears to be evaluated on the NSSQLEntity object prior to creating the Foo object.
It takes a rather specific cross-platform project to show this, but I have yet to find documentation that illuminates this difference.
Answer: In my specific case, the property in question is just a wrapper around an attribute that exists in the entity so I can modify my predicate specifically for iOS.  In the general case, however, this could be a major limitation of NSFetchedResultsController.


React-Native NativeModules - Is there an Android/Java callback pattern

Question: In my react-native JS code I'm calling a Native Module and it was blocking the UI thread for about 1.5sec. Running it on a different thread with a Runnable works but I can't capture the returned value that happens inside the Runnable?
@ReactMethod
  public void print(final String printerAddress, final String price, final String description, final String upc, Promise promise) {
    try {
      boolean success = false;

      new Thread(new Runnable() {
        public void run() {
          success = mEpsonPrinter.printLabel(printerAddress, price, description, upc);
        }
      }).start();

        promise.resolve(success);
    } catch (IllegalViewOperationException e) {
        promise.reject(e);
    }
  }

Comment: You want to know if it's true or false?
Comment: Yes, but also curious how to pass some value back in any other similar situation
Answer: To resolve the immediate problem I placed the promise.resolve(success) call inside the Runnable.run()
try {
      new Thread(new Runnable() {
        public void run() {
          boolean success = mEpsonPrinter.printLabel(printerAddress, price, description, upc);

        promise.resolve(success);
        }
      }).start();
    } catch (IllegalViewOperationException e) {
        promise.reject(e);
    }

Although I'm still left with questioning a solution for callback pattern with Java.


Como carregar uma lista de objeto no flutter?

Question: Por favor observem a lista de objetos.

Não consigo por falta de experiência capturar o content na minha consulta flutter. Falta somente isso para eu conseguir carregar perfeitamente a minha consulta essa foi minha tentativa, porém não seu certo.
@override
  Future<List<Discipulo>> findAllDiscipulo() async {
    List<Discipulo> discipulos = [];
    final response = await http.get(Uri.parse('https://endereçodaminhaaplicacao.com/discipulos'));

    final decoded = jsonDecode(response.body);

    Map<String, dynamic> data = decoded['content'];/*não consegue passa dessa linha*/

    if (response.statusCode == 200) {

      data.forEach((discipulosId, discipulos) {
        discipulos.add(
          Discipulo(
            codigo: discipulos['codigo'],
            nome: discipulos['nome'],
            dataNascimento: discipulos['dataNascimento'],
            logradouro: discipulos['logradouro'],
            origem: discipulos['origem'],
            telefone: discipulos['telefone'],
          ),
        );
      });

      return discipulos;
    }

    return [];
  }

Quando tiro o content ele fica assim;
Map<String, dynamic> data = decoded;/*Consegue passa dessa linha*/

if (response.statusCode == 200) {

  data.forEach((discipulosId, discipulos) {
    discipulos.add(
      Discipulo(
        codigo: discipulos['codigo'],/*Não consegue passa dessa linha por causa do "content"*/
        nome: discipulos['nome'],
        dataNascimento: discipulos['dataNascimento'],
        logradouro: discipulos['logradouro'],
        origem: discipulos['origem'],
        telefone: discipulos['telefone'],
      ),
    );
  });

Por favor como poderia fazer para conseguir lista o objeto corretamente?
Comment: Pelo que pude perceber, o content é um array né... Então você tem que receber um List>
Comment: Isso mesmo.  Estou tentando fazer isso
Answer: Altere a linha
Map<String, dynamic> data = decoded['content'];

para
List<Map<String, dynamic>> data = decoded['content'];


Monitor processes solution

Question: Scenario:

Linux machine ;
I need to "monitor" my processes: need to find every processes that is consuming >80% CPU over 20 seconds, and write the process info into a log .

Is there already a solution for this, or I'll write my own script ?
I've already have a small script, but I wanted to know If i can find something more advanced .
Answer: One of the solution you can use is munin: http://munin-monitoring.org/
Answer: Another tool that might be useful is 'lastcomm' which is in the acct package in Ubuntu.  It will show you how long processes run for.  For hardcore, detailed data you can use 'auditd'.

Monitor processes solution


Little 'aside' in a vocal

Question: What is the proper term for an 'aside' in music (mostly in vocals, but sometimes the score)? Many times these 'asides' MAY not be actually noted in the lyrics.
Two examples:
In Taylor Swifts 'Shake It Off' (2014) @ 0:18  there is a little 'giggle' that is presumably a comment on the 'absurdity of the previous lyric' OR an acknowledgement that maybe the lyric is close to the truth.
In the Rogue Traders 'Watching You' (2005) @ ~1:33-35 You can hear a little laugh (Best with headphones or in an environment with low ambient noise, it is subtle.)
I personally find these little details in the music endearing (when not over done) and notice the absence in different cuts.
I am mostly asking just about the technique in the vocals, not in the score.  However if the term is different or technique is considered different a discussion would be interesting.
Just as the 'right' accompaniment can compliment (or sometimes, IMO) surpass any vocals, these embellishments add to the overall character of the tune and add enjoyment. I've wondered for a while what the technique is called.
Answer: I am not sure there is actually a name for these impromptu embellishments or an official term to describe them.  In some cases you could describe it as ad-lib - but that's not an official music term.
Obviously in a live show there is often a situational variation or embellishment to the normal lyrics or an unrehearsed, ad-lib or spontaneous ornamental comment, inflection or gesture - and each live show is different, which is what is cool about a "live" show.
But when this type thing shows up in the studio recording that ends up on the album or single, it is often simply something spontaneous that happened during one of the takes in the studio and the producer thought that it would (as you say) "add to the overall character of the tune and add enjoyment".  So the producer decided to use that take as part of the final production as opposed to having it be an outtake.  It is not usually planned or rehearsed or scripted.  In fact you might say it's "unscripted".
You can read about a famous example of this in Wikipedia - "The famous "Turn it up" line uttered by Ronnie Van Zant in the beginning (of Sweet Home Alabama) was not intended to be in the song. Van Zant was simply asking producer Al Kooper and engineer Rodney Mills to turn up the volume in his headphones so that he could hear the track better."
I am simply not aware of any specific terminology in common use in the song writing or music production world to describe this sort of thing. But it does add interest to the song and makes the performance more endearing.
Comment: Thank you for this well thought out answer. Another example of an unplanned voice addition (that rarely made it past the DJ's) is at the end of "No One Needs to Know" - Shania Twain "There's your record Hoss...". I would expect this type of thing **much** more in a live show. There is **nothing** that can compare to Big Bad VooDoo Daddy live over the studio recordings (IMO). I suspect that you are likely correct that the producer is typically involved.
Comment: in the context of the question "ad lib" is definitely the best answer, though "sotto voce" also comes close.  Disparte is an interesting candidate, though it refers to something more specific (and somewhat out of context here)
Comment: @ErnieE - Yep - There you go Dude!  ;-)
Answer: There is an Italian term in disparte meaning "aside" to a person or persons offstage. Another Italian term is fra se which means "to oneself." Another term is sotto voce which really means "under voice." I'd guess that "sotto voce" would be the best term. For popular music, I'd just use "aside."
Comment: I like all of the answers and the information about _disparte_ is also interesting. Thanks.
Answer: In theater, this is called "breaking the fourth wall." It means that the actor acknowledges that there is an audience, and makes commentary or asides about the performance or offers "meta-detail" about the play or characters.
In music, it's much the same thing.  I'd call it "meta-discourse."
Comment: I actually hadn't thought of it in that way. (In my experience) this is not a technique that is often used in music. Certainly not in recorded music anyway. I have seen similar (purposely) scripted and obvious acknowledgments in musicals.

Little 'aside' in a vocal


Binomial theorem corollary puzzling, shouldn't $(-1)^k 1^{n-k}$ be $(-1)^{n-k}(1)^k$?

Question: According to the binomoial theorm
$$(x+y)^{n} = \sum_{j=0}^{n} \binom{n}{j}x^{n-j}y^{j}=\binom{n}{0}x^{n}+\binom{n}{1}x^{n-1}y +
... + \binom{n}{n-1}x y^{n-1}+\binom{n}{n}y^n$$
but my textbook says
$$0=0^{n}=((-1)+1)^{n} = \sum_{k=0}^{n}\binom{n}{k}(-1)^{n-k}1^{k}$$
shouldn't  $$(-1)^{k} 1^{n-k}$$ be $$(-1)^{n-k}1^{k}$$?
Since different k would determine different signs, namely + or -.
Please fill me in. thanks.
Comment: I think there's a typo in the formula, one $n$ should be over the sigma, but appears to multiply $\binom{n}{k}$.  I think there's a second typo where you've already switched $(-1)^k1^{n-k}$ with $(-1)^{n-k}1^k$.  To answer what I think the actual question is, note that $\binom{n}{k}=\binom{n}{n-k}$
Answer: Hint: The representation is valid, since
\begin{align*}
(x+y)^n=(y+x)^n
\end{align*}


Prove that $(n! +n) \leq (n+1)!$

Question: How can I prove that $(n! +n) \leq (n+1)!$ given that $n \geq 0$?
Answer: If $n \ge 1$, this is equivalent to
$$
1 \le n(n-1)!
$$
which is clear.
Answer: $\frac{1}{n+1} + \frac{n}{(n+1)!} \leq \frac{1}{n+1} + \frac{n}{(n+1)} = 1$
Therefore since $\frac{1}{n+1} + \frac{n}{(n+1)!}= \frac{n!}{(n+1)!} + \frac{n}{(n+1)!} $ your inequality follows immediately.
Answer: Also if $n=0$ it is obvious ($1\le 1$),
for $n\ge 1$:
$$n!+n\le n!+n!=n!2\le (n+1)!$$
Answer: $n!+n\le n!+n\cdot n!=n!(1+n)=(n+1)!\;$
for all $\;n\in\mathbb{N}\cup\left\{0\right\}.$

Prove that $(n! +n) \leq (n+1)!$


Solving system of PDEs with gradient

Question: I have the following system of PDEs:
$\partial_x q = -c(b_1 \partial_x u + b_2 \partial_y u)$
$\partial_y q = -c(\partial_y u + b_2 \partial_x u)$
where $b_1,b_2,c$ are constants, with $c$ positive. In more compact form:
$\nabla q = -c B \nabla u$
where $B = \left( \begin{matrix} b_1 & b_2 \\ b_2 &1\end{matrix} \right)$.
The matrix $B$ and the function $u$ are given. How can we find $q$?
Comment: write $U(x) = u(c B x)$, then the PDE is $\nabla (q-U) = 0$, so $q-U$ is constant
Comment: Thanks! Are you saying that $\nabla u (c B x) = c B \nabla u (x)$?
Comment: No, its $\nabla (u(cBx)) = cB\nabla u(cBx)$. which means I misspoke.... sorry
Comment: no worries! Thanks for trying to help anyway
Answer: Lets suppose that $q$ exists. Your right hand side is completely known so you can just integrate. Note that for any $\mathbf x = (x,y)$,
$$ \partial_t (q(t\mathbf x)) = \nabla q(t\mathbf x) \cdot \mathbf x$$
so that (assuming some initial condition $q(\mathbf 0)$ is given)
$$q(\mathbf x) = q(\mathbf 0) + \int_0^1 \nabla q(t\mathbf x) \cdot \mathbf x  \ dt$$
i.e. $$ q(\mathbf x) = q(\mathbf 0) - c\int_0^1 (B\nabla u(t\mathbf x))\cdot \mathbf x \ dt $$
If your domain doesn't contain every straight line from $\mathbf 0$ to any point, a variant of the above will work (since the integral of a gradient does not depend on the path of integration, only the endpoints.)

(edit) OP has clarified that the domain is $\mathbb R^2$. On a simply connected set, a vector field $F$ is a gradient iff it is curl free, so for existence, we will need to assume
$$\operatorname{curl} (B \nabla u) = b_2 \partial^2_x u + \partial_{xy} u - b_1 \partial_{xy} u - b_2 \partial_y^2 u = 0.$$ Here, we verify that $\tilde q(\mathbf x) :=q(\mathbf 0) + \int_0^1 F(t\mathbf x)^T \mathbf x dt$, $q(\mathbf 0)$ arbitrary, is indeed a solution to $\nabla q = F$, if $\operatorname{curl}F = \partial_x F_2 - \partial_y F_1 = 0$. Equivalently, the jacobian $\nabla F$ is symmetric.
On the one hand,product and chain rules for differentiating in $\mathbf x$ give $$\partial_i (F(t\mathbf x)_j \mathbf x_j) = \partial_k F_j(t\mathbf x) \partial_i(t\mathbf x)_k\mathbf x_j + F(t\mathbf x)_j \delta_{ij} = t \underbrace{\partial_i F_j(t\mathbf x) \mathbf x_j}_{=(\nabla F(t\mathbf x)^T\mathbf x)_i }+ F_i(t\mathbf x), $$
so that
$$ \nabla \tilde q = \int_0^1 t\nabla F(t\mathbf x)^T\mathbf x + F(t\mathbf x) dt.$$
On the other hand, carefully differentiating a specially chosen function in $t$,
$$\partial_t(tF(t\mathbf x)_i) = F(t\mathbf x)_i + t\partial_t (F(t\mathbf x)_i) = F(t\mathbf x)_i + t\partial_k F_i(t\mathbf x) \partial_t (t\mathbf x_k) =  F(t\mathbf x)_i + t\underbrace{\partial_k F_i(t\mathbf x) x_k}_{=(\nabla F(t\mathbf x) \mathbf x)_i} $$
i.e.
$$ \partial_t (tF(t\mathbf x)) = F(t\mathbf x)+t\nabla F(t\mathbf x) \mathbf x$$
which is the integrand of $\nabla \tilde q$, since $\nabla F$ is symmetric; the result now follows from the Fundamental Theorem of Calculus.
Comment: Probably I should know better too ahaha
Comment: Thanks! Sorry, but I don't quite see how you go from the first equation to the second one...
Comment: @FredG., that's the fundamental theorem of calculus. $\int_0^1 G(t) dt = G(1) - G(0)$
Comment: @FredG. sorry, in the previous comment the fundamental theorem of calculus is of course $\int_0^1 G'(t) dt = G(1) - G(0)$, note the missing $'$ in the prior comment...hopefully it wasn't too confusing
Comment: Yes, sure! At the beginning I was not understanding how you were using it, but it is clear now. Thanks a lot!
Comment: Sorry for bothering you again...I was thinking about when q actually exists. I tested your solution with $u(x,y) = (x-y)^3 + y^3$ and it seems to me there is something wrong...is it because of some domain issues? I suspect the problem is in the matrix B. If I take it to be the identity, then your solution works perfectly
Comment: @FredG. I don't think that B would be a problem, what B did you try? Also what is your domain?
Comment: I kept B generic, with $b_1$ and $b_2$ as above. I am not sure about the domain, though...I would expect $q$ to have the same domain as $u$, that is $R^2$. Regularity should not be an issue....
Comment: @FredG. I was mistaken, you need to make an assumption that $B\nabla u$ is curl free. I will update the answer for this
Comment: Thanks a lot! This is great. I just would have one small question. In light of how you defined $Curl F$, shouldn't we write $Curl (B \nabla u) = b_2 \partial^2_x u + \partial_{xy} u - b_1 \partial_{xy} u - b_2 \partial_y^2 u$. It is not a big deal...just to check that everything is correct
Comment: @FredG. whoops, yes thats right
Comment: Ok, no worries! Thank you very much! I sincerely appreciate all your help and time :)
Comment: @FredG. you're welcome! Sorry for stumbling around, I should know better :)

Solving system of PDEs with gradient


Read and write to file before task is complete using cmd

Question: Consider, I am using the command
C:\>ping www.google.com 1>a.txt 2>&1 | type a.txt

It works well as by default windows sends 4 packets, the task ends and then the file content is displayed.
But when I use
C:\>ping www.google.com -t 1>a.txt 2>&1 | type a.txt

Here the task isn't complete as I have used the -t switch. How can I display the file contents as it is being written in the file.
I don't want to use tee from  GnuWin32 CoreUtils
Comment: if you can use powershell : `ping -t google.fr | tee -FilePath c:\temp\ping.txt`
Answer: You don't want to use tee from the GnuWin32 CoreUtils?
Why don't you try the PowerShell version of the tee command?
Here is a reading
If you are insistent in using only CMD, I think it would be difficult as there is no way (AFAIK) to immediately flush the log buffer to disk.
Comment: MiSAKACHi ~ Yes, actually I wanted to use it in Jenkins, so I didn't want to install any plugins there. Though I can use Powershell there, I will use this. Thanks for the solution :)


Resolver conflito de Toogles bootstrap e Checkbox

Question: Estou com um problema que não consegui resolver, tenho um toggle feito em bootstrapque está em conflito com um checkbox em minha página, tenho um checkbox que ao ao clicar para marca/desmarca o toggle é acionado.
O código do meu checkbox é esse:
<input id="MarcaDesmarca" type="checkbox" name="MarcaDesmarca" />

$(function () {
    $('#MarcaDesmarca').click(function () {
        var val = this.checked;
        $("input[name='Lista[]']").each(function(){
            $(this).prop('checked', val);
        });
    });
});

A imagem do que tenho é essa:

A estrutura está assim:

Descrição

Nome

Data

<input id="MarcaDesmarca" type="checkbox" name="MarcaDesmarca" />

    <?php foreach ($Resultado as $Retorno) {

        $IdUnicoop = $Retorno->IdUnicoop;

        // UNIDADE
        $sqlUnicoop = "SELECT *
                         FROM `cadUnicoop`
                        WHERE `IdUnicoop` = ?
                          AND `Ativo` = 1
                        ORDER BY Nome ASC";
        $arrayUnicoop  = array($IdUnicoop);
        $ResUnicoop = $crud->getSQLGeneric($sqlUnicoop, $arrayUnicoop, TRUE);

        // NOME DA UNIDADE
        foreach ($ResUnicoop as $NomeUnicoop) {
            $NomeUnicoop->Nome;
        }

    ?>

<?php echo $Retorno->Descricao; ?>

<?php echo $NomeUnicoop->Nome; ?>

<?php echo implode("/", array_reverse(explode("-", $Retorno->Data))); ?>

<input type="checkbox" name="Lista[]" value="<?php echo $Retorno->IdOrdem; ?>" />

<?php echo $Retorno->Produto; ?>

<?php echo $Retorno->Safra; ?>

<?php echo $Retorno->Peso; ?>

<?php echo $Retorno->Valor; ?>

<?php } ?>

Função Toggle
    function _toggle() {

    var $_t = this,
        previewParClosedHeight = 25;

    jQuery("div.toggle.active > p").addClass("preview-active");
    jQuery("div.toggle.active > div.toggle-content").slideDown(400);
    jQuery("div.toggle > label").click(function(e) {

        var parentSection   = jQuery(this).parent(),
            parentWrapper   = jQuery(this).parents("div.toggle"),
            previewPar      = false,
            isAccordion     = parentWrapper.hasClass("toggle-accordion");

        if(isAccordion && typeof(e.originalEvent) != "undefined") {
            parentWrapper.find("div.toggle.active > label").trigger("click");
        }

        parentSection.toggleClass("active");

        if(parentSection.find("> p").get(0)) {

            previewPar                  = parentSection.find("> p");
            var previewParCurrentHeight = previewPar.css("height");
            var previewParAnimateHeight = previewPar.css("height");
            previewPar.css("height", "auto");
            previewPar.css("height", previewParCurrentHeight);

        }

        var toggleContent = parentSection.find("> div.toggle-content");

        if(parentSection.hasClass("active")) {

            jQuery(previewPar).animate({height: previewParAnimateHeight}, 350, function() {jQuery(this).addClass("preview-active");});
            toggleContent.slideDown(350);

        } else {

            jQuery(previewPar).animate({height: previewParClosedHeight}, 350, function() {jQuery(this).removeClass("preview-active");});
            toggleContent.slideUp(350);

        }

    });
}

Comment: Não consegue colocar a parte relevante aqui nas snippets? O que acontece de mal?
Answer: Isso não é um conflito, o que está ocorrendo é que no seu código, o toggle está configurado para ativar quando ele clicar em toda a área do cabecalho, inclusive os checkboxes que fazem parte dele, por exemplo:

O ideal seria você definir um local onde o toggle deverá ser ativado, ou no nome do usuário, ou na seta, como por exemplo:

Assim após que estruturar de maneira correta, seu problema será solucionado.
Comment: Olá @Thales Chemenian, grande ajuda, obrigado.