text:
Q: How to get data from web api using asp.net web application I created my first project in ASP.net.
I created the ASP.Net Web Application project and selected Empty.
I have created many pages in it, also have some pages which fetch data from my SQL server database.
Now I am required to fetch data from Web API, how can I do this? I looked up videos and other help documents, and I see many results showing how to get data for web forms applications, or MVC or web API, but not what I am looking for. Can someone please guide me on how to accomplish this?

A: If the Web API that you are calling does not need any key then following is the sample that accesses yahoo finance API that returns JSON and the data is then put into data table. I have not shown here some JSON classes just for the simplicity. These are getting used when i parse the JSON output from API. If you need an example for API with key, you will have to add it as one of the attribute in the URL. Let me know if you need example with API key as well.

        public DataTable GetQuote(string symbol)
        {
            DataTable resultDataTable = null;
            try
            {
                string webservice_url = "";
                WebResponse wr;
                Stream receiveStream = null;
                StreamReader reader = null;
                //DataRow r;

                //https://query1.finance.yahoo.com/v7/finance/chart/HDFC.BO?range=1m&interval=1m&indicators=quote&timestamp=true
                webservice_url = string.Format(StockManager.urlGlobalQuote, symbol);

                Uri url = new Uri(webservice_url);
                var webRequest = WebRequest.Create(url);
                webRequest.Method = "GET";
                webRequest.ContentType = "application/json";
                wr = webRequest.GetResponseAsync().Result;
                receiveStream = wr.GetResponseStream();
                reader = new StreamReader(receiveStream);

                resultDataTable = getQuoteTableFromJSON(reader.ReadToEnd(), symbol);
                reader.Close();
                if (receiveStream != null)
                    receiveStream.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                if (resultDataTable != null)
                {
                    resultDataTable.Clear();
                    resultDataTable.Dispose();
                }
                resultDataTable = null;
            }
            return resultDataTable;
        }

        public DataTable getQuoteTableFromJSON(string record, string symbol)
        {
            DataTable resultDataTable = null;

            if (record.ToUpper().Contains("NOT FOUND"))
            {
                return null;
            }
            DateTime myDate;
            double close;
            double high;
            double low;
            double open;
            int volume;
            double change;
            double changepercent;
            double prevclose;
            //double adjusetedClose = 0.00;
            //string formatedDate;
            var errors = new List<string>();
            try
            {
                Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(record, new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore,
                    DefaultValueHandling = DefaultValueHandling.Populate,
                    Error = delegate (object sender, Newtonsoft.Json.Serialization.ErrorEventArgs args)
                    {
                        errors.Add(args.ErrorContext.Error.Message);
                        args.ErrorContext.Handled = true;
                        //args.ErrorContext.Handled = false;
                    }
                    //Converters = { new IsoDateTimeConverter() }

                });

                Chart myChart = myDeserializedClass.chart;

                Result myResult = myChart.result[0];

                Meta myMeta = myResult.meta;

                Indicators myIndicators = myResult.indicators;

                //this will be typically only 1 row and quote will have list of close, high, low, open, volume
                Quote myQuote = myIndicators.quote[0];

                //this will be typically only 1 row and adjClose will have list of adjClose
                //Adjclose myAdjClose = null;
                //if (bIsDaily)
                //{
                //    myAdjClose = myIndicators.adjclose[0];
                //}

                if (myResult.timestamp != null)
                {
                    resultDataTable = new DataTable();

                    resultDataTable.Columns.Add("Symbol", typeof(string));
                    resultDataTable.Columns.Add("Open", typeof(decimal));
                    resultDataTable.Columns.Add("High", typeof(decimal));
                    resultDataTable.Columns.Add("Low", typeof(decimal));
                    resultDataTable.Columns.Add("Price", typeof(decimal));
                    resultDataTable.Columns.Add("Volume", typeof(int));
                    resultDataTable.Columns.Add("latestDay", typeof(DateTime));
                    resultDataTable.Columns.Add("previousClose", typeof(decimal));
                    resultDataTable.Columns.Add("change", typeof(decimal));
                    resultDataTable.Columns.Add("changePercent", typeof(decimal));

                    for (int i = 0; i < myResult.timestamp.Count; i++)
                    {
                        if ((myQuote.close[i] == null) && (myQuote.high[i] == null) && (myQuote.low[i] == null) && (myQuote.open[i] == null)
                            && (myQuote.volume[i] == null))
                        {
                            continue;
                        }

                        //myDate = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(myResult.timestamp[i]).ToLocalTime();
                        myDate = convertUnixEpochToLocalDateTime(myResult.timestamp[i], myMeta.timezone);

                        //myDate = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(myResult.timestamp[i]);
                        //string formatedDate = myDate.ToString("dd-MM-yyyy");
                        //formatedDate = myDate.ToString("yyyy-dd-MM");

                        //myDate = System.Convert.ToDateTime(myResult.timestamp[i]);

                        //if all are null do not enter this row

                        if (myQuote.close[i] == null)
                        {
                            close = 0.00;
                        }
                        else
                        {
                            //close = (double)myQuote.close[i];
                            close = System.Convert.ToDouble(string.Format("{0:0.00}", myQuote.close[i]));
                        }

                        if (myQuote.high[i] == null)
                        {
                            high = 0.00;
                        }
                        else
                        {
                            //high = (double)myQuote.high[i];
                            high = System.Convert.ToDouble(string.Format("{0:0.00}", myQuote.high[i]));
                        }

                        if (myQuote.low[i] == null)
                        {
                            low = 0.00;
                        }
                        else
                        {
                            //low = (double)myQuote.low[i];
                            low = System.Convert.ToDouble(string.Format("{0:0.00}", myQuote.low[i]));
                        }

                        if (myQuote.open[i] == null)
                        {
                            open = 0.00;
                        }
                        else
                        {
                            //open = (double)myQuote.open[i];
                            open = System.Convert.ToDouble(string.Format("{0:0.00}", myQuote.open[i]));
                        }
                        if (myQuote.volume[i] == null)
                        {
                            volume = 0;
                        }
                        else
                        {
                            volume = (int)myQuote.volume[i];
                        }
                        prevclose = System.Convert.ToDouble(string.Format("{0:0.00}", myMeta.chartPreviousClose));
                        change = close - prevclose;
                        changepercent = (change / prevclose) * 100;
                        change = System.Convert.ToDouble(string.Format("{0:0.00}", change));
                        changepercent = System.Convert.ToDouble(string.Format("{0:0.00}", changepercent));

                        resultDataTable.Rows.Add(new object[] {
                                                                    symbol,
                                                                    Math.Round(open, 4),
                                                                    Math.Round(high, 4),
                                                                    Math.Round(low, 4),
                                                                    Math.Round(close, 4),
                                                                    volume,
                                                                    myDate,
                                                                    Math.Round(prevclose, 4),
                                                                    Math.Round(change, 4),
                                                                    Math.Round(changepercent, 4)
                                                                    //adjusetedClose
                                                                });
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                if (resultDataTable != null)
                {
                    resultDataTable.Clear();
                    resultDataTable.Dispose();
                }
                resultDataTable = null;
            }
            return resultDataTable;
        }


text:
Q: Log file not produced until WebLogic is restarted I'm working on the development of an application that is deployed on WebLogic 10.3. It is packaged as an EAR and includes one module. The application works fine by itself but I am faced with issue related to logging.
I am using Log4j. The library is included in the EAR file and log4j.xml is placed under JAR module. So the config location is the following:
A.ear/B.jar/log4j.xml
Log4j config is following:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

<appender name="CA" class="org.apache.log4j.ConsoleAppender">
    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="%d{dd-MMM-yyyy-HH:mm:ss} %p %C{1} - %m%n" />
    </layout>
</appender>

<appender name="DRFA" class="org.apache.log4j.DailyRollingFileAppender">
    <param name="file"
        value="servers/AdminServer/logs/EJB.log" />
    <param name="Append" value="true" />
    <param name="DatePattern" value="'-'yyyy-MM-dd" />
    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="%d{dd-MMM-yyyy-HH:mm:ss} %p %C{1} - %m%n" />
    </layout>
</appender>

<logger name="com.companyname.ejb" additivity="false">
    <level value="DEBUG" />
    <appender-ref ref="DRFA" />
    <appender-ref ref="CA" />
</logger>

<logger name="com.companyname.results" additivity="false">
    <level value="DEBUG" />
    <appender-ref ref="DRFA" />
    <appender-ref ref="CA" />
</logger>

<logger name="com.companyname.marketdata" additivity="false">
    <level value="DEBUG" />
    <appender-ref ref="DRFA" />
    <appender-ref ref="CA" />
</logger>

<root>
    <level value="DEBUG" />
    <appender-ref ref="CA" />
</root>

When I build and deploy EAR (using Maven and customized WebLogic plugin) and call application no log file appears. But if I restart WebLogic everything is fine.
WebLogic is running under Windows 7 in domain mode with single node.
I'd like to know if there is some way to make the log appear without weblogic restart (since it can cause issues on production environment)?
Update: Also I'd like to know what is the reason of such behavior (i.e. why the log file  is not created right after application deployment)? Is this an issue with Weblogic, log4j or with their coupling? I've tried to find the answer in the Oracle documentation, but no luck for now.

A: Some notes:

*

*In prod environment, you probably want to have your log configuration outside app packages, so you can change log levels without redeployment.

*You should plan for production to be able to handle restarts. We usually have hot and cold servers, so load can be balanced and servers restarted when doing the deployment.

About the issue, if you want to, you could specify a servlet that is run on startup of app and configures your log4j. Something like:
web.xml
<servlet>
  <servlet-name>SomeServlet</servlet-name>
  <servlet-class>YourServlet</servlet-class>
  <load-on-startup>0</load-on-startup>
</servlet>

Servlet
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.apache.log4j.xml.DOMConfigurator;

public class YourServlet extends HttpServlet
{
    @Override
    public void init(final ServletConfig config)
      throws ServletException
    {
        final java.net.URL url = Thread.currentThread().getContextClassLoader()
                .getResource("Log4j.xml");
        DOMConfigurator.configure(url);
    }
}

There's also an example on the web about using a servlet context listener.

Edit. as to why this happens, weblogic logging mechanism is initiated by default on startup with these kind of settings:
set JAVA_OPTIONS=%JAVA_OPTIONS% -Dlog4j.configuration=file:<path>/log4j.properties
set JAVA_OPTIONS=%JAVA_OPTIONS% -Dorg.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger
set JAVA_OPTIONS=%JAVA_OPTIONS% -Dweblogic.log.Log4jLoggingEnabled=true

so if you just redeploy your app without restarting the server, these settings will not be used -> logging will not get initiated.

A: I didn't found any quick configuration solution, so code change was required.
I've added Weblogic Application Lifecycle listener as suggested here. Its postStart() method initializes log4j explicitly through DOMConfigurator and now logs appear right after application deployment.
The are few alternatives how configuration can be initialized. One of them was mentioned in eis' post and another here. But I've choose listener in order to keep single module in EAR and in order to avoid issues with singleton EJB on cluster environment (i.e. I am not sure if Weblogic will create singleton on each node or just one instance per cluster).
Also in order to prevent environment changes for local and dev environment, I am using internal log4j.xml (i.e. placed within ear file) there.
For stage and prod - external config file is specified (in Maven profile).
External file is monitored by log4j so changes will be automatically applied without any redeployments or restarts.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do you import a custom python library onto an apache spark pool with Azure Synapse Analytics? According to Microsoft's documentation it is possible to upload a python wheel file so that you can use custom libraries in Synapse Analytics.
Here is that documentation: https://learn.microsoft.com/en-us/azure/synapse-analytics/spark/apache-spark-azure-portal-add-libraries
I have created a simple library with just a hello world function that I was able to install with pip on my own computer. So I know my wheel file works.
I uploaded my wheel file to the location Microsoft's documentation say to upload the file.
I also found a youtube video of a person doing exactly what I am trying to do.
Here is the video: https://www.youtube.com/watch?v=t4-2i1sPD4U
Microsoft's documentation mentions this, "Custom packages can be added or modified between sessions. However, you will need to wait for the pool and session to restart to see the updated package."
As far as I can tell there is no way to restart a pool, and I also do not know how to tell if the pool is down or has restarted.
When I try to use the library in a notebook I get a module not found error.

A: Scaling up or down will force the cluster to restart .

A: Making changes to the spark pool's scale settings does restart the spark pool as HimanshuSinha-msft suggested. That was not my problem though.
The actual problem was that I needed the Storage Blob Data Contributor role in the data lake storage the files were stored in. I assumed because I already had owner permissions and because I could create a folder and upload there I had all the permissions I needed. Once I got the Storage Blob Data Contributor role though everything worked.


text:
Q: implode(): Invalid arguments passed Estou trabalhando num sistema para upload de conteúdos e diversas fotos no qual preciso mudar os nomes dos arquivos usando a hash md5 e criando uma string com os novos nomes porém estou encontrando dificuldades em usar o MD5 com o implode;
//segue parte do meu código
$string = implode( ";", md5($fotos['name']) );
                   echo $string;
}

