问:
Convert string[] to Int[] without losing leading zeros
Input:

```<code>string param = "1100,1110,0110,0001";
</code>```

Output:

```<code>int[] matrix = new[]
    {
              1,1,0,0,
              1,1,1,0,
              0,1,1,0,
              0,0,0,1
    };
</code>```

What I did?

First of all I splited string to string[].

```<code>string[] resultantArray = param.Split(',');
</code>```

Created one method, where I passed my string[].

```<code>var intArray = toIntArray(resultantArray);

static private int[] toIntArray(string[] strArray)
{
    int[] intArray = new int[strArray.Length];
    for (int i = 0; i < strArray.Length; i++)
    {
        intArray[i] = int.Parse(strArray[i]);
    }

    return intArray;
}
</code>```

Issue?

I tried many solutions of SO, but none of them helped me.

Ended up with array without leading zeroes.

答:
yet another way to do this</p>

```<code>static private IEnumerable<int> toIntArray(string[] strArray)
{
    foreach (string str in strArray)
    {
        foreach (char c in str)
        {
            yield return (int)char.GetNumericValue(c);
        }
    }
}
</code>```

Body:
Input:

string param = "1100,1110,0110,0001";

Output:

int[] matrix = new[]
    {
              1,1,0,0,
              1,1,1,0,
              0,1,1,0,
              0,0,0,1
    };

What I did?

First of all I splited string to string[].

string[] resultantArray = param.Split(',');

Created one method, where I passed my string[].

var intArray = toIntArray(resultantArray);

static private int[] toIntArray(string[] strArray)
{
    int[] intArray = new int[strArray.Length];
    for (int i = 0; i < strArray.Length; i++)
    {
        intArray[i] = int.Parse(strArray[i]);
    }

    return intArray;
}

Issue?

I tried many solutions of SO, but none of them helped me.

Ended up with array without leading zeroes.

Body:
yet another way to do this

static private IEnumerable<int> toIntArray(string[] strArray)
{
    foreach (string str in strArray)
    {
        foreach (char c in str)
        {
            yield return (int)char.GetNumericValue(c);
        }
    }
}


来源: stackexchange

问:
Sending email from Spring Boot application using Gmail
I have studied the following question  and answers:
Spring Boot - Could not connect to SMTP host: smtp.gmail.com, port: 25, response: 421

I want to do the same thing - send email from a Spring Boot application using the Gmail servers.

My config is this:

```<code>spring.mail.host = smtp.gmail.com
spring.mail.username = ***@otherdomain
spring.mail.password = ***
spring.mail.properties.mail.smtp.auth = true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.socketFactory.port = 465
spring.mail.properties.mail.smtp.socketFactory.class = javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.smtp.socketFactory.fallback = false
spring.mail.properties.mail.smtp.ssl.enable = true
</code>```

This has been copied from the other question, only the username and password have been changed for my needs. The only different thing about my scienario as that the domain of the email address is not gmail.com.

My Email Client class is:

```<code>@Service
public class MailClient {

  @Autowired
  private JavaMailSender mailSender;

  public void prepareAndSend(String recipient, String message) {
    MimeMessagePreparator messagePreparator = mimeMessage -> {
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
        messageHelper.setFrom("me@otherdomain.org.uk");
        messageHelper.setTo(recipient);
        messageHelper.setSubject("Sample mail subject");
        messageHelper.setText(message);
    };
    mailSender.send(messagePreparator);
  }
}
</code>```

My exception is:

```<code>Failed message 1: com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. g78sm6788965wrd.11 - gsmtp
</code>```

答:
you used smtp.gmail.com so the email should be gmail

EDIT :
in my application in spring mvc i do like this :
service:

```<code>import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;

    /**
         * This method will send compose and send the message
         * */
        public void sendMail(String to, String subject, String body)
        {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setTo(to);
            message.setSubject(subject);
            message.setText(body);
            mailSender.send(message);
        }
</code>```

in the controller i used my service

```<code>applicationMailer.sendMail("*******@gmail.com", "Message from "+ userName , mailModel.getBody());
</code>```

and for configuration :

```<code><bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="smtp.gmail.com"/>
        <property name="port" value="587"/>  <!--   ou 25 -->
        <property name="username" value="*****@gmail.com"/>
        <property name="password" value="******"/>
        <property name="javaMailProperties">
            <props>
                <prop key="mail.transport.protocol">smtp</prop>
                <prop key="mail.smtp.auth">true</prop>
                <prop key="mail.smtp.starttls.enable">true</prop>
                <prop key="mail.debug">true</prop>
            </props>
        </property>
    </bean>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have studied the following question  and answers:
Spring Boot - Could not connect to SMTP host: smtp.gmail.com, port: 25, response: 421

I want to do the same thing - send email from a Spring Boot application using the Gmail servers.

My config is this:

spring.mail.host = smtp.gmail.com
spring.mail.username = ***@otherdomain
spring.mail.password = ***
spring.mail.properties.mail.smtp.auth = true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.socketFactory.port = 465
spring.mail.properties.mail.smtp.socketFactory.class = javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.smtp.socketFactory.fallback = false
spring.mail.properties.mail.smtp.ssl.enable = true

This has been copied from the other question, only the username and password have been changed for my needs. The only different thing about my scienario as that the domain of the email address is not gmail.com.

My Email Client class is:

@Service
public class MailClient {

  @Autowired
  private JavaMailSender mailSender;

  public void prepareAndSend(String recipient, String message) {
    MimeMessagePreparator messagePreparator = mimeMessage -> {
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
        messageHelper.setFrom("me@otherdomain.org.uk");
        messageHelper.setTo(recipient);
        messageHelper.setSubject("Sample mail subject");
        messageHelper.setText(message);
    };
    mailSender.send(messagePreparator);
  }
}

My exception is:

Failed message 1: com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. g78sm6788965wrd.11 - gsmtp

Body:
you used smtp.gmail.com so the email should be gmail

EDIT :
in my application in spring mvc i do like this :
service:

import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;

    /**
         * This method will send compose and send the message
         * */
        public void sendMail(String to, String subject, String body)
        {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setTo(to);
            message.setSubject(subject);
            message.setText(body);
            mailSender.send(message);
        }

in the controller i used my service

applicationMailer.sendMail("*******@gmail.com", "Message from "+ userName , mailModel.getBody());

and for configuration :

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="smtp.gmail.com"/>
        <property name="port" value="587"/>  <!--   ou 25 -->
        <property name="username" value="*****@gmail.com"/>
        <property name="password" value="******"/>
        <property name="javaMailProperties">
            <props>
                <prop key="mail.transport.protocol">smtp</prop>
                <prop key="mail.smtp.auth">true</prop>
                <prop key="mail.smtp.starttls.enable">true</prop>
                <prop key="mail.debug">true</prop>
            </props>
        </property>
    </bean>

ContentLicense: CC BY-SA 3.0


问:
Retrofti Json RecyclerView: No adapter attached;
I put on my json data in this URL= http://api.myjson.com/bins/1fblzn

it contains location data and has 5 fields, three of them are Strings and two of them are Doubles.

I want to show it in recyclerview.

but I keep getting this error.

I searched a lot but I couldn't get an answer.

Here's my code:

MainActivityRecyc

```<code>    public class MainActivityRecyc extends AppCompatActivity {
    private static final String TAG = MainActivityRecyc.class.getSimpleName();

    private RecyclerView recyclerView;
    private ArrayList<Locations> data;
    private DataAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_recyc);
        final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.card_recycler_view);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        RequestInterface requestInterface =
                JsonClient.getClient().create(RequestInterface.class);
        Call<JSONResponse> call = requestInterface.getJson();
        call.enqueue(new Callback<JSONResponse>() {
            @Override
            public void onResponse(Call<JSONResponse> call,
                                   Response<JSONResponse> response) {
                int statusCode = response.code();
                List<Locations> data = response.body().getData();
                recyclerView.setAdapter(new DataAdapter(data, R.layout.card_row, getApplicationContext()));            }
            @Override
            public void onFailure(Call<JSONResponse> call, Throwable t) {
            }        });    }     }
</code>```

Locations

```<code>      public class Locations {
    private String name;
    private String pname;
    private String bicycleno;
    private Double lat;
    private Double lang;
            public Locations(String name, String pname, String bicycleno,
                             Double lat, Double lang){
                this.name= name;
                this.pname= pname;
                this.bicycleno= bicycleno;
                this.lat= lat;
                this.lang= lang;
            }
   public String getName() {
        return name;
    }
    public void  setName (String name){
        this.name=name;
    }
    public String getPname() {
        return pname;
    }
    public void  setPname(String pname){
        this.pname=pname;
    }
    public String getBicycleno() {
        return bicycleno;
    }
    public void setBicycleno (String bicycleno){
        this.bicycleno=bicycleno;
    }
    public Double getLat() {
        return lat;
    }
    public void setLat (Double lat){
        this.lat=lat;
    }
    public Double getLang() {
        return lang;
    }
    public void setLang (Double lang){
        this.lang=lang;
    }    }
</code>```

RequestInterface

```<code>     public interface RequestInterface {
    @Headers("Content-Type:application/json")
    @GET("/bins/1fblzn/")
    Call<JSONResponse> getJson();
    }
