问:
Progress Dialog is not showing while retrieving photos from Firebase
As title says, my progress dialog is not showing when i try to retrieve some photos from Firebase storage.
Here my code :

```<code>progress = ProgressDialog.show(getActivity(), "Loading...", "Please wait...", true);
//Retrieve photos from storage
mDatabase.child("TopCommentPhotos").addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {

        Iterable<DataSnapshot> children = dataSnapshot.getChildren();
        Random r = new Random();
        int random = r.nextInt((size+1) - 1) + 1;

        int count=0;
        for(DataSnapshot child: children) {
            count = count+1;
            if (count == random){
                progress.dismiss();
                ImageModel imageModel = child.getValue(ImageModel.class);
                String downloadUrl = imageModel.getUrl();
               // Display photo
                Glide.with(getActivity())
                        .load(downloadUrl)
                        .into(mImageView);

            }
        }

    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        Toast.makeText(getActivity(),"Error",Toast.LENGTH_LONG).show();

    }
});
</code>```

Thanks for help

答:
```<code>public void onDataChange(DataSnapshot dataSnapshot) {

                                Iterable<DataSnapshot> children = dataSnapshot.getChildren();
                                Random r = new Random();
                                int random = r.nextInt((size+1) - 1) + 1;

                                int count=0;
                                for(DataSnapshot child: children) {
                                    count = count+1;
                                    if (count == random){

                                        ImageModel imageModel = child.getValue(ImageModel.class);
                                        String downloadUrl = imageModel.getUrl();
                                       // Display photo
                                        Glide.with(getActivity())
                                                .load(downloadUrl)
                                                .into(mImageView);

                                    }
                                }
progress.dismiss();

                            }
</code>```

and,

```<code>@Override
                            public void onCancelled(DatabaseError databaseError) {
                                Toast.makeText(getActivity(),"Error",Toast.LENGTH_LONG).show();
progress.dismiss();
                      }
</code>```

Body:
As title says, my progress dialog is not showing when i try to retrieve some photos from Firebase storage.
Here my code :

progress = ProgressDialog.show(getActivity(), "Loading...", "Please wait...", true);
//Retrieve photos from storage
mDatabase.child("TopCommentPhotos").addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {

        Iterable<DataSnapshot> children = dataSnapshot.getChildren();
        Random r = new Random();
        int random = r.nextInt((size+1) - 1) + 1;

        int count=0;
        for(DataSnapshot child: children) {
            count = count+1;
            if (count == random){
                progress.dismiss();
                ImageModel imageModel = child.getValue(ImageModel.class);
                String downloadUrl = imageModel.getUrl();
               // Display photo
                Glide.with(getActivity())
                        .load(downloadUrl)
                        .into(mImageView);

            }
        }

    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        Toast.makeText(getActivity(),"Error",Toast.LENGTH_LONG).show();

    }
});

Thanks for help

Body:
public void onDataChange(DataSnapshot dataSnapshot) {

                                Iterable<DataSnapshot> children = dataSnapshot.getChildren();
                                Random r = new Random();
                                int random = r.nextInt((size+1) - 1) + 1;

                                int count=0;
                                for(DataSnapshot child: children) {
                                    count = count+1;
                                    if (count == random){

                                        ImageModel imageModel = child.getValue(ImageModel.class);
                                        String downloadUrl = imageModel.getUrl();
                                       // Display photo
                                        Glide.with(getActivity())
                                                .load(downloadUrl)
                                                .into(mImageView);

                                    }
                                }
progress.dismiss();

                            }

and,

@Override
                            public void onCancelled(DatabaseError databaseError) {
                                Toast.makeText(getActivity(),"Error",Toast.LENGTH_LONG).show();
progress.dismiss();
                      }


来源: stackexchange

问:
Attempt was made to access a socket in a way forbidden by its access permissions
I'm using smtp google's server to send a email through my contact form..In local server it works fine but in web server it shows this error.First ,I've used port number 587 which gives error "Security Exception" and error was on the line using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber)), but I've changed port to 25 and it gives this new error on the line .

```<code>smtp.Send(mail);
</code>```

Description:

An unhandled exception occurred during the execution of the current
  web request. Please review the stack trace for more information about
  the error and where it originated in the code.

Exception Details:

System.Net.Sockets.SocketException: An attempt was made to access a
  socket in a way forbidden by its access permissions 74.125.206.108:25

My code is:

```<code>protected void send_Click(object sender, EventArgs e)
{
    string smtpAddress = "smtp.gmail.com";
    int portNumber = 25;
    bool enableSSL = true;

    string emailfrom = "isl@gmail.com";
    string password = "******";
    string subject = "Contact Form Data";
    string emailto = "isl@gmail.com";
    string name = n.Value;
    string useremail = em.Value;
    string phone = tel.Value;
    string dept = dep.Value;
    string dest = des.Value;
    string adu = ad.Value;

    string msg = mes.Value;
    string body = "Name: " + name + " ;" + " Email: " + useremail + " ;" + "Telephone: " + phone + " ;" + " Departure Place: " + dept + " ;" + "Destination Place: " + dest + " ;" + " Adults: " + adu + " ;" + " ;" + "Children: " + chil + " ;" + "Message: " + msg + " ;";

    using (MailMessage mail = new MailMessage())
    {
        mail.From = new MailAddress(emailfrom);
        mail.To.Add(emailto);
        mail.Subject = subject;
        mail.Body = body;
        mail.IsBodyHtml = true;

        using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
        {
            smtp.Credentials = new NetworkCredential(emailfrom, password);
            smtp.EnableSsl = enableSSL;
            smtp.Send(mail);
        }
    }
}
</code>```

Stack Trace

[SocketException (0x271d): An attempt was made to access a socket in a
  way          forbidden by its access permissions 74.125.206.108:25]
  System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot,
  SocketAddress socketAddress) +208
  System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure,
  Socket s4, Socket s6, Socket& socket, IPAddress& address,
  ConnectSocketState state, IAsyncResult asyncResult, Exception&
  exception) +464

[WebException: Unable to connect to the remote server]
  System.Net.ServicePoint.GetConnection(PooledStream PooledStream,
  Object owner, Boolean async, IPAddress& address, Socket& abortSocket,
  Socket& abortSocket6) +6662436 System.Net.PooledStream.Activate(Object
  owningObject, Boolean async, GeneralAsyncDelegate asyncCallback) +307
  System.Net.PooledStream.Activate(Object owningObject,
  GeneralAsyncDelegate asyncCallback) +19
  System.Net.ConnectionPool.GetConnection(Object owningObject,
  GeneralAsyncDelegate asyncCallback, Int32 creationTimeout) +324
  System.Net.Mail.SmtpConnection.GetConnection(ServicePoint
  servicePoint) +141
  System.Net.Mail.SmtpTransport.GetConnection(ServicePoint servicePoint)
  +170 System.Net.Mail.SmtpClient.GetConnection() +44 System.Net.Mail.SmtpClient.Send(MailMessage message) +1554

[SmtpException: Failure sending mail.]
  System.Net.Mail.SmtpClient.Send(MailMessage message) +1906
  Contact.send_Click(Object sender, EventArgs e) in
  \smb-whst-www02\whst_www02$\ff8b1b\user\medviewair.uk\web\Contact.aspx.cs:51
  System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9628462
  System.Web.UI.WebControls.Button.RaisePostBackEvent(String
  eventArgument) +103
  System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String
  eventArgument) +10
  System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler
  sourceControl, String eventArgument) +13
  System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
  +35 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
  +1724

答: I had to disable Kaspersky End Point Security anti-virus</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm using smtp google's server to send a email through my contact form..In local server it works fine but in web server it shows this error.First ,I've used port number 587 which gives error "Security Exception" and error was on the line using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber)), but I've changed port to 25 and it gives this new error on the line .

smtp.Send(mail);

Description:

An unhandled exception occurred during the execution of the current
  web request. Please review the stack trace for more information about
  the error and where it originated in the code.

Exception Details:

System.Net.Sockets.SocketException: An attempt was made to access a
  socket in a way forbidden by its access permissions 74.125.206.108:25

My code is:

protected void send_Click(object sender, EventArgs e)
{
    string smtpAddress = "smtp.gmail.com";
    int portNumber = 25;
    bool enableSSL = true;

    string emailfrom = "isl@gmail.com";
    string password = "******";
    string subject = "Contact Form Data";
    string emailto = "isl@gmail.com";
    string name = n.Value;
    string useremail = em.Value;
    string phone = tel.Value;
    string dept = dep.Value;
    string dest = des.Value;
    string adu = ad.Value;

    string msg = mes.Value;
    string body = "Name: " + name + " ;" + " Email: " + useremail + " ;" + "Telephone: " + phone + " ;" + " Departure Place: " + dept + " ;" + "Destination Place: " + dest + " ;" + " Adults: " + adu + " ;" + " ;" + "Children: " + chil + " ;" + "Message: " + msg + " ;";

    using (MailMessage mail = new MailMessage())
    {
        mail.From = new MailAddress(emailfrom);
        mail.To.Add(emailto);
        mail.Subject = subject;
        mail.Body = body;
        mail.IsBodyHtml = true;

        using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
        {
            smtp.Credentials = new NetworkCredential(emailfrom, password);
            smtp.EnableSsl = enableSSL;
            smtp.Send(mail);
        }
    }
}

Stack Trace

[SocketException (0x271d): An attempt was made to access a socket in a
  way          forbidden by its access permissions 74.125.206.108:25]
  System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot,
  SocketAddress socketAddress) +208
  System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure,
  Socket s4, Socket s6, Socket& socket, IPAddress& address,
  ConnectSocketState state, IAsyncResult asyncResult, Exception&
  exception) +464

[WebException: Unable to connect to the remote server]
  System.Net.ServicePoint.GetConnection(PooledStream PooledStream,
  Object owner, Boolean async, IPAddress& address, Socket& abortSocket,
  Socket& abortSocket6) +6662436 System.Net.PooledStream.Activate(Object
  owningObject, Boolean async, GeneralAsyncDelegate asyncCallback) +307
  System.Net.PooledStream.Activate(Object owningObject,
  GeneralAsyncDelegate asyncCallback) +19
  System.Net.ConnectionPool.GetConnection(Object owningObject,
  GeneralAsyncDelegate asyncCallback, Int32 creationTimeout) +324
  System.Net.Mail.SmtpConnection.GetConnection(ServicePoint
  servicePoint) +141
  System.Net.Mail.SmtpTransport.GetConnection(ServicePoint servicePoint)
  +170 System.Net.Mail.SmtpClient.GetConnection() +44 System.Net.Mail.SmtpClient.Send(MailMessage message) +1554