//segue o erro
implode(): Invalid arguments passed

//Queria que a string final fosse algo como:
46e3cca98604344b0dcc1dfbf4d96c68.jpg;abfb69de2141ef5002ce364ccf7af37d.jpg;

//código completo
//faz a conexão
include( "../../../include/funcoes/conexao.php" );
//calcula o tamanho do arquivo
include( "../../../include/funcoes/tamanho-arquivo.php" );

//resgata as variáveis
$titulo = $_POST["titulo"];
$categoria = $_POST["categoria"];
$conteudo = addslashes( $_POST["texto"] );
$status = $_POST["status"];
$tag = $_POST["tag"];

//inicia a função
if ( isset( $_FILES['arquivos'] ) && !empty( $_FILES['arquivos']['name'] ) ) {
    //pega o nome
    $fotos = $_FILES['arquivos'];
    //quantidade de fotos
    $total = count( $fotos['name'] );
    //executa o laço
    for ( $i = 0; $i < $total; $i++ ) {
   //pega o caminho
        $caminho = "../fotos/";
        //pega o nome
        $nome = pathinfo( $fotos['name'][$i], PATHINFO_FILENAME );
        //pega a extensão
        $entensao = pathinfo( $fotos['name'][$i], PATHINFO_EXTENSION );
        //pega o endereço do arquivo, nome e a extensão
        $nome_final = $caminho.md5($nome).".".$entensao;
        //pega o tamanho do arquivo
        $tamanho = tamanho_arquivo( $caminho.md5($nome).".".$entensao );
        //verifica a extensão do arquivo
        if ( $entensao != "jpg" and $entensao != "jpeg" and $entensao != "png" and $entensao != "webp" and $entensao != "gif" ) {
            //exibe a mensagem
            echo "O arquivo precisa ser uma imagem";
        } else {
            //verifica o tamanho
            if ( $tamanho >= "1024" ) {
                //exibe a mensagem
                "O arquivo é muito grande. É preciso carregar fotos com menos de 1MB";
            } else {
                //executa o upload
                if ( move_uploaded_file( $fotos['tmp_name'][$i], $nome_final ) ) {

                    //exibe a mensagem
                    echo "Upload realizado com sucesso";

                } else {
                    //exibe a mensagem
                    echo "Houve um erro com upload do arquivo, por favor verifique o tamanho das imagens e tente novamente!";
                }
            }
        }
    }
}

$string = implode( ";", md5($fotos['name']) );
echo $string;

A: Há 2 problemas acontecendo no código. O primeiro é que a função md5() espera ter uma string como parâmetro e no código você está passando um array à ela ($fotos['name']):
$string = implode( ";", md5($fotos['name']) );

O outro problema é que o segundo parâmetro da função implode() deve ser um array e, como a função md5() retorna uma string, o erro implode(): Invalid arguments passed aparece.
Uma forma de resolver o problema é criar um novo array com os nomes das fotos já formatados e depois passar este array na função implode():
$fotos_renomeadas = [];
foreach ($fotos['name'] as $key=>$foto){
        $fotos_renomeadas[$key] = md5($foto).".jpg";
}
$string = implode( ";", $fotos_renomeadas);
echo $string;

O output será:
# Considerando fotos['name'] = ['img1','img2']

a8a63b4d63a08aed720d0f5f249e07d9.jpg;fe5067706fde605fcc635835a1e52fc8.jpg


text:
Q: Android start Service in an aspect I'm trying to start an android service in an aspect. My project is basicly doing the following :

*

*Sımple Activity has a method called callMethodA() and

*In my Test.aj Aspect, I want to start my senderService just before callMethodA() called.

but, everytime I try to startService, it throws InvocationTargetException. Appearently, My problem is in my aspect, because honestly I have no idea how to start a service with an aspect.
Here's my Sender1Activity.java
 package com.example.sender;

    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.View;
    import android.widget.Button;

    public class Sender1Activity extends Activity {
        Button btn_send;
        Intent serviceIntent;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            setContentView(R.layout.activity_sender1);
            btn_send = (Button) findViewById(R.id.buttonSend);
        }

        public void callMethodA(View v){

            System.out.println("Method A called");
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }

    }

And Here's senderService.java :
    package com.example.sender;

import java.util.Random;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;

public class senderService extends Service {

    String value = String.valueOf("a");

    @Override
    public void onCreate() {
        super.onCreate();

    }

    public int onStartCommand(Intent intent, int flags, int startId) {

        mSendValue.removeCallbacks(hMyValueTask);
        mSendValue.post(hMyValueTask);
        return startId;
    }

    public Handler mSendValue = new Handler();
    public Runnable hMyValueTask = new Runnable() {
        public void run() {
            int n = new Random().nextInt(3000);
            System.out.println("A random delay : " + n);
            publishBuiltinAccelResults(value);
            mSendValue.postDelayed(hMyValueTask, (long) n);

        }
    };

    @Override
    public void onDestroy() {

    }

    public void publishBuiltinAccelResults(String value) {

        Intent intent = new Intent("ResultsA");
        intent.putExtra("resultA", value);
        sendBroadcast(intent);
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

}

And finally, here's the Test.aj  Aspect code :
package com.example.sender;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

public aspect Test extends Activity {
    int i = 1;

    protected void onCreate(Bundle savedInstanceState) {

    };

    pointcut pointcutCatchMethod() :  execution(* callMethodA(*))
     &&  within(com.example.sender.Sender1Activity);

    before() : pointcutCatchMethod() {
        Intent sendIntent = new Intent(this, senderService.class);
        startService(sendIntent);

        System.out.println(" sendBroadcast cought by Aspect , aspect No: " + i);

    }

}

Logcat :
03-07 15:20:27.015: E/AndroidRuntime(6714): FATAL EXCEPTION: main
03-07 15:20:27.015: E/AndroidRuntime(6714): java.lang.IllegalStateException: Could not execute method of the activity
03-07 15:20:27.015: E/AndroidRuntime(6714):     at android.view.View$1.onClick(View.java:3660)
03-07 15:20:27.015: E/AndroidRuntime(6714):     at android.view.View.performClick(View.java:4162)
03-07 15:20:27.015: E/AndroidRuntime(6714):     at android.view.View$PerformClick.run(View.java:17082)
03-07 15:20:27.015: E/AndroidRuntime(6714):     at android.os.Handler.handleCallback(Handler.java:615)
03-07 15:20:27.015: E/AndroidRuntime(6714):     at android.os.Handler.dispatchMessage(Handler.java:92)
03-07 15:20:27.015: E/AndroidRuntime(6714):     at android.os.Looper.loop(Looper.java:137)
03-07 15:20:27.015: E/AndroidRuntime(6714):     at android.app.ActivityThread.main(ActivityThread.java:4867)
03-07 15:20:27.015: E/AndroidRuntime(6714):     at java.lang.reflect.Method.invokeNative(Native Method)
03-07 15:20:27.015: E/AndroidRuntime(6714):     at java.lang.reflect.Method.invoke(Method.java:511)
03-07 15:20:27.015: E/AndroidRuntime(6714):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
03-07 15:20:27.015: E/AndroidRuntime(6714):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
03-07 15:20:27.015: E/AndroidRuntime(6714):     at dalvik.system.NativeStart.main(Native Method)
03-07 15:20:27.015: E/AndroidRuntime(6714): Caused by: java.lang.reflect.InvocationTargetException
03-07 15:20:27.015: E/AndroidRuntime(6714):     at java.lang.reflect.Method.invokeNative(Native Method)
03-07 15:20:27.015: E/AndroidRuntime(6714):     at java.lang.reflect.Method.invoke(Method.java:511)
03-07 15:20:27.015: E/AndroidRuntime(6714):     at android.view.View$1.onClick(View.java:3655)
03-07 15:20:27.015: E/AndroidRuntime(6714):     ... 11 more
03-07 15:20:27.015: E/AndroidRuntime(6714): Caused by: java.lang.NullPointerException
03-07 15:20:27.015: E/AndroidRuntime(6714):     at android.content.ContextWrapper.startService(ContextWrapper.java:390)
03-07 15:20:27.015: E/AndroidRuntime(6714):     at com.example.sender.Test.ajc$before$com_example_sender_Test$1$61afa7eb(Test.aj:23)
03-07 15:20:27.015: E/AndroidRuntime(6714):     at com.example.sender.Sender1Activity.callMethodA(Sender1Activity.java:25)
03-07 15:20:27.015: E/AndroidRuntime(6714):     ... 14 more

A: an activity needs to be new'ed by android. you have 2 activities in this project, but only the main one is new'ed by android. the second one (the aspect) is not.
i would capture the target in the pointcut (Sender1Activity), and create a method there to start a service, since that is the only Activity with a valid context.

A: I've solved the problem for now, thanks to aepurniet , Here's the solution, The pointcut in the aspect should be :
public aspect Test extends Activity{
    int i = 1;

    pointcut pointcutCatchMethod(Activity activity) :  execution(* callMethodA(*))
     && target(activity);

    before(Activity activity) : pointcutCatchMethod(activity) {

        Intent sendIntent = new Intent(activity.getApplicationContext(),senderService.class);

        activity.startService(sendIntent);

        System.out.println(" sendBroadcast cought by Aspect , aspect No: " + i);

    }

}


text:
Q: How to compare id of two tables and when they are equal add a value in another column I have to verify the "number_id" in a column that contains a list of ids from table 1 and create a new column with a list of control number from the table 2.
I am doing:
import pandas as pd

table_1 = pd.read_excel('path/file.xlsx', sheet_name="sheet 1")
table_2 = pd.read_excel('path/file.xlsx', dtype='str')

table_1[['Number_id_table_1']].head(5)