</code>```

DataAdapter

```<code>      public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder>{
    private List<Locations> data=new ArrayList<>();
    private int rowLayout;
    private Context context;
    public DataAdapter(List<Locations> data ,int rowLayout, Context context){
        this.data = data;
        this.rowLayout = rowLayout;
        this.context = context;
    }
    @Override
    public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(rowLayout, viewGroup, false);
        return new ViewHolder(view);
    }
    @Override
    public void onBindViewHolder(ViewHolder viewHolder, final int i) {
        Locations locations= data.get(i);
        viewHolder.name.setText(data.get(i).getName());
        viewHolder.pname.setText(data.get(i).getPname());
        viewHolder.bicycleno.setText(data.get(i).getBicycleno());
        viewHolder.lat.setText(data.get(i).getLat().toString());
        viewHolder.lang.setText(data.get(i).getLang().toString());
    }
    @Override
    public int getItemCount() {

        return data.size();
    }
    public class ViewHolder extends RecyclerView.ViewHolder{
        private TextView name,pname,bicycleno, lat, lang;
        public ViewHolder(View view) {
            super(view);
            name = (TextView)view.findViewById(R.id.name);
            pname = (TextView)view.findViewById(R.id.pname);
            bicycleno = (TextView)view.findViewById(R.id.bicycleno);
            lat = (TextView)view.findViewById(R.id.lat);
            lang = (TextView)view.findViewById(R.id.lang);
        }   } }
</code>```

JSONResponse

```<code>public class JSONResponse {

@SerializedName("data")
@Expose
private List<Locations> data =new ArrayList<>();

public List<Locations> getData() {
    return data;
}
</code>```

JsonClient

```<code> public class JsonClient {

public static final String BASE_URL = "https://api.myjson.com/";
private static Retrofit retrofit = null;

public static Retrofit getClient() {
    if (retrofit==null) {
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return retrofit;
}}
</code>```

答:
You are missing LinearLayoutManager in your implementation, use this code instead

DataAdapter adapter = new DataAdapter(data, R.layout.card_row, getApplicationContext());
 recyclerView.setLayoutManager(newLinearLayoutManager(getContext()));
 recyclerView.setAdapter(adapter);

Hope this helps, Happy codding!

Body:
I put on my json data in this URL= http://api.myjson.com/bins/1fblzn

it contains location data and has 5 fields, three of them are Strings and two of them are Doubles.

I want to show it in recyclerview.

but I keep getting this error.

I searched a lot but I couldn't get an answer.

Here's my code:

MainActivityRecyc

    public class MainActivityRecyc extends AppCompatActivity {
    private static final String TAG = MainActivityRecyc.class.getSimpleName();

    private RecyclerView recyclerView;
    private ArrayList<Locations> data;
    private DataAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_recyc);
        final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.card_recycler_view);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        RequestInterface requestInterface =
                JsonClient.getClient().create(RequestInterface.class);
        Call<JSONResponse> call = requestInterface.getJson();
        call.enqueue(new Callback<JSONResponse>() {
            @Override
            public void onResponse(Call<JSONResponse> call,
                                   Response<JSONResponse> response) {
                int statusCode = response.code();
                List<Locations> data = response.body().getData();
                recyclerView.setAdapter(new DataAdapter(data, R.layout.card_row, getApplicationContext()));            }
            @Override
            public void onFailure(Call<JSONResponse> call, Throwable t) {
            }        });    }     }

Locations

      public class Locations {
    private String name;
    private String pname;
    private String bicycleno;
    private Double lat;
    private Double lang;
            public Locations(String name, String pname, String bicycleno,
                             Double lat, Double lang){
                this.name= name;
                this.pname= pname;
                this.bicycleno= bicycleno;
                this.lat= lat;
                this.lang= lang;
            }
   public String getName() {
        return name;
    }
    public void  setName (String name){
        this.name=name;
    }
    public String getPname() {
        return pname;
    }
    public void  setPname(String pname){
        this.pname=pname;
    }
    public String getBicycleno() {
        return bicycleno;
    }
    public void setBicycleno (String bicycleno){
        this.bicycleno=bicycleno;
    }
    public Double getLat() {
        return lat;
    }
    public void setLat (Double lat){
        this.lat=lat;
    }
    public Double getLang() {
        return lang;
    }
    public void setLang (Double lang){
        this.lang=lang;
    }    }

RequestInterface

     public interface RequestInterface {
    @Headers("Content-Type:application/json")
    @GET("/bins/1fblzn/")
    Call<JSONResponse> getJson();
    }

DataAdapter

      public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder>{
    private List<Locations> data=new ArrayList<>();
    private int rowLayout;
    private Context context;
    public DataAdapter(List<Locations> data ,int rowLayout, Context context){
        this.data = data;
        this.rowLayout = rowLayout;
        this.context = context;
    }
    @Override
    public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(rowLayout, viewGroup, false);
        return new ViewHolder(view);
    }
    @Override
    public void onBindViewHolder(ViewHolder viewHolder, final int i) {
        Locations locations= data.get(i);
        viewHolder.name.setText(data.get(i).getName());
        viewHolder.pname.setText(data.get(i).getPname());
        viewHolder.bicycleno.setText(data.get(i).getBicycleno());
        viewHolder.lat.setText(data.get(i).getLat().toString());
        viewHolder.lang.setText(data.get(i).getLang().toString());
    }
    @Override
    public int getItemCount() {

        return data.size();
    }
    public class ViewHolder extends RecyclerView.ViewHolder{
        private TextView name,pname,bicycleno, lat, lang;
        public ViewHolder(View view) {
            super(view);
            name = (TextView)view.findViewById(R.id.name);
            pname = (TextView)view.findViewById(R.id.pname);
            bicycleno = (TextView)view.findViewById(R.id.bicycleno);
            lat = (TextView)view.findViewById(R.id.lat);
            lang = (TextView)view.findViewById(R.id.lang);
        }   } }

JSONResponse

public class JSONResponse {

@SerializedName("data")
@Expose
private List<Locations> data =new ArrayList<>();

public List<Locations> getData() {
    return data;
}

JsonClient

 public class JsonClient {

public static final String BASE_URL = "https://api.myjson.com/";
private static Retrofit retrofit = null;

public static Retrofit getClient() {
    if (retrofit==null) {
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return retrofit;
}}


问:
Loading external SWF with masked content - need width/height
I am loading an external swf using the SWFLoader component. The swf that is being loaded is masked so that only a portion is being shown. However, when it's loaded the actual size of the swf (loader.content.width/loader.content.height) is the complete swf including the masked area. Therefore, the loaded swf does not display properly in the itemrenderer Is there a way to to grab the size of the just the masked area as opposed to getting the size of the entire swf's contents?

One item to note that is complicating the issue, is that these are swf files that have already been created and there are many of them. In some instances, the size of the stage matches up with the size of the masked area. In other instances, the stage is larger (or possibly smaller) than the masked area movieclip as well as possibly the actual size of the movieclip (w/o the mask).

I am currently loading the external swf in using a Loader. Once loaded, I make a copy (screen shot) of the swf by creating a bmp of the loader.content.This is done as I don't want to have any animations being shown on screen at this moment. I am setting the size of the bmp using using loader.content.width & loader.content.height. I then set the SWFLoader.source to the bitmap.

答: If you can't find the mask in the loaded swf, there is a brute-force way: render it into BitmapData with transparent background, then analyze pixels to find out where non-transparent area ends. If you do it smart, you should fit into several dozen of samples (unless swf itself is transparent). Of course, render part will be costly as hell, but maybe your app allows such delays...</p>

ContentLicense: CC BY-SA 2.5


问:
How to fix "invalid Web Uri" for Powershell Register-PSRepository?
A few weeks ago this error started popping up.

```<code>Set-PSRepository : The specified Uri 'http://*****' for parameter
'SourceLocation' is an invalid Web Uri.
Please ensure that it meets the Web Uri requirements.
</code>```

I'm not sure how to fix this short of uninstalling Powershell. There is a workaround available on StackOverflow but it's clunky and will not work for me long term.

Frankly I'd rather just find where the PSRepositories are stored and edit the files manually when I need to.

答:
The answer to this other question should help: Invalid Web Uri error on Register-PSRepository

It involves registering the repository using a local path first, then updating it to point to the URL.

Body:
A few weeks ago this error started popping up.

Set-PSRepository : The specified Uri 'http://*****' for parameter
'SourceLocation' is an invalid Web Uri.
Please ensure that it meets the Web Uri requirements.

I'm not sure how to fix this short of uninstalling Powershell. There is a workaround available on StackOverflow but it's clunky and will not work for me long term.

Frankly I'd rather just find where the PSRepositories are stored and edit the files manually when I need to.


问:
How to disable Apache keep-alive only for iOS?
Is it possible to disable keep-alive mechanism in apache for only iOS clients through CPanel?
I have found this question as a solution:
Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."

But I cannot find the file setenvif.conf.
How should I edit the setenvif.conf?

答:
You won't need this exact conf-file. Just put it in your default server config:</p>

```<code>BrowserMatch "iOS \d\." nokeepalive
</code>```

Body:
You won't need this exact conf-file. Just put it in your default server config:

BrowserMatch "iOS \d\." nokeepalive


问:
SQL Case Statement - how to do it
I have the below statement which works nicely in Tableau.

However, I'd like to turn this into SQL and save all the results into a temporary column name.

Does anyone know how I might do this?

Essentially, the below removes the .com/.net etc... from the domain name.

I then have another script that removes the subdomain (everything from the first . to the left of the resulting value).

If anyone can help me with these, that would be incredible as I'm not sure how to do this in SQL

```<code>IF CONTAINS([domain], ".co.uk") then LEFT([domain],LEN([domain])-6)
elseif  CONTAINS([domain], ".com") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".net") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".org") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".biz") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".edu") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".ac") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".gov") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".biz") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".co") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".ca") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".io") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".in") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".it") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".uk") then LEFT([domain],LEN([domain])- 3)
elseif  CONTAINS([domain], ".ru") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".ie") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".tv") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".info") then LEFT([domain],LEN([domain])-5)
elseif  CONTAINS([domain], ".fr") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".es") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".pl") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".is") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".hu") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".xxx") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".nl") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".ro") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".xyz") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".no") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".eu") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".me") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".cz") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".fi") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".nl") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".al") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".am") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".af") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".st") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".cn") then LEFT([domain],LEN([domain])-3)
else [domain]
end
</code>```

答:
if
You could use CASE WHEN  this way  the ... mean that you must addapr the code properly

```<code>select   CASE domain
            WHEN  domain like "%.co.uk" THEN LEFT(domain,LENGTH(domain)-6)
            WHEN  domain LIKE "%. com"  THEN LEFT(domain,LENGTH(domain)-4)
            WHEN  domain LIKE "%. net"  THEN LEFT(domain,LENGTH(domain)-4)
            .....
            WHEN domain LIKE "%.co" THEN LEFT(domain,LENGTH(domain)-3)
            WHEN domain LIKE "%.ca" THEN LEFT(domain,LENGTH(domain)-3)
            ....
          END