[SmtpException: Failure sending mail.]
  System.Net.Mail.SmtpClient.Send(MailMessage message) +1906
  Contact.send_Click(Object sender, EventArgs e) in
  \smb-whst-www02\whst_www02$\ff8b1b\user\medviewair.uk\web\Contact.aspx.cs:51
  System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9628462
  System.Web.UI.WebControls.Button.RaisePostBackEvent(String
  eventArgument) +103
  System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String
  eventArgument) +10
  System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler
  sourceControl, String eventArgument) +13
  System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
  +35 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
  +1724


问:
Where is the words in ' ' located?
I am learning php, (absolute beginner) and want to know where the words in '' are located. I downloaded a code from online for a login system and am trying to learn how it works. Here is the code portion:

```<code><?php

// any HTML input *must* be HTML-escaped to prevent the user from injecting malicious JavaScript code
function html_escape($raw_input, $encoding)
{
return htmlspecialchars($raw_input, ENT_QUOTES | ENT_SUBSTITUTE, $encoding);
}

/* Displays user information and some useful messages */
session_start();

if ($_SESSION['logged_in'] != 1) {
$first_name = 'Guest, Please Login or Sign Up to Play!';
$last_name = '';
}
else {
// Makes it easier to read
$first_name = $_SESSION['first_name'];
$last_name = $_SESSION['last_name'];
}
?>
</code>```

So where it says, "if ($_SESSION['logged_in'] != 1) {", when it says logged_in, where would that be defined? Is it defined in another file with the $logged_in, or what?

Also, i found some file where it says "$_SESSION['logged_in'] = true;" but i don't know if it means something, if it does please tell me!

Thanks so much.

