text:
Q: Code works on PC but not Android (Gson) I'm not having good luck moving code from my PC to Android. I am having problems with code that works on my PC but not on my Android phone. I am using the same libraries (GSON) and nothing I am doing should be problem for an Android device. Can someone help me?
Logcat:
08-10 22:39:22.400: E/AndroidRuntime(29153): FATAL EXCEPTION: AsyncTask #1
08-10 22:39:22.400: E/AndroidRuntime(29153): java.lang.RuntimeException: An error occured while executing doInBackground()
08-10 22:39:22.400: E/AndroidRuntime(29153):    at android.os.AsyncTask$3.done(AsyncTask.java:278)
08-10 22:39:22.400: E/AndroidRuntime(29153):    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
08-10 22:39:22.400: E/AndroidRuntime(29153):    at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
08-10 22:39:22.400: E/AndroidRuntime(29153):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
08-10 22:39:22.400: E/AndroidRuntime(29153):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
08-10 22:39:22.400: E/AndroidRuntime(29153):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
08-10 22:39:22.400: E/AndroidRuntime(29153):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
08-10 22:39:22.400: E/AndroidRuntime(29153):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
08-10 22:39:22.400: E/AndroidRuntime(29153):    at java.lang.Thread.run(Thread.java:856)
08-10 22:39:22.400: E/AndroidRuntime(29153): Caused by: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 2
08-10 22:39:22.400: E/AndroidRuntime(29153):    at com.google.gson.Gson.fromJson(Gson.java:806)
08-10 22:39:22.400: E/AndroidRuntime(29153):    at com.google.gson.Gson.fromJson(Gson.java:761)
08-10 22:39:22.400: E/AndroidRuntime(29153):    at com.google.gson.Gson.fromJson(Gson.java:710)
08-10 22:39:22.400: E/AndroidRuntime(29153):    at com.g4apps.json.android.verification.client.JsonVerificationClass.jsonVerificationCall(JsonVerificationClass.java:73)
08-10 22:39:22.400: E/AndroidRuntime(29153):    at com.g4apps.json.android.verification.client.MainActivity$SmpProcessor.doInBackground(MainActivity.java:45)
08-10 22:39:22.400: E/AndroidRuntime(29153):    at com.g4apps.json.android.verification.client.MainActivity$SmpProcessor.doInBackground(MainActivity.java:1)
08-10 22:39:22.400: E/AndroidRuntime(29153):    at android.os.AsyncTask$2.call(AsyncTask.java:264)
08-10 22:39:22.400: E/AndroidRuntime(29153):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
08-10 22:39:22.400: E/AndroidRuntime(29153):    ... 5 more
08-10 22:39:22.400: E/AndroidRuntime(29153): Caused by: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 2
08-10 22:39:22.400: E/AndroidRuntime(29153):    at com.google.gson.stream.JsonReader.nextString(JsonReader.java:464)
08-10 22:39:22.400: E/AndroidRuntime(29153):    at com.google.gson.internal.bind.TypeAdapters$13.read(TypeAdapters.java:349)
08-10 22:39:22.400: E/AndroidRuntime(29153):    at com.google.gson.internal.bind.TypeAdapters$13.read(TypeAdapters.java:337)
08-10 22:39:22.400: E/AndroidRuntime(29153):    at com.google.gson.Gson.fromJson(Gson.java:795)
08-10 22:39:22.400: E/AndroidRuntime(29153):    ... 12 more

My class:
package com.g4apps.json.android.verification.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import com.google.gson.*;
import com.google.gson.reflect.TypeToken;

// The Return class defines the structure of the json object returned by the web service
public class JsonVerificationClass {

    public static class VerificationData {
        private String Name;
        private String Phone;

        public VerificationData (String name, String smartphone){
            this.Name=name;
            this.Phone=smartphone;
        }

        public String getName() { return Name; }

        public String getSmartPhone() { return Phone; }
    }

    // jsonCall is the actual call to the webservice
    public static String jsonVerificationCall(URI url, String app, VerificationData data) {

        try {
            //We need to json objects. One for the request and one for the response
            //The request object is simple and doesn't require an object class to define it.
            Gson json = new Gson();
            String jsondata= json.toJson(data);

            // We use the same HttpClient and HttpPost commands in both the PC and Android versions.
            // These libraries are included in the Android SDK but must be added for the PC.
            HttpClient client = new DefaultHttpClient();
            HttpPost post2 = new HttpPost(url);

            // We use list to List to make the Post Entities
            List<NameValuePair> namevaluePairs = new ArrayList<NameValuePair>(1);
            namevaluePairs.add(new BasicNameValuePair("app",app));
            namevaluePairs.add(new BasicNameValuePair("data",jsondata.toString()));
            //System.out.println(namevaluePairs.toString());
            post2.setEntity(new UrlEncodedFormEntity(namevaluePairs));
            HttpResponse response = client.execute(post2);

            //Read in the response and rebuild the json string
            BufferedReader rd= new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuilder myresponse = new StringBuilder();
            String inputline;
            while((inputline = rd.readLine()) !=null) myresponse.append(inputline);

            //Get the type from Return Object so we can remove it from the Json String
            java.lang.reflect.Type StringType = new TypeToken<String>(){}.getType();
            rd.close();
            //System.out.println(myresponse.toString());
            String return2= new Gson().fromJson(myresponse.toString(), StringType);
            return return2;
        }
        catch (UnsupportedEncodingException uee) {
            uee.printStackTrace();
        }
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

}

My Activity:
package com.g4apps.json.android.verification.client;

import java.net.URI;
import java.net.URISyntaxException;

import com.g4apps.json.android.verification.client.JsonVerificationClass;
import com.g4apps.json.android.verification.client.JsonVerificationClass.VerificationData;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {
    private TextView tv;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = (TextView)findViewById(R.id.TextView01);

       //Start new task and run SmpProcessor (Android 2.3+ prohibits Networking activities from running in main thread.
        SmpProcessor task = new SmpProcessor();
        task.execute();

    }
  // added asynctask though other thread methods can be used
  private class SmpProcessor extends AsyncTask <Void,Void,String> {

            // doInBackground sets up variables and calls jsonCall. multiple to jsoncall can be made from the same thread.
            @Override
            protected String doInBackground(Void... voids){ //String[] doInBackground(Void... voids){

                try {

                    URI url = new URI("http://myservice.com/webservices.php");
                    String app="verify";
                    VerificationData data = new VerificationData("Sam","9055551212");

                    // Make jsonCall with will return Return Object
                    String result = JsonVerificationClass.jsonVerificationCall(url,app,data);

                    return result;
                } catch (URISyntaxException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                //return null;
                return null;
            }
            // Handled the retrieval of the data in onPostExecute so I could output it to the android device through the MainActivity.
            protected void onPostExecute(String result) {

                tv.setText("Response: " + result);

                // Handle or call processing for data here as it needs to be done post html call.
            }
        }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}

A: Sorry I guess I called the wrong service and it was returning an error message in a different format from what the client expected.
it was expecting {"String"} and got {"Status":"String","Data":"String[]"}
Thanks to Dirk who's suggestion to look at the json string revealed the answer.


text:
Q: How to fix MySQL Query Alias unknown column? 2018 Server version: 5.6.38 - MySQL Community Server (GPL)
PHP version: 7.2.1
PHPMyAdmin: Version information: 4.7.7
This is my mysql query
SELECT r.id, r.url, MAX(date) as `max_date`, date
FROM report as r
WHERE max_date = date
GROUP BY id, url
ORDER BY bid DESC;

I wanted to retrieve the result of maxdate.
I have already tried Having and Between it just doesn't work. The alias is unknown column
What I am trying to do is,
I want to retrieve the most recent date of a url.
Example:
id, url, date
1, facebook.com, jan 1, 2018
2, google.com, jan 2, 2018
3, facebook.com, jan 5, 2018
4, youtube.com, jan 6, 2018
5, youtube.com, jan 1, 2018
6, stackoverflow.com, jan 7, 2018
7, stackoverflow.com, jan 8, 2018
By running the query it should retrieve,
3, facebook.com, jan 5, 2018
2, google.com, jan 2, 2018
4, youtube.com, jan 6, 2018
7, stackoverflow.com, jan 8, 2018

A: According to MySQL 5.7 Reference Manual,

Standard SQL disallows references to column aliases in a WHERE
  clause

You should not use an alias in WHERE clause since the alias is generated upon running the query and may not be ready when the WHERE condition executes. You get alias is unknown column error because MySQL is not aware of the alias until after it is generated as result of the query. Therefore you can not use alias in WHERE clause here.
(Addition after question edit)
You can get desired result with following query:
SELECT r.id, r.url, MAX(date) as `max_date`
FROM report as r
GROUP BY id, url;

Query Explanation: In SELECT clause you only mention the columns you want to display, the MAX() function will already select the maximum values itself (so you do not need a WHERE clause), and the GROUP BY clause tells the result to group all results based on id and then url.

redpajama_set_name: RedPajamaStackExchange


text:
Q: datatables recuperar valor não mostrado na tabela Tenho uma tabela gerada pelo datatables que mostra nome, documento e telefone. Ela funciona perfeitamente mais eu quero que apareça tooltip para mostrar informações adicionais, eu até consegui mostrar pegando o valor inserido no tr mais o problema e que as informações adicionais não vão aparecer e preciso de ajuda para isso pois meu conhecimento da biblioteca é limitado, segue abaixo o código:
tabela:

                    Nome
                    Documento
                    Telefone

jquery:
    $(document).ready(function() {
/*
 * First step is to create title attributes for the rows in the table
 * This isn't needed if the required 'title' attribute is already set in the HTML in the
 * DOM
 */

/* Init DataTables */
var oTable = $('#tabelaclientes').DataTable({
        "lengthMenu": [ [10, 25, 50, 100, -1], [10, 25, 50, 100, "Todos"] ],
        "processing": true,
        "serverSide": true,
        "oLanguage": {
            "sUrl": "busca/pt-br.txt"
        },

        "ajax": "busca/clientes.php",

        "fnDrawCallback": function( settings ) {
     $('#tabelaclientes tbody tr').each( function() {
    var sTitle;
    var nTds = $('td', this);
    var nome = $(nTds[0]).text();
    var documento = $(nTds[1]).text();
    var telefone = $(nTds[2]).text();
    var ie = $(nTds[4]).text();
    var endereco = $(nTds[5]).text();
    var bairro = $(nTds[6]).text();
    var uf = $(nTds[7]).text();
    var cidade = $(nTds[8]).text();
    var email = $(nTds[9]).text();
        sTitle =  'Nome da Empresa: ' +nome+ '\nCPF/CNPF: ' +documento+ '\nIE: ' +ie+ '\nEndereço: ' +endereco+ '\nBairro: ' +bairro+ '\nUF: ' +uf+ '\nCidade: ' +cidade+ '\nTelefone: ' +telefone+ '\nEmail: ' +email;

    this.setAttribute( 'title', sTitle );
} );
}

    });

/* Apply the tooltips */
oTable.$('tr').tooltip( {
    "delay": 0,
    "track": true,
    "fade": 250
} );

} );
recebo os dados assim:
{"draw":1,"recordsTotal":821,"recordsFiltered":821,"data":[["3 MARC IMPRESSOS GRAFICOS LTDA ME","02651657000144"
,null,"<\/a><\/a>",null,"R JOAO PINHEIRO, 613",null,"RJ",null,null]]}

A: Depois de muito procurar achei uma solução para esta questão e volto aqui para compartilhar para que se alguém mais passar por este problema poder solucionar.
substitui isto:
var endereco = $(nTds[5]).text();

por isso:
var endereco = oTable.row(this).data()[5];

como o valor estava oculto na tabela eu não poderia pegar da mesma forma selecionando o td.


text:
Q: Passing id of tag that submited form with onchange=this.form.submit() Is there a way to know which select tag submitted form?
<form method="POST" action="submit.php">
    <select id="id1" name="sel1" onchange="this.form.submit()">
        <option value="1">First</option>
        <option value="2" selected="selected">Second</option>
    </select>

    <select id="id2" name="sel2" onchange="this.form.submit()">
        <option value="1">First</option>
        <option value="2" selected="selected">Second</option>
    </select>
</form>

Non-jQuery solution is preferable, but not mandatory...
P.S. Problem is that selected="select" attribute is generated dynamically (i don't know which option would be selected as default - so i can't compare default with submitted)

A: The first thing that comes to mind is a hidden field with a value you set. Something like this should do.
<form method="POST" action="submit.php">
    <input type="hidden" name="submitselect" value="" id="submitselect">
    <select id="id1" name="sel1" onchange="document.getElementById('submitselect').value='sel1';this.form.submit()">
        <option value="1">First</option>
        <option value="2" selected="selected">Second</option>
    </select>

    <select id="id2" name="sel2" onchange="document.getElementById('submitselect').value='sel2';this.form.submit()">
        <option value="1">First</option>
        <option value="2" selected="selected">Second</option>
    </select>
</form>

Alternatively, you could have a default option chosen, e.g.
<option value="" selected>-</option>

That would never otherwise be chosen. That way, this option would remain unset in the selects that didn't cause the submit.


text:
Q: TISE and uncertainty in energy We use time independent schrodinger equation to find Stationary state solution for some potentials. My question is that, these Stationary state solutions are physically reliable or not? I am asking this because these solutions provide us state of definite energy i.e, we can measure energy with zero uncertainty. But physically there must be some non-zero uncertainty associated with them.

A: There are many kinds of physical uncertainties, not all of them (directly) related to quantum mechanics. To name just a few:

*

*the fundamental quantum uncertainty

*the uncertainty due to the fact that our model only approximates the essential elements of the system that we study

*the uncertainty due to some  objective limitations, like impossibility to write down and solve the equations for all the particles in the system (the subject of statistical physics), the fact that energy measurements done withing finite time, etc.

*Finally, there are uncertainties due to the limitations of the existing equipment (like the biggest available particle accelerator)

The fundamental difference between quantum mechanics and classical mechanics is in treating the first type of uncertainty. Where in classical mechanics measurements are theoretically possible with infinite precision (assuming that we have overcome other uncertainties), in quantum mechanics this is possible only in some situations. Stationary state is such a situation. This does not prevent other uncertainties from disturbing our measurements:

*

*the interactions mean that the actual energy is not the one that we calculated and that the stationary state decays

*the finite measurement time means that we are limited by the Heisenberg uncertainty principle ($\Delta E\Delta t \geq \hbar/2$).

*the imperfect equipment adds additional error bars


text:
Q: Spring Integration - http inbound im trying to make a http inbound but when i print my message the payload its empty, what am i missing here?
@Slf4j
@Component
public class HttpInboundGateway {

  @Bean
  public IntegrationFlow inGate1() {
      log.info("Initializing inbound gateway...");
      return IntegrationFlows.from(Http.inboundChannelAdapter("/")
            .requestPayloadType(PayloadObj.class))
            .channel("transfer_next_channel")
            .get();
  }

  @Bean
  @ServiceActivator(inputChannel = "transfer_next_channel")
  public MessageHandler handler() {
      return new MessageHandler() {
        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            System.out.println("myHandlerPayload: " + message.getPayload());
            System.out.println("myHandlerHeader: " + message.getHeaders());
        }
    };
  }
}

PayloadObj class expected:
@Data
@NoArgsConstructor
public class PayloadObj {

    String name;
    String job;
}

EDIT 1: As requested
Curl from Postman
curl --location --request GET 'http://localhost:9090/' \
--header 'Content-Type: application/json' \
--data-raw '{
    "name":"Marcos",
    "job":"Dev Jr"
}'