FROM MY_TABLE
</code>```

Title: SQL Case Statement - how to do it

Body:
I have the below statement which works nicely in Tableau.

However, I'd like to turn this into SQL and save all the results into a temporary column name.

Does anyone know how I might do this?

Essentially, the below removes the .com/.net etc... from the domain name.

I then have another script that removes the subdomain (everything from the first . to the left of the resulting value).

If anyone can help me with these, that would be incredible as I'm not sure how to do this in SQL

IF CONTAINS([domain], ".co.uk") then LEFT([domain],LEN([domain])-6)
elseif  CONTAINS([domain], ".com") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".net") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".org") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".biz") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".edu") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".ac") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".gov") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".biz") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".co") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".ca") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".io") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".in") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".it") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".uk") then LEFT([domain],LEN([domain])- 3)
elseif  CONTAINS([domain], ".ru") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".ie") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".tv") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".info") then LEFT([domain],LEN([domain])-5)
elseif  CONTAINS([domain], ".fr") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".es") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".pl") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".is") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".hu") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".xxx") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".nl") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".ro") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".xyz") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".no") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".eu") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".me") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".cz") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".fi") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".nl") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".al") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".am") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".af") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".st") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".cn") then LEFT([domain],LEN([domain])-3)
else [domain]
end

Body:
if
You could use CASE WHEN  this way  the ... mean that you must addapr the code properly

select   CASE domain
            WHEN  domain like "%.co.uk" THEN LEFT(domain,LENGTH(domain)-6)
            WHEN  domain LIKE "%. com"  THEN LEFT(domain,LENGTH(domain)-4)
            WHEN  domain LIKE "%. net"  THEN LEFT(domain,LENGTH(domain)-4)
            .....
            WHEN domain LIKE "%.co" THEN LEFT(domain,LENGTH(domain)-3)
            WHEN domain LIKE "%.ca" THEN LEFT(domain,LENGTH(domain)-3)
            ....
          END
FROM MY_TABLE


问:
Months with less than 31 days omitted from list
Consider the following code that was working perfectly yesterday, but now today (30th March), it has stopped working...

```<code><form class="date">
<select name="date" onchange="this.form.submit()">

<?php
  for ($i = 0; $i <= 60; ++$i) {
    $time = strtotime(sprintf('+%d months', $i));
    $value = date('Y-m', $time);
    $label = date('F Y', $time);
    $nowvalue = date('Y-m');
    $nowlabel = date('F Y');
        if(isset($_GET['date'])) {
          if(strcmp($value,$_GET['date']) == 0) {
             //If 0, $value and $_GET['date'] are the same: The option is selected
             printf('<option value="%s" selected>%s</option>', $value, $label);
          } else {
             printf('<option value="%s">%s</option>', $value, $label);
          }
        } else {
          if($value == $nowvalue) {
            printf('<option value="%s" selected>%s</option>', $value, $label);
          } else {
            printf('<option value="%s">%s</option>', $value, $label);
          }
    }
  }
  ?>
</select>
</form>
</code>```

This outputs a select list of upcoming months, that onchange, reloads the page with a different query in the URL for the calendar on that page to react on.

If i manually update the query in the URL, it works fine, but this select list is repeating dates, have a look at the image below...

This cant be a coincidence that all of the months with the shortest days are missing, or in fact have been replaced with the same name as the month before?

Does anyone have an idea why this might be happening?

答:
This is just an FYI as I realise that you've added your own answer.

You could instead use DateTime() to simplify your code (if you want).

So you could end up with something like:

```<code><select name="date" onchange="this.form.submit()">

    <?php

    $selected = DateTime::createFromFormat('Y-m-d', @$_GET['date'] . '-01') ?: new DateTime('first day of this month');

    for ($i = 0; $i <= 60; $i++) {

        $date = (new DateTime('first day of this month'))->modify("+$i months");

        $select = $date == $selected ? 'selected' : '';

        printf('<option value="%s" %s>%s</option>', $date->format('Y-m'), $select, $date->format('F-Y'));

    }
    ?>

</select>
</code>```

Hope this helps!

Body:
Consider the following code that was working perfectly yesterday, but now today (30th March), it has stopped working...

<form class="date">
<select name="date" onchange="this.form.submit()">

<?php
  for ($i = 0; $i <= 60; ++$i) {
    $time = strtotime(sprintf('+%d months', $i));
    $value = date('Y-m', $time);
    $label = date('F Y', $time);
    $nowvalue = date('Y-m');
    $nowlabel = date('F Y');
        if(isset($_GET['date'])) {
          if(strcmp($value,$_GET['date']) == 0) {
             //If 0, $value and $_GET['date'] are the same: The option is selected
             printf('<option value="%s" selected>%s</option>', $value, $label);
          } else {
             printf('<option value="%s">%s</option>', $value, $label);
          }
        } else {
          if($value == $nowvalue) {
            printf('<option value="%s" selected>%s</option>', $value, $label);
          } else {
            printf('<option value="%s">%s</option>', $value, $label);
          }
    }
  }
  ?>
</select>
</form>

This outputs a select list of upcoming months, that onchange, reloads the page with a different query in the URL for the calendar on that page to react on.

If i manually update the query in the URL, it works fine, but this select list is repeating dates, have a look at the image below...

This cant be a coincidence that all of the months with the shortest days are missing, or in fact have been replaced with the same name as the month before?

Does anyone have an idea why this might be happening?

Body:
This is just an FYI as I realise that you've added your own answer.

You could instead use DateTime() to simplify your code (if you want).

So you could end up with something like:

<select name="date" onchange="this.form.submit()">

    <?php

    $selected = DateTime::createFromFormat('Y-m-d', @$_GET['date'] . '-01') ?: new DateTime('first day of this month');

    for ($i = 0; $i <= 60; $i++) {

        $date = (new DateTime('first day of this month'))->modify("+$i months");

        $select = $date == $selected ? 'selected' : '';

        printf('<option value="%s" %s>%s</option>', $date->format('Y-m'), $select, $date->format('F-Y'));

    }
    ?>

</select>

Hope this helps!


问:
Why must I click twice to open and close my menu
Hello I got a situation which I do not understand quite well. I have the following setup:

 $(document).ready(function(){
  $('.menuBtn').on('click touch', function () {
  $(this).toggleClass('act');
   if($(this).hasClass('act')) {
    $('.mobileMenu').addClass('act');
    //$('body').addClass('positionfixed');
   }
   else {
    $('.mobileMenu').removeClass('act');
    //$('body').removeClass('positionfixed');
   }
 });
   });```
<pre class="snippet-code-css lang-css prettyprint-override"><code> .mobile-menu-button{
  display:block;
  position:fixed;
  top:20px;
  left:20px;
  z-index:99;
    background-color:#19b698;
    padding:5px 10px;
    color:#fff;
    font-family: Open Sans;
    font-weight:bold;
 }
 .mobile-menu-button i{
  font-size:26px;
  background-color:#00adee;
  padding:5px 10px;
  color:#fff;
 }
.mobileMenu {
  background-color: #fff !important;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 100;
  height: 100vh;
  width: 100vw;
  display: block;
  text-align: center;
  opacity: 0;
  -webkit-transition: all 500ms cubic-bezier(0.68, -0.55, 0.265, 1.55);
  transition: all 500ms cubic-bezier(0.68, -0.55, 0.265, 1.55);
  -webkit-transform: scale(0);
     transform: scale(0);
  overflow:hidden;
 }
 .mobileMenu img{
  max-width:90%;
  margin:0 auto;
  margin-top:20px;
  margin-bottom:10px;
  border-bottom:1px dotted #717274;
  padding-bottom:20px;
 }
 .mobileMenu.act {
  opacity: 1;
  -webkit-transform: scale(1);
     transform: scale(1);
 }
 .mobileMenu.act ul li {
  opacity: 1;
  -webkit-transform: translateX(0);
     transform: translateX(0);
  display:block !important;
 }
 .mobileMenu ul {
  display: block;
  vertical-align: middle;
 }
 .mobileMenu li {
  padding: 10px 0 !important;
  -webkit-transition: all 400ms 510ms;
  transition: all 400ms 510ms;
  opacity: 0;
 }
 .mobileMenu li:nth-child(odd) {
   -webkit-transform: translateX(30%);
     transform: translateX(30%);
 }
 .mobileMenu li:nth-child(even) {
   -webkit-transform: translateX(-30%);
     transform: translateX(-30%);
 }
 .mobileMenu li:last-child {
   -webkit-transform: none;
     transform: none;
 }
 .mobileMenu a {
   color: #00adee !important;
   display: inline-block;
   font-size: 18px;
 }
 .mobileMenu a.suBtn {
   color: #fff;
 }</code>```

Open

  Close

Home

Testimonials

Contact

```