(i'm a beginner so go easy on me please)

答:
In the code you shown, this is the check login step in login process. In login process, there is two step we need to do:

Check login: determine that current session is logged in or not. If not, shown/redirect to login page.

Login page: is used to input username & password and check inputed value. If username & password is correct, we save a value to $_SESSION to flag this user is logged in.

To find how the $_SESSION['logged_in'] is set, you must find in your downloaded code the check login section.

In general this can be simple as:

```<code>if ($_POST['username'] == 'abc' && $_POST['password'] == 'xyz') {
    $_SESSION['logged_in'] = 1;
    // some code to refresh or redirect to main content
}
</code>```

I hope this will help you!

Title: Where is the words in ' ' located?

Body:
I am learning php, (absolute beginner) and want to know where the words in '' are located. I downloaded a code from online for a login system and am trying to learn how it works. Here is the code portion:

<?php

// any HTML input *must* be HTML-escaped to prevent the user from injecting malicious JavaScript code
function html_escape($raw_input, $encoding)
{
return htmlspecialchars($raw_input, ENT_QUOTES | ENT_SUBSTITUTE, $encoding);
}

/* Displays user information and some useful messages */
session_start();

if ($_SESSION['logged_in'] != 1) {
$first_name = 'Guest, Please Login or Sign Up to Play!';
$last_name = '';
}
else {
// Makes it easier to read
$first_name = $_SESSION['first_name'];
$last_name = $_SESSION['last_name'];
}
?>

So where it says, "if ($_SESSION['logged_in'] != 1) {", when it says logged_in, where would that be defined? Is it defined in another file with the $logged_in, or what?

Also, i found some file where it says "$_SESSION['logged_in'] = true;" but i don't know if it means something, if it does please tell me!

Thanks so much.

(i'm a beginner so go easy on me please)

Body:
In the code you shown, this is the check login step in login process. In login process, there is two step we need to do:

Check login: determine that current session is logged in or not. If not, shown/redirect to login page.

Login page: is used to input username & password and check inputed value. If username & password is correct, we save a value to $_SESSION to flag this user is logged in.

To find how the $_SESSION['logged_in'] is set, you must find in your downloaded code the check login section.

In general this can be simple as:

if ($_POST['username'] == 'abc' && $_POST['password'] == 'xyz') {
    $_SESSION['logged_in'] = 1;
    // some code to refresh or redirect to main content
}

I hope this will help you!


问:
Trying to play multiple, selected files in Java/Processing in order of selection
I'm trying to write Java code in which I can select multiple audio files, and have the script play the files in order of selection via a music visualiser.

I currently can select multiple files but only play the first one on a loop.

Here is my code:

```<code>import ddf.minim.*;
import ddf.minim.analysis.*;
import javax.swing.JFileChooser;
import processing.pdf.*;
PImage mouseCursor;
Minim         minim;
AudioPlayer   player;
AudioMetaData meta;
BeatDetect    beat;
FFT           fft;
int           w;
float         rad = 70;
int           r   = 2000;

void setup() {
  beginRecord(PDF, "/Users/Luke/Desktop/Processing Projects and     Files/f.pdf");
  fullScreen();
  JFileChooser chooser = new JFileChooser();
  chooser.setMultiSelectionEnabled(true);
  chooser.setFileFilter(chooser.getAcceptAllFileFilter());
  //chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
  int returnVal = chooser.showOpenDialog(null);
  minim = new Minim(this);
  player =                 minim.loadFile(chooser.getSelectedFile().getAbsolutePath());
  meta = player.getMetaData();
  beat = new BeatDetect();
  player.loop();
  //player.isLooping();
  fft = new FFT(player.bufferSize(), player.sampleRate());
  fft.logAverages(60, 7);
  noStroke();
  w = width/fft.avgSize();
  background(0);
}
void draw() {
  noCursor();
  background(0);
  fill(255);
  fft.forward(player.mix);
  //stroke(255);
  stroke(random(255), random(255), random(255));
  for (int i = 0; i < fft.avgSize(); i++) {
    line((i * w) + (w / 2), height, (i * w) + (w / 2), height -                     fft.getAvg(i) * 4);
    strokeWeight(20);
  }
  beat.detect(player.mix);
  fill(0, 20);
  noStroke();
  rect(0, 0, width, height);
  //translate(width/1, height/50);
  noFill();
  fill(-1, 0);
  if (beat.isOnset()) rad = rad * 0.9f;
    else rad = 70;
  ellipse(0, 0, 2 * rad, 2 * rad);
  strokeCap(PROJECT);
  stroke(-1, 30);
  int bsize = player.bufferSize();
  for (int i = 0; i < bsize - 1; i += 5) {
    float x = 4 * (r)*cos(i*2*PI/bsize);
    float y =  4 * (r)*sin(i*2*PI/bsize);
    float x2 = 4 * (r + player.left.get(i)*100)*cos(i*2*PI/bsize);
    float y2 = 4 * (r + player.left.get(i)*100)*sin(i*2*PI/bsize);
    line(x, y, x2, y2);
  }
}
void keyPressed() {
  if (key==' ')exit();
  if (key=='s' || key=='S')endRecord();
}
</code>```

At the moment it only plays one file and loops

Many thanks for the help

K

答:
You need to break your problem down into smaller steps and only focus on one of those steps at a time.

For example, you should probably create a separate sketch that uses JFileChooser to allow the user to select multiple files. Don't worry about playing them yet, just print their names out to the console. You should read the Java API for useful functions.

When you get that working perfectly, then you can think about getting the click order. That's more advanced, but Google is your friend, and here is a question with a few promising answers. Again, you should do this in its own small example sketch. Don't worry about playing the audio files yet. Just print them to the console.

Separately from that, create a sketch that uses a hard-coded array or ArrayList of audio files and plays them in order. Get that working separately from the file selection logic.

When you get them all working by themselves, it'll be much easier to combine them into a single sketch. And if you get stuck on a specific step, then you can post a MCVE of just that step and we'll go from there. Good luck.

Body:
I'm trying to write Java code in which I can select multiple audio files, and have the script play the files in order of selection via a music visualiser.

I currently can select multiple files but only play the first one on a loop.

Here is my code:

import ddf.minim.*;
import ddf.minim.analysis.*;
import javax.swing.JFileChooser;
import processing.pdf.*;
PImage mouseCursor;
Minim         minim;
AudioPlayer   player;
AudioMetaData meta;
BeatDetect    beat;
FFT           fft;
int           w;
float         rad = 70;
int           r   = 2000;

void setup() {
  beginRecord(PDF, "/Users/Luke/Desktop/Processing Projects and     Files/f.pdf");
  fullScreen();
  JFileChooser chooser = new JFileChooser();
  chooser.setMultiSelectionEnabled(true);
  chooser.setFileFilter(chooser.getAcceptAllFileFilter());
  //chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
  int returnVal = chooser.showOpenDialog(null);
  minim = new Minim(this);
  player =                 minim.loadFile(chooser.getSelectedFile().getAbsolutePath());
  meta = player.getMetaData();
  beat = new BeatDetect();
  player.loop();
  //player.isLooping();
  fft = new FFT(player.bufferSize(), player.sampleRate());
  fft.logAverages(60, 7);
  noStroke();
  w = width/fft.avgSize();
  background(0);
}
void draw() {
  noCursor();
  background(0);
  fill(255);
  fft.forward(player.mix);
  //stroke(255);
  stroke(random(255), random(255), random(255));
  for (int i = 0; i < fft.avgSize(); i++) {
    line((i * w) + (w / 2), height, (i * w) + (w / 2), height -                     fft.getAvg(i) * 4);
    strokeWeight(20);
  }
  beat.detect(player.mix);
  fill(0, 20);
  noStroke();
  rect(0, 0, width, height);
  //translate(width/1, height/50);
  noFill();
  fill(-1, 0);
  if (beat.isOnset()) rad = rad * 0.9f;
    else rad = 70;
  ellipse(0, 0, 2 * rad, 2 * rad);
  strokeCap(PROJECT);
  stroke(-1, 30);
  int bsize = player.bufferSize();
  for (int i = 0; i < bsize - 1; i += 5) {
    float x = 4 * (r)*cos(i*2*PI/bsize);
    float y =  4 * (r)*sin(i*2*PI/bsize);
    float x2 = 4 * (r + player.left.get(i)*100)*cos(i*2*PI/bsize);
    float y2 = 4 * (r + player.left.get(i)*100)*sin(i*2*PI/bsize);
    line(x, y, x2, y2);
  }
}
void keyPressed() {
  if (key==' ')exit();
  if (key=='s' || key=='S')endRecord();
}

At the moment it only plays one file and loops

Many thanks for the help

K


问:
How to wrap content views rather than background drawable?
How can I get a LinearLayout (or any other ViewGroup) to assume the size of it's child views rather than assuming the size of the background image?

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/large_image300x300pix">

 <TextView android:id="@+id/TextView01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello world!"/>
</LinearLayout>
</code>```

The linear layout becomes the same size as the background image.
How can I get my linear layout to assume the same size as the textview?

答: If your image lends itself to being converted to a scalable 9-patch image, then doing that would cause the background to scale around the TextView.</p>

ContentLicense: CC BY-SA 2.5

Body:
How can I get a LinearLayout (or any other ViewGroup) to assume the size of it's child views rather than assuming the size of the background image?

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/large_image300x300pix">

 <TextView android:id="@+id/TextView01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello world!"/>
</LinearLayout>

The linear layout becomes the same size as the background image.
How can I get my linear layout to assume the same size as the textview?


问:
C++ - creating a thread within instances of classes inside the main() method and calling Sleep()
So I wanted to create a thread to be able to have parts of my program run independently of each other. (The only other way was to create an event based timer and I dont have time for that).

I can create a thread in the main method (entry point) of my application and it works as intended. That is, when I attach my thread to a function located in my main source file. It will call that function in a separate thread and so I can call Sleep() in that function by my program will continue executing code outside of that thread.

```<code>#include "stdafx.h"
#include <thread>
#include <windows.h>
#include <iostream>
#include <thread>

void makeThread()
{
    while (true)
    {
        Sleep(2000);
        printf("thread print");
    }
}

int main()
{
    std::thread th(&makeThread);
    printf("normal print");
    int x;
    std::cin >> x;
}
</code>```

This code will print "normal print" before it prints "thread print". But when I try to create a thread within a class which I have instantiated in the Main class, this is not the case. I notice that it forces me to join the thread if it's not inside the main class, and as a result, I am unable to execute logic separately. How do I correctly call sleep() within a class so that only the thread I have created sleeps and not the main thread? This is my code for the thread created within a class used by main().

```<code>Alarm::Alarm(int cID, int port, string fileName) : ClientObserver(cID, port, fileName)
{
    std::thread th(&Alarm::runLoop, this);
    th.join();
}

void Alarm::runLoop()
{
    while(true)
    {
        bRaiseAlarm = true;
        Sleep(3500);
        if(bRaiseAlarm == true)
        {
            //Sound the alarm
            alarmStep = alarmStep >= 3 ? 1 : alarmStep + 1;
            printf("\nALARM FOR %c with alarm number: %i\n", fileName.c_str(), alarmStep);
            bRaiseAlarm = false;
        }
    }
}
</code>```

In the following code, only the while(true) loop executes and the functionality of the rest of my program is halted because of the Sleep()

答: Creating a pointer to the thread was the first step. The pointer was needed because the variable th went out of scope. Joining the thread somehow solved the problem. Ridding that line solves the problem. </p>

Body:
So I wanted to create a thread to be able to have parts of my program run independently of each other. (The only other way was to create an event based timer and I dont have time for that).

I can create a thread in the main method (entry point) of my application and it works as intended. That is, when I attach my thread to a function located in my main source file. It will call that function in a separate thread and so I can call Sleep() in that function by my program will continue executing code outside of that thread.

#include "stdafx.h"
#include <thread>
#include <windows.h>
#include <iostream>
#include <thread>

void makeThread()
{
    while (true)
    {
        Sleep(2000);
        printf("thread print");
    }
}

int main()
{
    std::thread th(&makeThread);
    printf("normal print");
    int x;
    std::cin >> x;
}

This code will print "normal print" before it prints "thread print". But when I try to create a thread within a class which I have instantiated in the Main class, this is not the case. I notice that it forces me to join the thread if it's not inside the main class, and as a result, I am unable to execute logic separately. How do I correctly call sleep() within a class so that only the thread I have created sleeps and not the main thread? This is my code for the thread created within a class used by main().

Alarm::Alarm(int cID, int port, string fileName) : ClientObserver(cID, port, fileName)
{
    std::thread th(&Alarm::runLoop, this);
    th.join();
}

void Alarm::runLoop()
{
    while(true)
    {
        bRaiseAlarm = true;
        Sleep(3500);
        if(bRaiseAlarm == true)
        {
            //Sound the alarm
            alarmStep = alarmStep >= 3 ? 1 : alarmStep + 1;
            printf("\nALARM FOR %c with alarm number: %i\n", fileName.c_str(), alarmStep);
            bRaiseAlarm = false;
        }
    }
}

In the following code, only the while(true) loop executes and the functionality of the rest of my program is halted because of the Sleep()


问:
javascript fails to identify space character
i am getting a stack trace from a REST service which looks like:

```<code> oracle.mds.core.MetadataNotFoundException: MDS-00013: no metadata found for metadata object "/WEB-INF/root_menu_tm.xml" [[MDS-00201: PDocument not found in MetadataStore : [store-type=DefaultMetadataStore app-name=ORA_CRM_UIAPP lookup-order=ServletContext,Classpath]     at oracle.mds.core.MetadataObject.getBaseMO(MetadataObject.java:1600)   at oracle.mds.core.MDSSession.getMetadataObject(MDSSession.java:1663)   at oracle.apps.fnd.applcore.patterns.uishell.model.ApplicationsMenuModel.getMetadatObject(ApplicationsMenuModel.java:891)   at oracle.apps.fnd.applcore.patterns.uishell.model.ApplicationsMenuModel._createModel(ApplicationsMenuModel.java:492)   at oracle.apps.fnd.applcore.patterns.uishell.model.ApplicationsMenuModel.setSource(ApplicationsMenuModel.java:177)  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  at
</code>```

I am trying to format it in my javascript before displaying on UI. The idea is simple: just replace all the

```<code><space>at
</code>```

with

at

I have tried various options like:

```<code>var trace = (d.MsgDetails).replace(new RegExp('\sat','g'),'</p><p>at');
</code>```

or

```<code>var trace = (d.MsgDetails).replace(new RegExp(' at','g'),'</p><p>at');
</code>```

or

```<code> var trace = (d.MsgDetails).replace(/at/g),'</p><p>at');
</code>```

or

```<code> var trace = (d.MsgDetails).replace(/ at/g),'</p><p>at');
</code>```

and nothing works. I am hoping the space which it looks is really a space. removing the space works fine but that is not what i want as it will break good words too.

答:
The character before “at” is a tab, so:

```<code>var trace = d.MsgDetails.replace(/\tat/g, '</p><p>at');
</code>```

(Your first regular expression with \s would have worked if you had escaped \ in the string literal for an overall \\s; a string literal '\s' is equivalent to 's'. Don’t use the RegExp constructor to create static regular expressions.)

If there are in fact some newlines in there, a neater solution might be:

```<code>var traceLines = d.MsgDetails.split('\n');
var trace = document.createDocumentFragment();

traceLines.forEach(function (line) {
    trace.appendChild(document.createElement('p')).textContent = line;
});
</code>```

Body:
i am getting a stack trace from a REST service which looks like:

 oracle.mds.core.MetadataNotFoundException: MDS-00013: no metadata found for metadata object "/WEB-INF/root_menu_tm.xml" [[MDS-00201: PDocument not found in MetadataStore : [store-type=DefaultMetadataStore app-name=ORA_CRM_UIAPP lookup-order=ServletContext,Classpath]     at oracle.mds.core.MetadataObject.getBaseMO(MetadataObject.java:1600)   at oracle.mds.core.MDSSession.getMetadataObject(MDSSession.java:1663)   at oracle.apps.fnd.applcore.patterns.uishell.model.ApplicationsMenuModel.getMetadatObject(ApplicationsMenuModel.java:891)   at oracle.apps.fnd.applcore.patterns.uishell.model.ApplicationsMenuModel._createModel(ApplicationsMenuModel.java:492)   at oracle.apps.fnd.applcore.patterns.uishell.model.ApplicationsMenuModel.setSource(ApplicationsMenuModel.java:177)  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  at

I am trying to format it in my javascript before displaying on UI. The idea is simple: just replace all the

<space>at

with

at

I have tried various options like:

var trace = (d.MsgDetails).replace(new RegExp('\sat','g'),'

at');

or

var trace = (d.MsgDetails).replace(new RegExp(' at','g'),'

at');

or

 var trace = (d.MsgDetails).replace(/at/g),'

at');

or

 var trace = (d.MsgDetails).replace(/ at/g),'

at');

and nothing works. I am hoping the space which it looks is really a space. removing the space works fine but that is not what i want as it will break good words too.

Body:
The character before “at” is a tab, so:

var trace = d.MsgDetails.replace(/\tat/g, '</p><p>at');

(Your first regular expression with \s would have worked if you had escaped \ in the string literal for an overall \\s; a string literal '\s' is equivalent to 's'. Don’t use the RegExp constructor to create static regular expressions.)

If there are in fact some newlines in there, a neater solution might be:

var traceLines = d.MsgDetails.split('\n');
var trace = document.createDocumentFragment();

traceLines.forEach(function (line) {
    trace.appendChild(document.createElement('p')).textContent = line;
});


问:
PHP Dynamically create SQL query with AND condition
I am trying to write some PHP that fits in to a larger method so that I can dynamically create  a MySQL query.

I haven't included the code to the larger method that contains this code because I think the logic of this bit is self-contained.

So, I have a multi-dimensional array:

```<code>$where=array(array('username', 'pid', 'name'), array('=','<=', '='), array('alex',2,'james'));
</code>```

which when I print_r() shows this structure:

```<code>Array
(
[0] => Array
    (
        [0] => username
        [1] => pid
        [2] => name
    )

[1] => Array
    (
        [0] => =
        [1] => <=
        [2] => =
    )

[2] => Array
    (
        [0] => alex
        [1] => 2
        [2] => james
    )

)
</code>```

What I would like to do if use the first value in each second level array to build up the start of the query such as

```<code>SELECT * FROM table WHERE username = alex
</code>```

and then use the other values to build up the query such as (depending upon the number of items in the arrays)

```<code>SELECT * FROM table WHERE username = alex AND pid <= 2 AND name = james
</code>```

Below is the code I have written

```<code> if (is_array($where[0])){
        $i=0;
        $field = $where[0][$i];
        $operator = $where[1][$i];
        $value= $where[2][$i];
        $sql= "SELECT * FROM table WHERE {$field} {$operator} {$value}";
        while($i=0 ) {
            print $sql;
            $i++;
        }
        while($i>0 AND $i< sizeof($where[0]))
        $field = $where[0][$i];
        $operator = $where[1][$i];
        $value= $where[2][$i];
        print $sql .= " AND {$field} {$operator} {$value}";
        $i++;

}
</code>```

However this prints out just one query

```<code>SELECT * FROM table WHERE username = alex AND username = alex
</code>```

I am using PDO so in reality {$value} is replaced by ? and bound elsewhere in the method.  I've just shown it here in full.

答:
```<code>$companyFilter = "";
$auth = getFormulaAuth();
$companyFilter = "AND company_id = {$auth['company_id']} ";
$arguments = func_get_args();

if ($WhereFilterName_xxx) {

} else {
    $db = new Database();
    $this_get_table_form = getFormulaFormDetails($FormName);
    $tbfields_data = Formula::getTBFields($this_get_table_form["id"], $db);

    $q_string = "SELECT * FROM `" . $this_get_table_form["form_table_name"] . "`";
    $valid_param_check = count($arguments) - 2;
    $cache_key = "*";

    if ($valid_param_check >= 1 && $valid_param_check % 3 == 0) {
        $found_indexes = array();
        $q_string_where = " WHERE ";
        $search = " (NOT EXISTS(SELECT * FROM tbtrash_bin WHERE record_id = " . $this_get_table_form["form_table_name"] . ".id
                                        AND form_id = " . $this_get_table_form["id"] . "
                                        AND table_name='" . $this_get_table_form["form_table_name"] . "')) AND ";
        $q_string_where .= $search;
        for ($i = 2; $i < count($arguments); $i+=3) {
            $field_key = $arguments[$i];
            $operator = $arguments[$i + 1];
            $value = $arguments[$i + 2];

            if ($i > 2) {
                $q_string_where .= " AND ";
            }
            $q_string_where .= " `" . $field_key . "` " . $operator;

            if (($tbfields_data["" . $field_key]["field_input_type"] == "Number" || $tbfields_data["" . $field_key]["field_input_type"] == "Currency") || strtoupper($operator) == "IN") {
                $q_string_where .= " " . $value . " ";
            } else {
                $q_string_where .= " '" . $value . "' ";
            }

        $q_string_orderby .= $q_string_where;
        $sort_by = isset($_GET['s']) ? $_GET['s'] : false;

            switch ($sort_by) {
                case $tbfields_data;
                    break;
                default:
                    $sort_by = 'DateCreated';
            }

        $q_string_orderby .= ' ORDER BY '.$sort_by.' ';

        $direction = isset($_GET['d']) ? $_GET['d'] : false;
            if ($direction != 'ASC' && $direction != 'DESC')
                $direction = 'DESC';
            $q_string_orderby .= $direction;

        $res = $db->query($q_string_orderby);
        $results = array();
        if ($res) {
            while ($r = mysql_fetch_assoc($res)) {
                $results[] = $r;
            }
        }

            $cache_key.="::" . $field_key . "::" . $operator . "::" . $value . "::" . $q_string_orderby;
        }

        $q_string .= $q_string_orderby;
    }

    $this_record = Formula::getLookupValue("formula_lookup_where_array", $this_get_table_form, $q_string, $cache_key);
    array_push($GLOBALS['formula_executed_data_collector']['collected_form_id'], array(
        "form_id" => $this_get_table_form['id'],
        "where" => $q_string_where,
        "function_name" => "Total",
        "whole_query" => $q_string
    ));

    $rslt = array_values(array_map(function($a) use($ReturnField) {
                if (gettype($ReturnField) == "array") {
                    $array_collector = array();
                    foreach ($ReturnField as $key => $value) {
                        $array_collector[$value] = $a[$value];
                    }
                    return $array_collector;
                } else if ($ReturnField == "*") {
                    return $a;
                } else {
                    return $a[$ReturnField];
                }
            }, $this_record));
    return $rslt;
}
</code>```

<p>}</p>

Body:
I am trying to write some PHP that fits in to a larger method so that I can dynamically create  a MySQL query.

I haven't included the code to the larger method that contains this code because I think the logic of this bit is self-contained.

So, I have a multi-dimensional array:

$where=array(array('username', 'pid', 'name'), array('=','<=', '='), array('alex',2,'james'));

which when I print_r() shows this structure:

Array
(
[0] => Array
    (
        [0] => username
        [1] => pid
        [2] => name
    )

[1] => Array
    (
        [0] => =
        [1] => <=
        [2] => =
    )

[2] => Array
    (
        [0] => alex
        [1] => 2
        [2] => james
    )

)

What I would like to do if use the first value in each second level array to build up the start of the query such as

SELECT * FROM table WHERE username = alex

and then use the other values to build up the query such as (depending upon the number of items in the arrays)

SELECT * FROM table WHERE username = alex AND pid <= 2 AND name = james

Below is the code I have written

 if (is_array($where[0])){
        $i=0;
        $field = $where[0][$i];
        $operator = $where[1][$i];
        $value= $where[2][$i];
        $sql= "SELECT * FROM table WHERE {$field} {$operator} {$value}";
        while($i=0 ) {
            print $sql;
            $i++;
        }
        while($i>0 AND $i< sizeof($where[0]))
        $field = $where[0][$i];
        $operator = $where[1][$i];
        $value= $where[2][$i];
        print $sql .= " AND {$field} {$operator} {$value}";
        $i++;

}

However this prints out just one query

SELECT * FROM table WHERE username = alex AND username = alex

I am using PDO so in reality {$value} is replaced by ? and bound elsewhere in the method.  I've just shown it here in full.

Body:
$companyFilter = "";
$auth = getFormulaAuth();
$companyFilter = "AND company_id = {$auth['company_id']} ";
$arguments = func_get_args();

if ($WhereFilterName_xxx) {

} else {
    $db = new Database();
    $this_get_table_form = getFormulaFormDetails($FormName);
    $tbfields_data = Formula::getTBFields($this_get_table_form["id"], $db);

    $q_string = "SELECT * FROM `" . $this_get_table_form["form_table_name"] . "`";
    $valid_param_check = count($arguments) - 2;
    $cache_key = "*";

    if ($valid_param_check >= 1 && $valid_param_check % 3 == 0) {
        $found_indexes = array();
        $q_string_where = " WHERE ";
        $search = " (NOT EXISTS(SELECT * FROM tbtrash_bin WHERE record_id = " . $this_get_table_form["form_table_name"] . ".id
                                        AND form_id = " . $this_get_table_form["id"] . "
                                        AND table_name='" . $this_get_table_form["form_table_name"] . "')) AND ";
        $q_string_where .= $search;
        for ($i = 2; $i < count($arguments); $i+=3) {
            $field_key = $arguments[$i];
            $operator = $arguments[$i + 1];
            $value = $arguments[$i + 2];

            if ($i > 2) {
                $q_string_where .= " AND ";
            }
            $q_string_where .= " `" . $field_key . "` " . $operator;

            if (($tbfields_data["" . $field_key]["field_input_type"] == "Number" || $tbfields_data["" . $field_key]["field_input_type"] == "Currency") || strtoupper($operator) == "IN") {
                $q_string_where .= " " . $value . " ";
            } else {
                $q_string_where .= " '" . $value . "' ";
            }

        $q_string_orderby .= $q_string_where;
        $sort_by = isset($_GET['s']) ? $_GET['s'] : false;

            switch ($sort_by) {
                case $tbfields_data;
                    break;
                default:
                    $sort_by = 'DateCreated';
            }

        $q_string_orderby .= ' ORDER BY '.$sort_by.' ';

        $direction = isset($_GET['d']) ? $_GET['d'] : false;
            if ($direction != 'ASC' && $direction != 'DESC')
                $direction = 'DESC';
            $q_string_orderby .= $direction;

        $res = $db->query($q_string_orderby);
        $results = array();
        if ($res) {
            while ($r = mysql_fetch_assoc($res)) {
                $results[] = $r;
            }
        }

            $cache_key.="::" . $field_key . "::" . $operator . "::" . $value . "::" . $q_string_orderby;
        }

        $q_string .= $q_string_orderby;
    }

    $this_record = Formula::getLookupValue("formula_lookup_where_array", $this_get_table_form, $q_string, $cache_key);
    array_push($GLOBALS['formula_executed_data_collector']['collected_form_id'], array(
        "form_id" => $this_get_table_form['id'],
        "where" => $q_string_where,
        "function_name" => "Total",
        "whole_query" => $q_string
    ));

    $rslt = array_values(array_map(function($a) use($ReturnField) {
                if (gettype($ReturnField) == "array") {
                    $array_collector = array();
                    foreach ($ReturnField as $key => $value) {
                        $array_collector[$value] = $a[$value];
                    }
                    return $array_collector;
                } else if ($ReturnField == "*") {
                    return $a;
                } else {
                    return $a[$ReturnField];
                }
            }, $this_record));
    return $rslt;
}

}


答:
Assume you have form with field 'username' and 'password' at HTML:

```<code><form action='login.php' method='post'>
  <input type='text' name='username'>
  <input type='password' name='password'>
  <input type='submit' value='Login'>