        Number_id_table_1
    0   [35904690, 20344131]
    1   [26360006]
    2   NaN
    3   [46780790]
    4   [355343]

table_2.head()

    control     account_id_nk
0   71996761124 10197651
1   49991227097 1263884
2   71981020953 876828
3   11964723845 35661849
4   47992004868 19071134

To campare the values and add the control number I am doing:
from itertools import chain

def mapping_account_id(index, original_df, column_id_name = str()):
    original_index = index
    list_column_id = []
    if original_index in original_df:
        for ind in original_index:
            list_column_id.append(original_df.iloc[original_index][column_id_name])
            return list(set(list(chain(*list_column_id))))
    else:
        return None

table_1 ['Number_id_table_1_teste'] = table_1 ['Number_id_table_1'].apply(mapping_account_id, args = (table_2, 'control'))

The result is "None" for every row. But i know that the values exist in the table.
Number_id_table_1_teste
0   None
1   None
2   None
3   None
4   None

I expected the column "Number_id_table_1_teste" to contain the control number for each number_id.
Number_id_table_1_teste
0   [21964258763, 81999403136]
1   [92993930352]
2   NaN
3   [17996018821]
4   [85988943884]


text:
Q: JavaScript: Making a subclass of Blob I am experimenting to see if I can customize a Blob that I will pass to a FileReader.  The goal of the sample code is to be able to programmatically
generate data on the fly for the FileReader to consume.  However, it looks like I am not subclassing correctly as I get a TypeError when I try to use my custom class.
Here is my sample code:
// Example of reading a real blob
var realBlob = new Blob(['foo', 'bar']);
var reader1 = new FileReader();
reader1.onload = function(event){
    console.log(JSON.stringify(reader1.result));
};
reader1.readAsText(realBlob);
// Writes "foobar"

// (non-working) streaming blob
function StreamingBlob() {}
StreamingBlob.prototype = new Blob;
StreamingBlob.prototype.constructor = StreamingBlob;
var bInst = new StreamingBlob();

bInst.slice = function (start, end) {
    str = '';
    while (start++ < end) {
        str += 'A';
    }
    return new Blob([str]);
}

// Instance of says it's a Blob
console.log(bInst instanceof StreamingBlob);
console.log(bInst instanceof Blob);

console.log(bInst);
console.log(bInst.slice(1,5));

var reader2 = new FileReader();
reader2.onload = function(event){
    console.log(JSON.stringify(reader2.result));
};
reader2.readAsText(bInst);
// Error!

When I run this I see:
true
true
StreamingBlob {slice: function, type: "", size: 0, constructor: function}
Blob {type: "", size: 4, slice: function}
Uncaught TypeError: Failed to execute 'readAsText' on 'FileReader': parameter 1 is not of type 'Blob'.
"foobar"

I'm confused, because the instanceof check claims that my object is a Blob, but the readAsText method generates an error that claims otherwise.
Is there a better way to do this?


text:
Q: how to write this not Exists sql features is a primary table
feature_groups is a join table joining features and groups
group_orgs another join table joining groups and orgs
in simplicity
features
--------
feature_id
name

feature_groups
----------
feature_id
group_id

group_orgs
---------
group_id
org_id

I want to find all features that exist in feature_groups whose group_id NOT exist in group_orgs.  The following seems to work, but just wondering if this is the best way to do it.
select f.feature_id
from   features f
       left join feature_groups fg
       on f.feature_id = fg.feature_id
where  fg.feature_id is not null
and    not exists
           ( select group_id
             from   group_orgs gor
             where  fg.group_id = gor.group_id )

A: If it gives you the right results and isn't too slow then it's probably good enough, however I would note that your LEFT JOIN WHERE x IS NOT NULL is effectively an INNER JOIN:
select f.feature_id
from   features f
       inner join feature_groups fg
       on f.feature_id = fg.feature_id
and    not exists
           ( select group_id
             from   group_orgs gor
             where  fg.group_id = gor.group_id )

A: Another option:
SELECT f.feature_id
FROM   features f
WHERE  EXISTS (
  SELECT 'X'
  FROM   feature_groups fg
  WHERE  f.feature_id = fg.feature_id
  AND    NOT EXISTS(
    SELECT 'X'
    FROM   group_orgs gor
    WHERE  fg.group_id = gor.group_id
  )
);

Using a join between features and feature_groups can produce duplicate results if there is a one-many relationship. Using EXISTS will only return a single row whereas a one-many join will return duplicate rows.
Another options is to use IN and NOT IN instead of EXISTS and NOT EXISTS.


text:
Q: Check if a function is in H2 I want to check if the Function
$u(x)=|x-1|$
is in
$H^{2}(\Omega) , \Omega = (0,2) $
My idea: I want to check if the function has a weak derivative. But that would only proof $L^{1}$ what should I do next? Checking if there is a weak derivative for the weak derivate? Then I would have at least proven $L^{2}$.  How do I proof that the set is in $H^{2}$ now?

A: I think you're a little confused about what all this is saying. Or at least, I'm confused reading your question. Let's unravel everything and make sure we're on the same page. $H^2(\Omega)$ is the function space $W^{2,2}(\Omega)$ consisting of all functions on $\Omega$ with all weak-partials of order $l \leq 2$ being $L^2$ functions. Since $\Omega$ is a region in $\mathbb{R}$, we just drop the word 'partial.' So it has to have two weak derivatives, and they both need to be $L^2$ functions. There's two steps then clearly, one is to calculate the weak derivatives, and the other is to observe they are in $L^2(\Omega)$.
For both steps, I see no reason why we should use $\Omega$ as you've been given it, rather than translate it so that things are at the origin, just to make the algebra easier. So let's move everything so that $f(x) = |x|$ and $\Omega = (-1,1)$. From here, I provide a sketch of the argument, leaving the details to you - there is really no good way to get a grip on Sobolev spaces other than doing some of these calculations.
I claim a weak-derivative of this function is the Heaviside step function $H(x)$. I leave the proof to you - this should be not so hard since the definition of the weak derivative is basically just integration by parts against test functions, and on each ray, the derivative is $\pm 1$, only being undefined at $0$. Is this function $L^2$? Yes. What's $|H(x)|$? Why is it clearly $L^p$?
What is the second weak derivative? Well it's a weak derivative of $H(x)$. If this function exists, again, it satisfies an integration by parts formula, by definition. But this one is a bit more problematic. One way to prove that such a function does not exist is to take a sequence of test functions, with $\varphi_1(0) = 1$, and then define $\varphi_n(x) = \varphi_1(nx)$. Then since all of these functions have their support contained in $\Omega$, and we are compressing them by a factor of $n$, they go to $0$ in the $L^2$ norm. On the other hand, if you write $\int_\Omega f(x) \varphi_n(x)$ where $f$ denotes a candidate for weak derivative, then can you evaluate this for each $n$? Take the limit, and obtain a contradiction.


text:
Q: Control Raspberry pi with another raspberry pi remotely I am currently working on two projects that both use the raspberry pi and am trying to figure out how to control one pi with the other wirelessly. Is there a way to do this with ssh or another method? Help and other suggestions are greatly appreciated

A: Depends on what you mean by "control".  If both Pi's are on your WiFi network you can surely use SSH between them to run various commands... "ssh pi@192.168.1.x".
If you have Xwindows running on both, you can display X-clients (xterm, etc) that are running on one Pi back on the other Pi's display.

A: You should use to VNC Viewer
Click to link
https://www.realvnc.com/en/connect/download/viewer/


text:
Q: How do I interpret Input size / records in Spark Stage UI I'm looking at the Spark UI (Spark v1.6.0) for a stage of a job I'm currently running and I don't understand how to interpret what its telling me:

The number of records in the "Shuffle Write Size / Records" column makes sense, those numbers are consistent with the data I'm processing.
What I do not understand is the numbers in "Input Size / Records". They indicate that the incoming data has only ~67 records in each partition; the job has 200 partitions so ~1200 records in all. I dont know what that is referring to, none of the input datasets to this job (which was implemented using SparkSQL) have ~1200 records in them.
So, I'm flummoxed as to what those numbers are referring to. Can anyone enlighten me?

A: Your Input Size/Record is too low. It means that at a time, your task is only executing approximately 14 MB of data which is too low. The thumb rule is that it should be 128 MB.
You can change this by change the HDFS block size to 128 MB i.e. hdfs.block.size to 134217728 or if you are accessing from AWS S3 Storage, then you can set fs.s3a.block.size to 134217728 in core-site.xml file
Changing this will also bring down the number of parititions.
Next is your Shuffle Write Size / Records is too high. This means that the lot many data is getting exchanged between shuffles which is an expensive operation. You need to look at your code to see if you can optimize it or write your operations different so that it doesn't shuffle too much.


text:
Q: Problema con java.lang.NumberFormatException: null soy nuevo en la programación y estoy haciendo un programa que resuelva la formula general, pero cuando lo ejecuto me marca esto:
Este es el codigo que estoy haciendo:
import javax.swing.JOptionPane;
import java.util.*;
public class FormulaGeneral {
    String NumeroA;
    String NumeroB;
    String NumeroC;
    float Resultado;
    float Raiz;
    int Interior;
    public FormulaGeneral() {
        int NumeralA=Integer.parseInt(NumeroA);
        int NumeralB=Integer.parseInt(NumeroB);
        int NumeralC=Integer.parseInt(NumeroC);
        NumeroA=JOptionPane.showInputDialog("Escribe el numero A");
        NumeroB=JOptionPane.showInputDialog("Escribe el numero B");
        NumeroC=JOptionPane.showInputDialog("Escribe el numero C");
        JOptionPane.showMessageDialog(null, "El resultado es "+Resultado);
        Resultado=-NumeralB+Raiz/2;
        Interior=NumeralB-4*NumeralA*NumeralC;
        double Raiz = Math.sqrt(Interior);
        }
    public static void main (String[] args) {
        new FormulaGeneral();
}
}

Cuando compilo me dice que está bien pero al ejecutarlo me dice esto:
Exception in thread "main" java.lang.NumberFormatException: null
    at java.base/java.lang.Integer.parseInt(Integer.java:614)
    at java.base/java.lang.Integer.parseInt(Integer.java:770)
    at FormulaGeneral.<init>(FormulaGeneral.java:11)
    at FormulaGeneral.main(FormulaGeneral.java:23)

Process completed.

Acepto criticas o sugerencias para cambiar o modificar el codigo y espero que me puedan ayudar a saber que pasa.
Cita en bloque


text:
Q: What happens when exception occurs in a thread in tomcat I want to know how Tomcat works.
As I know Tomcat assigns a thread when receiving a request from clients.
Then what happens when exception occurs in a thread in tomcat?
All threads in tomcat die due to the exception?
I have another question.
Tomcat run new JVM process when receiving a request from clients?
or.. it just uses its thread to handle the request?

A: I checked by myself.

*

*Server don't die when an exception in a thread occurs.

*It seems embedded tomcat and my spring app run in one single JVM.


text:
Q: SMTP error using PHPMailer on web server I am using the PHPMailer for mail, when the site run on localhost mails are successfully sent but after uploading on webserver(freehosting.com) it shows the error and mails are not going ,i checked the path of all files all are proper ,i show the used code, how can i solve it?

**ERROR :  ****Connection: opening to smtp.gmail.com:587, timeout=300, options=array ( ) 2016-04-18 11:09:39   SMTP ERROR: Failed to connect to server: Cannot assign requested address (99) 2016-04-18 11:09:39   SMTP connect() failed.******