Why should I press two times on the open / close button to open / close the menu?

Anyone any idea / fix?

答:
```<code>$(this).toggleClass('act');
</code>```

to

```<code>$('.menuBtn').toggleClass('act');
</code>```

because this will return the only span which is clicked not other. Hence it is not going toggle class on both div.

please find working snippet below

$(document).ready(function(){
  $('.menuBtn').on('click touch', function () {
   $('.menuBtn').toggleClass('act');
   if($(this).hasClass('act')) {
    $('.mobileMenu').addClass('act');
    //$('body').addClass('positionfixed');
   }
   else {
    $('.mobileMenu').removeClass('act');
    //$('body').removeClass('positionfixed');
   }
 });
   });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.mobile-menu-button{
  display:block;
  position:fixed;
  top:20px;
  left:20px;
  z-index:99;
    background-color:#19b698;
    padding:5px 10px;
    color:#fff;
    font-family: Open Sans;
    font-weight:bold;
 }
 .mobile-menu-button i{
  font-size:26px;
  background-color:#00adee;
  padding:5px 10px;
  color:#fff;
 }
.mobileMenu {
  background-color: #fff !important;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 100;
  height: 100vh;
  width: 100vw;
  display: block;
  text-align: center;
  opacity: 0;
  -webkit-transition: all 500ms cubic-bezier(0.68, -0.55, 0.265, 1.55);
  transition: all 500ms cubic-bezier(0.68, -0.55, 0.265, 1.55);
  -webkit-transform: scale(0);
     transform: scale(0);
  overflow:hidden;
 }
 .mobileMenu img{
  max-width:90%;
  margin:0 auto;
  margin-top:20px;
  margin-bottom:10px;
  border-bottom:1px dotted #717274;
  padding-bottom:20px;
 }
 .mobileMenu.act {
  opacity: 1;
  -webkit-transform: scale(1);
     transform: scale(1);
 }
 .mobileMenu.act ul li {
  opacity: 1;
  -webkit-transform: translateX(0);
     transform: translateX(0);
  display:block !important;
 }
 .mobileMenu ul {
  display: block;
  vertical-align: middle;
 }
 .mobileMenu li {
  padding: 10px 0 !important;
  -webkit-transition: all 400ms 510ms;
  transition: all 400ms 510ms;
  opacity: 0;
 }
 .mobileMenu li:nth-child(odd) {
   -webkit-transform: translateX(30%);
     transform: translateX(30%);
 }
 .mobileMenu li:nth-child(even) {
   -webkit-transform: translateX(-30%);
     transform: translateX(-30%);
 }
 .mobileMenu li:last-child {
   -webkit-transform: none;
     transform: none;
 }
 .mobileMenu a {
   color: #00adee !important;
   display: inline-block;
   font-size: 18px;
 }
 .mobileMenu a.suBtn {
   color: #fff;
 }</code>```

Open

  Close

Home

Testimonials

Contact

```

Body:
Hello I got a situation which I do not understand quite well. I have the following setup:

 $(document).ready(function(){
  $('.menuBtn').on('click touch', function () {
  $(this).toggleClass('act');
   if($(this).hasClass('act')) {
    $('.mobileMenu').addClass('act');
    //$('body').addClass('positionfixed');
   }
   else {
    $('.mobileMenu').removeClass('act');
    //$('body').removeClass('positionfixed');
   }
 });
   });

 .mobile-menu-button{
  display:block;
  position:fixed;
  top:20px;
  left:20px;
  z-index:99;
    background-color:#19b698;
    padding:5px 10px;
    color:#fff;
    font-family: Open Sans;
    font-weight:bold;
 }
 .mobile-menu-button i{
  font-size:26px;
  background-color:#00adee;
  padding:5px 10px;
  color:#fff;
 }
.mobileMenu {
  background-color: #fff !important;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 100;
  height: 100vh;
  width: 100vw;
  display: block;
  text-align: center;
  opacity: 0;
  -webkit-transition: all 500ms cubic-bezier(0.68, -0.55, 0.265, 1.55);
  transition: all 500ms cubic-bezier(0.68, -0.55, 0.265, 1.55);
  -webkit-transform: scale(0);
     transform: scale(0);
  overflow:hidden;
 }
 .mobileMenu img{
  max-width:90%;
  margin:0 auto;
  margin-top:20px;
  margin-bottom:10px;
  border-bottom:1px dotted #717274;
  padding-bottom:20px;
 }
 .mobileMenu.act {
  opacity: 1;
  -webkit-transform: scale(1);
     transform: scale(1);
 }
 .mobileMenu.act ul li {
  opacity: 1;
  -webkit-transform: translateX(0);
     transform: translateX(0);
  display:block !important;
 }
 .mobileMenu ul {
  display: block;
  vertical-align: middle;
 }
 .mobileMenu li {
  padding: 10px 0 !important;
  -webkit-transition: all 400ms 510ms;
  transition: all 400ms 510ms;
  opacity: 0;
 }
 .mobileMenu li:nth-child(odd) {
   -webkit-transform: translateX(30%);
     transform: translateX(30%);
 }
 .mobileMenu li:nth-child(even) {
   -webkit-transform: translateX(-30%);
     transform: translateX(-30%);
 }
 .mobileMenu li:last-child {
   -webkit-transform: none;
     transform: none;
 }
 .mobileMenu a {
   color: #00adee !important;
   display: inline-block;
   font-size: 18px;
 }
 .mobileMenu a.suBtn {
   color: #fff;
 }

Open

  Close

Home

Testimonials

Contact

Why should I press two times on the open / close button to open / close the menu?

Anyone any idea / fix?

Body:
$(this).toggleClass('act');

to

$('.menuBtn').toggleClass('act');

because this will return the only span which is clicked not other. Hence it is not going toggle class on both div.

please find working snippet below

$(document).ready(function(){
  $('.menuBtn').on('click touch', function () {
   $('.menuBtn').toggleClass('act');
   if($(this).hasClass('act')) {
    $('.mobileMenu').addClass('act');
    //$('body').addClass('positionfixed');
   }
   else {
    $('.mobileMenu').removeClass('act');
    //$('body').removeClass('positionfixed');
   }
 });
   });

.mobile-menu-button{
  display:block;
  position:fixed;
  top:20px;
  left:20px;
  z-index:99;
    background-color:#19b698;
    padding:5px 10px;
    color:#fff;
    font-family: Open Sans;
    font-weight:bold;
 }
 .mobile-menu-button i{
  font-size:26px;
  background-color:#00adee;
  padding:5px 10px;
  color:#fff;
 }
.mobileMenu {
  background-color: #fff !important;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 100;
  height: 100vh;
  width: 100vw;
  display: block;
  text-align: center;
  opacity: 0;
  -webkit-transition: all 500ms cubic-bezier(0.68, -0.55, 0.265, 1.55);
  transition: all 500ms cubic-bezier(0.68, -0.55, 0.265, 1.55);
  -webkit-transform: scale(0);
     transform: scale(0);
  overflow:hidden;
 }
 .mobileMenu img{
  max-width:90%;
  margin:0 auto;
  margin-top:20px;
  margin-bottom:10px;
  border-bottom:1px dotted #717274;
  padding-bottom:20px;
 }
 .mobileMenu.act {
  opacity: 1;
  -webkit-transform: scale(1);
     transform: scale(1);
 }
 .mobileMenu.act ul li {
  opacity: 1;
  -webkit-transform: translateX(0);
     transform: translateX(0);
  display:block !important;
 }
 .mobileMenu ul {
  display: block;
  vertical-align: middle;
 }
 .mobileMenu li {
  padding: 10px 0 !important;
  -webkit-transition: all 400ms 510ms;
  transition: all 400ms 510ms;
  opacity: 0;
 }
 .mobileMenu li:nth-child(odd) {
   -webkit-transform: translateX(30%);
     transform: translateX(30%);
 }
 .mobileMenu li:nth-child(even) {
   -webkit-transform: translateX(-30%);
     transform: translateX(-30%);
 }
 .mobileMenu li:last-child {
   -webkit-transform: none;
     transform: none;
 }
 .mobileMenu a {
   color: #00adee !important;
   display: inline-block;
   font-size: 18px;
 }
 .mobileMenu a.suBtn {
   color: #fff;
 }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="mobile-menu-button menuBtn">Open</span>
  <nav class="mobileMenu">
  <span class="mobile-menu-button menuBtn">Close</span>
  <ul>
    <li><a href="index.html">Home</a></li>
    <li><a href="testimonials.html">Testimonials</a></li>
    <li><a href="contact.html">Contact</a></li>
  </ul>
</nav>


问:
.NET Core project throwing error after installing VS 2017 alongside VS 2015
I was working with VS 2015 Professional with update 3. I have an asp .net core project. It was running fine. Then I installed VS 2017. Then I tried to build by original .net core project in VS 2015. It gives following error:

" Severity  Code    Description Project File    Line    Suppression State
Error   MSB4019 The imported project "C:\Program Files\dotnet\sdk\1.0.1\Microsoft\VisualStudio\v14.0\DotNet\Microsoft.DotNet.Props" was not found. Confirm that the path in the  declaration is correct, and that the file exists on disk."

So unistalled VS 2017 and all VS 2015 and resinstalled VS 2015. But still I am getting the above error.

答:
with both versions installed you must put a global.json file in the root folder of the vs2015 solution to tell it which sdk to use:</p>

```<code>{
  "projects": [ "src", "test" ],
  "sdk": {
    "version": "1.0.0-preview2-1-003177"
  }
}
</code>```