</form>
</code>```

after clicking 'Login' button you will run login.php:

```<code><?php
  $allowedUser = 'johnny';
  $allowedPass = 'mypassword';

  session_start();
  if (($_POST['username']!= '') && ($_POST['password'] !=''))
  {
     if (($_POST['username'] == $allowedUser) && ($_POST['username'] ==  $allowedPass))
     $_SESSION['is_loged'] = 1; // session variable will be set when you have allowed credentials
  }
?>
</code>```

Title: Where is the words in ' ' located?

Body:
Assume you have form with field 'username' and 'password' at HTML:

<form action='login.php' method='post'>
  <input type='text' name='username'>
  <input type='password' name='password'>
  <input type='submit' value='Login'>
</form>

after clicking 'Login' button you will run login.php:

<?php
  $allowedUser = 'johnny';
  $allowedPass = 'mypassword';

  session_start();
  if (($_POST['username']!= '') && ($_POST['password'] !=''))
  {
     if (($_POST['username'] == $allowedUser) && ($_POST['username'] ==  $allowedPass))
     $_SESSION['is_loged'] = 1; // session variable will be set when you have allowed credentials
  }
?>


问:
JS expression for a function with a property
Is it possible to write a single expression in ES6 for a function that also has a property?

i.e. is there a simpler way to write the expression after f= without the wrapper?

```<code>f = (function(){
  const f = function(x) { return 2*x; };
  f.foo = 'bar';
  return f;
})();
</code>```

答:
```<code>Object.assign(function(x) { return 2 * x }, {foo: 'bar'})
</code>```

would do it.

Body:
Is it possible to write a single expression in ES6 for a function that also has a property?

i.e. is there a simpler way to write the expression after f= without the wrapper?

f = (function(){
  const f = function(x) { return 2*x; };
  f.foo = 'bar';
  return f;
})();

Body:
Object.assign(function(x) { return 2 * x }, {foo: 'bar'})

would do it.


问:
Setting Android images from string value
Currently I'm drawing a PNG image in my Android application like so:

```<code>ImageView image = new ImageView(context);
image.setImageDrawable(context.getResources().getDrawable(R.drawable.testimage))
</code>```

If I have a list of image names in a database, is there a way to set the drawable above using the image name? I already have the code to go through the database, I'm just looking to draw the image based on the value taken from here.

For example, a record for the DB:

```<code>ID:    Name:    ImageName:
-      Test     testimage
</code>```

So when I'm reading this record, I have a string with the value of "testimage" and I'd then want to set the image drawable to R.drawable.testimage.

One way I was thinking of doing it would be something like this:

```<code>int image = R.drawable.blank; // blank image