  if ($Flag==true)
`{

    require("../../PHPMailer-master/PHPMailerAutoload.php");

$mail = new PHPMailer();

$mail->SMTPDebug  = 3;

$mail->isSMTP();

$mail->Host = 'smtp.gmail.com';

$mail->SMTPAuth = true;

$mail->Username = "abc@gmail.com";

$mail->Password = "pass";

$mail->SMTPSecure = 'tls';

$mail->Port = 587;

$recev = $to;

$mail->AddAddress($recev'); //by user

$mail->isHTML(true);

$mail->Subject  = $subject ; //yby user

$mail->Body =$header; //by user

$mail->WordWrap = 200;

if(!$mail->Send()) {

echo 'Message was not sent!.';

echo 'Mailer error: ' . $mail->ErrorInfo;

} else {

echo  //Fill in the document.location thing'

<script type="text/javascript">

                        if(confirm("Your mail has been sent"))

                        document.location = "/";
        </script>';
}
}
else
{
echo $msg;
}
?>


text:
Q: Logon time and date I want to know when I login to a computer or domain. I want a pop up show me who has been logged on before me and what time he was logged on and date. By using Group Policy Script.

A: I've got a simple batch file set as a logon script for users via group policy:

echo %logonserver% %username% %date%
  %time% >> \\server\share$\logon.txt

I've set the share as hidden too (not ideal, but better than nothing if you're worried about security).
Regarding the "popping" up, you'd have to look into that one...

A: add to that batch %computername%
take that text file and parse it with a vbscript using regex to find the line with a %computername% that matches the machine the user is logging onto.  then have the vbscript do a console.writeline of that line from the txt file.  visualbasicscript.com has some good examples, just search for it there.


text:
Q: Solving a system of equations in a non-square matrix Mrs Brown has pet cats, pet parrots, pet fish and pet rocks. Each pet rock has three eyes, no legs and no tail. The other pets have as many of these features as you would expect. Let the number of cats, parrots, fish and rocks be given by c, p, f and r respectively.
(a) Suppose N = [ c p f r ]^T. Find the matrix M so that MN is the matrix whose entries are: the total number of eyes, legs and tails of Mrs Brown's pets.
(b) Together, Mrs Brown's pets have 25 eyes, 14 legs and 8 tails. How many pets of each type might she have? Explain your answer carefully.
I'm not sure if part b needs me to state just the general expressions or find actual solutions because it seems to me that the system has infinitely many solutions, i.e. total number of eyes ( 2c + 2p + 2f + 3r = 25 ), legs ( 4c + 2p = 14 ) and tails ( c + p + f = 8 ).

A: There is an implicit side condition that the numbers of the various kinds of pet are all non-negative integers.
Since there are $25$ eyes, there cannot be more than $12$ pets. In particular, there cannot be infinitely many solutions.
Added: As you mentioned, we arrive at the equations $2c+2p+2f+3r=25$, $4c+2p=14$, and $c+p+f=8$.
It seems reasonable to start with the simplest equation, $4c+2p=14$, which we rewrite as $2c+p=7$. Clearly $p$ must be odd. We have the possibilities (i) $p=1$, $c=3$; (ii) $p=3$, $c=2$; (iii) $p=5$, $c=1$; (iv) $p=7$, $c=0$.
In case (i), from the equation $c+p+f=8$, we get $f=4$, and then from $2c+2p+2f+3r=25$ we get $r=3$. Indeed in all cases we must have $r=3$. For since $c+p+f=8$, we have $2c+2p+2f=16$, and therefore $3r=25-(2c+2p+2f)=9$.
Cases (ii), (iii), and (iv) are dealt with similarly.
We could also use matrix row reduction procedures to get at the solutions.


text:
Q: Resque workers do not start properly I use devise and I can send mails with resque. I use this wiki:
How To: Send devise emails in background (Resque, Sidekiq and Delayed::Job)
I have jobs in queue but no workers. Do I have to create task, or workers?

A: OK, try adding this to your Rakefile:
require 'resque/tasks'

Then run your jobs:
QUEUE=* rake resque:work


text:
Q: Adobe Air Android / Arabic text issue i'm using Adobe Flash Air for IOS & Android problem now is the Arabic RTL i can't write arabic.
My

Input Text is Classic not " TLF Text "

The TLF problem is the keyboard not showing up in android..
Example

A: 1) Did you try doing some research? I googled as3 "android" keyboard not showing.
What's wrong with solutions suggested on first page results of the above link?
2) Consider using Stage text and there's an introduction article about it.
3) Try something like below (untested) as a starting point. Hard to fix your code since none shown.
Also read this guide first. Might be useful.
var testInput : TextField = new TextField();
testInput.needsSoftKeyboard = true;
testInput.type = "input";
testInput.addEventListener(FocusEvent.FOCUS_IN, onFocusText);

stage.addChild(testInput);

function onFocusText( e:FocusEvent ):void
{
    testInput.requestSoftKeyboard();
}


text:
Q: System.Web.Http.ApiController gives null parameter when deserialization fails I have a custom JsonConverter implementation for a class which is passed as a parameter to a rest POST method.
Under certain circumstances the JsonConverter will throw an exception. When this happens the rest POST method is invoked with a null value for the object, rather than a 500 being returned to the client as I would expect.
This means I cannot supply a meaningful error to the client.
How can I change or workaround this behaviour?
using System.Web.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace MyControllers
{
  class MyConverter: JsonConverter
  {
...
      public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
      {
        throw new Exception("You can't do that");
      }
   }
  [JsonConverter(typeof(MyConverter))]
  public class MyClass
  {
...
  }
  public class MyController : ApiController
  {
    public string Post([FromBody]MyClass MyObject)
    {
      // Method is invoked with null value for MyObject
    }
  }
}

A: Based on this answer I have a workaround
https://stackoverflow.com/a/32950529/1273906
Each API class has a ModelState property which contains, among other things, any exception that were raised during deserialization.
So I have now created this method on my api base class:
protected void CheckForDeserializationErrors()
{
  foreach (Exception ex in ModelState.SelectMany(v => v.Value.Errors.Select(e => e.Exception)))
  {
    throw new Newtonsoft.Json.JsonException(ex.Message, ex);
  }
}

so a simple call to CheckForDeserializationErrors() as the first line of any API method is sufficient to re-throw any deserialization errors


text:
Q: Richfaces 3.3/JBoss Seam 2.2. Dynamic loading of multiple combo boxes I have three combo boxes. The first one is populated with values. When I select a value from it, the second must be updated. After that, when I select a value from the second combo, the third should be populated. I know that this is already communicated, but with two combos. With more than two it is not working. Could you please tell me what I didn't do properly?
Here is the view:
<h:form>
    <h:panelGrid columns="2">
        <h:outputText value="Choose the produce type:"/>

        <h:selectOneMenu id="firstList"
                            value="#{userBean.firstItem}"
                            valueChangeListener="#{userBean.valueChanged}">
            <f:selectItems value="#{userBean.firstList}"
                           var="element"
                           itemLabel="#{element.label}"
                           itemValue="#{element.value}" />
                <a4j:support reRender="outputPanel"
                             event="onchange"
                             ajaxSingle="true"
                             bypassUpdates="false" />
        </h:selectOneMenu>

        <a4j:outputPanel id="outputPanel">
            <h:selectOneMenu value="#{userBean.secondItem}"
                             valueChangeListener="#{userBean.valueChanged}">
            <f:selectItems value="#{userBean.secondList}"
                           var="element"
                           itemLabel="#{element.label}"
                           itemValue="#{element.value}" />
                    <a4j:support reRender="outputPanel"
                             event="onchange"
                             ajaxSingle="true"
                             bypassUpdates="false" />
            </h:selectOneMenu>

            <h:selectOneMenu value="#{userBean.thirdItem}"
                             valueChangeListener="#{userBean.valueChanged}">
            <f:selectItems value="#{userBean.thirdList}"
                           var="element"
                           itemLabel="#{element.label}"
                           itemValue="#{element.value}" />
            </h:selectOneMenu>
        </a4j:outputPanel>

    </h:panelGrid>
</h:form>

This is the Bean (this is a sample code without any meaningful sence):
@Name("userBean")
public class UserBean
{
@Logger private Log log;

@In StatusMessages statusMessages;

private String firstItem="";
private String secondItem="";
private String thirdItem="";
public List<SelectItem> firstList = new ArrayList<SelectItem>();
public List<SelectItem> secondList = new ArrayList<SelectItem>();
public List<SelectItem> thirdList = new ArrayList<SelectItem>();
private static final String [] FRUITS = {"Banana", "Cranberry", "Blueberry", "Orange"};
private static final String [] VEGETABLES = {"Potatoes", "Broccoli", "Garlic", "Carrot"};
private static final String [] GIRLS = {"Victoria", "Nana", "Etc.."};

public UserBean() {
    SelectItem item = new SelectItem("fruits", "Fruits");
    firstList.add(item);
    item = new SelectItem("vegetables", "Vegetables");
    firstList.add(item);
    item = new SelectItem("girls", "Girls");
    firstList.add(item);
    for (int i = 0; i < FRUITS.length; i++) {
        item = new SelectItem(FRUITS[i]);
    }
}

public List<SelectItem> getFirstList() {
    return firstList;
}

public List<SelectItem> getSecondList() {
    return secondList;
}

public List<SelectItem> getThirdList() {
    return thirdList;
}

public static String[] getFRUITS() {
    return FRUITS;
}

public static String[] getVEGETABLES() {
    return VEGETABLES;
}

public static String[] getGIRLS() {
    return GIRLS;
}

public void valueChanged(ValueChangeEvent event){
    String[] currentItems;
    String id = ((HtmlSelectOneMenu)event.getSource()).getId();
    if (id.equals("firstList")) {
        currentItems = FRUITS;

        for (int i = 0; i < currentItems.length; i++) {
            SelectItem item = new SelectItem(currentItems[i]);
            secondList.add(item);
        }

        thirdList.clear();
    } else {
        currentItems = GIRLS;

        for (int i = 0; i < currentItems.length; i++) {
            SelectItem item = new SelectItem(currentItems[i]);
            thirdList.add(item);
        }
    }
}

public String getFirstItem() {
    return firstItem;
}

public void setFirstItem(String firstItemArg) {
    firstItem = firstItemArg;
}

public String getSecondItem() {
    return secondItem;
}

public void setSecondItem(String secondItemArg) {
    secondItem = secondItemArg;
}

public String getThirdItem() {
    return thirdItem;
}

public void setThirdItem(String thirdItemArg) {
    thirdItem = thirdItemArg;
}

The problem is that when I select a value from the second combo box (values of which were loaded dynamically), the page is reloaded (instead of ajax request being executed) and I have exception:
Exception during request processing:
Caused by javax.servlet.ServletException with message: "java.util.NoSuchElementException"
The second list is successfully updated from the first list, but after that something is wrong.
Thanks in advance!
Cheers!

A: Make sure your bean has a wider scope than Request, like Conversation scope. It looks like you're using JSF 1.2, in this case RichFaces has a <a4j:keepAlive> tag component to elevate the scope of a managed bean from Request to View (using session variables behind the scenes). This option could be what you need. There are two ways to implement it

*

*Using the tag component. This will make the bean have the "View Scope" only for this page.
<a4j:keepAlive bean="userBean" />
<h:form>
    <h:panelGrid columns="2">
    <!-- the rest of your code... -->

*Using the tag annotation. This will make the bean have the "View Scope" on every page is used.
@Name("userBean")
@KeepAlive
public class UserBean {
    //your managed bean code...
}

Note: To use this tag (as component or annotation), the bean must have Request scope.


text:
Q: What is android:layout_alignLeft in Android? i couldnt understand  the attribute android:layout_alignLeft .i am new to android development.
<RelativeLayout
        android:id="@+id/r5"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/r4"

        > <TextView
              android:id="@+id/tv3"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_centerHorizontal="true"
              android:layout_centerVertical="true"
              android:layout_marginTop="10dp"
               android:textSize="16sp"
              android:textColor="#663300"
              android:text="TextView"

               />

          <TextView
              android:id="@+id/tv5"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_marginTop="10dp"

              android:layout_alignLeft="@id/tv3"
               android:textSize="16sp"
              android:textColor="#663300"
              android:text="TextView"

               />
         <TextView
              android:id="@+id/tv6"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_toRightOf="@id/tv5"
              android:layout_marginTop="10dp"
               android:textSize="16sp"
              android:textColor="#663300"
              android:text="TextView"

               />

          </RelativeLayout>

anyone can explain clearly?what is the difference between android:layout_Leftof and android:layout_alignLeft?

A: layout_alignLeft makes the left edge of your view match the left edge of the view whose ID you use as the parameters.
layout_toLeftOf makes your view placed to the left side of the view whose ID you use (the right edge will be aligned with the left edge of the other view).

A: ALIGN_LEFT  Rule that aligns a child's left edge with another child's left edge.
LEFT_OF     Rule that aligns a child's right edge with another child's left edge.
in your above example the align left is used in a way below.

 tv5 textview is align left of the tv3 layout in android.

A: Both parameters are used in relative layout. Talking about android:layout_Leftof, this parameter makes your view to be placed "to the left" (not align) of view whose id you are passing as a value.On the other hand android:layout_alignLeft will place you view starting from the same point(from left in this case) where the view your have passed the id is starting. Also int this case, your view may overlap the other view (as sometimes it is used to keep a view inside another view)

A: android:layout_alignLeft aligns both left sides. (pic 1)
android:layout_toLeftOf aligns one layout to the left of another. (pic 2)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#D6D6D6"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:layout_width="400dp"
            android:layout_height="400dp"
            android:layout_alignLeft="@+id/ll1"
            android:background="#00FF00"
            android:orientation="vertical">  </LinearLayout>

            <LinearLayout
                android:id="@+id/ll1"
                android:layout_width="200dp"
                android:layout_alignParentRight="true"
                android:layout_height="200dp"
                android:background="#00FFFF"
                android:orientation="vertical"></LinearLayout>

    </RelativeLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp">

        <LinearLayout
            android:layout_width="400dp"
            android:layout_height="400dp"
            android:layout_toLeftOf="@+id/ll2"
            android:background="#00FF00"
            android:orientation="vertical"></LinearLayout>

            <LinearLayout
                android:id="@+id/ll2"
                android:layout_width="200px"
                android:layout_height="200px"
                android:layout_alignParentRight="true"
                android:background="#00FFFF"
                android:orientation="vertical">
        </LinearLayout>

    </RelativeLayout>

</LinearLayout>

A: android:layout_alignLeft is for eg: you are using a TextView.Let's take an  eg. There are two
textview.ur first text id as @+id/t1. Next textview say t2is @+id/t2. if you want to place
second textview to the left of first textview, you can refer the id in the t2 ie
android:layout_Leftof="@+id/t1"


text:
Q: sendTextMessage(phoneNumber, null, message, null, null); always returns success even when message not sent I tried sms activity using this link
but the problem is that it always gives "message sent"
how to know if the message is really sent!
here is code
try {
  SmsManager smsManager = SmsManager.getDefault();
  smsManager.sendTextMessage(phoneNo, null, sms, null, null);
  Toast.makeText(getApplicationContext(), "SMS Sent!",
    Toast.LENGTH_LONG).show();
  //...
}

A: In the mentioned link, there is no PendingIntent set for deliveryIntent or sentIntent in order to receive the status of message you need to send PendingIntent. See this link

A: I also faced similar NPE scenario but problem at my end was due to wrong phone number.
So you must also check if phone number was correct or not.


text:
Q: Subscripts and superscripts on accented math characters \documentclass{article}

\begin{document}

${x_i}^j$ works as expected but not with an hat as in ${\hat{x}_i}^j$.
The way I found to make it work is $\mbox{$\hat{x}_i$}^j$.  Is there
an nicer solution?

\end{document}

A: If you want the hat centered of the "x" and the "j" not too close, the most simple code would be  \hat{x}_i{}^{j}. This  way the height of the symbol is not taken into account, so is not exactly the same result, but {{}\hat{x}_i}^{j} obtain exactly the same result. Some comparisons:

\documentclass[a5paper,12pt,twocolumn]{article}
\begin{document}
$\widehat{x_i}^j$ \dotfill{\tiny   \verb|$\widehat{x_i}^j$|}\par
$\hat{x}_i{}^{j}$ \dotfill{\tiny    \verb|$\hat{x}_i{}^{j}$|}\par
${{}\hat{x}_i}^{j}$ \dotfill{\tiny    \verb|${{}\hat{x}_i}^{j}$|}\par
${\strut\hat{x}_i}^{j}$ \dotfill{\tiny    \verb|$\strut\hat{x}_i{}^{j}$|}\par
$\mbox{$\hat{x}_i$}^j$  \dotfill{\tiny  \verb|$\mbox{$\hat{x}_i$}^j$|}\par
$\hat{x_i}^j$ \dotfill{\tiny   \verb|$\hat{x_i}^j$|}\par
${\hat{x}_i}^j$ \dotfill{\tiny   \verb|${\hat{x}_i}^j$|}\par
\end{document}


text:
Q: Json POST To Curl PHP I'm trying to fetch some data from this  json javascript code and print them to PHP using CURL
<html>
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<body>
<script type="text/javascript">
jQuery.ajax(
   {
       type:"POST",
       contentType:"application/json;charset=utf-8",
       url:"https://www.bancopromerica.com.gt/wsservicebus/wsonlineservicebus.asmx/getTipoCambio",
       data:"{}",
       dataType:"json",
       async: false,
       success: function(msg) {
          a("#compInter",msg.d.compraInternet); //Compra Internacional
          a("#ventInter",msg.d.ventaInternet); //Venta Internacional
          a("#compAgencia",msg.d.compraAgencia); //Compra Agencia
          a("#ventAgencia",msg.d.ventaAgencia); //Venta Agencia
      },
      error: function(textStatus, errorThrown, errorDetail){
          alert(errorDetail);
      }
   });
function a(a,b)
{
   jQuery(a).append(b);
}
</script>
</body>
</html>

I receive this error:

[Exception... "Failure"  nsresult: "0x80004005 (NS_ERROR_FAILURE)"
  location: "JS frame :: http://code.jquery.com/jquery-1.12.0.min.js ::
  .send :: line 4"  data: no]

Do you have any idea how to do this right in PHP ?

A: I think all of your JQuery.ajax is correct(By the way, you can change it to $.ajax). The problem that I am thinking is in youra function. This is how I think it should look, and how I do it:
function a(a, b)
{
    $(a).html(b);
}

I have not checked it out on codepin, or jsfiddle, or anything, but I think that will work.

A: A very basic php cURL example would be:
    // create curl resource
    $ch = curl_init();

    // set url
    curl_setopt($ch, CURLOPT_URL, "https://www.bancopromerica.com.gt/wsservicebus/wsonlineservicebus.asmx/getTipoCambio");

    //return the transfer as a string
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    // $output contains the output string
    $output = curl_exec($ch);

    // close curl resource to free up system resources
    curl_close($ch);

    echo json_encode($output)

You would need to var_dump the output as you will want to assign array key/values that suit your needs.


text:
Q: using tuples as a dictionary key in an anagram finder in python So I am writing a program that reads from a word file and prints out sets of words that are anagrams.
Currently, I have a function that takes a string, and returns a tuple with the letters all sorted out.
def getLetters(string):
    """Purpose, to nab letters from a string and to put them in a tuple in
    sorted order."""
    tuple_o_letters = sorted(tuple(string))
    if _DEBUG:
        print tuple_o_letters

    return tuple_o_letters

Sent to this function is this code
try:
    fin = open("words.txt")
except:
    print("no, no, file no here.")
    sys.exit(0)

wordList = []
for eachline in fin:
   wordList.append(eachline.strip())
for eachWord in wordList:
   getLetters(eachWord)

Now, while I can make tuples easily, where I am stuck is I'm trying to store these as dictionary keys, which would be optimal since tuples and keys are immutable, but I'm confused on the method of doing this. Also, the values would be lists of the words with these keys.

A: sorted() returns a list, you want to swap your line:
tuple_o_letters = tuple(sorted(string))

which sorts the letters in string, then turns the resulting sorted list into a tuple.


text:
Q: Fearless and priceless In' Fearless, painless and harmless"less" means "without" and in' priceless' it means too precious to be priced,the opposite of 'worthless'. Can we express the idea "without price" other than the way 'free of cost' or 'cost free' ?

A: Priceless and fearless are exactly the same(in regards to the suffix less), as are your other examples, because less translates better to "have no" and not without.
as in:

*

*He has no fear -> He is very courageous(or very stupid; depends of the point of view).

*It has no price -> Nothing can buy it.
It differs from free, in that free doesn't mean it has no price. it means you are free to get it (from this specific vendor or what have you).
So you can see now why free and priceless are very different, and why "without" cost is not the same as free of cost or cost free.
If you are looking for other words for free, then you might use:

*

*complimentary

*freebie

*gratuitous

*for nothing

and other synonyms (dictionary.com)
for priceless:

*

*incalculable

*invaluable

*irreplaceable

and other synonyms (dictionary.com)
Different roots of the word create different meanings.

A: I suppose that priceless means without in the sense of, "can't put a price on it." There's also irreplaceable, one-of-a-kind, and invaluable.


text:
Q: Difference between & and * in function parameters
Possible Duplicate:
difference between a pointer and reference parameter?

Using C++ i'm wondering what's the difference in the use of & and * in parameters?
For example:
void swap(int &a, int &b)
{
    int temp = a;
    a = b;
    b = temp;
}

That apparently would swap the integers a and b. But wouldn't the following function do exactly the same?
void swap(int *a, int *b)
{
    int temp = *b;
    *b = *a;
    *a = temp;
}

I was just wondering when it is appropriate to use each one, and perhaps the advantages of each one.

A: The difference between pointers and references is that pointers can point to "nothing", while references cannot. Your second sample should null-check pointers before dereferencing them; there is no need to do so with references.


text:
Q: signup button linked to sqlite database public void onSignUpClick(View v){
        if(v.getId() == R.id.btnRegister)
        {
            EditText name = (EditText)findViewById(R.id.TFname);
            EditText email = (EditText)findViewById(R.id.TFemail);
            EditText pass1 = (EditText)findViewById(R.id.TFpass1);
            EditText pass2 = (EditText)findViewById(R.id.TFpass2);

            String namestr = name.getText().toString();
            String emailstr = name.getText().toString();
            String pass1str = name.getText().toString();
            String pass2str = name.getText().toString();

            if(!pass1str.equals(pass2str))
            {
                //popup msg:
                Toast tpass = Toast.makeText(signup.this, "passwords don't match", Toast.LENGTH_LONG);
                tpass.show();
            }
            else
            {
                //insert the details in DB:
                Contact c = new Contact();
                c.setName(namestr);
                c.setEmail(emailstr);
                c.setPass(pass1str);

                helper.insertContact(c);
            }

        }
    }

I'm trying to make a signup form linked to sqlite database. the registraion button that's linked to onSignUpClick method doesn't work. any help to fix this error?

A: I have implemented a similar functionality to my app.. You can use this as a reference.You need to add whatever elements needed for your signup activity.
1. Create a database handler for your sqlite application.(DatabaseHandler.java)
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHandler extends SQLiteOpenHelper {

    public DatabaseHandler(Context context, Object name,
                           Object factory, int version) {
        // TODO Auto-generated constructor stub
        super(context,  DATABASE_NAME, null, DATABASE_VERSION);
    }

    String password;
    // Database Version
    private static final int DATABASE_VERSION = 1;
    // Database Name
    private static final String DATABASE_NAME = "Mydatabase.db";

    // Contacts table name
    private static final String TABLE_REGISTER= "register";
    public static final String KEY_EMAIL_ID="email_id";
    public static final String KEY_MOB_NO = "mobile_number";
    public static final String KEY_PASSWORD = "password";
    public static final String CREATE_TABLE="CREATE TABLE " + TABLE_REGISTER + "("
            + KEY_EMAIL_ID+ " TEXT,"
            + KEY_MOB_NO + " TEXT," + KEY_PASSWORD + " TEXT " + ")";

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL(CREATE_TABLE);
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_REGISTER);

        // Create tables again
        onCreate(db);
    }

    void addregister(UserRegister registerdata)
    // code to add the new register
    {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(KEY_EMAIL_ID, registerdata.getEmailId());//register email id
        values.put(KEY_MOB_NO, registerdata.getMobNo());//register mobile no
        values.put(KEY_PASSWORD, registerdata.getPassword());
        // Inserting Row

        db.insert(TABLE_REGISTER, null, values);
        db.close(); // Closing database connection

    }

    //code to get the register
    String getregister(String username){
        SQLiteDatabase db = this.getReadableDatabase();
        //String selectquery="SELECT * FROM TABLE_REGISTER";
        Cursor cursor=db.query(TABLE_REGISTER,null,  "email_id=?",new String[]{username},null, null, null, null);

        if(cursor.getCount()<1){
            cursor.close();
            return "Not Exist";
        }
        else if(cursor.getCount()>=1 && cursor.moveToFirst()){

            password = cursor.getString(cursor.getColumnIndex(KEY_PASSWORD));
            cursor.close();

        }
        return password;

    }

    public String getDatabaseName() {
        return DATABASE_NAME;
    }

    public static String getTableContacts() {
        return TABLE_REGISTER;
    }

    public static int getDatabaseVersion() {
        return DATABASE_VERSION;
    }

}

2. Create a modal class UserRegister
public class UserRegister {
    //private variables

    String email_id;
    String mobile_number;
    String password;

    // Empty constructor
    public UserRegister(){}

    // constructor
    public UserRegister( String email_id,String mobile_number, String password){
    this.email_id=email_id;
    this.mobile_number=mobile_number;
    this.password = password;
    }

    public String getEmailId() {
    return email_id;
    }

    public void setEmailId(String email_id){
    this.email_id = email_id;
    }

    public String getMobNo() {
    // TODO Auto-generated method stub
    return mobile_number;
    }

    public void setMobNo(String mobile_number){
    this.mobile_number=mobile_number;
    }

public String getPassword() {
    return password;
    }

public void setPassword(String password) {
    this.password = password;
    }

}
3.Create the RegistrationActivity
  public class Registration_Activity extends AppCompatActivity {

    EditText reg_email,reg_phone,reg_password;
    Button reg_button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);
        final DatabaseHandler db = new DatabaseHandler(this, null, null, 2);
        reg_email = (EditText)findViewById(R.id.reg_email);
        reg_phone = (EditText)findViewById(R.id.reg_phone);
        reg_password = (EditText) findViewById(R.id.reg_password);
        reg_button = (Button)findViewById(R.id.reg_button);
        final String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";

        reg_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String email = reg_email.getText().toString();
                String phone = reg_phone.getText().toString();
                String password = reg_password.getText().toString();
                if (email.matches(emailPattern)) {
                    DatabaseHandler db = new DatabaseHandler(Registration_Activity.this, null, null, 2);
                    UserRegister userRegister = new UserRegister();
                    userRegister.setEmailId(email);
                    userRegister.setMobNo(phone);
                    userRegister.setPassword(password);
                    db.addregister(userRegister);
                    Toast.makeText(getApplicationContext(), "Account Created", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(Registration_Activity.this, Login_Activity.class);
                    startActivity(intent);
                    Registration_Activity.this.finish();
                }
                else
                {
                    Toast.makeText(getApplicationContext(),"Enter a valid Email Address",Toast.LENGTH_SHORT).show();
                }

            }
        });

    }
}

4. Login_Activity
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class Login_Activity extends AppCompatActivity {

    TextView signup;
    String email,password;
    EditText log_username,log_password;
    Button login_button;
    DatabaseHandler db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        signup = (TextView)findViewById(R.id.signup);
        String htmlString="<u>Signup</u>";
        signup.setText(Html.fromHtml(htmlString));
        log_username = (EditText)findViewById(R.id.log_username);
        log_password = (EditText)findViewById(R.id.log_password);
        login_button = (Button)findViewById(R.id.login_button);

        login_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                db=new DatabaseHandler(Login_Activity.this, null, null, 2);
                email = log_username.getText().toString();
                password = log_password.getText().toString();
                String StoredPassword =db.getregister(email);
                if(password.equals(StoredPassword)){

                    Toast.makeText(getApplicationContext(),"Login Successfully", Toast.LENGTH_LONG).show();
                    Intent intent = new Intent(Login_Activity.this,VideoActivity.class);
                    startActivity(intent);
                    Login_Activity.this.finish();

                }
                else{
                    Toast.makeText(getApplicationContext(), "Username/Password incorrect", Toast.LENGTH_LONG).show();
                    log_username.setText("");
                    log_password.setText("");
                }

            }
        });

        signup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Login_Activity.this,Registration_Activity.class);
                startActivity(intent);
                Login_Activity.this.finish();
            }
        });

    }
}


text:
Q: Why Python Vincent map visuzalization does not map data from Data Frame? I am using Python vincent map visualization with the use of this package introductory examples. I work in ipython notebook.
I defined simple pandas DataFrame with country FIPS codes (taken from here). Then I tried to map DataFrame data with vincent map by these FIPS codes, but resulted visualization fails to colour countries in any manner. How can I make it work?
country_data_tmp = pd.DataFrame({'country_names' : np.array(['Argentina', 'Armenia', 'Australia', 'Austria']),
                                 'country_FIPS' : np.array(['032', '051', '036', '040']),
                                 'my_rate' : np.array([0.254, 0.3456, 0.26, 0.357])})
country_data_tmp.head()

world_topo = r'world-countries.topo.json'

geo_data = [{'name': 'countries',
             'url': world_topo,
             'feature': 'world-countries'}]

vis = vincent.Map(data=country_data_tmp,
                  geo_data=geo_data,
                  scale=1100,
                  data_bind='my_rate',
                  data_key='country_FIPS',
                  map_key={'counties': 'properties.FIPS'})

vis.display()

A: They don't display because you have not set the map_key correctly. The world_countries.topo.json file identifies the countries by 3 letter code, named id in that file (this corresponds to the field called alpha-3 in the page you linked to).  You can see this if you look at the raw data in that json file.
Also, you set 'name': 'countries' in geo_data, but in map_key you try to reference it as counties (note the missing r). Easy mistake to make, as it's counties in the example page where they're mapping US counties.
If you change the variable names so that they reference non-empty fields - you'll get a lovely map as country_alpha3 in your data table matches id in the JSON variable countries.
N.B. As your code stands, only the countries for which you have data will be plotted. You could add a layer with all country outlines as per the second example here if you want all outlined, but only the ones with data coloured.  I've provided changes to the code to do that in the second code / output section below.
N.B. 2 With your current values of my_rate the colour contrast is not very noticeable.  Try it out with [0,0.3,0.7,1.0] to convince yourself it is colouring them differently.
Code
#Data setup bit - Input[1] from your notebook
#Note new name for country code country_alpha3

import pandas as pd
import numpy as np

country_data_tmp = pd.DataFrame({'country_names' : np.array(['Argentina', 'Armenia', 'Australia', 'Austria']),
                                 'country_alpha3' : np.array(['ARG','ARM','AUS','AUT']),
                                 'my_rate' : np.array([0.254, 0.3456, 0.26, 0.357])})
country_data_tmp.head()

#map drawing bit Input[2] from your notebook
#Note the changes in variable names

world_topo = r'world-countries.topo.json'

geo_data = [{'name': 'countries',
             'url': world_topo,
             'feature': 'world-countries'}]

vis = vincent.Map(data=country_data_tmp,
                  geo_data=geo_data,
                  scale=1100,
                  data_bind='my_rate',
                  data_key='country_alpha3',
                  map_key={'countries': 'id'})

vis.display()

Output

Code with outline layer plus data layer (coloured for those with data):
#Replace input[2] with this to add a layer with outline only

world_topo = r'world-countries.topo.json'

geo_data = [{'name': 'countries',
             'url': world_topo,
             'feature': 'world-countries'},
           {'name': 'countries_outline',
             'url': world_topo,
             'feature': 'world-countries'}]

vis = vincent.Map(data=country_data_tmp,
                  geo_data=geo_data,
                  scale=100,
                  data_bind='my_rate',
                  data_key='country_alpha3',
                  map_key={'countries': 'id'})

del vis.marks[1].properties.update
vis.marks[1].properties.enter.stroke.value = '#000'

vis.display()

Output (output layer plus data layer)


text:
Q: CSS Background Image Blurry on mobile and tablet device I have a background image on a local site that appears fine at desktop and when inspecting tablet/mobile devices in chrome. When site is loaded on mobile and tablet the background image appears incredible blurry to the point it looks terrible. Main image size is 1200px x 1124px. Any help would be great. CSS is posted below.
Thanks in advance.
background-image: url('../assets/Web_BGD.jpg');
background-position: center top;
background-repeat: no-repeat;
background-attachment: fixed;
background-size: cover;


text:
Q: Annihilator matrix transforming all variables in deviations from their sample means? In my econometrics notes (not a proper textbook) I find that given a partitioning of the sample matrix X into $$ X =(X_1 1),$$ where 1 is the (nx1) vector of all unity elements, then $$M_{[1]}=I - 1(1'1)^{-1}1'$$ transforms all variables in deviations from their sample means, where M is the "annihilator matrix" or also called the "residual maker".
Can someone please give me an intuition or even a full proof of this? Or maybe just a reference of where to look up the relationship between the unity vector being in the sample matrix and variables being in deviations from their sample means. I feel like I am stuck on this matrix as I am at a loss of what does this relationship look like. Thank you.

A: $\DeclareMathOperator{\1}{\mathbf 1}$
Few elementary observations:

*

*\begin{align}\1\frac{1}n\1^\mathsf T\mathbf x &= \frac 1n\1\1^\mathsf T\mathbf x\\ &=\begin{bmatrix}\bar x\\\bar x\\\vdots \\ \bar x\end{bmatrix}.\tag 1\end{align}

*\begin{align}\begin{bmatrix}x_1-\bar x\\ x_2-\bar x\\ \vdots \\x_n-\bar x\end{bmatrix}&=\begin{bmatrix}\mathbf x -\1\bar x\end{bmatrix}\\&= \begin{bmatrix}\mathbf x-\frac 1n\1\1^\mathsf T\mathbf x\end{bmatrix}\\&= \begin{bmatrix}\mathbf I\mathbf x-\frac 1n\1\1^\mathsf T\mathbf x\end{bmatrix}\\&=
\underbrace{\begin{bmatrix}\mathbf I-\frac 1n\1\1^\mathsf T\end{bmatrix}}_{:=\mathbf M_{\1}}\mathbf x  .\tag 2\end{align}

*Since $\left(\1^\mathsf T\1\right)^{-1}=\frac 1n, ~\mathbf M_{\1}= \mathbf I-\1 \left(\1^\mathsf T\1\right)^{-1} \1^\mathsf T. $

Further Reading:
$[\rm I]$ Econometric Analysis, William H. Greene, Pearson Education, $2018, $ appendix $\rm A. 2.8,$ pp. $1059-1061.$


text:
Q: How to solve ordinary differential equations: $({2xy^2 - y}){dx} + ({y^2 + x+ y}){dy} = 0$? I used the integrating factor for this equation, when i supposed that it only have ${x}$ or ${y}$, i found that the integrating factor have $x$ and $y$:$$$$
Call $u(x,y)$ is integrating factor, we have:
$${u(2xy^2-y)}{dx} + {u(y^2 + x + y)dy} = 0$$
and: $$\frac{du}{dy}P + \frac{dP}{dy}u = \frac{du}{dx}Q + \frac{dQ}{dx}u$$
I suppose that ${u}$ only have ${x}$, we have:
$$\frac{dP}{dy}u=\frac{du}{dx}Q+\frac{dQ}{dx}u$$
I found the result of $u$ is:
$$u=e^{2x^2y-2x} $$
So how to solve this problem? I need your help.

A: Solving as an exact ODE method. (as it looks like that is what the book wants, from the way the ode is written).
The first step is to write the ODE in standard form for exact, which is
\begin{align*}
           M(x,y) \mathop{\mathrm{d}x}+ N(x,y) \mathop{\mathrm{d}y}=0 \tag{1A}
\end{align*}
Therefore
\begin{align*}
                 \left(2 x \,y^{2}-y\right)\mathop{\mathrm{d}x} + \left(y^{2}+x +y\right)\mathop{\mathrm{d}y} &= 0  \tag{2A}
           \end{align*}
Comparing (1A) and (2A) shows that
\begin{align*}
           M(x,y) &= 2 x \,y^{2}-y\\
           N(x,y) &= y^{2}+x +y
        \end{align*}
The next step is to determine if the ODE is is exact or not. The ODE is exact when
the  following condition is satisfied
$$
         \frac{\partial M}{\partial y} = \frac{\partial N}{\partial x}
      $$
Using result found above gives
\begin{align*}
      \frac{\partial M}{\partial y} &=  \frac{\partial}{\partial y} \left(2 x \,y^{2}-y\right)\\
                                     &= 4 x y -1
        \end{align*}
And
\begin{align*}
      \frac{\partial N}{\partial x} &=  \frac{\partial}{\partial x} \left(y^{2}+x +y\right)\\
                                                  &= 1
      \end{align*}
Since $\frac{\partial M}{\partial y} \neq \frac{\partial N}{\partial x}$
then the ODE is not exact.
Since the ODE is not exact, we will try to find an integrating factor to make it exact.
Let
\begin{align*}
              A &= \frac{1}{N} \left(\frac{\partial M}{\partial y} - \frac{\partial N}{\partial x}   \right)   \\
                &=\frac{1}{y^{2}+x +y}\left( \left( 4 x y -1\right) - \left(1 \right)   \right) \\
                &=\frac{4 x y -2}{y^{2}+x +y}
         \end{align*}
Since $A$ depends on $y$, it can not be used to obtain an integrating factor.
We will now try a second method to find an integrating factor. Let
\begin{align*}
          B &= \frac{1}{M} \left( \frac{\partial N}{\partial x} - \frac{\partial M}{\partial y}  \right)   \\
            &=\frac{1}{2 x \,y^{2}-y}\left( \left( 1\right) - \left(4 x y -1   \right)   \right) \\
            &=-\frac{2}{y}
       \end{align*}
Since $B$ does not depend on $x$, it can be used to obtain an integrating factor.
Let the integrating factor be $\mu$. Then
\begin{align*}
                  \mu &= e^{\int B \mathop{\mathrm{d}y}} \\
                       &= e^{\int  -\frac{2}{y}\mathop{\mathrm{d}y} }
              \end{align*}
The result of integrating gives
\begin{align*}
                     \mu &= e^{-2 \ln \left(y \right) } \\
                          &= \frac{1}{y^{2}}
                \end{align*}
$M$ and $N$ are now multiplied by this integrating factor, giving new  $M$ and new $N$
which are called $\overline{M}$ and $\overline{N}$ so not to confuse them with the
original $M$ and $N$
\begin{align*}
                   \overline{M}  &=\mu  M \\
                                  &= \frac{1}{y^{2}}\left(2 x \,y^{2}-y\right) \\
                                  &= \frac{2 x y -1}{y}
                \end{align*}
and
\begin{align*}
                   \overline{N}   &=\mu  N \\
                                   &= \frac{1}{y^{2}}\left(y^{2}+x +y\right) \\
                                   &= \frac{y^{2}+x +y}{y^{2}}
                  \end{align*}
So now a modified ODE is obtained from the original ODE which will be exact
and can be solved using the standard method. The modified ODE is
\begin{align*}
                     \overline{M} + \overline{N}  \frac{  \mathop{\mathrm{d}y}}{\mathop{\mathrm{d}x}}  &= 0 \\
                     \left(\frac{2 x y -1}{y}\right)  + \left(\frac{y^{2}+x +y}{y^{2}}\right)  \frac{  \mathop{\mathrm{d}y}}{\mathop{\mathrm{d}x}} &= 0
                  \end{align*}
The following equations are now set up to solve for the function
$\phi\left(x,y\right)$
\begin{align*}
           \frac{\partial \phi}{\partial x } &= \overline{M} \\
                                                           &= \frac{2 x y -1}{y}\tag{1} \\
           \frac{\partial \phi}{\partial y } &= \overline{N} \\
                                                           &= \frac{y^{2}+x +y}{y^{2}}\tag{2}
        \end{align*}
Integrating (1) w.r.t $x$ gives
\begin{align*}
       \int \frac{\partial \phi}{\partial x} \mathop{\mathrm{d}x} &= \int \frac{2 x y -1}{y}\mathop{\mathrm{d}x} \\
       \phi &= \frac{x \left(x y -1\right)}{y}+ f(y) \tag{3}
     \end{align*}
Where $f(y)$ is used for the constant of integration since $\phi$ is a function of
both $x$ and $y$.
Taking derivative of equation (3) w.r.t $y$ gives
\begin{align*}
        \frac{\partial \phi}{\partial y} &= -\frac{x^{2} y -x}{y^{2}}+\frac{x^{2}}{y}+f'(y) \tag{4}   \\
                                                         &= \frac{x}{y^{2}}+f'(y)
        \end{align*}
But equation (2) says that $\frac{\partial \phi}{\partial y} = \frac{y^{2}+x +y}{y^{2}}$.
Therefore equation (4) becomes
\begin{align*}
        \frac{y^{2}+x +y}{y^{2}} &= \frac{x}{y^{2}}+f'(y) \tag{5}
     \end{align*}
Solving equation (5) for $ f'(y)$ gives\begin{align*}
            f'(y) &= \frac{y +1}{y}
         \end{align*}
Integrating the above w.r.t $y$ gives\begin{align*}
      \int f'(y) \mathop{\mathrm{d}y} &=  \int \left( \frac{y +1}{y}\right) \mathop{\mathrm{d}y} \\
        f(y)                   &= y +\ln \left(y \right)+ c_1
    \end{align*}
Where $c_1$ is constant of integration. Substituting result found above for
$f(y)$ into equation (3) gives $\phi$
$$
       \phi = \frac{x^{2} y -x}{y}+y +\ln \left(y \right)+ c_1
    $$
But since $\phi$ itself is a constant function, then let $\phi=c_0$ where $c_0$ is new constant and
combining $c_1$ and $c_0$ constants into new constant $c_1$ gives the solution as
$$
       c_1 = \frac{x \left(x y -1\right)}{y}+y +\ln \left(y \right)
    $$

A: Hint
If you try to work with $y(x)$, as you almost noticed, you will arrive to some implicit equation.
So, consider instead
$$({2xy^2 - y})x' + ({y^2 + x+ y}) = 0$$ and first let $x=u+\frac 1{2y}$ (because of the first term).
Try it and see how simple it is.


text:
Q: How to add printing of number of days in a year also for leap years? I am having trouble adding it so that my program prints out the days in a certain year. What's messing me up is the leap years. Don't want to scrap it.
I am confused and was trying to put it together by myself and should have asked for help. wanted to know if there was a way to fix it or if i had to scrap it and start all over again. My problem so far is designating the days. since i'm not sure if i should just separate the days by the month over just have the total for each year and do that for the leap year as well.
if (month == 1) {
    month1 = "January";
    daysInMonth = 31;
} else if (month == 2 ) {
    month1 = "February";
    daysInMonth = 28;
} else if (month == 3) {
    month1 = "March";
    daysInMonth = 31;
} else if (month == 4) {
    month1 = "April";
    daysInMonth = 30;
} else if (month == 5) {
    month1 = "May";
    daysInMonth = 31;
} else if (month == 6) {
    month1 = "June";
    daysInMonth = 30;
} else if (month == 7) {
    month1 = "July";
    daysInMonth = 31;
} else if (month == 8) {
    month1 = "August";
    daysInMonth = 30;
} else if (month == 9 ) {
    month1 = "September";
    daysInMonth = 30;
} else if (month == 10) {
    month1 = "October";
    daysInMonth = 31;
} else if (month == 11) {
    month1 = "November";
    daysInMonth = 30;
} else if (month == 12) {
    month1 = "December";
    daysInMonth = 31;
} else if (month >= 13 ) {
    System.out.println("this date does not exist please try again");
}

if (month <= 12) {
    System.out.println("this is the year you put in " + year);
    System.out.println("this is the month you entered " + month1);
    System.out.println("this is how many days are in that year " + daysInMonth);
    }
}

A: You would get several advantages if you used java.time for this:

*

*it will be easier to check for invalid input

*you can easily find out if a year is a leap year or not

*you can easily print month names and even abbreviations depending on a locale, that means you can switch languages and standards

Here's a small example for a method:
public static void printInformationAbout(int month, int year) {
    // create an instance of month and year from the arguments
    Year y = Year.of(year);
    Month m = Month.of(month);

    // collect information about the year
    boolean isLeap = y.isLeap();
    int days = y.length();
    // and print that information
    if (isLeap) {
        System.out.println(year + " is a leap year and has " + days + " days");
    } else {
        System.out.println(year + " is a regular year and has " + days + " days");
    }

    // print month info (directly this time)
    System.out.println(String.format("%s (month no. %d) has %d days in %d",
                            m.getDisplayName(TextStyle.FULL, Locale.ENGLISH),
                            m.getValue(),   //  number of the month
                            m.length(isLeap), // length of month in days
                            year));
}

If you used this in a main, let's say like this:
public static void main(String[] args) {
    printInformationAbout(5, 2020);
}

You'd get the following output:
2020 is a leap year and has 366 days
May (month no. 5) has 31 days in 2020


text:
Q: How to copy my build folder to remote server using gulp I am new to Gulp build tool.I recently starts using Gulp in my project.I done correctly the following things minified, compress,jsx file to js file.But My requirement is to send my build folder to my remote server which is located at another place.For this i am using gulp-scp npm to copy folder to remote server but it not copying folder to server.
The below code is gulpfile.js
var gulp   = require('gulp'),
    scp    = require('gulp-scp2');
gulp.task('default', function() {
  return gulp.src('src/*.js')
  .pipe(scp({
    host: '192.50.10.31',
    username: 'applmgr',
    password:'123456',
    dest: '/Data/project'
  }))
  .on('error', function(err) {
    console.log(err);
  });
});

In this code i am copying all js files project in Data folder of remote server.
 I run my gulpfile,js
c:\gulpproject>gulp
[10:19:36] Using gulpfile c:\gulpproject\gulpfile.js
[10:19:36] Starting 'default'...
coming like this and not showing any hing
can any help me why it is coming like this and in which place my code is wrong

A: Ok I solved this problem using gulp-rsync npm plugin.But In windows it you want copy file from your local to remote system for this you system support rsync and also contain ssh command.I tried this one in Linux and install rsync.
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var react = require('gulp-react');
var rsync = require('gulp-rsync');

gulp.task('scripts', function() {
  // Minify and copy all JavaScript (except vendor scripts)
  // with sourcemaps all the way down
  return gulp.src("src/*.jsx")
    .pipe(react())
    .pipe(uglify())
    .pipe(gulp.dest('build/js'));
});
gulp.task('deploy',['scripts'], function() {
  gulp.src('build/**')
    .pipe(rsync({
      root: 'build',
      hostname: 'ramprasad@10.60.48.11',
      destination: '/Data/rrv'
    }));
 gulp.src('build/**')
    .pipe(rsync({
      root: 'build',
      hostname: 'appl@10.30.10.42',
      destination: '/Data/rrv'
    }));
   });

// The default task (called when you run `gulp` from cli)
gulp.task('default', ['deploy']);

A: you can use powershell or cmd or batch:
var spawn = require("child_process").spawn,child;
child = spawn("powershell.exe",["c:\\temp\\helloworld.ps1"]);
child.stdout.on("data",function(data){
    console.log("Powershell Data: " + data);
});
child.stderr.on("data",function(data){
    console.log("Powershell Errors: " + data);
});
child.on("exit",function(){
    console.log("Powershell Script finished");
});
child.stdin.end(); //end input


text:
Q: UglifyJS2 call minify function programmatically I would like to know if I can call the minify main function programmatically.
I am able to run the same code as defined in compress, however replacing UglifyJS.Compressor with UglifyJS.minify does not work.
This is because I would like to pass the same options defined in the README of UglifyJS2, instead of the ones in compress.
Please note that I am running the code in Nashorn, and not in Node.js so that would be similar to a browser environment.

A: This is a work in progress: see this issue and this PR.


text:
Q: .each loop iterate based on element type and name Currently I have the following:
 $("textarea").each(function () {

    });

I like to do the loop only for textareas where the element name starts with dvSummary.

A: Use an 'attribute value starts with' selector, such as:
$("textarea[name^='dvSummary']")

See documentation here https://api.jquery.com/attribute-starts-with-selector for more examples.


text:
Q: JPA: How to represent JoinTable and composite key of a JoinTable? Let's say I have a webapp where users can follow other users.
In my database, I have a User table, and a Following table.
The Following table just has two values: a followingUserId and a followedUserId.
In Java, I have a User class. Most tutorials I see involve one object containing a set of objects it's related to. So many tutorials can describe how to have Users have a set of users following that user, and a set of users followed by a user. But that would require a lot of memory.
I'm thinking of an alternate structure where a User object has no info about following. Instead, there is a Following object that looks like this
@Entity
@Table(name = "Following")
public class Following {
    RegisteredUser follower;
    RegisteredUser followed;
}

and corresponds to the join table. When I want to get all the followers of a user, I can do a query for all Following objects with that user as the follower.
My issues are:

*

*The Followers Table has a composite key of each of the two userids. How can I use annotations to represent that composite key? The @Id annotation denotes a single variable as the key

*How can I do such a query?
If it's relevant, I am using MySQL as the db

A: If using JPA > 2.0, you can mark relationships as your ID:
@Entity
@Table(name = "Following")
@IdClass(FollowingId.class)
public class Following {
    @Id
    RegisteredUser follower;
    @Id
    RegisteredUser followed;
}

public class FollowingId implements Serializable {
    private int follower;
    private int followed;
}

the types within the followingId class must match the type of the RegisteredUser Id. There are plenty of more complex examples if you search on JPA derived ID.
For queries, it depends on what you are looking for.  A collection of followers for a particular user could be obtained using JPQL:
"Select f.follower from Following f where f.followed = :user"


text:
Q: Area of a rectangular triangle We need to calculate the area of the triangle shown in figure:

The text of the problem also says that: $\sin \alpha =2 \sin \beta$. What is the area of the triangle?

A: Hint: the law is sines tells you one leg is twice the other. If the short one is $x$, apply the Pythagorean theorem to find $x$.

A: Opposite to $\alpha$ is $a$ and opposite to $\beta$ is $b$
Then $\sin \alpha=a/20, \sin \beta =b/20$
By given $\sin \alpha=2\sin \beta $
$\implies a/20  = 2*b/20\implies a=2b$
By Pythagorean theorem $a^2+b^2=20^2$
$\implies (2b)^2 +b^2 =400$
$\implies 5b^2 =400$
$\implies b=\sqrt {80}$
$\implies a=2\sqrt {80}$
$area=(1/2)*b*a $
$\implies area=80$ sq cms


text: Q: How do I display only some objects in django? I have a basic blog app, where you can write blogs from the django admin panel. I want to display only ten blogs per page(on the public homepage) and then display the next ten blogs in the next page and so on and display a page number at the bottom of the page, like stackoverflow does on the questions page. It displays 15 questions and then shows which page you're currently on. I am new to django and don't know if any function is available for this purpose. I tried searching on google and stackoverflow, but cannot find any relevant answer.