Body:
with both versions installed you must put a global.json file in the root folder of the vs2015 solution to tell it which sdk to use:

{
  "projects": [ "src", "test" ],
  "sdk": {
    "version": "1.0.0-preview2-1-003177"
  }
}


答:
I suggest a different approach: Create a table with a list of the suffix you want to purge) and make a general substition.  I did it in MSSQL (but you can adapt for other DB with small changes).

Anyway (in your solution too) be sure that the characters your are going to purge cannot be in the middle of the text (eg. http://test.com.blabla.us)

dot_nation is the table with contains all the suffix to purge.
It is just an example and I think you have to work on it.

```<code>CREATE TABLE dot_nation
(
SUFFIX VARCHAR(10) NOT NULL
);
ALTER TABLE dot_nation ADD CONSTRAINT dot_nation_PK PRIMARY KEY (SUFFIX);

INSERT INTO dot_nation VALUES('.co.uk');
INSERT INTO dot_nation VALUES('.com');
INSERT INTO dot_nation VALUES('.org');
INSERT INTO dot_nation VALUES('.fr');

CREATE TABLE demo (ID INT, SITE_ADDRESS VARCHAR(500));
INSERT INTO demo VALUES (1, 'http:/xxxxx.com');
INSERT INTO demo VALUES (2, 'http:/xxxxx.fr');
INSERT INTO demo VALUES (3, 'http:/org.en');
INSERT INTO demo VALUES (4, 'http:/yyyyyy.co.uk');

SELECT demo.*, LEFT(demo.SITE_ADDRESS, LEN(demo.SITE_ADDRESS)-LEN(suffix)) AS ADDRESS_CLEANED
FROM demo
LEFT JOIN dot_nation ON SITE_ADDRESS LIKE '%'+SUFFIX+'%'
</code>```

Output:

```<code>    ID          SITE_ADDRESS         ADDRESS_CLEANED
----------- -------------------- --------------------
1           http:/xxxxx.com      http:/xxxxx
2           http:/xxxxx.fr       http:/xxxxx
3           http:/org.en         NULL
4           http:/yyyyyy.co.uk   http:/yyyyyy
</code>```

Title: SQL Case Statement - how to do it

Body:
I suggest a different approach: Create a table with a list of the suffix you want to purge) and make a general substition.  I did it in MSSQL (but you can adapt for other DB with small changes).