// testimage.png is the image name from the database
if(imageName.toString().equals("testimage.png"))
    image = R.drawable.testimage;
else if(imageName.toString().equals("another.png"))
    image = R.drawable.another;
else if(imageName.toString().equals("etc.png"))
    image = R.drawable.etc;
</code>```

However this isn't very efficient!

Thanks

答:
I'm using:

```<code>int resId = getResources().getIdentifier("testimage", "drawable", getPackageName());
image.setImageResource(resId);
</code>```

"testimage" - corresponds to for instance testimage.jpg, i.e. dont include ".jpg"

"drawable" - is the resource type, like in: @drawable/testimage

Check Resources.getIdentifier(...)

Body:
Currently I'm drawing a PNG image in my Android application like so:

ImageView image = new ImageView(context);
image.setImageDrawable(context.getResources().getDrawable(R.drawable.testimage))

If I have a list of image names in a database, is there a way to set the drawable above using the image name? I already have the code to go through the database, I'm just looking to draw the image based on the value taken from here.

For example, a record for the DB:

ID:    Name:    ImageName:
-      Test     testimage

So when I'm reading this record, I have a string with the value of "testimage" and I'd then want to set the image drawable to R.drawable.testimage.

One way I was thinking of doing it would be something like this:

int image = R.drawable.blank; // blank image

// testimage.png is the image name from the database
if(imageName.toString().equals("testimage.png"))
    image = R.drawable.testimage;
else if(imageName.toString().equals("another.png"))
    image = R.drawable.another;
else if(imageName.toString().equals("etc.png"))
    image = R.drawable.etc;

However this isn't very efficient!

Thanks

Body:
I'm using:

int resId = getResources().getIdentifier("testimage", "drawable", getPackageName());
image.setImageResource(resId);

"testimage" - corresponds to for instance testimage.jpg, i.e. dont include ".jpg"

"drawable" - is the resource type, like in: @drawable/testimage

Check Resources.getIdentifier(...)


问:
Set remaining progress bar color in android
I'm setting the color of the progress bar using the following style code

```<code><item android:id="@android:id/progress">
    <clip>
      <shape>
        <corners android:radius="0dip" />
          <gradient
            android:angle="0"
            android:endColor="#36A19C"
            android:startColor="#36A19C" />
      </shape>
    </clip>
  </item>
</code>```

My progressbar looks like below image

How can I set the color of the grey part shown in my progress bar???

答:
Add this line of code to your progress bar XML.

```<code>android:progressBackgroundTint="#ReplaceThisWithYourColor"
</code>```

It works for me.

Body:
I'm setting the color of the progress bar using the following style code

<item android:id="@android:id/progress">
    <clip>
      <shape>
        <corners android:radius="0dip" />
          <gradient
            android:angle="0"
            android:endColor="#36A19C"
            android:startColor="#36A19C" />
      </shape>
    </clip>
  </item>

My progressbar looks like below image

How can I set the color of the grey part shown in my progress bar???

Body:
Add this line of code to your progress bar XML.

android:progressBackgroundTint="#ReplaceThisWithYourColor"

It works for me.


问:
Redirect to https and www with one 301 redirect
all

I want to redirect all requests to land on https://www URL, e.g.

```<code>case1: http://www.example.com --301--> https://www.example.com
case2: https://example.com    --301--> https://www.example.com
case3: http://example.com     --301--> https://www.example.com
</code>```

Here I have my code in .htaccess file

```<code>RewriteCond %{HTTPS} off
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</code>```

It works fine in case 1 and 2. However when I have a http and non-www request (case3), it will require two 301 redirects to land on https://www

```<code>http://example.com
--301-->
https://example.com
--301-->
https://www.example.com
</code>```

How can we force https and www with always just 1 301 redirect.

I am not very familiar with Apache and rewrite module. Help please!

答:
To redirect to https://www in a single request, you can use :</p>

```<code>RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\. [OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
 RewriteRule ^ https://www.%1%{REQUEST_URI} [NE,L,R=301]
</code>```

Body:
all

I want to redirect all requests to land on https://www URL, e.g.

case1: http://www.example.com --301--> https://www.example.com
case2: https://example.com    --301--> https://www.example.com
case3: http://example.com     --301--> https://www.example.com

Here I have my code in .htaccess file

RewriteCond %{HTTPS} off
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

It works fine in case 1 and 2. However when I have a http and non-www request (case3), it will require two 301 redirects to land on https://www

http://example.com
--301-->
https://example.com
--301-->
https://www.example.com

How can we force https and www with always just 1 301 redirect.

I am not very familiar with Apache and rewrite module. Help please!

Body:
To redirect to https://www in a single request, you can use :

RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\. [OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
 RewriteRule ^ https://www.%1%{REQUEST_URI} [NE,L,R=301]


问:
Disable NavBar Translucency in MFMailComposeViewController
My first view is embedded in a navigation controller where I set its translucent property to NO. This gives me the flat green I want, and the status bar a white color. However, when I open an MFMailComposeViewController, the translucent property is set back to YES and the status bar goes back to black.

How do I remove the translucency and set the status bar back to white? Below is my code.

```<code>- (void)viewDidLoad
{
    [super viewDidLoad];

    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];

    self.navigationController.navigationBar.barStyle = UIBarStyleBlackOpaque;
    [self.navigationController.navigationBar setTranslucent:NO];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            NSArray *toRecipents = [NSArray arrayWithObject:@"email goes here"];
            MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
            mc.mailComposeDelegate = self;
            [mc.navigationBar setTintColor:[UIColor whiteColor]];

            [mc.navigationController.navigationBar setTranslucent:NO];

            [mc setSubject:@"Inquiry"];
            [mc setMessageBody:@"Hi, " isHTML:NO];
            [mc setToRecipients:toRecipents];
            [self presentViewController:mc animated:YES completion:NULL];
        }
    }
}
</code>```

答:
This worked for me:</p>

```<code>[[UINavigationBar appearance] setTranslucent:NO];
</code>```

Body:
My first view is embedded in a navigation controller where I set its translucent property to NO. This gives me the flat green I want, and the status bar a white color. However, when I open an MFMailComposeViewController, the translucent property is set back to YES and the status bar goes back to black.

How do I remove the translucency and set the status bar back to white? Below is my code.

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];

    self.navigationController.navigationBar.barStyle = UIBarStyleBlackOpaque;
    [self.navigationController.navigationBar setTranslucent:NO];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            NSArray *toRecipents = [NSArray arrayWithObject:@"email goes here"];
            MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
            mc.mailComposeDelegate = self;
            [mc.navigationBar setTintColor:[UIColor whiteColor]];

            [mc.navigationController.navigationBar setTranslucent:NO];

            [mc setSubject:@"Inquiry"];
            [mc setMessageBody:@"Hi, " isHTML:NO];
            [mc setToRecipients:toRecipents];
            [self presentViewController:mc animated:YES completion:NULL];
        }
    }
}

Body:
This worked for me:

[[UINavigationBar appearance] setTranslucent:NO];


问:
How to avoid data race with GCD DispatchWorkItem.notify?
With Swift 3.1 on XCode 8.3, running the following code with the Thread Sanitizer finds a data race (see the write and read comments in the code):

```<code>  private func incrementAsync() {
    let item = DispatchWorkItem { [weak self] in
      guard let strongSelf = self else { return }
      strongSelf.x += 1 // <--- the write

      // Uncomment following line and there's no race, probably because print introduces a barrier
      //print("> DispatchWorkItem done")
    }
    item.notify(queue: .main) { [weak self] in
      guard let strongSelf = self else { return }
      print("> \(strongSelf.x)") // <--- the read
    }

    DispatchQueue.global(qos: .background).async(execute: item)
  }