Print from handler:
myHandlerPayload: {} --- Payload
myHandlerHeader: {content-length=46, http_requestMethod=GET,
host=localhost:9090, http_requestUrl=http://localhost:9090/,
connection=keep-alive, id=e67aef3d-938a-7ac3-eb7d-ddaf9cd74f4e,
contentType=application/json;charset=UTF-8, accept-encoding=gzip,
deflate, br, user-agent=PostmanRuntime/7.28.4, accept=*/*,
timestamp=1642168826837}

A:
curl --location --request GET 'http://localhost:9090/'

You do GET request. This way the body of the request is ignored.
And only request params are transferred as payload. Since you don't have those as well, that means the payload is empty Map.
Consider to use POST or PUT instead.
And learn more about an HTTP protocol and its method specifics.


text:
Q: What is the best practice to initialize an empty list in python ([] or list())? I'm new to python and I've seen two different ways to initialize an empty list:
# way 1
empty_list = []

# way 2
other_empty_list = list()

Is there a "preferred" way to do it? Maybe one way is better for certain conditions than the other?
Thank you

A: [] is the pythonic way.
[] way is quite efficient as you can see from below image.

A: No there isn't much of a difference, you can neglect the difference and pick anyone of them
As most of the times it's a one or limited execution any difference in execution won't have much impact

A: Using parenthesis will create a tuple, which is immutable. A list uses brackets.


text:
Q: Running Parallel Servers in Ubuntu in localhost using bash/python script I have 5 python servers in different Directories.
I want to write a bash/python script that can open 5 terminal tabs to run each server parallelly.
As I also want to monitor the output of the server on the terminal I don't want them to run in the background.
#!/bin/bash
cd /home/user/dir_1
source venv/bin/activate
python manage.py runserver 8009
gnome-terminal --tab
cd /home/user/dir_2
source venv/bin/activate
python manage.py runserver 8001

This was my initial thought. But as these are servers, until one command is completed it will not go to another one so it cant achieve the desired result.
As i don't have much experience with this kinda stuff please explain in a noobs langauage.


text:
Q: Inconsistent LLC-loads value with perf stat I'm trying to use perf stat to fetch hardware counter information for a benchmark on Intel's Xeon processor (based on Skylake). When I provide the -e LLC-loads -d -d -d flag, perf stat prints out LLC-loads twice - one due to -e LLC-loads and the other due to detailed flag turned on. However, the results are inconsistent:
$ perf stat -e LLC-loads,LLC-stores,L1-dcache-loads,L1-dcache-stores -d -d -d <my benchmark executable>

Performance counter stats for '<my benchmark executable>':

        5145246847      LLC-loads                                                     (30.78%)
        8167130238      LLC-stores                                                    (30.80%)
      198057619358      L1-dcache-loads                                               (30.80%)
       83142567530      L1-dcache-stores                                              (30.80%)
      197792116698      L1-dcache-loads                                               (30.79%)
       27391515211      L1-dcache-load-misses     #   13.84% of all L1-dcache hits    (30.78%)
        5114059688      LLC-loads                                                     (30.78%)
        3025020254      LLC-load-misses           #   58.97% of all LL-cache hits     (30.76%)
   <not supported>      L1-icache-loads
          58697135      L1-icache-load-misses                                         (30.75%)
      198322967573      dTLB-loads                                                    (30.74%)
         209105723      dTLB-load-misses          #    0.11% of all dTLB cache hits   (30.72%)
           2639992      iTLB-loads                                                    (30.74%)
           1368656      iTLB-load-misses          #   51.84% of all iTLB cache hits   (30.76%)
   <not supported>      L1-dcache-prefetches
   <not supported>      L1-dcache-prefetch-misses

      25.301480157 seconds time elapsed

     585.222699000 seconds user
       1.070800000 seconds sys

As can be seen in the output, there are two LLC-loads in the output with different values. What am I getting wrong?
I've tried multiple different benchmarks assuming that it could be benchmark specific but this behavior is observed everywhere.

A: Note the multiplexing because you specified so many events: they were sampled for (30.78%) of the total time, with the number extrapolated from that.  Skylake only has 4 programmable counters per logical core that can be counting different hardware events at once.
Your program isn't 100% uniform with time, and there's sampling / extrapolation noise, so the numbers are close but differ by a couple %.  (The multiplexing code didn't combine an event specified twice, instead it just put two instances of it into the rotation.)
If you just counted two instances of the event without many other events, you'd expect exactly equal counts since they'd both be active at the same time on different HW counters.  (Unless the first counter would count any events after being programmed, while the kernel was still programming the second.  --all-user would avoid that, telling the HW to count only when the logical core was in user-space.)  e.g.
$ perf stat -e LLC-loads,LLC-loads cmp /dev/zero /dev/full
^Ccmp: Interrupt

 Performance counter stats for 'cmp /dev/zero /dev/full':

            31,425      LLC-loads
            31,425      LLC-loads

       2.748813842 seconds time elapsed

       1.113722000 seconds user
       1.633880000 seconds sys

(Small number of counts, I guess cmp uses buffers small enough to fit in L3 cache.  I used two different files that would read as all-zeros so it couldn't just detect they were identical.)
Related:

*

*Perf tool stat output: multiplex and scaling of "cycles" - instructions:D and cycles:D will tell perf to always count those; there are dedicated non-programmable counters for those events on Intel CPUs, but the multiplexing code doesn't know that.  You could do this with other events, but that would take away slots from events where you didn't specify :D.


text:
Q: Remove Section Index In Table view Xamarin.iOS I simply want to have a grouped table view without drawing the side section index part that gets drawn automatically.
I could only find
tblProducts.SectionIndexMinimumDisplayRowCount = 1000000000;

but this only doesn't draw the section index but it still reserves it's space.

A: See UITableViewSource.SectionIndexTitles Method
The method above returns an array of titles to be displayed as an index on the table view, you just need to return null, the SectionIndex will never appear.
public override String[] SectionIndexTitles (UITableView tableView)
{
    return null;
}


text:
Q: I am getting following error "Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code." Chrome version :79.0.3945.79
Chrome Webdriver :Chrome WebDriver 79
Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code.
Dec 13, 2019 3:06:44 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C


text:
Q: Effect of the pipe diameter in speed of the simulation - Modelica I use Ansys TwinBuilder R2.4 for Modelica simulations. I modeled a hydraulic system in Modelica which can be simulated in certain conditions, e.g. when the diameter of the pipe, which is located before the "Auslass" boundary condition, is 5 mm, when I change it to 8 mm, simulation doesn´t proceed. It slows down the progress of the simulation considerably. What can be reason of the difference in speed of the simulation only if the diameter of the pipe is changed? I added block diagram and the code of the model.

model HD_3Kolben_bsp
    //Declaration(s)
    Real V_max = 0.000003;
    Real V_tod = 0.000002;
    Real N = 2800;
    replaceable package medium = Modelica.Media.Water.StandardWater( );
    Real opening_HP;
    Real opening_LP;
    constant Modelica.SIunits.AbsolutePressure patm = 1e5;
    Real opening_HP_2;
    Real opening_LP_2;
    Real opening_HP_3;
    Real opening_LP_3;
    constant Modelica.SIunits.Frequency freq = 46;
    //Component(s)
    Modelica.Fluid.Machines.SweptVolume Kolben1 (
        pistonCrossArea = 0.0001131,
        clearance = 0.00000250621,
        redeclare package Medium = Modelica.Media.Water.StandardWater,
        nPorts = 1,
        use_portsData = false,
        use_T_start = true,
        T_start = 293.15,
        V(start = 0.005),
        m(start = 0.005));
    inner Modelica.Fluid.System system (p_ambient = 101325);
    Modelica.Mechanics.Translational.Sources.Position Posit1 (exact = true, useSupport = false);
    Modelica.Blocks.Sources.Sine Sine1 (
        amplitude = 0.005567,
        freqHz = freq,
        offset = 0.005567,
        phase = +Modelica.Constants.pi/2.01,
        startTime = 0);
    Modelica.Fluid.Vessels.ClosedVolume ClosedVolume1 (
        V = 0.000005/2,
        nPorts = 3,
        redeclare package Medium = medium,
        use_portsData = false);
    Modelica.Fluid.Pipes.DynamicPipe pipe_Swept_CV_1 (
        length = 0.005,
        diameter = 0.002,
        redeclare package Medium = medium,
        roughness = 2.5E-5);
    Modelica.Fluid.Pipes.DynamicPipe pipe_CV_HD_1 (
        length = 0.005,
        diameter = 0.002,
        redeclare package Medium = medium,
        roughness = 2.5E-5);
    Modelica.Fluid.Sources.FixedBoundary Auslass (p = patm, redeclare package Medium = medium, nPorts = 1);
    Modelica.Fluid.Valves.ValveLinear HDVentile1 (
        dp_nominal = 95,
        m_flow_nominal = 0.05867441,
        redeclare package Medium = medium,
        opening = opening_HP);
    Modelica.Fluid.Pipes.DynamicPipe pipe_ND_CV_1 (
        length = 0.005,
        diameter = 0.002,
        redeclare package Medium = medium,
        roughness = 2.5E-5);
    Modelica.Fluid.Valves.ValveLinear NDVentile1 (
        dp_nominal = 94.35,
        m_flow_nominal = 0.05867441,
        redeclare package Medium = medium,
        opening = opening_LP);
    Modelica.Fluid.Pipes.DynamicPipe pipe_Ein_ND (
        length = 0.005,
        diameter = 0.002,
        redeclare package Medium = medium,
        roughness = 2.5E-5);
    Modelica.Fluid.Sources.FixedBoundary Einlass (p = 4e5, redeclare package Medium = Modelica.Media.Water.StandardWater, nPorts = 1);
    Modelica.Mechanics.Translational.Sensors.PositionSensor Position;
    Modelica.Mechanics.Translational.Sensors.PositionSensor Position2;
    Modelica.Fluid.Valves.ValveLinear NDVentile2 (
        dp_nominal = 94.35,
        m_flow_nominal = 0.05867441,
        redeclare package Medium = medium,
        opening = opening_LP_2);
    Modelica.Fluid.Pipes.DynamicPipe pipe_ND_CV_2 (
        length = 0.005,
        diameter = 0.002,
        redeclare package Medium = medium,
        roughness = 2.5E-5);
    Modelica.Fluid.Valves.ValveLinear HDVentile2 (
        dp_nominal = 95,
        m_flow_nominal = 0.05867441,
        redeclare package Medium = medium,
        opening = opening_HP_2);
    Modelica.Fluid.Pipes.DynamicPipe pipe_CV_HD_2 (
        length = 0.005,
        diameter = 0.002,
        redeclare package Medium = medium,
        roughness = 2.5E-5);
    Modelica.Fluid.Pipes.DynamicPipe pipe_Swept_CV_2 (
        length = 0.005,
        diameter = 0.002,
        redeclare package Medium = medium,
        roughness = 2.5E-5);
    Modelica.Fluid.Vessels.ClosedVolume ClosedVolume2 (
        V = 0.000005/2,
        nPorts = 3,
        redeclare package Medium = medium,
        use_portsData = false);
    Modelica.Blocks.Sources.Sine Sine2 (
        amplitude = 0.005567,
        freqHz = freq,
        offset = 0.005567,
        phase = +Modelica.Constants.pi/2.01,
        startTime = 7/(3*freq));
    Modelica.Mechanics.Translational.Sources.Position Posit2 (exact = true, useSupport = false);
    Modelica.Fluid.Machines.SweptVolume Kolben2 (
        pistonCrossArea = 0.0001131,
        clearance = 0.00000250621,
        redeclare package Medium = Modelica.Media.Water.StandardWater,
        nPorts = 1,
        use_portsData = false,
        use_T_start = true,
        T_start = 293.15,
        V(start = 0.005),
        m(start = 0.005));
    Modelica.Mechanics.Translational.Sensors.PositionSensor Position3;
    Modelica.Fluid.Valves.ValveLinear NDVentile3 (
        dp_nominal = 94.35,
        m_flow_nominal = 0.05867441,
        redeclare package Medium = medium,
        opening = opening_LP_3);
    Modelica.Fluid.Pipes.DynamicPipe pipe_ND_CV_3 (
        length = 0.005,
        diameter = 0.002,
        redeclare package Medium = medium,
        roughness = 2.5E-5);
    Modelica.Fluid.Valves.ValveLinear HDVentile3 (
        dp_nominal = 95,
        m_flow_nominal = 0.05867441,
        redeclare package Medium = medium,
        opening = opening_HP_3);
    Modelica.Fluid.Pipes.DynamicPipe pipe_CV_HD_3 (
        length = 0.005,
        diameter = 0.002,
        redeclare package Medium = medium,
        roughness = 2.5E-5);
    Modelica.Fluid.Pipes.DynamicPipe pipe_Swept_CV_3 (
        length = 0.005,
        diameter = 0.002,
        redeclare package Medium = medium,
        roughness = 2.5E-5);
    Modelica.Fluid.Vessels.ClosedVolume ClosedVolume3 (
        V = 0.000005/2,
        nPorts = 3,
        redeclare package Medium = medium,
        use_portsData = false);
    Modelica.Blocks.Sources.Sine Sine3 (
        amplitude = 0.005567,
        freqHz = freq,
        offset = 0.005567,
        phase = +Modelica.Constants.pi/2.01,
        startTime = 14/(3*freq));
    Modelica.Mechanics.Translational.Sources.Position Posit3 (exact = true, useSupport = false);
    Modelica.Fluid.Machines.SweptVolume Kolben3 (
        pistonCrossArea = 0.0001131,
        clearance = 0.00000250621,
        redeclare package Medium = Modelica.Media.Water.StandardWater,
        nPorts = 1,
        use_portsData = false,
        use_T_start = true,
        T_start = 293.15,
        V(start = 0.005),
        m(start = 0.005));
    Modelica.Fluid.Sources.FixedBoundary boundary1 (p = 4e5, redeclare package Medium = Modelica.Media.Water.StandardWater, nPorts = 1);
    Modelica.Fluid.Pipes.DynamicPipe pipe1 (
        length = 0.005,
        diameter = 0.002,
        redeclare package Medium = medium,
        roughness = 2.5E-5);
    Modelica.Fluid.Sources.FixedBoundary boundary2 (p = 4e5, redeclare package Medium = Modelica.Media.Water.StandardWater, nPorts = 1);
    Modelica.Fluid.Pipes.DynamicPipe pipe2 (
        length = 0.005,
        diameter = 0.002,
        redeclare package Medium = medium,
        roughness = 2.5E-5);
    Modelica.Fluid.Pipes.DynamicPipe pipe3 (
        length = 0.005,
        diameter = 0.0055,
        redeclare package Medium = medium,
        roughness = 2.5E-5,
        modelStructure = Modelica.Fluid.Types.ModelStructure.av_b);
    Modelica.Fluid.Pipes.DynamicPipe pipe4 (
        length = 0.005,
        diameter = 0.0055,
        redeclare package Medium = medium,
        roughness = 2.5E-5,
        modelStructure = Modelica.Fluid.Types.ModelStructure.av_b);
    Modelica.Fluid.Pipes.DynamicPipe pipe5 (
        length = 0.005,
        diameter = 0.0055,
        redeclare package Medium = medium,
        roughness = 2.5E-5,
        modelStructure = Modelica.Fluid.Types.ModelStructure.av_b);
    Modelica.Fluid.Pipes.DynamicPipe pipe6 (
        length = 5,
        diameter = 0.005,
        redeclare package Medium = medium,
        roughness = 2.5E-5,
        modelStructure = Modelica.Fluid.Types.ModelStructure.a_vb);
    Modelica.Fluid.Vessels.ClosedVolume volume2 (
        V = 3.13e-6,
        nPorts = 4,
        redeclare package Medium = medium,
        use_portsData = false);
    Modelica.Fluid.Fittings.SimpleGenericOrifice orifice (diameter = 0.005, zeta = 5, redeclare package Medium = medium);
    Modelica.Fluid.Pipes.DynamicPipe pipe7 (
        length = 0.005,
        diameter = 0.005,
        redeclare package Medium = medium,
        roughness = 2.5E-5);

equation
    if der(Position.s)>=0 then
           opening_LP=1;
           opening_HP=0;
     else
           opening_LP=0;
           opening_HP=1;
     end if;
    if der(Position2.s)>=0 then
           opening_LP_2=1;
           opening_HP_2=0;
     else
           opening_LP_2=0;
           opening_HP_2=1;
     end if;
     if der(Position3.s)>=0 then
           opening_LP_3=1;
           opening_HP_3=0;
     else
           opening_LP_3=0;
           opening_HP_3=1;
     end if;
    //Connection(s)
    connect(Posit1.flange, Kolben1.flange);
    connect(Sine1.y, Posit1.s_ref);
    connect(pipe_Swept_CV_1.port_a, Kolben1.ports[1]);
    connect(pipe_CV_HD_1.port_b, HDVentile1.port_a);
    connect(NDVentile1.port_b, pipe_ND_CV_1.port_a);
    connect(Einlass.ports[1], pipe_Ein_ND.port_a);
    connect(Posit1.flange, Position.flange);
    connect(Position2.flange, Posit2.flange);
    connect(NDVentile2.port_b, pipe_ND_CV_2.port_a);
    connect(HDVentile2.port_a, pipe_CV_HD_2.port_b);
    connect(pipe_Swept_CV_2.port_a, Kolben2.ports[1]);
    connect(Sine2.y, Posit2.s_ref);
    connect(Posit2.flange, Kolben2.flange);
    connect(Position3.flange, Posit3.flange);
    connect(NDVentile3.port_b, pipe_ND_CV_3.port_a);
    connect(HDVentile3.port_a, pipe_CV_HD_3.port_b);
    connect(pipe_Swept_CV_3.port_a, Kolben3.ports[1]);
    connect(Sine3.y, Posit3.s_ref);
    connect(Posit3.flange, Kolben3.flange);
    connect(boundary1.ports[1], pipe1.port_a);
    connect(boundary2.ports[1], pipe2.port_a);
    connect(pipe_Ein_ND.port_b, NDVentile1.port_a);
    connect(pipe1.port_b, NDVentile2.port_a);
    connect(pipe2.port_b, NDVentile3.port_a);
    connect(HDVentile1.port_b, pipe3.port_a);
    connect(HDVentile2.port_b, pipe4.port_a);
    connect(HDVentile3.port_b, pipe5.port_a);
    connect(pipe_Swept_CV_1.port_b, ClosedVolume1.ports[1]);
    connect(pipe_ND_CV_1.port_b, ClosedVolume1.ports[2]);
    connect(pipe_CV_HD_1.port_a, ClosedVolume1.ports[3]);
    connect(pipe_Swept_CV_2.port_b, ClosedVolume2.ports[1]);
    connect(pipe_ND_CV_2.port_b, ClosedVolume2.ports[2]);
    connect(pipe_CV_HD_2.port_a, ClosedVolume2.ports[3]);
    connect(pipe_Swept_CV_3.port_b, ClosedVolume3.ports[1]);
    connect(pipe_ND_CV_3.port_b, ClosedVolume3.ports[2]);
    connect(pipe_CV_HD_3.port_a, ClosedVolume3.ports[3]);
    connect(pipe3.port_b, volume2.ports[1]);
    connect(pipe4.port_b, volume2.ports[2]);
    connect(pipe5.port_b, volume2.ports[3]);
    connect(volume2.ports[4], pipe6.port_a);
    connect(orifice.port_a, pipe6.port_b);
    connect(orifice.port_b, pipe7.port_a);
    connect(pipe7.port_b, Auslass.ports[1]);
end  HD_3Kolben_bsp;

Best regards

A: This can be a number of things. From a screenshot it is only possible to give very general advice. As it is "only" a parameter the system's structure shouldn't change. Therefore it is likely related to dynamics of the system. I would take a look at the solver log first, starting with the number of computed steps or the step-size. If that changed in an order of magnitude of the slow-down you experience this is a good starting point.
Another issue could be chattering, which could be judged with knowledge about the number of events that happened. These should also be visible from the solver log.
Some additional information that would help:

*

*Which Modelica-Tool are you using?

*The model itself (with which all of the below can be generated)

*The solver log (before and after the parameter change)

*The translation log incl. system properties like the sizes of equation systems (before and after the parameter change)

I'm afraid without any additional information you will not get utterly helpful advice...

A: It seems to me that you have used the default flowModel to calculate the pressure drop. This model depends on the pipe diameter (flow regime turbulent/laminar).
For a further detailed answer, I would need the information my colleague asks for in his answer above.


text:
Q: Преобразование списка в строку Python Есть код который берет из Эксель столбик, преобразует каждую строку в массив, миксует в нем слова.
На выходе должны получиться строки, а выводятся массивы
import numpy as np
import pandas as pd
def gencombs(comb, lst, idx):
    if idx >= len(lst):
        print(comb)
    else:
        for i in range(len(comb),-1, -1):
            gencombs(comb[:i] + [lst[idx]] + comb[i:], lst, idx + 1)
        gencombs(comb, lst, idx + 1)
df = pd.read_excel(r'C:\Users\Iclub\Desktop\parserTest.xls', sheet_name='Sheet1')
var1 = df['first (A1)'].tolist()

for i in range(len(var1)):
    array = np.array(var1[i])

for i in var1:
    last = i.split()
    momo = gencombs([], last, 0)
empty_lists = [-1] + [i for i, x in enumerate(momo) if x == []]
parsed_momo = [[' '.join(x) for x in momo[(empty_lists[i - 1] + 1):(empty_lists[i] - 1)]] for i in range(1, len(empty_lists))]
for x in parsed_momo:
    print(x)

Output:
['first', '1']
['1', 'first']
['first']
['1']
[]
['third', '2']
['2', 'third']
['third']
['2']
[]
['white', '3']
['3', 'white']
['white']
['3']
[]

Нужный output:
first 1, 1 first, 1, first
third 2, 2 third, 2, third
white 3, 3 white, 3, white


text:
Q: Trouble finding server root directory i am working on a php project. I have uploaded the files in the server. When i login to the ftp account, it takes me to the main directory of files. I cannot implement the file download script. because i cannot obtain the root folder. when i use echo "$_SERVER["DOCUMENT_ROOT"]", it shows - "(/var/chroot/home/content/30/6323230/html/)". but this does not work for me. if i use file location like - "$_SERVER["DOCUMENT_ROOT"]/songs/", it simply gives error.
Its kinda unknown to me. because previously in another server outputs like - "/home/tskbdcom/public_html". when i log in to this ftp i get the root directory. then i go to "public_html" or "www" directory.
How can I solve this problem?

A: Try using
$_SERVER["DOCUMENT_ROOT"] . "songs/"

no leading slash before directory name because $_SERVER["DOCUMENT_ROOT"] has one slash at the and of path.
This is not answer to your question this is just reason why you got error using
"$_SERVER["DOCUMENT_ROOT"]/songs/"

Also you have double-quotes inside of double-quotes.


text:
Q: XSLT for-each select syntax I've inherited a gross xslt project - I can't figure out how this line of code reads
<xsl:for-each select="*[local-name()='CustomerOrderLine'][count(. | key('orderline-by-ShipAddress', *[local-name()='CustomerOrderPostalAddresses']/*[local-name()='CustomerOrderPostalAddress']/*[local-name()='PostalAddress']/*[local-name()='Line3'])[1]) = 1]">

I understand that this for-each is selecting 'CustomerOrderLine' nodes based off something to do with the 'orderline-by-ShipAddress' key and some kind of union between it and the current node.
I'm looking to understand how this code "reads" so I can better understand how it's working and what I'll need to change in order to re-use the technique.

A: This looks like Grouping Using the Muenchian Method
Basically it is a way to group elements.

A: Read about Muenchian grouping here: http://www.jenitennison.com/xslt/grouping/muenchian.xml. It is used together with an xsl:key to group and identify the first item in each group. So that for-each processes the first CustomerOrderLine in each group where the grouping is based on the value of the Line3 descendant.


text:
Q: How to call image choosen from dialog box by specific function in python I want to implement the image processing system in python and I choose the image from a dialog box by specific function in my tkinter frame. Now I don't know how to call the image in other function to process the image.
Here is the code of the function that opens the image from the dialog box: (Package is my frame with title and color background)
def Open(self):
            global tk_image

            filename = tkinter.filedialog.askopenfilename(initialdir='path of my dataset')

            img2 = Image.open(filename)
            label4 = Label(Package)
            label4.tk_image = ImageTk.PhotoImage(img2)
            label4.configure(image=label4.tk_image)
            label4.pack()

After the above function, I want to define the processing function to process the image and use img2 from the above function:
def Process(self):
...


text:
Q: View number of items in a folder in Icon view In Downloads folder I see that the number of items present in a folder is displayed under the folder name in Icon view.
But I am unable to view such detail in Desktop, Documents, etc folders. How can I get that info to be always displayed in the Icon view?
I checked Folder actions but I do not find any difference (Finder folder icon showing items count when empty)

A: This option is called "Show item Info" and is toggled from the View menu rather from Preferences.

*

*Select the finder window you want to apply this view to, even the desktop. And set it to icon view.

*Go to the View menu and select "Show view options."

*A window opens up (like below) check the Show Item Info checkbox.

Now folder icons will show the number of files in them for that window.


text:
Q: setOrientation problem I have a really strange orientation issue.  I have a sequence of view controllers under a navigation controller.  One of them can take any orientation.  When I'm leaving the orientation I have to use setOrientation.  The funny thing is the rotation takes place as the transition occurs to the next page.  This isn't normally a problem except for a single case -- from UIDeviceOrientationPortraitUpsideDown to normal causes all my top mounted items to migrate up about an eighth of a page.
There are three ways I think I could fix it:

*

*Somehow separate the setOrientation from my
pushViewController call (so the new view doesn't need to flip)

*Set my items to be
anchored at the top of the device in a better manner
(I checked and they appear to be)

*Reset the Y dimension on the elements on the
ViewDidLoad method but that seems wrong.

Here's my push the new view onto the stack code:
[[UIDevice currentDevice] setOrientation:UIInterfaceOrientationPortrait];

ResultSelect_ViewController *resultSelect = [[ResultSelect_ViewController alloc] initWithNibName:@"ResultSelect" bundle:nil];
[self.navigationController pushViewController:resultSelect animated:YES];

Anybody else find it odd that the simulator doesn't allow you to test the upside down to portrait behavior?

A: Just to note: Apple started using a static (maybe even dynamic) analyzer and blocks apps that use private methods (e.g. setOrientation:) from entering the store. Happened to a friend of mine last week.
Have you tried building against iPhone OS 3.0 and relying only on shouldRotateToInterfaceOrientation:? The behaviour seems to be fixed (compared to the implementation in 2.x) and - at least for me - does the job.

A: Typically you wouldn't support the upside down orientation.  That seems to be the standard Apple app behavior and makes sense. The upside down case is not really useful and can cause confusion to the user.
We had a similar problem where subviews would migrate up and down the main view when flipping through the upside down case.  We just stopped supporting upside down and that basically solved the problem.

A: The way to avoid the rotation bug when rotating from upside down to portrait is not to do it.  Instead, rotate twice stopping halfway (say UIDeviceOrientationLandscapeRight).  The question of timing is not to use sleep but instead implement didRotateFromInterfaceOrientation and fire the second rotation (or push to next view) at that point.


text:
Q: Add + before word, see all between quotes as one word I have a question. I need to add a + before every word and see all between quotes as one word.
A have this code
preg_replace("/\w+/", '+\0', $string);

which results in this
+test +demo "+bla +bla2"
But I need
+test +demo +"bla bla2"
Can someone help me :)
And is it possible to not add a + if there is already one? So you don't get ++test
Thanks!

A: I can't test this but could you try it and let me know how it goes?
First the regex: choose from either, a series of letters which may or may not be preceded by a '+', or, a quotation, followed by any number of letters or spaces, which may be preceded by a '+' followed by a quotation.
I would hope this matches all your examples.
We then get all the matches of the regex in your string, store them in the variable "$matches" which is an array. We then loop through this array testing if there is a '+' as the first character. If there is, do nothing, otherwise add one.
We then implode the array into a string, separating the elements by a space.
Note: I believe     $matches in created when given as a parameter to preg_match.
$regex = '/[((\+)?[a-zA-z]+)(\"(\+)?[a-zA-Z ]+\")]/';

preg_match($regex, $string, $matches);

foreach($matches as $match)
{
    if(substr($match, 0, 1) != "+") $match = "+" + $match;
}

$result = implode($matches, " ");

A: Maybe you can use this regex:
$string = '+test demo between "double quotes" and between \'single quotes\' test';
$result = preg_replace('/\b(?<!\+)\w+|["|\'].+?["|\']/', '+$0', $string);
var_dump($result);

// which will result in:
string '+test +demo +between +"double quotes" +and +between +'single quotes' +test' (length=74)

I've used a 'negative lookbehind' to check for the '+'.
Regex lookahead, lookbehind and atomic groups


text:
Q: Notification casting causes compile error I am making a generic function to handle the stopping and starting of different media types in C4. I tried the following method to be called but it seems that the play method conflicts with the play method in the AVPlayer play method when called in this way. Is there a way to solve this problem?
-(void) StartStop: (NSNotification *) notification
{
    if( [[notification object] isKindOfClass:[C4Movie class]] )
    {
        if( [[notification object] isPlaying])
            [[notification object] pause];
        else
            [[notification object] play];
    }
}

A: The solution is to cast the notifying object into the specific class so that the compiler knows which object to call. Objective-C uses dynamic binding. See this question for a detailed explanation: Late Binding vs Dynamic Binding
-(void) StartStop: (NSNotification *) notification
{
    if( [[notification object] isKindOfClass:[C4Movie class]] )
    {
        C4Movie * temp = [notification object];
        if( [temp isPlaying])
            [temp pause];
        else
            [temp play];
    }
}


text:
Q: Angular JS shows HTML within the tag I am trying to insert HTML inside template using ng-bind-html-unsafe attribute. But for some reason its not working.
My code:

I am not able to see the HTML.
If I change ng-bind-html-unsafe="value.button" to ng-bind-html-unsafe="{{value.button}}" then it shows HTML but within the attribute, something like this:

A: make a filter like this
.filter('trusted',
   function($sce) {
     return function(ss) {
       return $sce.trustAsHtml(ss)
     };
   }
)

and apply this as a filter to the ng-bind-html like

A: Ok I found solution for this:
JS:
$scope.renderHtml = function(html_code)
{
    return $sce.trustAsHtml(html_code);
};

HTML:


text:
Q: What is the meaning of option 'by' in TikZ Intersections Pg 65 of the PGF Manual, shows different operations with the intersections library in TikZ. But I am not able to understand the code. What is the meaning of the option by here.

The explanation given is:
The name intersections takes an optional argument
by, which lets you specify names for the coordinates and options for them. This creates more compact code.
This is not clear.

A: Just for completeness. You can name the intersections by C-1 etc. by just using name=C. What is perhaps also worth pointing out is that, if you want so sort the intersections along a straight line, then you have to draw the straight line pretending it is a curve.
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{intersections}

\begin{document}
\begin{tikzpicture}
    \draw[name path=grid] [xstep=3,ystep=2] (9,8) grid (0,0);
    \draw[->, name path=line] (2,1) to[bend left=0] (7,7);
    \draw[name intersections={of=grid and line, sort by=line, name=C, total=\t}]
        \foreach \s in {1,...,\t}{(C-\s) node {\s}};
\end{tikzpicture}
\end{document}

A: The relevant line is
\path [name intersections={of=D and E, by={[label=above:$C$]C, [label=below:$C'$]C'}}];

Compare with this simpler version:
\path [name intersections={of=D and E, by={C, C'}}];

Here the intersection points are computed and named C and C' ("name the intersection points of D and E by the names C and C'").
It is shortcut for
\coordinate (C) at ...;
\coordinate (C') at ...;

for some computed coordinates.
Adding the optional styling [label=above:$C$]C is equivalent to
\coordinate[label=above:$C$] (C) at ...;

and allows you to style the intersection point directly. It would be equivalent, though longer, to write
\path [name intersections={of=D and E, by={C, C'}}];
\node[above] at (C) {$C$};
\node[below] at (C') {$C'$};

A: By default, intersections are named (intersection-1), (intersection-2), etc.
When you write by={a,b} the first two intersections will be called (a) and (b).
Let's look at the example on page 142, slightly modified. It displays the 9 intersections of two curves.
The total number of intersections is given by total.
By writing by={a,b}, the first 2 intersections now have two names:

*

*(a) or (intersection-1)

*(b) or (intersection-2)
(a) is an alias of (intersection-1), the others do not have aliases and remain accessibles.

\documentclass[border=5mm,tikz]{standalone}

\usetikzlibrary{intersections}

\begin{document}
\begin{tikzpicture}
\clip (-2,-2) rectangle (2,2);
\draw [name path=curve 1] (-2,-1) .. controls (8,-1) and (-8,1) .. (2,1);
\draw [name path=curve 2] (-1,-2) .. controls (-1,8) and (1,-8) .. (1,2);
\fill [name intersections={of=curve 1 and curve 2, by={a,b}, total=\t}]
[red, opacity=0.5, every node/.style={above left, black, opacity=1}]
\foreach \s in {1,...,\t}{(intersection-\s) circle (2pt) node {\footnotesize\s}};
\draw[fill=blue!50,opacity=.5] (a) circle (4pt);
\end{tikzpicture}
\end{document}


text:
Q: Skip lein uberjar when sources are unchanged? Is it possible to make lein uberjar not create a jar if no changes have been made since the previous jar was made?
Either as a feature of leiningen or with some bash scripting?
My specific use case is that I'm calling lein from within a CMake build system of a larger project.
execute_process(COMMAND lein uberjar
                WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})

All the C++ sources are skipped if they haven't changed, but uberjars keep being made.

A: The find command will allow you to find all files that are newer than another file.
A script built on that might look something like this:
#!/bin/sh

UBERJAR=*-standalone.jar

if [ -f ${UBERJAR} ]; then
     modified_files=$(find src project.clj -newer ${UBERJAR})

     if [ ${#modified_files} -eq 0 ]; then
         echo "Skipping uberjar because no files modified"
         exit 0
     fi
fi

lein uberjar

If your project has snapshot dependencies you will skip the check that determines whether you should update your snapshots from the central repo.
I suspect you'd be better off just taking the hit of building the uberjar everytime.


text:
Q: Random websites not display on iframe This code is generating a random link from variable but that link is not opening in iframe I need to display random links in iframe whenever the button is clicked. How to do that?

<button id="btn">Click</button>

A: You have to put the script tag after all your HTML or wait for the window to load.
Also, you're calling a function before it's defined.
This code is generating a random link from variable
I don't think this is happening, if you open your console it should tell you the function and iframe are both undefined, as I stated above.


text:
Q: How do I specify the version of react-native-onesignal in my podfile? I'm following this guide on how to set up OneSignal with React Native. In the section where it says In your Podfile, add the notification service extension..., it says to add the following to my Podfile:
target 'OneSignalNotificationServiceExtension' do
  pod 'OneSignal', '>= 2.9.3', '< 3.0'
end

I think this is outdated though, because my version of react-native-onesignal is 3.7.2. How should I change this line in my Podfile to accommodate this newer version?

A: You haven't specified which version range you think is appropriate instead, but if this Pod follows the common convention where breaking changes only happen when the major version changes, then you would use the constraints
target 'OneSignalNotificationServiceExtension' do
  pod 'OneSignal', '>= 3.7.2', '< 4.0'
end


text:
Q: MYSQL Remote access php I have a project on a hosted server. They are very unreliable so I have decided to move to another host. In the interim I want to leave the php files on the existing server and point them at another MySQL database on my rackspace server. I have configured the mysql on the rackspace server to accept remote connections. I can successfully connect to it via the terminal from my ubuntu at home. However every time the php files on the hosting server try to connect to it I get the error below :
This is the code in the php....
mysql_pconnect("1.2.3.4","user","password")
or die("Unable to connect to SQL server".mysql_error());

This is the error/output

Unable to connect to SQL serverLost connection to MySQL server during
  query

Any ideas why I can connect via the terminal but not from php ?
Thanks

A: Check your wait_timeout. Set it to a high number while you are doing your move .

A: If the connection is refused immediately then either your old or your new hosting providers are blocking the connection, or you have a problem with the host mask on the user account you're using to connect. You could try fsockopen() to try directly connecting to see if the connection is refused if you don't have access to command line mysql clients at the old host to try and identify which of these is the case. If it's blocked after a timeout, it's almost certainly a firewall policy at one or both ends.
However, can I just say that:
a) mysql_ functions are deprecated, so you should probably also look at upgrading to mysqli or pdo or something.
and
b) unless you tell whatever api you're using to connect with SSL or some other secure method (in the mysql_ case it's the MYSQL_CLIENT_SSL flag) your data (and possibly your password or some variation on it that could let attackers connect as you) will go over the open internet unecrypted... of course, this requires an SSL certificate or is vulnerable to man in the middle attacks, so... yeah.


text:
Q: Magento, add VAT nr to billing address It is possible in Magento to add a VAT number to your account but in Belgium it's more common to add a VAT number to your billing address. Is this possible in some kind of way ?

A: Yes, almost anything is possible as Magento is built with php and is completely open-source.  But what you are requesting is not very easy, unfortunately.  You will have to write a custom module to do this, and it's not an easy one to write.
Here are a couple possible options (I haven't tried them) that may get you started:

*

*http://www.aitoc.com/en/magentomods_checkoutfieldsmanager.html

*http://kernelhack.com/?p=37
Good luck!


text:
Q: Restore original text from Keras's imdb dataset Restore original text from Keras's imdb dataset
I want to restore imdb's original text from Keras's imdb dataset.
First, when I load Keras's imdb dataset, it returned sequence of word index.

>>> (X_train, y_train), (X_test, y_test) = imdb.load_data()
>>> X_train[0]
[1, 14, 22, 16, 43, 530, 973, 1622, 1385, 65, 458, 4468, 66, 3941, 4, 173, 36, 256, 5, 25, 100, 43, 838, 112, 50, 670, 22665, 9, 35, 480, 284, 5, 150, 4, 172, 112, 167, 21631, 336, 385, 39, 4, 172, 4536, 1111, 17, 546, 38, 13, 447, 4, 192, 50, 16, 6, 147, 2025, 19, 14, 22, 4, 1920, 4613, 469, 4, 22, 71, 87, 12, 16, 43, 530, 38, 76, 15, 13, 1247, 4, 22, 17, 515, 17, 12, 16, 626, 18, 19193, 5, 62, 386, 12, 8, 316, 8, 106, 5, 4, 2223, 5244, 16, 480, 66, 3785, 33, 4, 130, 12, 16, 38, 619, 5, 25, 124, 51, 36, 135, 48, 25, 1415, 33, 6, 22, 12, 215, 28, 77, 52, 5, 14, 407, 16, 82, 10311, 8, 4, 107, 117, 5952, 15, 256, 4, 31050, 7, 3766, 5, 723, 36, 71, 43, 530, 476, 26, 400, 317, 46, 7, 4, 12118, 1029, 13, 104, 88, 4, 381, 15, 297, 98, 32, 2071, 56, 26, 141, 6, 194, 7486, 18, 4, 226, 22, 21, 134, 476, 26, 480, 5, 144, 30, 5535, 18, 51, 36, 28, 224, 92, 25, 104, 4, 226, 65, 16, 38, 1334, 88, 12, 16, 283, 5, 16, 4472, 113, 103, 32, 15, 16, 5345, 19, 178, 32]

I found imdb.get_word_index method(), it returns word index dictionary like {'create': 984, 'make': 94,…}. For converting, I create index word dictionary.

>>> word_index = imdb.get_word_index()
>>> index_word = {v:k for k,v in word_index.items()}

Then, I tried to restore original text like following.

>>> ' '.join(index_word.get(w) for w in X_train[5])
"the effort still been that usually makes for of finished sucking ended cbc's an because before if just though something know novel female i i slowly lot of above freshened with connect in of script their that out end his deceptively i i"

I'm not good at English, but I know this sentence is something strange.
Why is this happened? How can I restore original text?

A: You can get the original dataset without stop words removed using get_file from  keras.utils.data_utils:
path = get_file('imdb_full.pkl',
               origin='https://s3.amazonaws.com/text-datasets/imdb_full.pkl',
                md5_hash='d091312047c43cf9e4e38fef92437263')
f = open(path, 'rb')
(training_data, training_labels), (test_data, test_labels) = pickle.load(f)

Credit - Jeremy Howards fast.ai course lesson 5

A: Your example is coming out as gibberish, it's much worse than just some missing stop words.
If you re-read the docs for the start_char, oov_char, and index_from parameters of the [keras.datasets.imdb.load_data](https://keras.io/datasets/#imdb-movie-reviews-sentiment-classification
) method they explain what is happening:
start_char: int. The start of a sequence will be marked with this character. Set to 1 because 0 is usually the padding character.
oov_char: int. words that were cut out because of the num_words or skip_top limit will be replaced with this character.
index_from: int. Index actual words with this index and higher.
That dictionary you inverted assumes the word indices start from 1.
But the indices returned my keras have <START> and <UNKNOWN> as indexes 1 and 2. (And it assumes you will use 0 for <PADDING>).
This works for me:
import keras
NUM_WORDS=1000 # only use top 1000 words
INDEX_FROM=3   # word index offset

train,test = keras.datasets.imdb.load_data(num_words=NUM_WORDS, index_from=INDEX_FROM)
train_x,train_y = train
test_x,test_y = test

word_to_id = keras.datasets.imdb.get_word_index()
word_to_id = {k:(v+INDEX_FROM) for k,v in word_to_id.items()}
word_to_id["<PAD>"] = 0
word_to_id["<START>"] = 1
word_to_id["<UNK>"] = 2
word_to_id["<UNUSED>"] = 3

id_to_word = {value:key for key,value in word_to_id.items()}
print(' '.join(id_to_word[id] for id in train_x[0] ))

The punctuation is missing, but that's all:
"<START> this film was just brilliant casting <UNK> <UNK> story
 direction <UNK> really <UNK> the part they played and you could just
 imagine being there robert <UNK> is an amazing actor ..."

A: This happened because of a basic NLP data preparation. Loads of the so called stop words were removed from text in order to make learning feasible. Usually - also the most of puntuation and less frequent words are removed from text during preprocessing. I think that the only way to restore original text is to find the most matching texts at IMDB using e.g. a Google's browser API.

A: This encoding will work along with the labels:
from keras.datasets import imdb
(x_train,y_train),(x_test,y_test) = imdb.load_data()
word_index = imdb.get_word_index() # get {word : index}
index_word = {v : k for k,v in word_index.items()} # get {index : word}

index = 1
print(" ".join([index_word[idx] for idx in x_train[index]]))
print("positve" if y_train[index]==1 else "negetive")

Upvote if helps. :)

A: The indices are offset by 3 because 0, 1 and 2 are reserved indices for "padding", "start of sequence" and "unknown". The following should work.
imdb = tf.keras.datasets.imdb
(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000)

word_index = imdb.get_word_index()
reverse_word_index = dict([(value, key) for (key, value) in word_index.items()])

review = [reverse_word_index.get(i-3, "?") for i in train_data[0]]

A: This works for me:
word_index = imdb.get_word_index()
reverse_word_index = dict([(value, key) for (key, value) in word_index.items()])
decoded_review = ' '.join([reverse_word_index.get(i - 3, "") for i in train_data[0]])

A: To get an equivalent array of all the reviews:
def decode_imdb_reviews(text_data):
    result = [0 for x in range(len(text_data))]
    word_index = imdb.get_word_index()
    reverse_word_index = dict([(value, key) for (key, value) in word_index.items()])
    for review in range(0,len(text_data)):
        for index in enumerate(text_data[review]):
            decoded_review = ' '.join([reverse_word_index.get(index - 3, '#') for index in text_data[review]])
        result[review] = decoded_review
    return result

text_data = []
text_data = decode_imdb_reviews(train_data)

A: Try below code. this code worked.
# load dataset
from tensorflow.keras.datasets import imdb
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=500)

# vec 2 num
imdb_vec2num = imdb.get_word_index(path="imdb_word_index.json")
# num 2 vec
imdb_num2vec = {value+3:key for key, value in imdb_vec2num.items()}
imdb_num2vec[0] = "<PAD>"
imdb_num2vec[1] = "<START>"
imdb_num2vec[2] = "<UNK>"
imdb_num2vec[3] = "<UNUSED>"

# index-word table
imdb_num2vec = {value:key for key, value in imdb_index.items()}

# change encoded sentences to sentences
def restore_sentences(num2word, encoded_sentences):
    sentences = []
    for encoded_sentence in encoded_sentences:
        sentences.append([num2word[ele] for ele in encoded_sentence])
    return sentences

# example
sentences = restore_sentences(imdb_num2vec, x_train)

A: from keras.datasets import imdb
NUM_WORDS=1000 # only use top 1000 words

(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=NUM_WORDS)

Get the index details:
word_to_id = keras.datasets.imdb.get_word_index()

Build the Key-Value pair:
id_to_word = {value:key for key,value in word_to_id.items()}
print(' '.join(id_to_word[id] for id in x_train[0] ))


text:
Q: jQuery Ajax -> How to avoid including every class for one query I have several classes in PHP. All separated in files. (class1.php, class2.php)
On my site, I have included them all together, so I can use all of them.
Now, when I use jQuery Ajax to get data from the database I have to call another file (like getData.php)
But on this file, I have to include all of the classes (or at least some) again. So every time I want to receive data from the database, it loads all classes again(I think). The problem is, that they're not that small and they are still growing. That's bad, I think.
Is there a way to avoid this? So that I include the classes only once.

A: step one: only include the files you need. How? using an autoloader (and a system that can easily determine what file contains which class, like Classname.class.php or something) will help: If you call new yourClass() the autoloader will load the file, but only that file.
Now you have a minimal set of files loaded. This set will not get smaller, as you are actually using the files. What you can do is speed stuff up by

*

*using APC. Your PHP files get 'cached' and they don't need to be re-parsed again and again.

*use other forms of cache, like memcached: save certain data in memory so you don't need anything other then your memcache-class loaded (heck, you won't even hit your database anymore for these requests :)  )


text:
Q: Rest API get Content-Length of Body I got a Problem. Im working on a Datatransfer to a Restful API at the Moment. All the arrays and everything and json objects should be fine, but i just do not understand how to determine the Content-Length of my Body?
$http = new Client([
        'headers' => ['Authorization' => 'Bearer ' . $token["access_token"], 'Transfer-Encoding' => 'chunked', 'Content-Encoding' => 'chunked']
    ]);

This is my code at the moment. But the Answer thats coming back is always
HTTP Error 400. There is an invalid content length or chunk length in the request.

Can you help me to determine the right Content-Length?
Cheers!

A: There are at least 2 ways to do it.
If you have content in variable then add to your headers array 'Content-Length' => strlen($var)
You can also use output buffering and get length with function ob_get_length()
'Content-Length' => ob_get_length()
Here you will find example


text:
Q: JS -> Accessing a variable from another function I'm new to this site and to programming in general and I'm a bit stuck on a school assignment.
For reference here is my code I'm currently working on: Pastebin
function initChests(){
  let gameChests = document.getElementById('chests');

  for(let i = 0; i < 3; i++) {
    let singleChest = document.createElement('img');
    singleChest.src = 'images/chest-closed.png';
    singleChest.alt = 'A chest'
    singleChest.style.marginRight = '20px';

    gameChests.appendChild(singleChest);
  }
}

function initChestEventListeners() {
  singleChest.addEventListener('click', chestClicked);
}

function chestClicked(e){
  console.log("hello");
}

Now to my problem. What I want to do is access the variable singleChest in my initChestEventListeners function without making the variable global.
I am aware I can just put the singleChest addEventListener inside the initChests function, but that's not quite what I want to do either. I want to make it work with the function structure I have if possible.
Is this something that is possible and if so, can someone please explain what I would need to do or redirect me to a guide that could help explain the solution?
Thank you in advance!
Kind regards.

A: One option is to add an event listener to the parent element instead, the gameChests, and on click, if the clicked element is an img, do something with it:

function initChests() {
  const gameChests = document.getElementById('chests');
  for (let i = 0; i < 3; i++) {
    let singleChest = document.createElement('img');
    singleChest.src = 'images/chest-closed.png';
    singleChest.alt = 'A chest'
    singleChest.style.marginRight = '20px';

    gameChests.appendChild(singleChest);
  }
}

function initChestEventListeners() {
  const gameChests = document.getElementById('chests');
  gameChests.addEventListener('click', chestContainerClicked);
}

function chestContainerClicked(e) {
  if (!e.target.matches('img')) {
    return;
  }
  console.log("hello", e.target);
}

initChests();
initChestEventListeners();

This method of watching for events that bubble up to the parent element is called event delegation.


text:
Q: gorm fails to populate nested structures with data after joining mysql tables Here I am trying to join the three tables Branches_organization, oragnization, and locations  and sent them as API response. However, organizationand location json fails to fetch any data.
Issue:
The below API response fails to retrieve organization and location details; always return zero values
{
    "Title": "OK",
    "status": 200,
    "records": 1,
    "data": [
        {
            "branch_id": 51,
            "name": "my branch name",
            "address": "Mun",
            "telephone": "+9xxxxx",
            "organization": {
                "org_id": 0,
                "name": ""
            },
            "location": {
                "loc_id": 0,
                "name": ""
            }
        }
    ]
}

Error on the console
2022/08/17 06:11:32 /apiserver/controllers/handlers.go:3475 invalid field found for struct apiserver/entities.Custom_branches_organization's field Organization: define a valid foreign key for relations or implement the Valuer/Scanner interface
[7.930ms] [rows:1] SELECT branches_organization.branch_id,branches_organization.name,branches_organization.address,branches_organization.telephone,organization.org_id,organization.name,location.loc_id,location.name FROM `branches_organization` left join  organization on organization.org_id = branches_organization.org_id left join  location on location.loc_id =  branches_organization.loc_id

Implementation details
structures used
Struct used for API response
type Custom_branches_organization struct {
    Branch_id    uint         `json:"branch_id"`
    Name         string       `json:"name" validate:"required"`
    Address      string       `json:"address" validate:"required"`
    Telephone    string       `json:"telephone" validate:"e164,required"`
    Organization Organization `json:"organization" gorm:"foreignkey:org_id;references:Org_id"`
    Location     Location     `json:"location" gorm:"foreignkey:loc_id;references:Loc_id"`
}

child structures
//Organization table in database
type Organization struct {
    Org_id    uint   `json:"org_id"`
    Name      string `json:"name" validate:"required"`
    Address   string `json:"address"`
    Telephone string `json:"telephone" validate:"e164,required"`
    Email     string `json:"email" validate:"required,email"`
}

//Location table in database
type Location struct {
    Loc_id    uint   `json:"loc_id"`
    Name      string `json:"name" validate:"required"`
    Address   string `json:"address" validate:"required"`
    Telephone string `json:"telephone" validate:"e164,required"`
}

//Actual Branches table in database
type Branches_organization struct {
    Branch_id uint   `json:"branch_id"`
    Name      string `json:"name" validate:"required"`
    Address   string `json:"address" validate:"required"`
    Telephone string `json:"telephone" validate:"e164,required"`
    Org_id    uint   `json:"org_id" validate:"number"`
    Loc_id    uint   `json:"loc_id" validate:"number"`
}

Gorm implementation
//Retrieve all records from the branches_organization table
var branches_organizations []entities.Custom_branches_organization

result := database.Instance.Model(&entities.Branches_organization{}).Preload("Organization").Preload("Location").Select("branches_organization.branch_id,branches_organization.name,branches_organization.address,branches_organization.telephone,organization.org_id,organization.name,location.loc_id,location.name").Joins("left join  organization on organization.org_id = branches_organization.org_id").Joins("left join  location on location.loc_id =  branches_organization.loc_id").Scan(&branches_organizations)

branches_organizationsdata := entities.Customebranches_organizationData{"OK", http.StatusOK, result.RowsAffected, branches_organizations}

json.NewEncoder(w).Encode(branches_organizationsdata)

Database tables
mysql> desc  organization;
+-----------+----------+------+-----+---------+----------------+
| Field     | Type     | Null | Key | Default | Extra          |
+-----------+----------+------+-----+---------+----------------+
| org_id    | int      | NO   | PRI | NULL    | auto_increment |
| name      | longtext | YES  |     | NULL    |                |
| address   | longtext | YES  |     | NULL    |                |
| telephone | longtext | YES  |     | NULL    |                |
| email     | longtext | YES  |     | NULL    |                |
+-----------+----------+------+-----+---------+----------------+
5 rows in set (0.12 sec)

mysql> desc  location;
+-----------+----------+------+-----+---------+----------------+
| Field     | Type     | Null | Key | Default | Extra          |
+-----------+----------+------+-----+---------+----------------+
| loc_id    | int      | NO   | PRI | NULL    | auto_increment |
| name      | longtext | YES  |     | NULL    |                |
| address   | longtext | YES  |     | NULL    |                |
| telephone | longtext | YES  |     | NULL    |                |
+-----------+----------+------+-----+---------+----------------+
4 rows in set (0.00 sec)

mysql> desc branches_organization;
+-----------+----------+------+-----+---------+----------------+
| Field     | Type     | Null | Key | Default | Extra          |
+-----------+----------+------+-----+---------+----------------+
| branch_id | int      | NO   | PRI | NULL    | auto_increment |
| name      | longtext | YES  |     | NULL    |                |
| address   | longtext | YES  |     | NULL    |                |
| telephone | longtext | YES  |     | NULL    |                |
| org_id    | int      | YES  | MUL | NULL    |                |
| loc_id    | int      | YES  | MUL | NULL    |                |
+-----------+----------+------+-----+---------+----------------+
6 rows in set (0.00 sec)

I am breaking my head for many days to create an json reply which will have organization and location details as nested structures. Hope you can support me.


text:
Q: Lotus notes enable api/data I am currently trying to develop an app for a company which uses a lotus notes 9.0.1 server. I am trying to work with their contractor who setup the server and I have no experience with lotus notes. I am going to use rest api to interact with the server but when I call GET on /api I see this the data is not enabled it seems to me that the Domino Data Service is not enabled for it can someone explain the steps to me for turning it on for the data view. So I can tell the contractor how.
Thanks
https://imgur.com/gallery/Gy5hf

A: What about using a search engine?
Each accessible database must be enabled to support the Domino® Data Service.
Tags: Enabling Domino Data Service on a database
To be able access a database with the Domino Data Service, each accessible database must be enabled to support the service.
Note: Remember to also make sure that the Data Service or any other service that you wish to access is first enabled on your server. The Core service is always enabled. Unlike the other services, the administrator does not have to intentionally enable the Core service. As long as the HTTP task is loaded, the Core service is available.
In Domino Designer or Notes®, do the following for each accessible database:
Open the database properties.
Click on the Advanced tab.
For Allow Domino Data Service, select either:
Views only to restrict access to views
Views and documents for full access
In Domino Designer, do the following for each accessible view:
Open the view properties.
Click on the Advanced tab.
Check Allow Domino Data Service operations.
Attempting to access a database that is not enabled typically returns error code 403 The Domino data service is not enabled for this database.
Attempting to access a view that is not enabled typically returns error code 403 The Domino data service is not enabled for this view.
https://www-10.lotus.com/ldd/ddwiki.nsf/xpAPIViewer.xsp?lookupName=IBM+Domino+Access+Services+9.0.1#action=openDocument&res_title=Enabling_Domino_Data_Service_on_a_database_das901&content=apicontent


text:
Q: Resource Access Exception When trying to resolve the test described in Where exactly is the NullPointer Exception?, I used a seemingly simpler approach, being the resource test the next:
public class CustomerResourceFunctionalTesting {

private static final String SERVER_URL = "http://localhost:8080/api/v0/";

@Rule
 public ExpectedException thrown = ExpectedException.none();

private int createCustomer(String name) {
    CustomerDto customerDto = new CustomerDto(name, name + " address");
    return new RestBuilder2<Integer>(SERVER_URL).path(CustomerResource.CUSTOMERS)
    .body(customerDto).clazz(Integer.class).post().build();
}

private int createCustomer() {
    return this.createCustomer("customer1");
}

@Test
public void testReadCustomers() {
     List<CustomerDto> customerDtoList = Arrays.asList(new RestBuilder2<CustomerDto[]>
     (SERVER_URL).path(CustomerResource.CUSTOMERS).clazz(CustomerDto[].class).get().build());
     assertEquals(0, customerDtoList.size());
     int id = this.createCustomer();
     customerDtoList = Arrays.asList(new RestBuilder2<CustomerDto[]>
     (SERVER_URL).path(CustomerResource.CUSTOMERS).clazz(CustomerDto[].class)
     .get().build());
     assertEquals(1, customerDtoList.size());
     this.deleteCustomer(id);
}

private void deleteCustomer(int id) {
     new RestBuilder<Object>
     (SERVER_URL).path(CustomerResource.CUSTOMERS).path(CustomerResource.CUSTOMER_ID)
     .expand(id).delete().build();
}
}

And the RestBuilder a bit different:
public class RestBuilder2<T> {

private RestTemplate restTemplate = new RestTemplate();

private String uri;

private List<Object> expandList;

private Map<String, String> headerValues;

private String authorization = null;

private Object body = null;

private MultiValueMap<String, String> params;

private Class<T> clazz;

private HttpMethod method;

public RestBuilder2(String serverUri) {
    restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
    this.uri = serverUri;
    this.expandList = new ArrayList<>();
    headerValues = new HashMap<>();
    params = new HttpHeaders();
}

public RestBuilder2<T> path(String path) {
    this.uri = this.uri + path;
    return this;
}

public RestBuilder2<T> expand(Object... values) {
   for (Object value : values) {
        this.expandList.add(value);
    }
    return this;
}

public RestBuilder2<T> pathId(int path) {
    this.uri = this.uri + "/" + path;
    return this;
}

public RestBuilder2<T> pathId(String path) {
    this.uri = this.uri + "/" + path;
    return this;
}

public RestBuilder2<T> authorization(String authorizationValue) {
    this.authorization = authorizationValue;
    return this;
}

public RestBuilder2<T> basicAuth(String nick, String pass) {
    String auth = nick + ":" + pass;
    String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8));
    String authHeader = "Basic " + encodedAuth;
    this.authorization = authHeader;
    return this;
}

public RestBuilder2<T> param(String key, String value) {
    this.params.add(key, value);
    return this;
}

public RestBuilder2<T> header(String key, String value) {
    this.headerValues.put(key, value);
    return this;
}

public RestBuilder2<T> body(Object body) {
    this.body = body;
    return this;
}

public RestBuilder2<T> notError() {
    restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
        protected boolean hasError(HttpStatus statusCode) {
            return false;
        }
    });
    return this;
}

public RestBuilder2<T> clazz(Class<T> clazz) {
    this.clazz = clazz;
    return this;
}

private HttpHeaders headers() {
    HttpHeaders headers = new HttpHeaders();
    for (String key : headerValues.keySet()) {
        headers.set(key, headerValues.get(key));
    }
    if (authorization != null) {
        headers.set("Authorization", authorization);
    }
    return headers;
}

private URI uri() {
    UriComponents uriComponents;
    if (params.isEmpty()) {
        uriComponents = UriComponentsBuilder.fromHttpUrl(uri).build();
    } else {
        uriComponents = UriComponentsBuilder.fromHttpUrl(uri).queryParams(params).build();
    }
    if (!expandList.isEmpty()) {
        uriComponents = uriComponents.expand(expandList.toArray());
    }
    return uriComponents.encode().toUri();

}

public T build() {
    if (body != null && !method.equals(HttpMethod.GET)) {
        return restTemplate.exchange(this.uri(), method, new HttpEntity<Object>(body, this.headers()), clazz).getBody();
    } else {
        return restTemplate.exchange(this.uri(), method, new HttpEntity<Object>(this.headers()), clazz).getBody();
    }
}

public RestBuilder2<T> post() {
    this.method = HttpMethod.POST;
    return this;
}

public RestBuilder2<T> get() {
    this.method = HttpMethod.GET;
    return this;
}

public RestBuilder2<T> put() {
    this.method = HttpMethod.PUT;
    return this;
}

public RestBuilder2<T> patch() {
    this.method = HttpMethod.PATCH;
    return this;
}

public RestBuilder2<T> delete() {
    this.method = HttpMethod.DELETE;
    return this;
}

}

But then I take an error whose trace is:
org.springframework.web.client.ResourceAccessException: I/O error on GET request for "http://localhost:8080/api/v0/customers": Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect; nested exception is org.apache.http.conn.HttpHostConnectException: Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:674)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:636)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:557)
at account.persistence.resources.RestBuilder2.build(RestBuilder2.java:143)
at account.persistence.resources.CustomerResource2FunctionalTesting.testReadCustomers(CustomerResource2FunctionalTesting.java:34)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:239)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
Caused by: org.apache.http.conn.HttpHostConnectException: Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect
at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:159)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:373)
at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:381)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:237)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:185)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:111)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56)
at org.springframework.http.client.HttpComponentsClientHttpRequest.executeInternal(HttpComponentsClientHttpRequest.java:89)
at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:53)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:660)
... 29 more
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)

The rest of implied parts of the application is the same as the indicated in the link post, except for not using any RestService.
I think that, in this case, I could not get the NullPointerException, but before I need to resolve the ResourceAccess Exception.


text:
Q: Chebyshev's inequality on compact sets Could anyone just tell me in which context Prof.
Martin Hairer here in page $31$ and Theorem $4.21$ has used Chebyshev's inequality to prove a sequence of probability measure is tight?
Roughly: there is a family of compact sets for a Lyapunov function $V$ for a transition probability measure $P$,  $K_c=\{x: V(x) \le c\}$ and he says by
Chebyshev's inequality $\dots$
Could anyone give some reference where I can read a bit that inequality can be applied on some compact sets? Thanks. If one could simplify that line for me, it would be really great.

A: This follows from the following inequalities:
\begin{align}
\widetilde{C}&\geqslant V_n=\int V(y)P^n(x,dy)\\
&\geqslant \int \mathbf 1_{\mathcal X\setminus K_c}(y) V(y)P^n(x,dy)\\
&\geqslant c \int \mathbf 1_{\mathcal X\setminus K_c}(y) P^n(x,dy) \quad\mbox{ because } \mathbf 1_{\mathcal X\setminus K_c}(y)V(y)P^n(x,dy)\geqslant c \mathbf 1_{\mathcal X\setminus K_c}(y)\\
& =c\left(1-P^n(x,K_c)\right)\quad\mbox{ because }P^n(x,\mathcal X)=1.
\end{align}


text:
Q: Xcode malloc error I'm getting this error in the Xcode console, sometimes it causes the simulator to exit and sometimes it is ignored. It will usually be ignore if I wait a few seconds once the game is loaded:
malloc: *** error for object 0x55ac484: incorrect checksum for freed object - object was probably modified after being freed.
*** set a breakpoint in malloc_error_break to debug

1) How can I identify this object?
2) How can I access malloc to put a BP in, and what will this achieve?
Thank you!

A: The Instruments-Tool provides a way to find Zombies.
To find the Zombie which causes your app to crash, select Product > Profile in XCode 4. A new window will open where you have to choose "Zombies". Now click "Profile" in the bottom-right corner of the window. If you now send a message to a freed object, it will show you what type of object it is and which method sent the message.
To set a breakpoint you just have to click on the line number you want your app to pause. After your app paused you can run your application step by step, so you will be able to see, which part of your code causes the crash.


text:
Q: Why Internet marketer using same format on their website? I wonder why most of marketing site will use same format? Example

*

*Learn PHP by Yourself In 11 Hours

*Spice up Your Site With Simple PHP

*and much more..

This is a standard design for web designing on site like this?

May admin move my question to another network which related to my question?

A: This "style" comes from treating a webpage as if it were a printed page, such as a piece of junk mail, which is what these sites strongly resemble. It is used by marketroids who care nothing for the medium as long as they get the "buy" message across to as many stupid people as possible. No coder with a conscience, or even a sense of style, would do this.