Anyway (in your solution too) be sure that the characters your are going to purge cannot be in the middle of the text (eg. http://test.com.blabla.us)

dot_nation is the table with contains all the suffix to purge.
It is just an example and I think you have to work on it.

CREATE TABLE dot_nation
(
SUFFIX VARCHAR(10) NOT NULL
);
ALTER TABLE dot_nation ADD CONSTRAINT dot_nation_PK PRIMARY KEY (SUFFIX);

INSERT INTO dot_nation VALUES('.co.uk');
INSERT INTO dot_nation VALUES('.com');
INSERT INTO dot_nation VALUES('.org');
INSERT INTO dot_nation VALUES('.fr');

CREATE TABLE demo (ID INT, SITE_ADDRESS VARCHAR(500));
INSERT INTO demo VALUES (1, 'http:/xxxxx.com');
INSERT INTO demo VALUES (2, 'http:/xxxxx.fr');
INSERT INTO demo VALUES (3, 'http:/org.en');
INSERT INTO demo VALUES (4, 'http:/yyyyyy.co.uk');

SELECT demo.*, LEFT(demo.SITE_ADDRESS, LEN(demo.SITE_ADDRESS)-LEN(suffix)) AS ADDRESS_CLEANED
FROM demo
LEFT JOIN dot_nation ON SITE_ADDRESS LIKE '%'+SUFFIX+'%'

Output:

    ID          SITE_ADDRESS         ADDRESS_CLEANED
----------- -------------------- --------------------
1           http:/xxxxx.com      http:/xxxxx
2           http:/xxxxx.fr       http:/xxxxx
3           http:/org.en         NULL
4           http:/yyyyyy.co.uk   http:/yyyyyy


问:
awk - How to print two parts of one record
I got fields like this one:

```<code>Dagmar Schlecht(ID: 1233), Taubenstr- 246, 71108 Germany, dr_schlecht@t-online-de 1233 Shopping cart #3664 - Grüne Pillen;
</code>```

How Can I print the characters until the first ")" appears in, e.g., $1 and the characters from ~/"Shopping" and 19 chars onward ( so the part "- Grüne Pillen" is being skipped) ?

The outcome shall be written to and new field, e.g. $2:

```<code>Dagmar Schlecht(ID: 1233) Shopping cart #3664
</code>```

答:
There may be a prettier way to do this in awk, but this does the job nicely:

```<code>awk -F"[ ,]" '{cartFound=0; printf "%s %s %s", $1, $2, $3; for (i=4;i<=NF;++i){if($i=="Shopping"){cartFound=1} if(cartFound==1){ printf " %s", $i} if($i ~ /^#/){cartFound=0}}}{printf "\n"}' inputFile
</code>```

Here we:

Split the record by either a space or a comma: F"[ ,]"

Since we are starting a new record we set our cartFound variable to 0: cartFound=0

And we print the first three fields using printf so it doesn't throw a line feed in: printf "%s %s %s", $1, $2, $3;

We go through the remaining fields with a for loop assigning each field ordinal to variable i: for (i=4;i<=NF;++i){

If the field is the value Shopping then we set our cartFound variable to 1: if($i=="Shopping"){cartFound=1}

If cartFound is 1 then we again use printf to add the field to our output: if(cartFound==1){ printf " %s", $i}

If we hit a field that starts with a hash then set cartFound back to 0: if($i ~ /^#/){cartFound=0}

Finally we printf out a line feed character to end the outputted record: {printf "\n"}.

Body:
I got fields like this one:

Dagmar Schlecht(ID: 1233), Taubenstr- 246, 71108 Germany, dr_schlecht@t-online-de 1233 Shopping cart #3664 - Grüne Pillen;

How Can I print the characters until the first ")" appears in, e.g., $1 and the characters from ~/"Shopping" and 19 chars onward ( so the part "- Grüne Pillen" is being skipped) ?

The outcome shall be written to and new field, e.g. $2:

Dagmar Schlecht(ID: 1233) Shopping cart #3664

Body:
There may be a prettier way to do this in awk, but this does the job nicely:

awk -F"[ ,]" '{cartFound=0; printf "%s %s %s", $1, $2, $3; for (i=4;i<=NF;++i){if($i=="Shopping"){cartFound=1} if(cartFound==1){ printf " %s", $i} if($i ~ /^#/){cartFound=0}}}{printf "\n"}' inputFile

Here we:

Split the record by either a space or a comma: F"[ ,]"

Since we are starting a new record we set our cartFound variable to 0: cartFound=0

And we print the first three fields using printf so it doesn't throw a line feed in: printf "%s %s %s", $1, $2, $3;

We go through the remaining fields with a for loop assigning each field ordinal to variable i: for (i=4;i<=NF;++i){

If the field is the value Shopping then we set our cartFound variable to 1: if($i=="Shopping"){cartFound=1}

If cartFound is 1 then we again use printf to add the field to our output: if(cartFound==1){ printf " %s", $i}

If we hit a field that starts with a hash then set cartFound back to 0: if($i ~ /^#/){cartFound=0}

Finally we printf out a line feed character to end the outputted record: {printf "\n"}.


问:
What event handlers are attached to a DOM node - how to find?
Is there a way to find what event handlers are attached to a given DOM node?

For example, when you click the "add comment" link, there's an event handler attached to it which shows the comment form. Now, if I have a DOM document (a web page), and want to list all the event handlers for one specific node, is there a way to do this?

(I suspect that it's not possible for JS running within the page; do browser extensions in FF have access to this data?)

答:
Chrome (and I suspect Safari) can show attached event listeners when you select an element in the DOM and then scroll down the right sidebar to the Event Listeners section. There, you can see which functions are attached.

I don't have a copy of Firebug at the moment, but I suspect the DOM tab to show similar information in Firefox as well.


问:
How do I fix this null pointer exception?
I'm a newbie to Android, and I'm using a ListView. No problem when scrolling the ListView slowly. But when I scroll it quickly, app crash occurs.

Can anyone help me?

Stack trace:

```<code> FATAL EXCEPTION: main
  Process: com.beco.ibeco, PID: 1764
  java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
      at com.beco.ibeco.app.account.ProfileFragmentNew$HelpListAdapter.getView(ProfileFragmentNew.java:417)
      at android.widget.HeaderViewListAdapter.getView(HeaderViewListAdapter.java:220)
      at android.widget.AbsListView.obtainView(AbsListView.java:2346)
      at android.widget.ListView.makeAndAddView(ListView.java:1876)
      at android.widget.ListView.fillDown(ListView.java:702)
      at android.widget.ListView.fillGap(ListView.java:666)
      at android.widget.AbsListView.trackMotionScroll(AbsListView.java:5106)
      at android.widget.AbsListView.scrollIfNeeded(AbsListView.java:3463)
      at android.widget.AbsListView.onTouchMove(AbsListView.java:3878)
      at android.widget.AbsListView.onTouchEvent(AbsListView.java:3691)
      at android.view.View.dispatchTouchEvent(View.java:9306)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2548)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2241)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at com.android.internal.policy.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2405)
      at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1737)
      at android.app.Activity.dispatchTouchEvent(Activity.java:2820)
      at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:63)
      at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:63)
      at com.android.internal.policy.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2366)
      at android.view.View.dispatchPointerEvent(View.java:9526)
      at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4262)
      at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4128)
      at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3669)
      at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3722)
      at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3688)
      at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3814)
      at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3696)
      at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3871)
      at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3669)
      at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3722)
      at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3688)
    at android.view.ViewRootI
</code>```

Code:

```<code>private class HelpListAdapter extends ArrayAdapter {

    private Holder holder;
    private Context context;

    public HelpListAdapter(Context context, int resource) {
        super(context, resource);
        this.context = context;
    }

    @Override
    public View getView(int position, View view, ViewGroup parent) {

        if (view == null) {
            holder = new Holder();
            if (position == 3) {
                view = View.inflate(getContext(), R.layout.list_item_with_expandable_new, null);
                holder.expandableListView = (ExpandableListView) view.findViewById(R.id.expand_list);
                holder.containerList = (LinearLayout) view.findViewById(R.id.container_expandable_list);
            } else {
                view = View.inflate(getContext(), R.layout.list_item_text, null);
                holder.textView = (TextView) view.findViewById(R.id.text);
            }
            view.setTag(holder);
        } else {
            holder = (Holder) view.getTag();
        }

        if (position != 3) {
            holder.textView.setText(mHelpLabels.get(position));
            Drawable[] iconLeft = {Util.getCustomDrawableColor(getActivity(),R.drawable.ic_favorite_18dp,R.color.beco_logout_red, PorterDuff.Mode.SRC_ATOP),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_checkin_18dp, R.color.beco_logout_red, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_faq, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_feedback, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_feedback, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_share_app, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_privacy, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_terms, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_faq, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_beco_settings, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_beco_settings, R.color.beco_white, PorterDuff.Mode.DST_IN),

            };
            holder.textView.setCompoundDrawablesWithIntrinsicBounds(iconLeft[position], null, null, null);

        } else {
            holder.expandableListView.setAdapter(new ExpandableListAdapter(context, mHelpLabels.get(position), view));
            holder.expandableListView.setOnGroupClickListener((parentExpand, v, groupPosition, id) -> {
                setListViewHeight(parentExpand, groupPosition);
                return false;
            });
        }

        return view;
    }

    class Holder {
        TextView textView;
        ExpandableListView expandableListView;
        LinearLayout containerList;
    }

    private void setListViewHeight(ExpandableListView listView, int group) {

        ExpandableListAdapter listAdapter = (ExpandableListAdapter) listView.getExpandableListAdapter();
        int height = 0;
        int groupCount = 0;
        int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.EXACTLY);
        View groupItem = listAdapter.getGroupView(groupCount, false, null, listView);
        groupItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
        height += groupItem.getMeasuredHeight();

        if (((listView.isGroupExpanded(groupCount)) && (groupCount != group))
                || ((!listView.isGroupExpanded(groupCount)) && (groupCount == group))) {
            for (int j = 0; j < listAdapter.getChildrenCount(groupCount); j++) {
                View listItem = listAdapter.getChildView(groupCount, j, false, null, listView);
                listItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
                height += listItem.getMeasuredHeight();
            }
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();

        if (height < 10)
            height = 200;
        params.height = height;
        listView.setLayoutParams(params);
        listView.requestLayout();
    }

    class ExpandableListAdapter extends BaseExpandableListAdapter {

        Context context;
        String title;
        View viewParent;

        ExpandableListAdapter(Context context, String title, View view) {
            this.context = context;
            this.title = title;
            this.viewParent = view;
        }

        @Override
        public String getChild(int groupPosition, int childPosititon) {
            return mContactLabels.get(childPosititon);
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View view, ViewGroup parent) {

            if (view == null) {
                LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = infalInflater.inflate(R.layout.list_item_text, null);
            }
            Drawable[] iconLeft = {Util.getCustomDrawableColor(getActivity(), R.drawable.ic_email, R.color.beco_icon_tint_color, PorterDuff.Mode.SRC_ATOP),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_phone_black, R.color.beco_icon_tint_color, PorterDuff.Mode.DST_IN)};

            TextView textView = (TextView) view.findViewById(R.id.text);
            textView.setText(mContactLabels.get(childPosition));
            textView.setCompoundDrawablesWithIntrinsicBounds(iconLeft[childPosition], null, null, null);
            textView.setOnClickListener(v -> {
                switch (childPosition) {
                    case 0:
                        Intent intentEmail = new Intent(Intent.ACTION_SENDTO);
                        intentEmail.setData(Uri.fromParts("mailto", mContactLabels.get(childPosition), null));
                        intentEmail.putExtra(Intent.EXTRA_SUBJECT, "Contact beCo");
                        startActivity(intentEmail);
                        break;
                    case 1:
                        Intent intentCall = new Intent(Intent.ACTION_DIAL);
                        intentCall.setData(Uri.parse("tel:" + mContactLabels.get(childPosition)));
                        startActivity(intentCall);
                        break;
                }
            });

            return view;
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            return mContactLabels.size();
        }

        @Override
        public Object getGroup(int groupPosition) {
            return mContactLabels.get(groupPosition);
        }

        @Override
        public int getGroupCount() {
            return 1;
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public View getGroupView(int groupPosition, boolean isExpanded, View view, ViewGroup parent) {

            if (view == null) {
                LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = infalInflater.inflate(R.layout.list_item_text, null);
            }
            TextView contact = (TextView) view.findViewById(R.id.text);
            contact.setText(title);
            Drawable iconLeft = Util.getCustomDrawableColor(getActivity(), R.drawable.ic_contact_blue, R.color.beco_white, PorterDuff.Mode.DST_IN);
            contact.setCompoundDrawablesWithIntrinsicBounds(null,null,iconLeft,null);

            LinearLayout border = (LinearLayout) viewParent.findViewById(R.id.container_expandable_list);

            Drawable iconRight = Util.getCustomDrawableColor(getActivity(), R.drawable.ic_keyboard_arrow_down_black, R.color.beco_black, PorterDuff.Mode.DST_IN);

            if (isExpanded) {
                border.setBackgroundResource(R.drawable.border);
                iconRight = Util.getCustomDrawableColor(getActivity(), R.drawable.ic_keyboard_arrow_up_black, R.color.beco_black, PorterDuff.Mode.DST_IN);
                contact.setTextColor(ContextCompat.getColor(getActivity(), R.color.beco_primary));
                contact.setCompoundDrawablesWithIntrinsicBounds(null, null, iconRight, null);

            } else {
                border.setBackgroundResource(0);
                contact.setTextColor(ContextCompat.getColor(getActivity(), R.color.beco_label_color));
                contact.setCompoundDrawablesWithIntrinsicBounds(null, null, iconRight, null);
            }

            return view;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }
    }
}
</code>```

答:
Your problem lies with the handling of different types of views:

With this:

```<code>        if (position == 3) {
            view = View.inflate(getContext(), R.layout.list_item_with_expandable_new, null);
            holder.expandableListView = (ExpandableListView) view.findViewById(R.id.expand_list);
            holder.containerList = (LinearLayout) view.findViewById(R.id.container_expandable_list);
        } else {
            view = View.inflate(getContext(), R.layout.list_item_text, null);
            holder.textView = (TextView) view.findViewById(R.id.text);
        }
</code>```

You create 2 types of views, but you don't tell the adapter that you have 2 types of views. So when it comes to recycling, any of those views can be used for the other.

You need to help you adapter make the difference with getItemViewType(int position):

```<code>@Override
public int getItemViewType (int position) {
    return position == 3 ? 0 : 1;
}

@Override
public int getViewTypeCount() {
    return 2;
}
</code>```

This way, the listview knows not to reuse the view create for position 3 for any other item.

Body:
I'm a newbie to Android, and I'm using a ListView. No problem when scrolling the ListView slowly. But when I scroll it quickly, app crash occurs.

Can anyone help me?

Stack trace:

 FATAL EXCEPTION: main
  Process: com.beco.ibeco, PID: 1764
  java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
      at com.beco.ibeco.app.account.ProfileFragmentNew$HelpListAdapter.getView(ProfileFragmentNew.java:417)
      at android.widget.HeaderViewListAdapter.getView(HeaderViewListAdapter.java:220)
      at android.widget.AbsListView.obtainView(AbsListView.java:2346)
      at android.widget.ListView.makeAndAddView(ListView.java:1876)
      at android.widget.ListView.fillDown(ListView.java:702)
      at android.widget.ListView.fillGap(ListView.java:666)
      at android.widget.AbsListView.trackMotionScroll(AbsListView.java:5106)
      at android.widget.AbsListView.scrollIfNeeded(AbsListView.java:3463)
      at android.widget.AbsListView.onTouchMove(AbsListView.java:3878)
      at android.widget.AbsListView.onTouchEvent(AbsListView.java:3691)
      at android.view.View.dispatchTouchEvent(View.java:9306)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2548)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2241)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at com.android.internal.policy.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2405)
      at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1737)
      at android.app.Activity.dispatchTouchEvent(Activity.java:2820)
      at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:63)
      at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:63)
      at com.android.internal.policy.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2366)
      at android.view.View.dispatchPointerEvent(View.java:9526)
      at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4262)
      at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4128)
      at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3669)
      at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3722)
      at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3688)
      at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3814)
      at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3696)
      at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3871)
      at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3669)
      at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3722)
      at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3688)
    at android.view.ViewRootI

Code:

private class HelpListAdapter extends ArrayAdapter {

    private Holder holder;
    private Context context;

    public HelpListAdapter(Context context, int resource) {
        super(context, resource);
        this.context = context;
    }