</code>```

This seems pretty strange to me as the documentation for the DispatchWorkItem mentions that it allows:

getting notified about their completion

which implies that the notify callback is called once the work item's execution is done.

So I would expect that there would be a happens-before relationship between the DispatchWorkItem's work closure and its notify closure. What would be the correct way, if any, to use a DispatchWorkItem with a registered notify callback like this that wouldn't trigger the Thread Sanitizer error?

I tried registering the notify with item.notify(flags: .barrier, queue: .main) ... but the race persisted (probably because the flag only applies to the same queue, documentation is sparse on what the .barrier flag does). But even calling notify on the same (background) queue as the work item's execution, with the flags: .barrier, results in a race.

If you wanna try this out, I published the complete XCode project on github here: https://github.com/mna/TestDispatchNotify

There's a TestDispatchNotify scheme that builds the app without tsan, and TestDispatchNotify+Tsan with the Thread Sanitizer activated.

Thanks,
Martin

答:
EDIT (2019-01-07): As mentioned by @Rob in a comment on the question, this can't be reproduced anymore with recent versions of Xcode/Foundation (I don't have Xcode installed anymore, I won't guess a version number). There is no workaround required.

Well looks like I found out. Using a DispatchGroup.notify to get notified when the group's dispatched items have completed, instead of DispatchWorkItem.notify, avoids the data race. Here's the same-ish snippet without the data race:

```<code>  private func incrementAsync() {
    let queue = DispatchQueue.global(qos: .background)

    let item = DispatchWorkItem { [weak self] in
      guard let strongSelf = self else { return }
      strongSelf.x += 1
    }

    let group = DispatchGroup()
    group.notify(queue: .main) { [weak self] in
      guard let strongSelf = self else { return }
      print("> \(strongSelf.x)")
    }
    queue.async(group: group, execute: item)
  }
</code>```

So DispatchGroup introduces a happens-before relationship and notify is safely called after the threads (in this case, a single async work item) finished execution, while DispatchWorkItem.notify doesn't offer this guarantee.

Body:
With Swift 3.1 on XCode 8.3, running the following code with the Thread Sanitizer finds a data race (see the write and read comments in the code):

  private func incrementAsync() {
    let item = DispatchWorkItem { [weak self] in
      guard let strongSelf = self else { return }
      strongSelf.x += 1 // <--- the write

      // Uncomment following line and there's no race, probably because print introduces a barrier
      //print("> DispatchWorkItem done")
    }
    item.notify(queue: .main) { [weak self] in
      guard let strongSelf = self else { return }
      print("> \(strongSelf.x)") // <--- the read
    }

    DispatchQueue.global(qos: .background).async(execute: item)
  }

This seems pretty strange to me as the documentation for the DispatchWorkItem mentions that it allows:

getting notified about their completion

which implies that the notify callback is called once the work item's execution is done.

So I would expect that there would be a happens-before relationship between the DispatchWorkItem's work closure and its notify closure. What would be the correct way, if any, to use a DispatchWorkItem with a registered notify callback like this that wouldn't trigger the Thread Sanitizer error?

I tried registering the notify with item.notify(flags: .barrier, queue: .main) ... but the race persisted (probably because the flag only applies to the same queue, documentation is sparse on what the .barrier flag does). But even calling notify on the same (background) queue as the work item's execution, with the flags: .barrier, results in a race.

If you wanna try this out, I published the complete XCode project on github here: https://github.com/mna/TestDispatchNotify

There's a TestDispatchNotify scheme that builds the app without tsan, and TestDispatchNotify+Tsan with the Thread Sanitizer activated.

Thanks,
Martin

Body:
EDIT (2019-01-07): As mentioned by @Rob in a comment on the question, this can't be reproduced anymore with recent versions of Xcode/Foundation (I don't have Xcode installed anymore, I won't guess a version number). There is no workaround required.

Well looks like I found out. Using a DispatchGroup.notify to get notified when the group's dispatched items have completed, instead of DispatchWorkItem.notify, avoids the data race. Here's the same-ish snippet without the data race:

  private func incrementAsync() {
    let queue = DispatchQueue.global(qos: .background)

    let item = DispatchWorkItem { [weak self] in
      guard let strongSelf = self else { return }
      strongSelf.x += 1
    }

    let group = DispatchGroup()
    group.notify(queue: .main) { [weak self] in
      guard let strongSelf = self else { return }
      print("> \(strongSelf.x)")
    }
    queue.async(group: group, execute: item)
  }

So DispatchGroup introduces a happens-before relationship and notify is safely called after the threads (in this case, a single async work item) finished execution, while DispatchWorkItem.notify doesn't offer this guarantee.

ContentLicense: CC BY-SA 4.0


问:
Implementing Tree structures in IPad
How to implement a tree structure in iPad, tree structure which contain parent & child nodes.</p>

答:
You should use tableview for doing this.

Setting the cell indentationLevel property to denote the tree structure. And, it's possible to expand/collapse "tree branches" if you write code to manipulate the cell heights (can be set to zero).

Or else try using a UITableview with UINavigation controller instead.

Title: Implementing Tree structures in IPad


问:
Select records with two data on two columns
I am using postgresql and I have a search function that you can search through ranging the prices. Textbox1 for minimum price and textbox2 for maximum price.

Table :

```<code>CREATE TABLE PRICE_T (ITEM VARCHAR2(255),PRICE_MIN VARCHAR2(6) , PRICE_MAX VARCHAR2(6) );
</code>```

Values :

```<code>INSERT INTO PRICE_T VALUES ('BOTTLE','450', '450');
INSERT INTO PRICE_T VALUES ('GUNDAM','500','600');
INSERT INTO PRICE_T VALUES ('CUP','2700', '4000');
INSERT INTO PRICE_T VALUES ('BEEF','500','700');
</code>```

If I input 0 for price min and 2000 for price max.
All of  these records should appear at output. But I am only getting one.

This is my code :

```<code>SELECT * FROM PRICE_T
WHERE
            (
                0 BETWEEN PRICE_MIN AND PRICE_MAX
            )
        OR  (
                2000 BETWEEN PRICE_MIN AND PRICE_MAX
            )
</code>```

How to select records using two data between two columns?

答:
I think you're confused with your where clause.
It should be

```<code>SELECT * FROM PRICE_T
WHERE
(CAST(PRICE_MIN AS DECIMAL(18,2)) BETWEEN 0 AND 2000)
OR
(CAST(PRICE_MAX AS DECIMAL(18,2)) BETWEEN 0 AND 2000)
</code>```

Why do you have string prices btw

(When you do change your table structure to not have varchar prices, you don't need to cast it to decimal. simply go with

```<code>SELECT * FROM PRICE_T
WHERE
(PRICE_MIN BETWEEN 0 AND 2000)
OR
(PRICE_MAX BETWEEN 0 AND 2000)
</code>```

Body:
I am using postgresql and I have a search function that you can search through ranging the prices. Textbox1 for minimum price and textbox2 for maximum price.

Table :

CREATE TABLE PRICE_T (ITEM VARCHAR2(255),PRICE_MIN VARCHAR2(6) , PRICE_MAX VARCHAR2(6) );

Values :

INSERT INTO PRICE_T VALUES ('BOTTLE','450', '450');
INSERT INTO PRICE_T VALUES ('GUNDAM','500','600');
INSERT INTO PRICE_T VALUES ('CUP','2700', '4000');
INSERT INTO PRICE_T VALUES ('BEEF','500','700');

If I input 0 for price min and 2000 for price max.
All of  these records should appear at output. But I am only getting one.

This is my code :

SELECT * FROM PRICE_T
WHERE
            (
                0 BETWEEN PRICE_MIN AND PRICE_MAX
            )
        OR  (
                2000 BETWEEN PRICE_MIN AND PRICE_MAX
            )

How to select records using two data between two columns?

Body:
I think you're confused with your where clause.
It should be

SELECT * FROM PRICE_T
WHERE
(CAST(PRICE_MIN AS DECIMAL(18,2)) BETWEEN 0 AND 2000)
OR
(CAST(PRICE_MAX AS DECIMAL(18,2)) BETWEEN 0 AND 2000)

Why do you have string prices btw

(When you do change your table structure to not have varchar prices, you don't need to cast it to decimal. simply go with

SELECT * FROM PRICE_T
WHERE
(PRICE_MIN BETWEEN 0 AND 2000)
OR
(PRICE_MAX BETWEEN 0 AND 2000)


问:
Referencing objects in java
In java, what is the difference between following 2 usage,

```<code>Employee e1 = new Employee();
1.Employee e2 = (Employee)e1.clone();
2.Employee e2 = e1;
</code>```

In second case, I think e2 reference to the object that e1 also reference. So, they have the same same object with different reference number(may be memory address).

How about first case? Do e1 and e2 have both different object and reference?

答:
In the first case you are instantiating a new object and store the reference in e1.

suppose you are changing the salary in this next step e1.setSalary(10000);

then if e1 object is cloned,
Employee e2 = (Employee)e1.clone(); a new instance with salary as current value stored in e1 will be saved.
basically e2 will be a new instance of Employee Class and whose salary is 10000

if you later change the salary of e2 it won't affect e1.
e.g.. e2.setSalary(2000); then salary in e1 would remain the same e1 -> 10000 whereas for e2 -> 2000

In the third step, you are referencing e1 to e2,i.e. e2 would point to an instance which was referenced by e1, e1 and e2 would point to same instance... so the cloned object will be like object without reference which is eligible for gc to act upon

For getting to know more about clone, you could refer this post https://stackoverflow.com/a/9834683

Title: Referencing objects in java

Body:
In java, what is the difference between following 2 usage,

Employee e1 = new Employee();
1.Employee e2 = (Employee)e1.clone();
2.Employee e2 = e1;

In second case, I think e2 reference to the object that e1 also reference. So, they have the same same object with different reference number(may be memory address).

How about first case? Do e1 and e2 have both different object and reference?


问:
Invert an array of booleans in JavaScript
I am trying to invert the values of a string of boolean values so that instead  of

inverted([true, false, true, false, true])

it is  [false, true, false, true, false]

So far I have come up with this:

```<code>function inverted(bools) {
    var inversion = [];
    var string= [];
    while(!bools) {
      string.push(bools);
    }
    return inversion;
}
</code>```

But my code is not working, any and all help will be much appreciated!

答:
Though many answers here are already great, I thought I would chip in my "golfed" regex solution:

function inverted (b) {
 return b.map(/f/.test, /f/)
}

console.log(
  inverted([true, false, true, false])
)```

Body:
I am trying to invert the values of a string of boolean values so that instead  of

inverted([true, false, true, false, true])

it is  [false, true, false, true, false]

So far I have come up with this:

function inverted(bools) {
    var inversion = [];
    var string= [];
    while(!bools) {
      string.push(bools);
    }
    return inversion;
}

But my code is not working, any and all help will be much appreciated!


问:
Cant figure out how to sort list by these criteria
Basically I have an arraylist of  objects which have a name and startDate and they are in a similar initial order to :

Frank 10/20/1990

Bill 1/2/1990

Frank 2/2/1990

John 9/8/1990

Bill 4/4/1990

Frank 5/1/1990

I'm trying to order them such that for each new customer name declared, all of the customer objects with the same name must be placed next to each other in ascending order of their dates, so the final sorted list should look like:

Frank 1/1/1990

Frank 5/1/1990

Frank 10/20/1990

Bill 1/2/1990

Bill 4/4/1990

John 9/8/1990

I've been trying to figure it out for a few hours to no avail, hopefully someone can help me thanks in advance!

答:
Java collections framework does not have a sorted list, so this answer gives you a way to sort a given unsorted list.  If you want to actually maintain a sorted collection, then you can look into things like a SortedSet such as TreeSet.

You can define a custom comparator for the class containing the name and date (let's call it Wrapper), and then sort the list using it:

```<code>public static Comparator<Wrapper> wrapperComparator
                      = new Comparator<Wrapper>() {

    public int compare(Wrapper w1, Wrapper w2) {
        if (w1 == null && w2 == null) {
            return -0;
        }
        else if (w1 == null && w2 != null) {
            return 1;
        }
        else if (w1 != null && w2 == null) {
            return -1;
        }
        else if (w1.getName().equals(w2.getName()) {
            return w1.getDate().compareTo(w2.getDate());
        }
        else {
            return w1.getName().compareTo(w2.getName());
        }
    }
};
</code>```

Now use this custom comparator to sort your list with the Collections.sort utility.

```<code>Collections.sort(yourList, wrapperComparator);
</code>```

Note that I have made some assumptions here.  I assume that your list might have null values, in which case I treat nulls as being greater than any other value.  I also assume that a given Wrapper object will never have null names or dates.  If this isn't the case, you'll have to add some null checks to the above code.

Body:
Java collections framework does not have a sorted list, so this answer gives you a way to sort a given unsorted list.  If you want to actually maintain a sorted collection, then you can look into things like a SortedSet such as TreeSet.

You can define a custom comparator for the class containing the name and date (let's call it Wrapper), and then sort the list using it:

public static Comparator<Wrapper> wrapperComparator
                      = new Comparator<Wrapper>() {

    public int compare(Wrapper w1, Wrapper w2) {
        if (w1 == null && w2 == null) {
            return -0;
        }
        else if (w1 == null && w2 != null) {
            return 1;
        }
        else if (w1 != null && w2 == null) {
            return -1;
        }
        else if (w1.getName().equals(w2.getName()) {
            return w1.getDate().compareTo(w2.getDate());
        }
        else {
            return w1.getName().compareTo(w2.getName());
        }
    }
};

Now use this custom comparator to sort your list with the Collections.sort utility.

Collections.sort(yourList, wrapperComparator);

Note that I have made some assumptions here.  I assume that your list might have null values, in which case I treat nulls as being greater than any other value.  I also assume that a given Wrapper object will never have null names or dates.  If this isn't the case, you'll have to add some null checks to the above code.


问:
jquery attributes from multiple elements
I am trying ot figure how to use jQuery to get the value of html attribute of many elements. My webpage updates dynamically using ajax. I have an attribute called number for in element in the part that is updated. I want to use the attribute value from each element so that i can use that data as parameters to a php file link. I have come across jquery's .attr() function, but it only seems to take the attribute value of the first element if finds. But what I want to do is get the attribute value for each element so that when I click on that element its corresponding attribute value is sent as parameters to the php file.

Thanks

答:
Inside a click handler (or any event handler), this will refer to that element, for example:

```<code>$("#content").delegate("a", "click", function() {
  alert($(this).attr("something")); //alerts "something" for the <a> you clicked
});
</code>```

In this case we're using .delegate() because you said "My webpage updates dynamically using ajax", so just attach the handler to a parent element that's not replaced via AJAX and it'll work for all elements you add beneath...in the example above we're binding to all  elements, but just change the selector accordingly.

Body:
Inside a click handler (or any event handler), this will refer to that element, for example:

$("#content").delegate("a", "click", function() {
  alert($(this).attr("something")); //alerts "something" for the <a> you clicked
});

In this case we're using .delegate() because you said "My webpage updates dynamically using ajax", so just attach the handler to a parent element that's not replaced via AJAX and it'll work for all elements you add beneath...in the example above we're binding to all <a> elements, but just change the selector accordingly.


问:
Unable to upload file in EC2 using PHP move_uploaded_file
I am trying to upload a zip file in EC2 suing PHP.

```<code>$count = 0;
    if ($_SERVER['REQUEST_METHOD'] == 'POST'){
        foreach ($_FILES['files']['name'] as $i => $name) {
            if (strlen($_FILES['files']['name'][$i]) > 1) {
                if (move_uploaded_file($_FILES['files']['tmp_name'][$i], $dirPath.strtolower($name))) {
                    $count++;
                }else{
                die ("not success no file sorry in move_upload" . $dirPath.strtolower($name) . "  ". $numFiles . " ".$count);
              }
            }else{
              die ("not success no file sorry in strlen" . $numFiles . " ".$count);
            }
        }
    }else{
      die ("not success no file sorry" . $numFiles . " ".$count);
    }
</code>```

This code failed at if (move_uploaded_file, $_FILES is OK. but the problem is in move_uploaded_file.

my ps aux | grep apache  output is

```<code>apache   23762  0.0  3.1 570272 32488 ?        Sl   Mar29   0:14 /usr/sbin/httpd
apache   26487  0.0  2.7 565912 27628 ?        Sl   Mar30   0:08 /usr/sbin/httpd
apache   26488  0.0  3.3 572044 34396 ?        Sl   Mar30   0:08 /usr/sbin/httpd
apache   27416  0.0  2.7 762324 28080 ?        Sl   Mar30   0:07 /usr/sbin/httpd
apache   27838  0.0  2.5 563948 26104 ?        Sl   Mar30   0:06 /usr/sbin/httpd
apache   27839  0.0  2.7 566384 28124 ?        Sl   Mar30   0:06 /usr/sbin/httpd
apache   28124  0.0  2.3 560860 23472 ?        Sl   Mar30   0:05 /usr/sbin/httpd
apache   28173  0.0  1.9 455504 20160 ?        Sl   Mar30   0:04 /usr/sbin/httpd
apache   28175  0.0  1.9 455504 20168 ?        Sl   Mar30   0:04 /usr/sbin/httpd
apache   28176  0.0  1.9 455504 20200 ?        Sl   Mar30   0:04 /usr/sbin/httpd
ec2-user 31044  0.0  0.2 110460  2192 pts/0    S+   01:47   0:00 grep --color=auto apache
</code>```

I tried to sudo chown -R ec2-user /var/www/html  but stll upload fails.

Please help. The same PHP upload code works on other shared hosting providers. This php file is getting called by Jquery Ajax.

答:
I think the problem is $dirPath.strtolower($name).

```<code>if (move_uploaded_file($_FILES['files']['tmp_name'][$i], $dirPath.strtolower($name))) {
</code>```

As I known, you you must write: strtolower($dirPath . $name)

```<code>if (move_uploaded_file($_FILES['files']['tmp_name'][$i], strtolower($dirPath . $name))) {
</code>```

An in all other code, you must change this!

Body:
I am trying to upload a zip file in EC2 suing PHP.

$count = 0;
    if ($_SERVER['REQUEST_METHOD'] == 'POST'){
        foreach ($_FILES['files']['name'] as $i => $name) {
            if (strlen($_FILES['files']['name'][$i]) > 1) {
                if (move_uploaded_file($_FILES['files']['tmp_name'][$i], $dirPath.strtolower($name))) {
                    $count++;
                }else{
                die ("not success no file sorry in move_upload" . $dirPath.strtolower($name) . "  ". $numFiles . " ".$count);
              }
            }else{
              die ("not success no file sorry in strlen" . $numFiles . " ".$count);
            }
        }
    }else{
      die ("not success no file sorry" . $numFiles . " ".$count);
    }

This code failed at if (move_uploaded_file, $_FILES is OK. but the problem is in move_uploaded_file.

my ps aux | grep apache  output is

apache   23762  0.0  3.1 570272 32488 ?        Sl   Mar29   0:14 /usr/sbin/httpd
apache   26487  0.0  2.7 565912 27628 ?        Sl   Mar30   0:08 /usr/sbin/httpd
apache   26488  0.0  3.3 572044 34396 ?        Sl   Mar30   0:08 /usr/sbin/httpd
apache   27416  0.0  2.7 762324 28080 ?        Sl   Mar30   0:07 /usr/sbin/httpd
apache   27838  0.0  2.5 563948 26104 ?        Sl   Mar30   0:06 /usr/sbin/httpd
apache   27839  0.0  2.7 566384 28124 ?        Sl   Mar30   0:06 /usr/sbin/httpd
apache   28124  0.0  2.3 560860 23472 ?        Sl   Mar30   0:05 /usr/sbin/httpd
apache   28173  0.0  1.9 455504 20160 ?        Sl   Mar30   0:04 /usr/sbin/httpd
apache   28175  0.0  1.9 455504 20168 ?        Sl   Mar30   0:04 /usr/sbin/httpd
apache   28176  0.0  1.9 455504 20200 ?        Sl   Mar30   0:04 /usr/sbin/httpd
ec2-user 31044  0.0  0.2 110460  2192 pts/0    S+   01:47   0:00 grep --color=auto apache

I tried to sudo chown -R ec2-user /var/www/html  but stll upload fails.

Please help. The same PHP upload code works on other shared hosting providers. This php file is getting called by Jquery Ajax.

Body:
I think the problem is $dirPath.strtolower($name).

if (move_uploaded_file($_FILES['files']['tmp_name'][$i], $dirPath.strtolower($name))) {

As I known, you you must write: strtolower($dirPath . $name)

if (move_uploaded_file($_FILES['files']['tmp_name'][$i], strtolower($dirPath . $name))) {

An in all other code, you must change this!


问:
Android - Custom EditText with different input types
I'm trying to make a custom EditText for currency which means I need to have a prefix of it for the currency and I have to limit users' input to numbers only.

This is my custom EditText code

```<code>public OpenSansEditText(Context context, AttributeSet attrs) {
    super(context, attrs);
    paint = getPaint();
    applyCustomFont(context, attrs);
}

public OpenSansEditText(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    paint = getPaint();
    applyCustomFont(context, attrs);
}

private void applyCustomFont(Context context, AttributeSet attrs) {
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.OpenSansET);

    ...

    // Prefix
    String prefix = a.getString(R.styleable.OpenSansET_prefix);
    if (prefix != null) {
        mPrefix = prefix;
    } else {
        mPrefix = "";
    }

    // Prefix Color
    int prefixColor = a.getColor(R.styleable.OpenSansET_prefixColor, 0);
    if (prefix != null) {
        mPrefixColor = prefixColor;
    } else {
        mPrefixColor = ContextCompat.getColor(context, R.color.miBlack);
    }

    a.recycle();
}

...
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    if (!mPrefix.equals("")) {
        getPaint().getTextBounds(mPrefix, 0, mPrefix.length(), mPrefixRect);
        mPrefixRect.right += getPaint().measureText(" "); // add some offset
    }

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    if (!mPrefix.equals("")) {
        paint.setColor(mPrefixColor);
        canvas.drawText(mPrefix, super.getCompoundPaddingLeft(), getBaseline(), paint);
    }
}

@Override
public int getCompoundPaddingLeft() {
    return mPrefix.equals("") ? super.getCompoundPaddingLeft()
            : super.getCompoundPaddingLeft() + mPrefixRect.width();
}
</code>```

This is how I use it in xml :

```<code><com.asta.www.classes.OpenSansEditText
    android:id="@+id/shopping_filter_priceMinRange"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="0.4"
    android:gravity="center"
    android:hint="@string/min"
    android:textColor="@color/miBlack"
    android:textColorHint="@color/miGrey"
    app:prefix="$"
    app:prefixColor="@color/miBlack" />

<com.asta.www.classes.OpenSansEditText
    android:id="@+id/shopping_filter_priceMaxRange"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="0.4"
    android:gravity="center"
    android:hint="@string/max"
    android:inputType="number"
    android:textColorHint="@color/miGrey"
    app:prefix="$"
    app:prefixColor="@color/miBlack" />
</code>```

Which yields :

Only the first one without inputType as number has the currency sign shown, whereas the second ET doesn't have its currency sign shown.

How to achieve currency prefix as text and still keeping inputType to numbers only for user? And I don't want to use two views, namely EditText and TextView to left of it, both inside a ViewGroup to achieve that.

答:
In the end I found this link https://gist.github.com/kennydude/5407963 which helps me in the right direction. So what it does is I think making the prefix as Drawable using this class :

```<code>private class TagDrawable extends Drawable {

    public String text = "";

    public void setText(String s){
        text = s;

        // Tell it we need to be as big as we want to be!
        setBounds(0,0,getIntrinsicWidth(),getIntrinsicHeight());

        invalidateSelf();
    }

    @Override
    public void draw(@NonNull Canvas canvas) {
        // I don't know why this y works here, but it does :)
        // (aka if you are from Google/are Jake Wharton and I have done it wrong, please tell me!)
        canvas.drawText( text, 0, mLine0Baseline + canvas.getClipBounds().top, mTextPaint );
    }

    @Override public void setAlpha(int i) {}
    @Override public void setColorFilter(ColorFilter colorFilter) {}
    @Override public int getOpacity() {return PixelFormat.UNKNOWN;}

    @Override public int getIntrinsicHeight (){
        return (int)mFontHeight;
    }
    @Override public int getIntrinsicWidth(){
        return (int)mTextPaint.measureText( text );
    }
}
</code>```

And draw it to the left of the TextView like

```<code>TagDrawable left = new TagDrawable();
left.setText("$");
setCompoundDrawablesRelative(left, null, null, null);
</code>```

The link I supplied even has suffix support which I haven't tried.

Body:
I'm trying to make a custom EditText for currency which means I need to have a prefix of it for the currency and I have to limit users' input to numbers only.

This is my custom EditText code

public OpenSansEditText(Context context, AttributeSet attrs) {
    super(context, attrs);
    paint = getPaint();
    applyCustomFont(context, attrs);
}

public OpenSansEditText(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    paint = getPaint();
    applyCustomFont(context, attrs);
}

private void applyCustomFont(Context context, AttributeSet attrs) {
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.OpenSansET);

    ...

    // Prefix
    String prefix = a.getString(R.styleable.OpenSansET_prefix);
    if (prefix != null) {
        mPrefix = prefix;
    } else {
        mPrefix = "";
    }

    // Prefix Color
    int prefixColor = a.getColor(R.styleable.OpenSansET_prefixColor, 0);
    if (prefix != null) {
        mPrefixColor = prefixColor;
    } else {
        mPrefixColor = ContextCompat.getColor(context, R.color.miBlack);
    }

    a.recycle();
}

...
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    if (!mPrefix.equals("")) {
        getPaint().getTextBounds(mPrefix, 0, mPrefix.length(), mPrefixRect);
        mPrefixRect.right += getPaint().measureText(" "); // add some offset
    }

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    if (!mPrefix.equals("")) {
        paint.setColor(mPrefixColor);
        canvas.drawText(mPrefix, super.getCompoundPaddingLeft(), getBaseline(), paint);
    }
}

@Override
public int getCompoundPaddingLeft() {
    return mPrefix.equals("") ? super.getCompoundPaddingLeft()
            : super.getCompoundPaddingLeft() + mPrefixRect.width();
}

This is how I use it in xml :

<com.asta.www.classes.OpenSansEditText
    android:id="@+id/shopping_filter_priceMinRange"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="0.4"
    android:gravity="center"
    android:hint="@string/min"
    android:textColor="@color/miBlack"
    android:textColorHint="@color/miGrey"
    app:prefix="$"
    app:prefixColor="@color/miBlack" />

<com.asta.www.classes.OpenSansEditText
    android:id="@+id/shopping_filter_priceMaxRange"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="0.4"
    android:gravity="center"
    android:hint="@string/max"
    android:inputType="number"
    android:textColorHint="@color/miGrey"
    app:prefix="$"
    app:prefixColor="@color/miBlack" />

Which yields :

Only the first one without inputType as number has the currency sign shown, whereas the second ET doesn't have its currency sign shown.

How to achieve currency prefix as text and still keeping inputType to numbers only for user? And I don't want to use two views, namely EditText and TextView to left of it, both inside a ViewGroup to achieve that.

Body:
In the end I found this link https://gist.github.com/kennydude/5407963 which helps me in the right direction. So what it does is I think making the prefix as Drawable using this class :

private class TagDrawable extends Drawable {

    public String text = "";

    public void setText(String s){
        text = s;

        // Tell it we need to be as big as we want to be!
        setBounds(0,0,getIntrinsicWidth(),getIntrinsicHeight());

        invalidateSelf();
    }

    @Override
    public void draw(@NonNull Canvas canvas) {
        // I don't know why this y works here, but it does :)
        // (aka if you are from Google/are Jake Wharton and I have done it wrong, please tell me!)
        canvas.drawText( text, 0, mLine0Baseline + canvas.getClipBounds().top, mTextPaint );
    }

    @Override public void setAlpha(int i) {}
    @Override public void setColorFilter(ColorFilter colorFilter) {}
    @Override public int getOpacity() {return PixelFormat.UNKNOWN;}

    @Override public int getIntrinsicHeight (){
        return (int)mFontHeight;
    }
    @Override public int getIntrinsicWidth(){
        return (int)mTextPaint.measureText( text );
    }
}

And draw it to the left of the TextView like

TagDrawable left = new TagDrawable();
left.setText("$");
setCompoundDrawablesRelative(left, null, null, null);

The link I supplied even has suffix support which I haven't tried.


问:
Should WebException.Response.GetResponseStream() be close / disposed?
When I catch a .NET WebException, should I close / dispose the Response.GetResponseStream()?

The MSDN example does not close or dispose anything in the exception.

Many SO answers recommend disposing the response and / or the stream.

I disposed the stream and this caused big problems. Because GetResponseStream() (always? / sometimes?) returns the same instance. So when I get the response stream and then dispose it, then maybe rethrow the exception to another layer that also gets the response stream it will be already disposed and unreadable and throw more exceptions because of that.

答:
A short answer is that you don't have to dispose it although it is a good exercise to dispose any IDisposable objects that you own.

In fact, trying to dispose WebException.Response or the stream returned from it would cause problems you mentioned since you may encounter code attempting to read its properties in upper call chain's exception handler.

The reason why it is safe not to dispose it is because HttpWebRequest internally makes a memory stream from the network stream before it throws WebException, and the underlying network stream has already been closed/disposed. So it doesn't really have any unmanaged resource associated at that point. This I assume was a decision to make it easier to handle the exception.

Unfortunately MSDN documentation doesn't have any explanation about this behavior. Technically the implementation can change in future causing problem to your code not disposing the HttpWebResponse and/or associated stream you get from WebException, but it is highly unlikely that this behavior would change the implementation given many applications depend on current behavior.

I have to add though that it is a good practice that you should dispose IDisposable objects you own. If possible, use HttpClient class instead so that you don't have to deal with this situation at all. If you can't, consider handling the WebException yourself and throw new type of exception that does not expose WebException to the caller of your code so that you don't run into a situation where a caller is trying to access WebException.Response after you dispose it.

Disclaimer: I work for Microsoft, but this does not represent my employer or .NET Framework team's view. No warranty implied.


问:
How to deploy an SQL Compact Edition database file (.sdf) in the AppData folder? Connection string?
I'm planning to deploy my DB file in the Users\CurrentUserName\AppData folder, because default User Account Control settings restrict write access to the Program Files directory where my program is installed.

First question - is this correct?

So far, I've created a custom folder, set the DefaultLocation property to [LocalAppDataFolder][ProductName], and put the .sdf file in that folder.

This works in Windows 7, but it doesn't seem to work in Windows XP - I can't find any sign of it being deployed anywhere.

So where and how should I deploy the DB file?

I'm also unsure how to set the connection string to the [LocalAppDataFolder] location - any suggestions?

Edit:  The application is a WinForms application which will be downloaded from a website and installed using the installer created with Setup Project.

答:
This works for me:</p>

```<code>string fileName = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "SqlCe35AddinStore.sdf");

string connString = string.Format("Data Source={0};", fileName);
</code>```

Body:
This works for me:

string fileName = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "SqlCe35AddinStore.sdf");

string connString = string.Format("Data Source={0};", fileName);