    @Override
    public View getView(int position, View view, ViewGroup parent) {

        if (view == null) {
            holder = new Holder();
            if (position == 3) {
                view = View.inflate(getContext(), R.layout.list_item_with_expandable_new, null);
                holder.expandableListView = (ExpandableListView) view.findViewById(R.id.expand_list);
                holder.containerList = (LinearLayout) view.findViewById(R.id.container_expandable_list);
            } else {
                view = View.inflate(getContext(), R.layout.list_item_text, null);
                holder.textView = (TextView) view.findViewById(R.id.text);
            }
            view.setTag(holder);
        } else {
            holder = (Holder) view.getTag();
        }

        if (position != 3) {
            holder.textView.setText(mHelpLabels.get(position));
            Drawable[] iconLeft = {Util.getCustomDrawableColor(getActivity(),R.drawable.ic_favorite_18dp,R.color.beco_logout_red, PorterDuff.Mode.SRC_ATOP),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_checkin_18dp, R.color.beco_logout_red, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_faq, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_feedback, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_feedback, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_share_app, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_privacy, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_terms, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_faq, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_beco_settings, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_beco_settings, R.color.beco_white, PorterDuff.Mode.DST_IN),

            };
            holder.textView.setCompoundDrawablesWithIntrinsicBounds(iconLeft[position], null, null, null);

        } else {
            holder.expandableListView.setAdapter(new ExpandableListAdapter(context, mHelpLabels.get(position), view));
            holder.expandableListView.setOnGroupClickListener((parentExpand, v, groupPosition, id) -> {
                setListViewHeight(parentExpand, groupPosition);
                return false;
            });
        }

        return view;
    }

    class Holder {
        TextView textView;
        ExpandableListView expandableListView;
        LinearLayout containerList;
    }

    private void setListViewHeight(ExpandableListView listView, int group) {

        ExpandableListAdapter listAdapter = (ExpandableListAdapter) listView.getExpandableListAdapter();
        int height = 0;
        int groupCount = 0;
        int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.EXACTLY);
        View groupItem = listAdapter.getGroupView(groupCount, false, null, listView);
        groupItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
        height += groupItem.getMeasuredHeight();

        if (((listView.isGroupExpanded(groupCount)) && (groupCount != group))
                || ((!listView.isGroupExpanded(groupCount)) && (groupCount == group))) {
            for (int j = 0; j < listAdapter.getChildrenCount(groupCount); j++) {
                View listItem = listAdapter.getChildView(groupCount, j, false, null, listView);
                listItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
                height += listItem.getMeasuredHeight();
            }
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();

        if (height < 10)
            height = 200;
        params.height = height;
        listView.setLayoutParams(params);
        listView.requestLayout();
    }

    class ExpandableListAdapter extends BaseExpandableListAdapter {

        Context context;
        String title;
        View viewParent;

        ExpandableListAdapter(Context context, String title, View view) {
            this.context = context;
            this.title = title;
            this.viewParent = view;
        }

        @Override
        public String getChild(int groupPosition, int childPosititon) {
            return mContactLabels.get(childPosititon);
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View view, ViewGroup parent) {

            if (view == null) {
                LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = infalInflater.inflate(R.layout.list_item_text, null);
            }
            Drawable[] iconLeft = {Util.getCustomDrawableColor(getActivity(), R.drawable.ic_email, R.color.beco_icon_tint_color, PorterDuff.Mode.SRC_ATOP),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_phone_black, R.color.beco_icon_tint_color, PorterDuff.Mode.DST_IN)};

            TextView textView = (TextView) view.findViewById(R.id.text);
            textView.setText(mContactLabels.get(childPosition));
            textView.setCompoundDrawablesWithIntrinsicBounds(iconLeft[childPosition], null, null, null);
            textView.setOnClickListener(v -> {
                switch (childPosition) {
                    case 0:
                        Intent intentEmail = new Intent(Intent.ACTION_SENDTO);
                        intentEmail.setData(Uri.fromParts("mailto", mContactLabels.get(childPosition), null));
                        intentEmail.putExtra(Intent.EXTRA_SUBJECT, "Contact beCo");
                        startActivity(intentEmail);
                        break;
                    case 1:
                        Intent intentCall = new Intent(Intent.ACTION_DIAL);
                        intentCall.setData(Uri.parse("tel:" + mContactLabels.get(childPosition)));
                        startActivity(intentCall);
                        break;
                }
            });

            return view;
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            return mContactLabels.size();
        }

        @Override
        public Object getGroup(int groupPosition) {
            return mContactLabels.get(groupPosition);
        }

        @Override
        public int getGroupCount() {
            return 1;
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public View getGroupView(int groupPosition, boolean isExpanded, View view, ViewGroup parent) {

            if (view == null) {
                LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = infalInflater.inflate(R.layout.list_item_text, null);
            }
            TextView contact = (TextView) view.findViewById(R.id.text);
            contact.setText(title);
            Drawable iconLeft = Util.getCustomDrawableColor(getActivity(), R.drawable.ic_contact_blue, R.color.beco_white, PorterDuff.Mode.DST_IN);
            contact.setCompoundDrawablesWithIntrinsicBounds(null,null,iconLeft,null);

            LinearLayout border = (LinearLayout) viewParent.findViewById(R.id.container_expandable_list);

            Drawable iconRight = Util.getCustomDrawableColor(getActivity(), R.drawable.ic_keyboard_arrow_down_black, R.color.beco_black, PorterDuff.Mode.DST_IN);

            if (isExpanded) {
                border.setBackgroundResource(R.drawable.border);
                iconRight = Util.getCustomDrawableColor(getActivity(), R.drawable.ic_keyboard_arrow_up_black, R.color.beco_black, PorterDuff.Mode.DST_IN);
                contact.setTextColor(ContextCompat.getColor(getActivity(), R.color.beco_primary));
                contact.setCompoundDrawablesWithIntrinsicBounds(null, null, iconRight, null);

            } else {
                border.setBackgroundResource(0);
                contact.setTextColor(ContextCompat.getColor(getActivity(), R.color.beco_label_color));
                contact.setCompoundDrawablesWithIntrinsicBounds(null, null, iconRight, null);
            }

            return view;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }
    }
}

Body:
Your problem lies with the handling of different types of views:

With this:

        if (position == 3) {
            view = View.inflate(getContext(), R.layout.list_item_with_expandable_new, null);
            holder.expandableListView = (ExpandableListView) view.findViewById(R.id.expand_list);
            holder.containerList = (LinearLayout) view.findViewById(R.id.container_expandable_list);
        } else {
            view = View.inflate(getContext(), R.layout.list_item_text, null);
            holder.textView = (TextView) view.findViewById(R.id.text);
        }

You create 2 types of views, but you don't tell the adapter that you have 2 types of views. So when it comes to recycling, any of those views can be used for the other.

You need to help you adapter make the difference with getItemViewType(int position):

@Override
public int getItemViewType (int position) {
    return position == 3 ? 0 : 1;
}

@Override
public int getViewTypeCount() {
    return 2;
}

This way, the listview knows not to reuse the view create for position 3 for any other item.


问:
Want to route one component to another component
I am new to ReactJS I have Three components App.js ,Login.js,Register.js when the wepapp is launched it first launched App.js in that component i have two buttons "Login" and "Register" ,By clicking on Login button it should goto the LogIn component and on click on Register button it should goto Register component,I am not finding a clean way to achieve that.
Here is my code for App.js

```<code>import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {

   constructor(props) {
    super(props);
    // This binding is necessary to make `this` work in the callback
    this.gotoLogin = this.gotoLogin.bind(this);
    this.gotoRegister = this.gotoRegister.bind(this);

  }

  gotoLogin() {

    alert("Login");
  }

   gotoRegister() {

      alert("Register");

  }
  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>
        <button  onClick={this.gotoLogin} class="Button ">Login</button>
        <button  onClick ={this.gotoRegister} class="Button">Register</button>
      </div>
    );
  }
}

export default App;
</code>```

code for index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';

ReactDOM.render(
  <App />,
  document.getElementById('root')
);
</code>```

Respective i have also component class for Login.js and Register.js

答:
Thanks all for your efforts @Mayank @Johib @hod caspi and @sneha i found the root cause of the issue .I was using react-router 4.0.0 which has an internal implementation error it doesn't find the location then i had to downgrade the react-router to 3.0.3 then again another error not undefined getCurrentlocation and i had to pass <Router history={browserHistory}>  the history like this.Here is my final code looks like

App.js

```<code>import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

import { Link, Router, RouterContext, browserHistory, hashHistory } from 'react-router';

class App extends Component {

  constructor(props) {
    super(props);
    // This binding is necessary to make `this` work in the callback
    this.gotoLogin = this.gotoLogin.bind(this);
    this.gotoRegister = this.gotoRegister.bind(this);
  }

  gotoLogin() {

    browserHistory.push("/login");
  }

  gotoRegister() {
    browserHistory.push("/register");

  }
  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>

        <button onClick={this.gotoLogin} >Login</button>
        <button onClick={this.gotoRegister} >Register</button>
        <Link to={'/login'} >Login</Link>
        {this.props.children}

      </div>
    );
  }

}

export default App;
</code>```

index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import Login from './Login';
import Register from './Register';

import './index.css';
import {Route, Router,browserHistory } from 'react-router';

ReactDOM.render(
<Router history={browserHistory}>

<Route path="/" component={App} />
<Route path="/login" component={Login} />
<Route path="/register" component={Register} />

</Router>,
document.getElementById('root')
)
</code>```

Body:
I am new to ReactJS I have Three components App.js ,Login.js,Register.js when the wepapp is launched it first launched App.js in that component i have two buttons "Login" and "Register" ,By clicking on Login button it should goto the LogIn component and on click on Register button it should goto Register component,I am not finding a clean way to achieve that.
Here is my code for App.js

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {

   constructor(props) {
    super(props);
    // This binding is necessary to make `this` work in the callback
    this.gotoLogin = this.gotoLogin.bind(this);
    this.gotoRegister = this.gotoRegister.bind(this);

  }

  gotoLogin() {

    alert("Login");
  }

   gotoRegister() {

      alert("Register");

  }
  render() {
    return (

Welcome to React

        <button  onClick={this.gotoLogin} class="Button ">Login</button>
        <button  onClick ={this.gotoRegister} class="Button">Register</button>

    );
  }
}

export default App;

code for index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

Respective i have also component class for Login.js and Register.js

Body:
Thanks all for your efforts @Mayank @Johib @hod caspi and @sneha i found the root cause of the issue .I was using react-router 4.0.0 which has an internal implementation error it doesn't find the location then i had to downgrade the react-router to 3.0.3 then again another error not undefined getCurrentlocation and i had to pass <Router history={browserHistory}>  the history like this.Here is my final code looks like

App.js

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

import { Link, Router, RouterContext, browserHistory, hashHistory } from 'react-router';

class App extends Component {

  constructor(props) {
    super(props);
    // This binding is necessary to make `this` work in the callback
    this.gotoLogin = this.gotoLogin.bind(this);
    this.gotoRegister = this.gotoRegister.bind(this);
  }

  gotoLogin() {

    browserHistory.push("/login");
  }

  gotoRegister() {
    browserHistory.push("/register");

  }
  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>

        <button onClick={this.gotoLogin} >Login</button>
        <button onClick={this.gotoRegister} >Register</button>
        <Link to={'/login'} >Login</Link>
        {this.props.children}

      </div>
    );
  }

}

export default App;

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import Login from './Login';
import Register from './Register';

import './index.css';
import {Route, Router,browserHistory } from 'react-router';

ReactDOM.render(
<Router history={browserHistory}>

<Route path="/" component={App} />
<Route path="/login" component={Login} />
<Route path="/register" component={Register} />

</Router>,
document.getElementById('root')
)


答:
In fact, there are two buttons (1 for open, 1 for close).

The 1 first click on "open" works, but then, it doesn't because the close button does not have the act class.

I think you should toggle class on both :

$('.menuBtn').on('click touch', function () {
  **$('.menuBtn')**.toggleClass('act');
    ...
    }```

Title: Why must I click twice to open and close my menu


问:
PHP greek url convert
I have a URL like: domain.tld/Σχετικά_με_μας

[edit]
Reading the $_SERVER['REQUEST_URI'] I get to work with:

```<code>%CE%A3%CF%87%CE%B5%CF%84%CE%B9%CE%BA%CE%AC_%CE%BC%CE%B5_%CE%BC%CE%B1%CF%82
</code>```

[/edit]

In PHP I need to convert it to HTML, I get pretty far with:

```<code>htmlentities(urldecode($navstring), ENT_QUOTES, 'UTF-8');
</code>```

It results in:

```<code>ΣχετικÎ¬_με_μας
</code>```

but the 'ά' becomes 'Î¬' But I need it converted to

```<code>ά
</code>```

I'dd really appreciate help. I need a universal solution, not a "string replace"

答:
Information

All modern web browsers understand UTF-8 character encoding.
My advice would be :

Always know the character encoding of the data you are using.

Store your data with UTF-8.

Output data with UTF-8

The mbstring php extension doesn't just manipulate Unicode strings. It also converts multibyte strings between various character encodings.
Use the mb_detect_encoding() (ref) and mb_convert_encoding() (ref 2) functions to convert Unicode strings from one character encoding to another.

PHP Needs to know !

You also need to tell PHP that you are working with UTF-8, to tell him the default value, you can do it in your php.ini file :

```<code>default_charset = "UTF-8";
</code>```

That default value is added to the default Content-Type header returned by PHP unless you specified it with the header() function :

```<code>header('Content-Type: application/json;charset=utf-8');
</code>```

Keep in mind

The default character set is used by a lot of functions in PHP such as :

htmlentities()

htmlspecialchars()

all the mbstring functions

...

Title: PHP greek url convert

Body:
I have a URL like: domain.tld/Σχετικά_με_μας

[edit]
Reading the $_SERVER['REQUEST_URI'] I get to work with:

%CE%A3%CF%87%CE%B5%CF%84%CE%B9%CE%BA%CE%AC_%CE%BC%CE%B5_%CE%BC%CE%B1%CF%82

[/edit]

In PHP I need to convert it to HTML, I get pretty far with:

htmlentities(urldecode($navstring), ENT_QUOTES, 'UTF-8');

It results in:

ΣχετικÎ¬_με_μας

but the 'ά' becomes 'Î¬' But I need it converted to

ά

I'dd really appreciate help. I need a universal solution, not a "string replace"

Body:
Information

All modern web browsers understand UTF-8 character encoding.
My advice would be :

Always know the character encoding of the data you are using.

Store your data with UTF-8.

Output data with UTF-8

The mbstring php extension doesn't just manipulate Unicode strings. It also converts multibyte strings between various character encodings.
Use the mb_detect_encoding() (ref) and mb_convert_encoding() (ref 2) functions to convert Unicode strings from one character encoding to another.

PHP Needs to know !

You also need to tell PHP that you are working with UTF-8, to tell him the default value, you can do it in your php.ini file :

default_charset = "UTF-8";

That default value is added to the default Content-Type header returned by PHP unless you specified it with the header() function :

header('Content-Type: application/json;charset=utf-8');

Keep in mind

The default character set is used by a lot of functions in PHP such as :

htmlentities()

htmlspecialchars()

all the mbstring functions

...


问:
Powershell Global scope with concurrent script execution
I am writing a script to power off and power on VM's from a list of servers the user provides.

In a function I verify that the server exists in our environment and need to track the good servers I actually power off in an array.  In order to solve a scope issue for this array variable I was going to make it global, but am wondering if a global variable would be affected if multiple users ran this script from the same server at the same time, since I know it would be in scope for the shell.

I have tried to run script level scope but it does not seem to work for me properly.  Does anyone know if global would cause an issue in this case?

ex:

```<code>$powerOn = [System.Collections.ArrayList]@()
foreach ($server in $servers){
      powerOff($server)
}

Function powerOff($name){
      #Code to check if server exists
      #if exists
      $Global:powerOn.add($name)
}
</code>```

答:
You need to include the scope every time you refer to a non-local variable:

```<code>$Global:powerOn = [System.Collections.ArrayList]@()
foreach ($server in $servers){
      powerOff($server)
}

Function powerOff($name){
      #Code to check if server exists
      #if exists
      $Global:powerOn.add($name)
}
</code>```

This should also allow you to use the script scope if you'd rather.

Body:
I am writing a script to power off and power on VM's from a list of servers the user provides.

In a function I verify that the server exists in our environment and need to track the good servers I actually power off in an array.  In order to solve a scope issue for this array variable I was going to make it global, but am wondering if a global variable would be affected if multiple users ran this script from the same server at the same time, since I know it would be in scope for the shell.

I have tried to run script level scope but it does not seem to work for me properly.  Does anyone know if global would cause an issue in this case?

ex:

$powerOn = [System.Collections.ArrayList]@()
foreach ($server in $servers){
      powerOff($server)
}

Function powerOff($name){
      #Code to check if server exists
      #if exists
      $Global:powerOn.add($name)
}

Body:
You need to include the scope every time you refer to a non-local variable:

$Global:powerOn = [System.Collections.ArrayList]@()
foreach ($server in $servers){
      powerOff($server)
}

Function powerOff($name){
      #Code to check if server exists
      #if exists
      $Global:powerOn.add($name)
}

This should also allow you to use the script scope if you'd rather.


问:
regex select not commented statements
```<code>echo '```'; print_r(1); echo '```';  <- select this

 echo '```'; print_r($temp); echo '```';  <- select this without space

// echo '```'; print_r($temp); echo '```';  <- skip this

echo '```'; print_r($temp3); echo '```';  <- select this

print_r($temp1);  <- select this

// print_r($temp11);  <- skip this

    print_r($temp2);  <- select this without spaces

    if (true) {
        print_r($temp4);  <- select this without spaces

    }
</code>```

I have a code with print statements I need to select only non commented statements

here is a regex

```<code>^((?!\/\/\s?))(echo '```';\s?)?(.+)?(print_r)(\.?)(\w+)?\((.+)?\);( echo '<\/pre>';)?
```

DEMO

how to skip spaces ?'      print_r($temp4);'
or how can I change regex to make it work ?

Title: regex select not commented statements

Body:
echo '
'; print_r(1); echo '
';  <- select this

 echo '
'; print_r($temp); echo '
';  <- select this without space

// echo '
'; print_r($temp); echo '
';  <- skip this

echo '
'; print_r($temp3); echo '
';  <- select this

print_r($temp1);  <- select this

// print_r($temp11);  <- skip this

    print_r($temp2);  <- select this without spaces

    if (true) {
        print_r($temp4);  <- select this without spaces

    }

I have a code with print statements I need to select only non commented statements

here is a regex

^((?!\/\/\s?))(echo '
';\s?)?(.+)?(print_r)(\.?)(\w+)?\((.+)?\);( echo '<\/pre>';)?

DEMO

how to skip spaces ?'      print_r($temp4);'
or how can I change regex to make it work ?

Body:
This regex wont capture the line if there's a comments (//, @*, /*, <!--) otherwise it will capture everything without spaces, hope this will solve your problem.

([\n]|^)(?P<group>(?! *\/\/| *@\*| *\/\*| *<!--| *\\\*)([^\n]*?)(\S)(((?! *\/\/| *@\*| *\/\*| *<!--| *\\\*).)*))