问:
Flash Builder 4 - using relative paths with the -output (-o) compiler argument
I'm trying to use a relative path in the -output compiler argument, here's what I've tried (with and without quotes):

```<code>-o="./deploy/file.swf"

-o="/./deploy/file.swf"

-o="./file.swf"

-o="/./file.swf"

-o="file.swf"

-o="file.swf"
</code>```

None of these attempts yields a new file, it's as if they are ignored. The deploy directory is in the root of my project directory. If I use an absolute path, it works great, but the project is less portable. Any help is greatly appreciated. Thanks in advance.

答: Not a good answer, but ANT allows you to create absolute paths from relative ones.</p>

Body:
I'm trying to use a relative path in the -output compiler argument, here's what I've tried (with and without quotes):

-o="./deploy/file.swf"

-o="/./deploy/file.swf"

-o="./file.swf"

-o="/./file.swf"

-o="file.swf"

-o="file.swf"

None of these attempts yields a new file, it's as if they are ignored. The deploy directory is in the root of my project directory. If I use an absolute path, it works great, but the project is less portable. Any help is greatly appreciated. Thanks in advance.


来源: stackexchange

问:
How to stop consuming message from selective queue - RabbitMQ - Javascript/node
I am building a REST-amqp sample in which I get messages from a given queue in rabbitmq and I send the messages back to the client via REST.

I have implemented the code following rabbitmq tutorial for node.js

```<code>var amqp = require('amqplib/callback_api');
amqp.connect('amqp://192.168.225.203:5672', function (err, conn) {
conn.createChannel(function (err, ch) {
    var q = 'aQueue';
    ch.assertQueue(q, { durable: false });
    var messages = [];
    console.log(" [*] Waiting for messages in %s. To exit press CTRL+C", q);
    ch.consume(q, function (msg) {
        console.log(" [x] Received %s", msg.content.toString());
        messages.push(msg.content.toString());
        messages.forEach(function(element) {
            console.log(element);
        });
    }, { noAck: true });
});
</code>```

});

I can consolidate all messages in an array (messages) but this function runs till the application is stopped, which is not a good thing as the REST client will wait forever....
I would like to stop the function and move on with the program when the queue is empty or after a period of time (2secs) if the first option is not possible.
I found the same problem solved in Java but not in JS.

Any hint is much appreciated.

Cheers, Giovanni

答:
You can use connection#close to stop the connection altogether and build up a new one on-demand.

However, you still need to detect when to terminate the connection.

May I ask what exactly the motivation behind this is? HTTP/REST and message queues are inherently different. Sending a message based on an HTTP request is one thing; receiving message for a certain request is definitely a place I would not go voluntarily.

ContentLicense: CC BY-SA 3.0

Body:
I am building a REST-amqp sample in which I get messages from a given queue in rabbitmq and I send the messages back to the client via REST.

I have implemented the code following rabbitmq tutorial for node.js

var amqp = require('amqplib/callback_api');
amqp.connect('amqp://192.168.225.203:5672', function (err, conn) {
conn.createChannel(function (err, ch) {
    var q = 'aQueue';
    ch.assertQueue(q, { durable: false });
    var messages = [];
    console.log(" [*] Waiting for messages in %s. To exit press CTRL+C", q);
    ch.consume(q, function (msg) {
        console.log(" [x] Received %s", msg.content.toString());
        messages.push(msg.content.toString());
        messages.forEach(function(element) {
            console.log(element);
        });
    }, { noAck: true });
});

});

I can consolidate all messages in an array (messages) but this function runs till the application is stopped, which is not a good thing as the REST client will wait forever....
I would like to stop the function and move on with the program when the queue is empty or after a period of time (2secs) if the first option is not possible.
I found the same problem solved in Java but not in JS.

Any hint is much appreciated.

Cheers, Giovanni


问:
Reduce multiple calls to a greedy method
I have the following JSF 2.0 beans:

```<code>@ApplicationScoped
class GreedyBean {
  Result doGreedyStuff(String userId) {
    ... // Takes lots of machine resources and time.
  }
}

@SessionScoped
class MyPageBean {
  String userId;
  GreedyBean greedyBean;
  String getFirstGreedyStuffStat() {
    Result result = greedyBean.doGreedyStuff(userId);
    return result.getString();
  }
  int getSecondGreedyStuffStat() {
    Result result = greedyBean.doGreedyStuff(userId);
    return result.getInt();
  }
  void setGreedyBean(GreedyBean greedyBean) { this.greedyBean = greedyBean; }
}
</code>```

Then in my JSF page:

```<code><h:outputText value="#{myPageBean.firstGreedyStuffStat}"/>
<h:outputText value="#{myPageBean.secondGreedyStuffStat}"/>
</code>```

How do I refactor this to have only one call to GreedyBean::doGreedyStuff without implementing a cache mechanism by myself? If JSF can't do that, saying so is a valid answer.

Notes:

I have barely any knowledge in JSF: I'm only fixing this one bug and then I resume my usual other tasks.

We use Spring for the injection, I tried to translate those in JSF annotation. If there's an error there, please indulge me.

As @JasperdeVries mentioned, I can't put the call in the @PostConstruct of MyPageBean because the data wouldn't be up to date. The result should be up to date at the moment of the request, not at the start of the session. I understand the principle and will enforce it, though it doesn't help me in this situation.

答:
From @JasperdeVries' explanations, I need to add a new request-scoped bean:

GreedyBean.java

```<code>@ApplicationScoped
class GreedyBean {
  Result doGreedyStuff(String userId) {
    ... // Takes lots of machine resources and time.
  }
}
</code>```

MyPageBean.java (should be renamed to something about the session, not the page)

```<code>@SessionScoped
class MyPageBean {
  String userId;
  String getUserId() { return userId; }
}
</code>```

MyPageRequestBean.java

```<code>@RequestScoped
class MyPageRequestBean {
  // Beans
  MyPageBean myPageBean;
  GreedyBean greedyBean;

  // Data
  String firstGreedyStat;
  int secondGreedyStat;

  @PostConstruct
  public void init() {
    Result result = greedyBean.doGreedyStuff(myPageBean.getUserId());
    firstGreedyStat = result.getString();
    secondGreedyStat = result.getInt();
  }

  String getFirstGreedyStat() { return firstGreedyStat; }
  int getSecondGreedyStat() { return secondGreedyStat; }

  void setMyPageBean(MyPageBean myPageBean) { this.myPageBean = myPageBean; }
  void setGreedyBean(GreedyBean greedyBean) { this.greedyBean = greedyBean; }
}
</code>```

myPage.xhtml

```<code><h:outputText value="#{myPageRequestBean.firstGreedyStuffStat}"/>
<h:outputText value="#{myPageRequestBean.secondGreedyStuffStat}"/>
</code>```

Body:
I have the following JSF 2.0 beans:

@ApplicationScoped
class GreedyBean {
  Result doGreedyStuff(String userId) {
    ... // Takes lots of machine resources and time.
  }
}

@SessionScoped
class MyPageBean {
  String userId;
  GreedyBean greedyBean;
  String getFirstGreedyStuffStat() {
    Result result = greedyBean.doGreedyStuff(userId);
    return result.getString();
  }
  int getSecondGreedyStuffStat() {
    Result result = greedyBean.doGreedyStuff(userId);
    return result.getInt();
  }
  void setGreedyBean(GreedyBean greedyBean) { this.greedyBean = greedyBean; }
}

Then in my JSF page:

<h:outputText value="#{myPageBean.firstGreedyStuffStat}"/>
<h:outputText value="#{myPageBean.secondGreedyStuffStat}"/>

How do I refactor this to have only one call to GreedyBean::doGreedyStuff without implementing a cache mechanism by myself? If JSF can't do that, saying so is a valid answer.

Notes:

I have barely any knowledge in JSF: I'm only fixing this one bug and then I resume my usual other tasks.

We use Spring for the injection, I tried to translate those in JSF annotation. If there's an error there, please indulge me.

As @JasperdeVries mentioned, I can't put the call in the @PostConstruct of MyPageBean because the data wouldn't be up to date. The result should be up to date at the moment of the request, not at the start of the session. I understand the principle and will enforce it, though it doesn't help me in this situation.

Body:
From @JasperdeVries' explanations, I need to add a new request-scoped bean:

GreedyBean.java

@ApplicationScoped
class GreedyBean {
  Result doGreedyStuff(String userId) {
    ... // Takes lots of machine resources and time.
  }
}

MyPageBean.java (should be renamed to something about the session, not the page)

@SessionScoped
class MyPageBean {
  String userId;
  String getUserId() { return userId; }
}

MyPageRequestBean.java

@RequestScoped
class MyPageRequestBean {
  // Beans
  MyPageBean myPageBean;
  GreedyBean greedyBean;

  // Data
  String firstGreedyStat;
  int secondGreedyStat;

  @PostConstruct
  public void init() {
    Result result = greedyBean.doGreedyStuff(myPageBean.getUserId());
    firstGreedyStat = result.getString();
    secondGreedyStat = result.getInt();
  }

  String getFirstGreedyStat() { return firstGreedyStat; }
  int getSecondGreedyStat() { return secondGreedyStat; }

  void setMyPageBean(MyPageBean myPageBean) { this.myPageBean = myPageBean; }
  void setGreedyBean(GreedyBean greedyBean) { this.greedyBean = greedyBean; }
}

myPage.xhtml

<h:outputText value="#{myPageRequestBean.firstGreedyStuffStat}"/>
<h:outputText value="#{myPageRequestBean.secondGreedyStuffStat}"/>


问:
How to retrieve correct value of date only field in SharePoint 2013 workflow
I am fairly new to SharePoint 2013 workflows with years of general C# and other SharePoint experience.

My problem is with timezones. I am developing a list workflow in Visual Studio 2013 which has to take some actions based on the value of a date only field of the current item in the list. I am retrieving the value of this field using GetDynamicValueProperties and assign it to a variable. However if I check this value, I can see that it is not correct as it is 23:00 on the day before the one I actually set for the list item. I am assuming this is because no matter being a date only field, behind the scenes it is still being stored in a regular DateTime object.

Because of this, all my date calculations are 1 day off (because I only use the date part). I have noticed that all the timezone specific classes and methods cannot be used within the workflow.

Is there any way I can correctly retrieve only the date part of this field value without hardcoding any offsets? I am preferably looking for a solution which does not include workarounds and hacks and works in all environments.

Background information: I have to execute tasks n days before this date at a given time (e.g. 8 AM). The second part is tricky too, as the time part will also be 1 hour off because of this. I am looking for a solution for this too.

答:
Managed to solve it calling the appropriate SharePoint REST API endpoints in an HttpSend activity.

SPTimeZone.utcToLocalTime endpoint

SPTimeZone.localTimeToUTC endpoint

I am passing the original date as an url parameter and receive the converted date in a JSON object which can easily be parsed in the workflow. The conversion occurrs according to the site collection regional settings.

Note: when converting from local to UTC, the result string contains the "Z" character at the end, indicating that it is indeed a UTC date. When parsing the whole string as a DateTime in the workflow, it converts it back to the original date because of this. I have cut the last character using the String.Substring method, and it is working fine now.


问:
android studio 2.3 instant run not working
I have updated android studio from 2.2 to 2.3,then I found Instant run not working.

Error while executing: am startservice com.example.codingmaster.testcc/com.android.tools.fd.runtime.InstantRunService
      Starting service: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.example.codingmaster.testcc/com.android.tools.fd.runtime.InstantRunService }
      Error: Not found; no service started.

I also try reinstall android studio 2.3 but not work.

答:
I was facing to the same issue too with an Asus phone.

```<code>Error while executing: am startservice com.eyelights.android/com.android.tools.fd.runtime.InstantRunService
Starting service: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.myapp.android/com.android.tools.fd.runtime.InstantRunService }
Error: Not found; no service started.
</code>```

Thanks to this post, i was able to start my app again :

https://code.google.com/p/android/issues/detail?id=235879

Go in Android Studio Preferences :

Disable Instant Run like this :

Now you can run your app again. Don't forget to enable again Instant run when you switch phone.

It's not the perfect solution, but it's working

```<code>$ adb shell am start -n "com.myapp.android/com.myapp.android.activity.SplashScreenActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 16367 on device asus-asus_z00ed-F9AZCY208273
</code>```

Body:
I was facing to the same issue too with an Asus phone.

Error while executing: am startservice com.eyelights.android/com.android.tools.fd.runtime.InstantRunService
Starting service: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.myapp.android/com.android.tools.fd.runtime.InstantRunService }
Error: Not found; no service started.

Thanks to this post, i was able to start my app again :

https://code.google.com/p/android/issues/detail?id=235879

Go in Android Studio Preferences :

Disable Instant Run like this :

Now you can run your app again. Don't forget to enable again Instant run when you switch phone.

It's not the perfect solution, but it's working

$ adb shell am start -n "com.myapp.android/com.myapp.android.activity.SplashScreenActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 16367 on device asus-asus_z00ed-F9AZCY208273


问:
GoogleToolboxForMac framework error
I try to add the Google Analytics into my project, but I see the error:

```<code>ld: framework not found GoogleToolboxForMac
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code>```

I've already tried to Clean my project, tried deleting Derived Data, tried  adding pod 'GoogleToolboxForMac/Logger' to the Podfile, tried removing and re-adding the Pod. However, nothing helps. I saw all the suggestions from another similar topics on Stackoverflow.

What may cause the described error and how can I fix it?

答:
It may be case that you have installed Pod successfully and thereafter you continued with your project by ignoring message on Terminal :

Now, close your project and open it using Workspace. This worked for me!

Title: GoogleToolboxForMac framework error

Body:
I try to add the Google Analytics into my project, but I see the error:

ld: framework not found GoogleToolboxForMac
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I've already tried to Clean my project, tried deleting Derived Data, tried  adding pod 'GoogleToolboxForMac/Logger' to the Podfile, tried removing and re-adding the Pod. However, nothing helps. I saw all the suggestions from another similar topics on Stackoverflow.

What may cause the described error and how can I fix it?


问:
CodeIgniter - I want to define array like config array in config.php file
I want to define my array like config array in config.php file. So I can access this array any where in my view.

config.php

```<code>$config['base_url'] = '';
$my_array['app_admin_panel'] = '';
$my_array['app_admin_panel_assets'] = '';
</code>```

答:
you can create your config files and declare array in this file. later you can put it on autoload .
so e.g application/config/customconfig.php

```<code>$Configarray = array();
$Configarray['key'] = "some value";
$config['configarray'] = $Configarray;
</code>```

load this config file from your autoload.php

Body:
I want to define my array like config array in config.php file. So I can access this array any where in my view.

config.php

$config['base_url'] = '';
$my_array['app_admin_panel'] = '';
$my_array['app_admin_panel_assets'] = '';

Body:
you can create your config files and declare array in this file. later you can put it on autoload .
so e.g application/config/customconfig.php

$Configarray = array();
$Configarray['key'] = "some value";
$config['configarray'] = $Configarray;

load this config file from your autoload.php


问:
What are the proper and complete steps to deploy a .NET application from Visual Studio for public use?
I usually write C# programs for myself, or just parts of other applications.  Now, I have been working on a project that I would like to eventually commercialize and I am interested in the easiest way to deploy a simple application from VS 2008 that will primarily be downloaded and installed.  I am not just interested in installer choices, but build options, exception handling settings, and any other essential details.

The documentation on MSDN is a little overwhelming.  Just the section on deployment how-to's has over 100 topics!

http://msdn.microsoft.com/en-us/library/ms184415.aspx

What should I focus on and in what order?  Does anyone have a personal checklist that they run through just to make sure all of the bases are covered?

答:
For that scenario I'd avoid clickonce, so this one seems to be the most relevant for deployment.

In terms of complier options, the standard Release build should be good enough; you might want to consider a code obfuscation tool, depending on how good a lawyer you can afford if people decide to reverse engineer your code...

OwnerDisplayName: Ben

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Rowland Shaw


问:
how data with file through work in ajax jquery post method
How can I upload an image in Php through jQuery post ajax method? I tried this code in simple way but it did not show in file data and not stored in directory ,even it is stored in database. Its all data through in form

```<code>        <form  id="Myform5" method="POST" action=""
       enctype="multipart/form-data">
                              <label >Class</label>
                           <select name="type" id="Class">
                           <option >Choose option</option>
                           <option value="Matric">Matric</option>
                            </select>
                             <input  type="text" id="Institute_Name" >
                                 <label >Institute Name</label>
                            <input type="text"  id="Board_Name">
                            <label  >Board Name</label>
                            <div class="form-group">
                            <label>Starting Year</label>
                         <select name="type" id="Starting_Year" >
                              <option >Select year</option>
                              <option value="1950">1950</option>
                         </select>

                                <label>Ending Year</label>
                                <select name="type" id="Ending_Year" >
                               <option >Select year</option>
                               <option value="1950">1950</option>
                                </select>

                     <input  type="text" id="Total_Marks" >
                         <label>Total Marks</label>
                  <input  type="text" id="Obtained_Marks" >
                  <label >Obtained Marks</label>

                                <label>Result_Card</label>
                      <input type="file" id="Result_Card"
                    id="file"  class="inputbox" placeholder="Default Input">

                      <textarea  id="Awards_Honors" type="text" ></textarea>
                              <label >Awards & Honors</label>
                  <textarea  id="Co-curricular" type="text"  ></textarea>
                              <label >Co-curricular</label>
                   <textarea   id="Additional_Info" type="text" ></textarea>
                              <label >Additional Info</label>
                      <button  type="button"  id="button4" >
</code>```

its juery ajax post

```<code>       $("#button4").click(function(){
  var Class = $("#Class").val();
  var Institute_Name =$("#Institute_Name").val();
  var Board_Name=$("#Board_Name").val();
  var Starting_Year = $("#Starting_Year").val();
  var Ending_Year =$("#Ending_Year").val();
   var Total_Marks=$("#Total_Marks").val();
   var Obtained_Marks = $("#Obtained_Marks").val();
  var Result_Card =$("#Result_Card").val();
  var filename = Result_Card.replace(/^.*\\/, "");
   console.log(filename);
  var Awards_Honors=$("#Awards_Honors").val();
  var Co_curricular = $("#Co-curricular").val();
   var Additional_Info =$("#Additional_Info").val();

if (Class.length == "" || Institute_Name.length =="") {
   alert("Fill the form");
}
else
{
    $.ajax({
        type:'POST',
        url :'view2.php',

        data : {
            Class:Class,
            Institute_Name:Institute_Name,
            Board_Name:Board_Name,
            Starting_Year:Starting_Year,
            Ending_Year:Ending_Year,
            Total_Marks:Total_Marks,
            Obtained_Marks:Obtained_Marks,
            filename:filename,
            Awards_Honors:Awards_Honors,
            Co_curricular:Co_curricular,
            Additional_Info:Additional_Info
        },
        // cache: false,
        // contentType: false,
         enctype: 'multipart/form-data',
        // processData: false,
        // enctype:'application/x-www-form-urlencoded',
        success : function(feedback){
         console.log(feedback);
          alert("sucess");
            $("#Myform5")[0].reset();
        }

    })
 }});
</code>```

now i give this page of php

```<code>  if (isset($_POST['Class']) &&
          isset($_POST['Institute_Name']) &&    isset($_POST['Board_Name'])
      && isset($_POST['Starting_Year']) && isset($_POST['Ending_Year'])
        && isset($_POST['Total_Marks']) &&  isset($_POST['Obtained_Marks'])
          &&  isset($_POST['filename']) && isset($_POST['Awards_Honors']) &&
      isset($_POST['Co_curricular']) ){
     /*Uploading FIle OF Image or other in jpg jpeg png size 2 MB */
                                         $errors= array();
                            $file_name = $_FILES['filename']['name'];
                            $file_tmp =$_FILES['filename']['tmp_name'];
                            $file_type=$_FILES['filename']['type'];

   $file_ext=strtolower(end(explode('.',$_FILES['filename']['name'])));

    $expensions=   array("jpeg","jpg","png","txt","pdf","docx","bmp",
                                          "gif","jpeg","jpg");

    if(in_array($file_ext,$expensions)=== false){
            $errors[]="extension not allowed, please choose a
      JPEG,txt,pdf,docx,bmp,gif,jpeg,jpg or PNG file.";
                                        }
      if(empty($errors)==true){

      move_uploaded_file($file_tmp,"files/".$file_name);
                  echo "Image Uploaded Successfully";
                                        }else{
                                            print_r($errors);
                                        }echo"<br />";
                 $Class = $_POST['Class'];
                 $Institute_Name= $_POST['Institute_Name'];
                 $Board_Name = $_POST['Board_Name'];
                 $Starting_Year= $_POST['Starting_Year'];
                 $Ending_Year = $_POST['Ending_Year'];
                 $Total_Marks= $_POST['Total_Marks'];
                 $Obtained_Marks = $_POST['Obtained_Marks'];
                 $filename = $_POST['filename'];
                 $Awards_Honors = $_POST['Awards_Honors'];
                 $Co_curricular = $_POST['Co_curricular'];
                 $Additional_Info = $_POST['Additional_Info'];
               $sql=" INSERT INTO `secondary level`
               (`Class`,`Institute_Name`, `Board_Name`, `Starting_Year`,
              `Ending_Year`, `Total_Marks`, `Obtained_Marks`, `Result_Card`,
                `Awards_Honors`, `Co-curricular`, `Additional_Info`) VALUES
                ( '$Class', '$Institute_Name', '$Board_Name',
                  '$Starting_Year', '$Ending_Year', '$Total_Marks',
              '$Obtained_Marks','$filename','$Awards_Honors',
                '$Co_curricular ','$Additional_Info' )";

          if ($conn->query($sql) === TRUE) {
          echo "New record created successfully";
        } else {
       echo "Error: " . $sql . "<br>" . $conn->error;
       }}
</code>```

答:
just provide name attribute to each element in the form and change input type button to submit then use this:

```<code>$("#Myform5").submit(function(a){
    a.preventDefault();
    var formData = new FormData(this);
   $.ajax({
                type:'POST',
                url: 'view2.php',
                data:formData,
                cache:false,
                success:function(data){
                console.log(data);
                location.reload();
                },
                error: function(data){
                console.log(data);
                }
            });

});
</code>```

this may upload image without posting your text data on your local machine but it will work on web server.

Body:
How can I upload an image in Php through jQuery post ajax method? I tried this code in simple way but it did not show in file data and not stored in directory ,even it is stored in database. Its all data through in form

        <form  id="Myform5" method="POST" action=""
       enctype="multipart/form-data">
                              Class
                           <select name="type" id="Class">
                           <option >Choose option</option>
                           <option value="Matric">Matric</option>
                            </select>
                             <input  type="text" id="Institute_Name" >
                                 Institute Name
                            <input type="text"  id="Board_Name">
                            Board Name

                            Starting Year
                         <select name="type" id="Starting_Year" >
                              <option >Select year</option>
                              <option value="1950">1950</option>
                         </select>

                                Ending Year
                                <select name="type" id="Ending_Year" >
                               <option >Select year</option>
                               <option value="1950">1950</option>
                                </select>

                     <input  type="text" id="Total_Marks" >
                         Total Marks
                  <input  type="text" id="Obtained_Marks" >
                  Obtained Marks

                                Result_Card
                      <input type="file" id="Result_Card"
                    id="file"  class="inputbox" placeholder="Default Input">

                      <textarea  id="Awards_Honors" type="text" ></textarea>
                              Awards & Honors
                  <textarea  id="Co-curricular" type="text"  ></textarea>
                              Co-curricular
                   <textarea   id="Additional_Info" type="text" ></textarea>
                              Additional Info
                      <button  type="button"  id="button4" >

its juery ajax post

       $("#button4").click(function(){
  var Class = $("#Class").val();
  var Institute_Name =$("#Institute_Name").val();
  var Board_Name=$("#Board_Name").val();
  var Starting_Year = $("#Starting_Year").val();
  var Ending_Year =$("#Ending_Year").val();
   var Total_Marks=$("#Total_Marks").val();
   var Obtained_Marks = $("#Obtained_Marks").val();
  var Result_Card =$("#Result_Card").val();
  var filename = Result_Card.replace(/^.*\\/, "");
   console.log(filename);
  var Awards_Honors=$("#Awards_Honors").val();
  var Co_curricular = $("#Co-curricular").val();
   var Additional_Info =$("#Additional_Info").val();

if (Class.length == "" || Institute_Name.length =="") {
   alert("Fill the form");
}
else
{
    $.ajax({
        type:'POST',
        url :'view2.php',

        data : {
            Class:Class,
            Institute_Name:Institute_Name,
            Board_Name:Board_Name,
            Starting_Year:Starting_Year,
            Ending_Year:Ending_Year,
            Total_Marks:Total_Marks,
            Obtained_Marks:Obtained_Marks,
            filename:filename,
            Awards_Honors:Awards_Honors,
            Co_curricular:Co_curricular,
            Additional_Info:Additional_Info
        },
        // cache: false,
        // contentType: false,
         enctype: 'multipart/form-data',
        // processData: false,
        // enctype:'application/x-www-form-urlencoded',
        success : function(feedback){
         console.log(feedback);
          alert("sucess");
            $("#Myform5")[0].reset();
        }

    })
 }});

now i give this page of php

  if (isset($_POST['Class']) &&
          isset($_POST['Institute_Name']) &&    isset($_POST['Board_Name'])
      && isset($_POST['Starting_Year']) && isset($_POST['Ending_Year'])
        && isset($_POST['Total_Marks']) &&  isset($_POST['Obtained_Marks'])
          &&  isset($_POST['filename']) && isset($_POST['Awards_Honors']) &&
      isset($_POST['Co_curricular']) ){
     /*Uploading FIle OF Image or other in jpg jpeg png size 2 MB */
                                         $errors= array();
                            $file_name = $_FILES['filename']['name'];
                            $file_tmp =$_FILES['filename']['tmp_name'];
                            $file_type=$_FILES['filename']['type'];

   $file_ext=strtolower(end(explode('.',$_FILES['filename']['name'])));

    $expensions=   array("jpeg","jpg","png","txt","pdf","docx","bmp",
                                          "gif","jpeg","jpg");

    if(in_array($file_ext,$expensions)=== false){
            $errors[]="extension not allowed, please choose a
      JPEG,txt,pdf,docx,bmp,gif,jpeg,jpg or PNG file.";
                                        }
      if(empty($errors)==true){

      move_uploaded_file($file_tmp,"files/".$file_name);
                  echo "Image Uploaded Successfully";
                                        }else{
                                            print_r($errors);
                                        }echo"
";
                 $Class = $_POST['Class'];
                 $Institute_Name= $_POST['Institute_Name'];
                 $Board_Name = $_POST['Board_Name'];
                 $Starting_Year= $_POST['Starting_Year'];
                 $Ending_Year = $_POST['Ending_Year'];
                 $Total_Marks= $_POST['Total_Marks'];
                 $Obtained_Marks = $_POST['Obtained_Marks'];
                 $filename = $_POST['filename'];
                 $Awards_Honors = $_POST['Awards_Honors'];
                 $Co_curricular = $_POST['Co_curricular'];
                 $Additional_Info = $_POST['Additional_Info'];
               $sql=" INSERT INTO `secondary level`
               (`Class`,`Institute_Name`, `Board_Name`, `Starting_Year`,
              `Ending_Year`, `Total_Marks`, `Obtained_Marks`, `Result_Card`,
                `Awards_Honors`, `Co-curricular`, `Additional_Info`) VALUES
                ( '$Class', '$Institute_Name', '$Board_Name',
                  '$Starting_Year', '$Ending_Year', '$Total_Marks',
              '$Obtained_Marks','$filename','$Awards_Honors',
                '$Co_curricular ','$Additional_Info' )";

          if ($conn->query($sql) === TRUE) {
          echo "New record created successfully";
        } else {
       echo "Error: " . $sql . "
" . $conn->error;
       }}

Body:
just provide name attribute to each element in the form and change input type button to submit then use this:

$("#Myform5").submit(function(a){
    a.preventDefault();
    var formData = new FormData(this);
   $.ajax({
                type:'POST',
                url: 'view2.php',
                data:formData,
                cache:false,
                success:function(data){
                console.log(data);
                location.reload();
                },
                error: function(data){
                console.log(data);
                }
            });

});

this may upload image without posting your text data on your local machine but it will work on web server.


问:
How to go back to Previous Activity?
Someone ask me a question a week ago and till now i did not get the answer of that question.The question was how we can go back to previous Activity by pressing back button of device without using intent or finish(). </p>

答:
If You Are Using Intent Than Make Sure You don't Call finish(); After Using

```<code>StartActivity(IntentObj);
</code>```

Method Than As per activity stack backbutton will do its work and go to previous Activity.

And Also Make Sure That You Are Not overriding onBackPressed() method in activity.

OR

You Can Set Home Button For go to Specific Activity,
For That You Have to Give Back button into Action bar.
For That in onCreate()

```<code>getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
</code>```

And in manifest.xml

```<code><activity
        android:name="com.example.myfirstapp.DisplayMessageActivity"
        android:label="@string/title_activity_display_message"
        android:parentActivityName="com.example.myfirstapp.MainActivity" >
        <!-- Parent activity meta-data to support 4.0 and lower -->
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.myfirstapp.MainActivity" />
    </activity>
</code>```

Title: How to go back to Previous Activity?

Body:
If You Are Using Intent Than Make Sure You don't Call finish(); After Using

StartActivity(IntentObj);

Method Than As per activity stack backbutton will do its work and go to previous Activity.

And Also Make Sure That You Are Not overriding onBackPressed() method in activity.

OR

You Can Set Home Button For go to Specific Activity,
For That You Have to Give Back button into Action bar.
For That in onCreate()

getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);

And in manifest.xml

<activity
        android:name="com.example.myfirstapp.DisplayMessageActivity"
        android:label="@string/title_activity_display_message"
        android:parentActivityName="com.example.myfirstapp.MainActivity" >
        <!-- Parent activity meta-data to support 4.0 and lower -->
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.myfirstapp.MainActivity" />
    </activity>


问:
PHP-FPM sending empty response with Nginx on macOS
I installed nginx 1.10.3 and php 5.5.38 as a development server on macOS 10.12.4

When I try a test php file in my browser the body is empty but the response headers seem ok:

HTTP/1.1 200 OK
Server: nginx/1.10.3
Date: Wed, 29 Mar 2017 11:35:21 GMT
Content-Type: text/html
Transfer-Encoding: chunked
Connection: keep-alive
X-Powered-By: PHP/5.5.38

There are no errors in php-fpm.log or nginx/error.log

my nginx.conf has:

```<code>server {
    listen       80;
    server_name  wordpress.bob;
    root /Users/mark/Sites/wordpress;

    include /usr/local/etc/nginx/global_restrictions.conf;
    include /usr/local/etc/nginx/wordpress.conf;

    location ~ \.php$ {
      try_files $uri =404;
      fastcgi_split_path_info ^(.+\.php)(/.+)$;
      fastcgi_pass   unix:/usr/local/var/run/php-www.sock;
      fastcgi_index  index.php;
      include        fastcgi_params;
    }

}
</code>```

wordpress.bob is a local hostname for testing pointing to 127.0.0.1 in etc/hosts

php-fpm.conf has:

```<code>listen = '/usr/local/var/run/php-www.sock'
</code>```

Any ideas what I'm doing wrong?

答:
To install NGINX with Homebrew :

```<code>$ brew install nginx
</code>```

Run NGINX :

```<code>$ sudo nginx
</code>```

Test the localhost nginx :

```<code>http://localhost:8080
</code>```

NGINX configuration file should be in :

```<code>$ /usr/local/etc/nginx/nginx.conf
</code>```

If you want to change the default port :

```<code>$ sudo nginx -s stop
$ vim /usr/local/etc/nginx/nginx.conf
</code>```

Change the : listen       8080;
To : listen       80;

To save and Conf and start NGINX run :

```<code>$ sudo nginx
</code>```

Then, according to your problem, you might simply be pointing to a an empty PHP file. Try to print a phpinfo() then look for "DOCUMENT_ROOT" to see where it goes.

Body:
I installed nginx 1.10.3 and php 5.5.38 as a development server on macOS 10.12.4

When I try a test php file in my browser the body is empty but the response headers seem ok:

HTTP/1.1 200 OK
Server: nginx/1.10.3
Date: Wed, 29 Mar 2017 11:35:21 GMT
Content-Type: text/html
Transfer-Encoding: chunked
Connection: keep-alive
X-Powered-By: PHP/5.5.38

There are no errors in php-fpm.log or nginx/error.log

my nginx.conf has:

server {
    listen       80;
    server_name  wordpress.bob;
    root /Users/mark/Sites/wordpress;

    include /usr/local/etc/nginx/global_restrictions.conf;
    include /usr/local/etc/nginx/wordpress.conf;

    location ~ \.php$ {
      try_files $uri =404;
      fastcgi_split_path_info ^(.+\.php)(/.+)$;
      fastcgi_pass   unix:/usr/local/var/run/php-www.sock;
      fastcgi_index  index.php;
      include        fastcgi_params;
    }

}

wordpress.bob is a local hostname for testing pointing to 127.0.0.1 in etc/hosts

php-fpm.conf has:

listen = '/usr/local/var/run/php-www.sock'

Any ideas what I'm doing wrong?

Body:
To install NGINX with Homebrew :

$ brew install nginx

Run NGINX :

$ sudo nginx

Test the localhost nginx :

http://localhost:8080

NGINX configuration file should be in :

$ /usr/local/etc/nginx/nginx.conf

If you want to change the default port :

$ sudo nginx -s stop
$ vim /usr/local/etc/nginx/nginx.conf

Change the : listen       8080;
To : listen       80;

To save and Conf and start NGINX run :

$ sudo nginx

Then, according to your problem, you might simply be pointing to a an empty PHP file. Try to print a phpinfo() then look for "DOCUMENT_ROOT" to see where it goes.


问:
Mom file creation (5 product limit)
Ok, I realize this is a very niche issue, but I'm hoping the process is straight forward enough...

I'm tasked with creating a data file out of Customer/Order information.  Problem is, the datafile has a 5 product max limit.

Basically, I get my data, group by cust_id, create the file structure, within that loop, group by product_id, rewrite the fields in previous file_struct with new product info.  That's worked all well and good until a user exceeded that max.

A brief example..  (keep in mind, the structure of the array is set by another process, this CANNOT change)

```<code>orderArray = arranyew(2);
set order = 1;

loop over cust_id;

    field[order][1] = "field(1)"; // cust_id
    field[order][2] = "field(2)"; // name
    field[order][3] = "field(3)"; // phone
    field[order][4] = ""; // product_1
    field[order][5] = ""; // quantity_1
    field[order][6] = ""; // product_2
    field[order][7] = ""; // quantity_2
    field[order][8] = ""; // product_3
    field[order][9] = ""; // quantity_3
    field[order][10] = ""; // product_4
    field[order][11] = ""; // quantity_4
    field[order][12] = ""; // product_5
    field[order][13] = ""; // quantity_5
    field[order][14] = "field(4)"; // trx_id
    field[order][15] = "field(5)"; // total_cost

    counter = 0;

    loop over product_id

        field[order[4+counter] = productCode;
        field[order[5+counter] = quantity;

        counter = counter + 2;

    end inner loop;

    order = order + 1;

end outer loop;
</code>```

Like I said, this worked fine until I had a user who ordered more than 5 products.

What I basically want to do is check the number of products for each user if that number is greater than 5, start a new line in the text field, but I'm stufk on how to get there.

I've tried numerous fixes, but nothing gives the results I need.

I can send the entire file if It can help, but I don't want to post it all here.

答:
As you put the data into the row, you need check if there are more than 5 products and then create an additional line.

```<code>loop over product_id
    if (counter mod 10 == 0 and counter > 0) {
         // create the new row, and mark it as a continuation of the previous order
         counter = 0;
         order = order + 1;

         field[order][1] = "";
         ...
         field[order][15] = "";
    }

    field[order[4+counter] = productCode;
    field[order[5+counter] = quantity;

    counter = counter + 2;

end inner loop;
</code>```

I've actually done the export from an ecommerce system to MOM, but that code has since been lost. I have samples of code in classic ASP.

Title: Mom file creation (5 product limit)

Body:
Ok, I realize this is a very niche issue, but I'm hoping the process is straight forward enough...

I'm tasked with creating a data file out of Customer/Order information.  Problem is, the datafile has a 5 product max limit.

Basically, I get my data, group by cust_id, create the file structure, within that loop, group by product_id, rewrite the fields in previous file_struct with new product info.  That's worked all well and good until a user exceeded that max.

A brief example..  (keep in mind, the structure of the array is set by another process, this CANNOT change)

orderArray = arranyew(2);
set order = 1;

loop over cust_id;

    field[order][1] = "field(1)"; // cust_id
    field[order][2] = "field(2)"; // name
    field[order][3] = "field(3)"; // phone
    field[order][4] = ""; // product_1
    field[order][5] = ""; // quantity_1
    field[order][6] = ""; // product_2
    field[order][7] = ""; // quantity_2
    field[order][8] = ""; // product_3
    field[order][9] = ""; // quantity_3
    field[order][10] = ""; // product_4
    field[order][11] = ""; // quantity_4
    field[order][12] = ""; // product_5
    field[order][13] = ""; // quantity_5
    field[order][14] = "field(4)"; // trx_id
    field[order][15] = "field(5)"; // total_cost

    counter = 0;

    loop over product_id

        field[order[4+counter] = productCode;
        field[order[5+counter] = quantity;

        counter = counter + 2;

    end inner loop;

    order = order + 1;

end outer loop;

Like I said, this worked fine until I had a user who ordered more than 5 products.

What I basically want to do is check the number of products for each user if that number is greater than 5, start a new line in the text field, but I'm stufk on how to get there.

I've tried numerous fixes, but nothing gives the results I need.

I can send the entire file if It can help, but I don't want to post it all here.

Body:
As you put the data into the row, you need check if there are more than 5 products and then create an additional line.

loop over product_id
    if (counter mod 10 == 0 and counter > 0) {
         // create the new row, and mark it as a continuation of the previous order
         counter = 0;
         order = order + 1;

         field[order][1] = "";
         ...
         field[order][15] = "";
    }

    field[order[4+counter] = productCode;
    field[order[5+counter] = quantity;

    counter = counter + 2;

end inner loop;

I've actually done the export from an ecommerce system to MOM, but that code has since been lost. I have samples of code in classic ASP.


问:
Windows service template missing?
When I go to create a new project, the "Windows Service" template isn't there!

Can someone please either tell me where I can get it, or provide a download link to it?

答: Go to File > New > Project; Templates > Visual C# > Windows > Classic Desktop; select Windows Service.

Title: Windows service template missing?


问:
multiple pull requests from the same branch
Say I have 3 branches: master, release and myfeature. Is it possible to create 2 pull requests from myfeature to both master and release without creating another branch?

Why might I want this?

Say master is the current latest, and release was a year ago. When a bug is fixed a PR is created against release, now this fix also needs to go into master, a cherry pick is perfect, but that will need a new branch as far as I know. I just wish it was possible to use the same original fix branch to merge into both (as long as master is still compatible).

答:
You probably want to think a little more about your branches, and why you have them.

There's nothing to stop you from creating pull requests between your branches. I assume you're creating pull requests so that you can have conversations about those changes. I guess my question is "how will the conversation be different in these two cases?"

It feels, to me, like you may want to use a PR to have a conversation as you merge changes from myfeature to master, but once that conversation has happened the merge from master to release doesn't need to occur...it's just a merge.

I wonder if you should be using tags, rather than branches, in place of release. You may also want to check out some of the following resources to define how you're going to use git to manage this sort of thing:

GitHub's docs on Pull Requests

Altasian's view on git workflows

The original post on git-flow


问:
ExecTask or (Insert)Task, whats the difference?
Can someone explain the use of using all the different tasks instead of using simply <exec/>?

The PHPunit task is giving me alot of problems at the moment for example, why bother and not go for a simple <exec/> ?

Cant seem to find anything in the docs at all.

The docs are f.e. very confusing giving examples such as:

https://www.phing.info/docs/guide/stable/ch04s02.html (4.2 Writing A Simple Buildfile)

```<code><target name="build" depends="prepare">
    <echo msg="Copying files to build directory..." />

    <echo msg="Copying ./about.php to ./build directory..." />
    <copy file="./about.php" tofile="./build/about.php" />

    <echo msg="Copying ./browsers.php to ./build directory..." />
    <copy file="./browsers.php" tofile="./build/browsers.php" />

    <echo msg="Copying ./contact.php to ./build directory..." />
    <copy file="./contact.php" tofile="./build/contact.php" />
</target>
</code>```

The copy task has a description property, you would think that this would be somehow seem logical to interpret by summary reporters or something, instead of having a echo on top of every task..

Whats the best practise?

答:
Phing's Copy Task does not have a description property...

...other than that, if expressing an action is more concise and less error-prone when written as a [custom] task than as an unwieldy exec task I usually take that as a hint to go looking and/or write that custom task.

Sometimes going a little further and submitting a pull-request ;-)

Body:
Can someone explain the use of using all the different tasks instead of using simply <exec/>?

The PHPunit task is giving me alot of problems at the moment for example, why bother and not go for a simple <exec/> ?

Cant seem to find anything in the docs at all.

The docs are f.e. very confusing giving examples such as:

https://www.phing.info/docs/guide/stable/ch04s02.html (4.2 Writing A Simple Buildfile)

<target name="build" depends="prepare">
    <echo msg="Copying files to build directory..." />

    <echo msg="Copying ./about.php to ./build directory..." />
    <copy file="./about.php" tofile="./build/about.php" />

    <echo msg="Copying ./browsers.php to ./build directory..." />
    <copy file="./browsers.php" tofile="./build/browsers.php" />

    <echo msg="Copying ./contact.php to ./build directory..." />
    <copy file="./contact.php" tofile="./build/contact.php" />
</target>

The copy task has a description property, you would think that this would be somehow seem logical to interpret by summary reporters or something, instead of having a echo on top of every task..

Whats the best practise?


问:
iTunes-style NSWindow subclass?
Is there an open-source library for Cocoa to create a window following iTunes' style?  That is the window controls are laid out vertically instead of horizontally:

I find it space-saving and good for utility-type applications that doesn't need a window title.

答:
This quickly hacked away NSWindow delegate should get you started:

```<code>//VerticalTrafficLightsWindowDelegate.h

#import <Cocoa/Cocoa.h>

@interface VerticalTrafficLightsWindowDelegate : NSObject <NSWindowDelegate> {
    NSWindow *window;
}

@property (assign) IBOutlet NSWindow *window;

- (void)verticalizeButtonsForWindow:(NSWindow *)aWindow;

@end

//VerticalTrafficLightsWindowDelegate.m

#import "VerticalTrafficLightsWindowDelegate.h"

@implementation VerticalTrafficLightsWindowDelegate

@synthesize window;

- (void)awakeFromNib {
    [self verticalizeButtonsForWindow:window];
}

- (void)windowDidResize:(NSNotification *)notification {
    [self verticalizeButtonsForWindow:window];
}

- (void)verticalizeButtonsForWindow:(NSWindow *)aWindow {
    NSArray *contentSuperViews = [[[aWindow contentView] superview] subviews];

    NSView *closeButton = [contentSuperViews objectAtIndex:0];
    NSRect closeButtonFrame = [closeButton frame];

    NSView *minimizeButton = [contentSuperViews objectAtIndex:2];
    NSRect minimizeButtonFrame = [minimizeButton frame];

    NSView *zoomButton = [contentSuperViews objectAtIndex:1];
    NSRect zoomButtonFrame = [zoomButton frame];

    [minimizeButton setFrame:NSMakeRect(closeButtonFrame.origin.x, closeButtonFrame.origin.y - 20.0, minimizeButtonFrame.size.width, minimizeButtonFrame.size.height)];
    [zoomButton setFrame:NSMakeRect(closeButtonFrame.origin.x, closeButtonFrame.origin.y - 40.0, zoomButtonFrame.size.width, zoomButtonFrame.size.height)];
}

@end
</code>```

However I got to say that just like JeremyP I can only hope Apple's not going to spread this any wider in OS X.

Title: iTunes-style NSWindow subclass?

Body:
This quickly hacked away NSWindow delegate should get you started:

//VerticalTrafficLightsWindowDelegate.h

#import <Cocoa/Cocoa.h>

@interface VerticalTrafficLightsWindowDelegate : NSObject <NSWindowDelegate> {
    NSWindow *window;
}

@property (assign) IBOutlet NSWindow *window;

- (void)verticalizeButtonsForWindow:(NSWindow *)aWindow;

@end

//VerticalTrafficLightsWindowDelegate.m

#import "VerticalTrafficLightsWindowDelegate.h"

@implementation VerticalTrafficLightsWindowDelegate

@synthesize window;

- (void)awakeFromNib {
    [self verticalizeButtonsForWindow:window];
}

- (void)windowDidResize:(NSNotification *)notification {
    [self verticalizeButtonsForWindow:window];
}

- (void)verticalizeButtonsForWindow:(NSWindow *)aWindow {
    NSArray *contentSuperViews = [[[aWindow contentView] superview] subviews];

    NSView *closeButton = [contentSuperViews objectAtIndex:0];
    NSRect closeButtonFrame = [closeButton frame];

    NSView *minimizeButton = [contentSuperViews objectAtIndex:2];
    NSRect minimizeButtonFrame = [minimizeButton frame];

    NSView *zoomButton = [contentSuperViews objectAtIndex:1];
    NSRect zoomButtonFrame = [zoomButton frame];

    [minimizeButton setFrame:NSMakeRect(closeButtonFrame.origin.x, closeButtonFrame.origin.y - 20.0, minimizeButtonFrame.size.width, minimizeButtonFrame.size.height)];
    [zoomButton setFrame:NSMakeRect(closeButtonFrame.origin.x, closeButtonFrame.origin.y - 40.0, zoomButtonFrame.size.width, zoomButtonFrame.size.height)];
}

@end

However I got to say that just like JeremyP I can only hope Apple's not going to spread this any wider in OS X.


问:
How to pass <option> attributes to select2?
I'm using Select2 4.0. I have a list of options, some of which are "deleted" and I want to signify which are which. My select element is like this:

```<code><style>.deleted { color: red; }</style>

<select name="itemid" id="item-list" tabindex="1">
    <option></option>
    <option value="1">Item 1</option>
    <option value="2" class="deleted">Item 2</option>
    <option value="3">Item 3</option>
</select>
</code>```

And it's initialised like this:

```<code><script src="/static/js/select2.min.js"></script>
<script>
$(function() {
    $("#item-list").select2({
        placeholder: 'Select item'
    });
});
</script>
</code>```

However, on the resulting HTML code that select2 generates I don't see any way to reference that class. Also tried a data-deleted attribute on the option, with no luck.

The only thing I see that comes close is the templateResult option, where I can check for opt.element.className. But I cannot see how to access the select2 option from there. Anyway that callback runs on every single search which is not at all what I want.

Is there some other way to style particular options in Select2?

UPDATE: as noted in the comments there is a find() function, but that only gets the original <option> elements, not the
 elements that select2 generates. Here's what I tried:

```<code>var sel2 = $("#item-list").select2({
    placeholder: 'Select item'
});

sel2.find('.deleted').each(function() {
    $(this).css('color', 'red');
});
</code>```

答:
If you want do this by default, every new select2 copy the class definition from option to select2-element.
Include the code after loading select2.js</p>

```<code>$.fn.select2.defaults.set("templateResult", function(item, li) {
  if (item && item.element && item.element.className.length) {
    $(li).addClass(item.element.className);
  }
  return item.text;
}
</code>```

Body:
I'm using Select2 4.0. I have a list of options, some of which are "deleted" and I want to signify which are which. My select element is like this:

<select name="itemid" id="item-list" tabindex="1">
    <option></option>
    <option value="1">Item 1</option>
    <option value="2" class="deleted">Item 2</option>
    <option value="3">Item 3</option>
</select>

And it's initialised like this:

However, on the resulting HTML code that select2 generates I don't see any way to reference that class. Also tried a data-deleted attribute on the option, with no luck.

The only thing I see that comes close is the templateResult option, where I can check for opt.element.className. But I cannot see how to access the select2 option from there. Anyway that callback runs on every single search which is not at all what I want.

Is there some other way to style particular options in Select2?

UPDATE: as noted in the comments there is a find() function, but that only gets the original <option> elements, not the
 elements that select2 generates. Here's what I tried:

var sel2 = $("#item-list").select2({
    placeholder: 'Select item'
});

sel2.find('.deleted').each(function() {
    $(this).css('color', 'red');
});

Body:
If you want do this by default, every new select2 copy the class definition from option to select2-element.
Include the code after loading select2.js

$.fn.select2.defaults.set("templateResult", function(item, li) {
  if (item && item.element && item.element.className.length) {
    $(li).addClass(item.element.className);
  }
  return item.text;
}

ContentLicense: CC BY-SA 4.0


问:
Imagebutton.setImageURI(uri) doesn't work
now my problem is that:
This is a workaround for Onclcick an ImageButton, which tries to cache the previous image Uri. Passing null effectively resets it.

```<code>private ImageButton mImageSelect;
private static  final int GALLERY_REQUEST =1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_post);

    mImageSelect=(ImageButton) findViewById(R.id.imageselect);
    mImageSelect.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent galleryIntent= new Intent(Intent.ACTION_GET_CONTENT);
            galleryIntent.setType("image/*");
            startActivityForResult(galleryIntent, GALLERY_REQUEST);
        }
    });

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   // super.onActivityResult(requestCode, resultCode, data);

    if(requestCode== GALLERY_REQUEST && resultCode==RESULT_OK){
        Uri selectedImageUri=data.getData();
        if (null != selectedImageUri) {

            mImageSelect.setImageURI(selectedImageUri);
            Toast.makeText(PostActivity.this, "Image Selected", Toast.LENGTH_SHORT).show();
        }
        else{
            Toast.makeText(PostActivity.this,"Image Not Selected",Toast.LENGTH_SHORT).show();
        }
    }
}
</code>```

答:
Try creating Bitmap from uri and setting bitmap on image button.
This can be done as:

```<code>String path = getPath(this,uri);
</code>```

Code for getPath():

```<code>public static String getPath(final Context context, final Uri uri) {
    Utils.context = context;
    Utils.uri = uri;

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }

            // TODO handle non-primary volumes
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {

            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[] {
                    split[1]
            };

            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {

        // Return the remote address
        if (isGooglePhotosUri(uri))
            return uri.getLastPathSegment();

        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}
</code>```

Now can get Bitmap as:

```<code>    if(path!=null)
        Bitmap bm = getBitmapFromPath(path)
</code>```

Set Image on imageButton as:

```<code>ImageButton.setImageBitmap(bm);
</code>```

Body:
now my problem is that:
This is a workaround for Onclcick an ImageButton, which tries to cache the previous image Uri. Passing null effectively resets it.

private ImageButton mImageSelect;
private static  final int GALLERY_REQUEST =1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_post);

    mImageSelect=(ImageButton) findViewById(R.id.imageselect);
    mImageSelect.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent galleryIntent= new Intent(Intent.ACTION_GET_CONTENT);
            galleryIntent.setType("image/*");
            startActivityForResult(galleryIntent, GALLERY_REQUEST);
        }
    });

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   // super.onActivityResult(requestCode, resultCode, data);

    if(requestCode== GALLERY_REQUEST && resultCode==RESULT_OK){
        Uri selectedImageUri=data.getData();
        if (null != selectedImageUri) {

            mImageSelect.setImageURI(selectedImageUri);
            Toast.makeText(PostActivity.this, "Image Selected", Toast.LENGTH_SHORT).show();
        }
        else{
            Toast.makeText(PostActivity.this,"Image Not Selected",Toast.LENGTH_SHORT).show();
        }
    }
}

Body:
Try creating Bitmap from uri and setting bitmap on image button.
This can be done as:

String path = getPath(this,uri);

Code for getPath():

public static String getPath(final Context context, final Uri uri) {
    Utils.context = context;
    Utils.uri = uri;

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }

            // TODO handle non-primary volumes
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {

            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[] {
                    split[1]
            };

            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {

        // Return the remote address
        if (isGooglePhotosUri(uri))
            return uri.getLastPathSegment();

        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

Now can get Bitmap as:

    if(path!=null)
        Bitmap bm = getBitmapFromPath(path)

Set Image on imageButton as:

ImageButton.setImageBitmap(bm);


问:
How to perform Join between multiple tables in LINQ lambda
I am trying to perform a Join between multiple tables in LINQ. I have the following classes:

```<code>Product {Id, ProdName, ProdQty}

Category {Id, CatName}

ProductCategory{ProdId, CatId} //association table
</code>```

And I use the following code (where product, category and productcategory are instances of the above classes):

```<code>var query = product.Join(productcategory, p => p.Id, pc => pc.ProdID, (p, pc) => new {product = p, productcategory = pc})
                   .Join(category, ppc => ppc.productcategory.CatId, c => c.Id, (ppc, c) => new { productproductcategory = ppc, category = c});
</code>```

With this code I obtain an object from the following class:

```<code>QueryClass { productproductcategory, category}
</code>```

Where producproductcategory is of type:

```<code>ProductProductCategoryClass {product, productcategory}
</code>```

I do not understand where the joined "table" is, I was expecting a single class that contains all the properties from the involved classes.

My aim is to populate another object with some properties resulting from the query:

```<code>CategorizedProducts catProducts = query.Select(m => new { m.ProdId = ???, m.CatId = ???, //other assignments });
</code>```

how can I achieve this goal?

答:
```<code> public ActionResult Index()
    {
        List<CustomerOrder_Result> obj = new List<CustomerOrder_Result>();

       var  orderlist = (from a in db.OrderMasters
                         join b in db.Customers on a.CustomerId equals b.Id
                         join c in db.CustomerAddresses on b.Id equals c.CustomerId
                         where a.Status == "Pending"
                         select new
                         {
                             Customername = b.Customername,
                             Phone = b.Phone,
                             OrderId = a.OrderId,
                             OrderDate = a.OrderDate,
                             NoOfItems = a.NoOfItems,
                             Order_amt = a.Order_amt,
                             dis_amt = a.Dis_amt,
                             net_amt = a.Net_amt,
                             status=a.Status,
                             address = c.address,
                             City = c.City,
                             State = c.State,
                             Pin = c.Pin

                         }) ;
       foreach (var item in orderlist)
       {

           CustomerOrder_Result clr = new CustomerOrder_Result();
           clr.Customername=item.Customername;
           clr.Phone = item.Phone;
           clr.OrderId = item.OrderId;
           clr.OrderDate = item.OrderDate;
           clr.NoOfItems = item.NoOfItems;
           clr.Order_amt = item.Order_amt;
           clr.net_amt = item.net_amt;
           clr.address = item.address;
           clr.City = item.City;
           clr.State = item.State;
           clr.Pin = item.Pin;
           clr.status = item.status;

           obj.Add(clr);

       }
</code>```

Body:
I am trying to perform a Join between multiple tables in LINQ. I have the following classes:

Product {Id, ProdName, ProdQty}

Category {Id, CatName}

ProductCategory{ProdId, CatId} //association table

And I use the following code (where product, category and productcategory are instances of the above classes):

var query = product.Join(productcategory, p => p.Id, pc => pc.ProdID, (p, pc) => new {product = p, productcategory = pc})
                   .Join(category, ppc => ppc.productcategory.CatId, c => c.Id, (ppc, c) => new { productproductcategory = ppc, category = c});

With this code I obtain an object from the following class:

QueryClass { productproductcategory, category}

Where producproductcategory is of type:

ProductProductCategoryClass {product, productcategory}

I do not understand where the joined "table" is, I was expecting a single class that contains all the properties from the involved classes.

My aim is to populate another object with some properties resulting from the query:

CategorizedProducts catProducts = query.Select(m => new { m.ProdId = ???, m.CatId = ???, //other assignments });

how can I achieve this goal?


问:
How to Execute second MySQL CONDITION if first one fails (PHP/MySQLi)
I need help. I know that I can use "if...elseif" in PHP but the problem is the current condition is already inside a long "elseif" so I don't want it to be nested by creating another "if..." inside it.

I have my search form (please see image below) and my mysqli statement that works fine for one side only (Price to).
I want to be able to : when a user select a "category" like "Coach", and enter one of the price (from & to), the search must work normally as expected.
if the user only enter "price from", the statement work from the inputted amount, and if he enters "price to" the statement also work to the inputted amount.

I tried to use many operators (OR / AND...) but still not achieving what I want.

```<code>elseif ($category=="coach"){
echo "3 !!!!!!!" ."<br>";
$result = $connection->query("select *
                            from tblcoach
                            where price>='$pricefrom'
                            and price<='$priceto'");
}
</code>```

Below is my sql statement that only work when I
and I want to

答:
One common approach is to add an "or input is null" clause to your WHERE clause.  Logically it might look something like this:

```<code>select *
from tblcoach
where (price >= ? or ? is null)
  and (price <= ? or ? is null)
</code>```

Then you'd bind the first two parameters to your "price from" value and the second two parameters to your "price to" value.

Hint: This is a good time to start using query parameters and prepared statements.  It will make this, and other things, easier.  You can do the same thing with your current potentially-SQL-injectable code, probably comparing with an empty string or default value instead of null.  But the idea is the same.  The logic is essentially to use the value for comparison if it exists or perform no meaningful comparison if it doesn't exist.

Body:
I need help. I know that I can use "if...elseif" in PHP but the problem is the current condition is already inside a long "elseif" so I don't want it to be nested by creating another "if..." inside it.

I have my search form (please see image below) and my mysqli statement that works fine for one side only (Price to).
I want to be able to : when a user select a "category" like "Coach", and enter one of the price (from & to), the search must work normally as expected.
if the user only enter "price from", the statement work from the inputted amount, and if he enters "price to" the statement also work to the inputted amount.

I tried to use many operators (OR / AND...) but still not achieving what I want.

elseif ($category=="coach"){
echo "3 !!!!!!!" ."
";
$result = $connection->query("select *
                            from tblcoach
                            where price>='$pricefrom'
                            and price<='$priceto'");
}

Below is my sql statement that only work when I
and I want to

Body:
One common approach is to add an "or input is null" clause to your WHERE clause.  Logically it might look something like this:

select *
from tblcoach
where (price >= ? or ? is null)
  and (price <= ? or ? is null)

Then you'd bind the first two parameters to your "price from" value and the second two parameters to your "price to" value.

Hint: This is a good time to start using query parameters and prepared statements.  It will make this, and other things, easier.  You can do the same thing with your current potentially-SQL-injectable code, probably comparing with an empty string or default value instead of null.  But the idea is the same.  The logic is essentially to use the value for comparison if it exists or perform no meaningful comparison if it doesn't exist.


问:
Integrating react-native With Existing Apps
com.facebook.stetho:stetho-okhttp:1.2.0
of react native conflict with my existing project components :

```<code>compile 'com.facebook.stetho:stetho:1.4.2'
</code>```

the error:

```<code>Error:Module 'com.facebook.stetho:stetho-okhttp:1.2.0' depends on one or more Android Libraries but is a jar
</code>```

app.gradle:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.0"
    defaultConfig {
        applicationId "cn.titaandroid.im"
        minSdkVersion 16
        targetSdkVersion 23
        versionCode 2017021610
        versionName '0.9.0'

        multiDexEnabled true
        ndk {
            abiFilters "armeabi-v7a", "x86"
        }
    }
    signingConfigs {
        config {
            storeFile file('titaandroid.keystory')
            storePassword '123456'
            keyAlias 'tita'
            keyPassword '123456'
        }
    }
    sourceSets {
        main {
            jni.srcDirs = []
            jniLibs.srcDirs = ['libs']
        }
    }
    packagingOptions {
        exclude 'AndroidManifest.xml'
    }
    buildTypes {
        release {
            minifyEnabled false
            signingConfig signingConfigs.config //for release
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
            minifyEnabled false
            signingConfig signingConfigs.config //for release
        }
    }
    lintOptions {
        checkReleaseBuilds false

        abortOnError false
    }
    dexOptions {
        javaMaxHeapSize "4g"
    }
    productFlavors {
    }

    dependencies {
        compile fileTree(include: ['*.jar'], dir: 'libs')
        compile 'com.android.support:appcompat-v7:21.0.3'
        compile 'com.android.support:support-v4:21.0.3'
        compile project(':Recognizer')
        compile project(':contactcard')
        compile project(':sticker')
        compile 'com.android.support:multidex:1.0.1'
        compile 'com.facebook.stetho:stetho:1.4.2'
        compile files('libs/MiPush_SDK_Client_3_1_2.jar')
        compile project(':IMKit')
        compile project(':CallKit')
        compile project(':RedPacket')
        compile 'com.facebook.react:react-native:+'
    }
    apply plugin: 'com.google.gms.google-services'
}
</code>```

答: As a workaround, I've just downgraded to 'com.facebook.stetho:stetho:1.3.1' and worked.</p>

Body:
com.facebook.stetho:stetho-okhttp:1.2.0
of react native conflict with my existing project components :

compile 'com.facebook.stetho:stetho:1.4.2'

the error:

Error:Module 'com.facebook.stetho:stetho-okhttp:1.2.0' depends on one or more Android Libraries but is a jar

app.gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.0"
    defaultConfig {
        applicationId "cn.titaandroid.im"
        minSdkVersion 16
        targetSdkVersion 23
        versionCode 2017021610
        versionName '0.9.0'

        multiDexEnabled true
        ndk {
            abiFilters "armeabi-v7a", "x86"
        }
    }
    signingConfigs {
        config {
            storeFile file('titaandroid.keystory')
            storePassword '123456'
            keyAlias 'tita'
            keyPassword '123456'
        }
    }
    sourceSets {
        main {
            jni.srcDirs = []
            jniLibs.srcDirs = ['libs']
        }
    }
    packagingOptions {
        exclude 'AndroidManifest.xml'
    }
    buildTypes {
        release {
            minifyEnabled false
            signingConfig signingConfigs.config //for release
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
            minifyEnabled false
            signingConfig signingConfigs.config //for release
        }
    }
    lintOptions {
        checkReleaseBuilds false

        abortOnError false
    }
    dexOptions {
        javaMaxHeapSize "4g"
    }
    productFlavors {
    }

    dependencies {
        compile fileTree(include: ['*.jar'], dir: 'libs')
        compile 'com.android.support:appcompat-v7:21.0.3'
        compile 'com.android.support:support-v4:21.0.3'
        compile project(':Recognizer')
        compile project(':contactcard')
        compile project(':sticker')
        compile 'com.android.support:multidex:1.0.1'
        compile 'com.facebook.stetho:stetho:1.4.2'
        compile files('libs/MiPush_SDK_Client_3_1_2.jar')
        compile project(':IMKit')
        compile project(':CallKit')
        compile project(':RedPacket')
        compile 'com.facebook.react:react-native:+'
    }
    apply plugin: 'com.google.gms.google-services'
}


问:
Refresh content of a Div
I have read through multiple posts regarding reloading the content of a div through the use of Jquery. I have a Dashboard with multiple floating divs that rotates data calculated in php scripts.

ie. i have a php script that calculates data and i include this in a div which then scrolls through the content (see below code)

The problem i have with the code examples available online is that it doesnt show my php content.

How can i go about reloading the php pages in the div and still keep my slideshow going?

Thanks in advance

```<code><div class="topdiv_1">
    <div id="topdiv_1_slideshow">
        <div align="center">
            <img src="images/elements/project.png" class="pull-left" alt="" height="100px" style="padding-left: 10px; margin-top: 50px;">
            <h1 style="font-size: 90px; color: #ffffff; font-weight: bold"><?php include_once('topdiv_1_stat1.php') ?></h1>
            <h6 style="font-size: 14px; color: #ffffff; font-weight: bold">Project Hours Total</h6>
        </div>
        <div align="center">
            <img src="images/elements/project.png" class="pull-left" alt="" height="100px"
                 style="padding-left: 10px; margin-top: 50px;">

            <h1 style="font-size: 90px; color: #ffffff; font-weight: bold"><?php include_once('topdiv_1_stat2.php') ?></h1>
            <h6 style="font-size: 14px; color: #ffffff; font-weight: bold">Project Hours System Center</h6>
        </div>
        <div align="center">
            <img src="images/elements/project.png" class="pull-left" alt="" height="100px"
                 style="padding-left: 10px; margin-top: 50px;">

            <h1 style="font-size: 90px; color: #ffffff; font-weight: bold"><?php include_once('topdiv_1_stat3.php') ?></h1>
            <h6 style="font-size: 14px; color: #ffffff; font-weight: bold">Project Hours Service Center</h6>
        </div>
    </div>
</div>
</code>```

UPDATE:

I have tried adding this code to the div but now it throws away the formatting of the returned value:

```<code><div id="topdiv_1_slideshow">
        <div align="center" id="1">
            <img src="images/elements/project.png" class="pull-left" alt="" height="100px" style="padding-left: 10px; margin-top: 50px;">
            <h1 style="font-size: 90px; color: #ffffff; font-weight: bold"><?php /*include_once('topdiv_1_stat1.php') */?>
                <script>
                    $(function(){
                    $("#1").load("topdiv_1_stat1.php");
                    });
                </script>

                </h1>
            <h6 style="font-size: 14px; color: #ffffff; font-weight: bold">Project Hours Total</h6>
        </div>
</code>```

答:
Your code:

```<code>$("#1").load("topdiv_1_stat1.php");
</code>```

will load the raw output of the topdiv_1_stat1.php script.

That means that links to stylesheets in that response will not be loaded as they would when you open the page in your browser.

Make sure your script "topdiv_1_stat1.php"only returns the html that you want in the #1 div.

Title: Refresh content of a Div

Body:
I have read through multiple posts regarding reloading the content of a div through the use of Jquery. I have a Dashboard with multiple floating divs that rotates data calculated in php scripts.

ie. i have a php script that calculates data and i include this in a div which then scrolls through the content (see below code)

The problem i have with the code examples available online is that it doesnt show my php content.

How can i go about reloading the php pages in the div and still keep my slideshow going?

Thanks in advance

<?php include_once('topdiv_1_stat1.php') ?>

Project Hours Total

<?php include_once('topdiv_1_stat2.php') ?>

Project Hours System Center

<?php include_once('topdiv_1_stat3.php') ?>

Project Hours Service Center

UPDATE:

I have tried adding this code to the div but now it throws away the formatting of the returned value:

<?php /*include_once('topdiv_1_stat1.php') */?>

Project Hours Total

Body:
Your code:

$("#1").load("topdiv_1_stat1.php");

will load the raw output of the topdiv_1_stat1.php script.

That means that links to stylesheets in that response will not be loaded as they would when you open the page in your browser.

Make sure your script "topdiv_1_stat1.php"only returns the html that you want in the #1 div.


问:
Naming a FK for a Post Author
I have the following tables

```<code>create table dbo.Users (
  UserId int identity not null,
  Name nvarchar (400) not null
)

create table dbo.Posts (
  PostId int identity not null,
  UserId int not null,
  Title nvarchar (400) not null,
  Content nvarchar (max) not null,
)
</code>```

On table Posts UserId is the author of the post and it is a FK to Users.UserId PK.

In this situations should I name the column UserId which is clear what the relation is or AuthorId describing of it is withing the post?

What is the most common approach for this naming?

答:
As a rule, I try to name foreign key relationships with the same name as the primary key.  So I would use:

```<code>create table dbo.Posts (
    PostId int identity not null,
    UserId int not null,  -- this is the author of the post
    Title nvarchar(400) not null,
    Content nvarchar(max) not null,
    constraint fk_posts_userid foreign key (UserId) references Users(UserId)
);
</code>```

I find that this makes it much easier to write queries and to follow queries that have been written.  This is also practical in databases that support ANSI standard USING syntax.

The one exception is when there are multiple references to the same reference table.  Then I try to include the primary key name in the column name:

```<code>create table dbo.Posts (
    PostId int identity not null,
    Author_UserId int not null,  -- this is the author of the post
    Approver_UserId int not null,
    Title nvarchar(400) not null,
    Content nvarchar(max) not null,
    constraint fk_posts_authoruserid foreign key (Author_UserId) references Users(UserId),
    constraint fk_posts_approveruserid foreign key (Approver_UserId) references Users(UserId)
);
</code>```

Admittedly, this is not the only style for naming, so the answer is a a matter of (informed) opinion.  Many databases name the id column id, for instance, so you couldn't follow this convention.

Title: Naming a FK for a Post Author

Body:
I have the following tables

create table dbo.Users (
  UserId int identity not null,
  Name nvarchar (400) not null
)

create table dbo.Posts (
  PostId int identity not null,
  UserId int not null,
  Title nvarchar (400) not null,
  Content nvarchar (max) not null,
)

On table Posts UserId is the author of the post and it is a FK to Users.UserId PK.

In this situations should I name the column UserId which is clear what the relation is or AuthorId describing of it is withing the post?

What is the most common approach for this naming?

Body:
As a rule, I try to name foreign key relationships with the same name as the primary key.  So I would use:

create table dbo.Posts (
    PostId int identity not null,
    UserId int not null,  -- this is the author of the post
    Title nvarchar(400) not null,
    Content nvarchar(max) not null,
    constraint fk_posts_userid foreign key (UserId) references Users(UserId)
);

I find that this makes it much easier to write queries and to follow queries that have been written.  This is also practical in databases that support ANSI standard USING syntax.

The one exception is when there are multiple references to the same reference table.  Then I try to include the primary key name in the column name:

create table dbo.Posts (
    PostId int identity not null,
    Author_UserId int not null,  -- this is the author of the post
    Approver_UserId int not null,
    Title nvarchar(400) not null,
    Content nvarchar(max) not null,
    constraint fk_posts_authoruserid foreign key (Author_UserId) references Users(UserId),
    constraint fk_posts_approveruserid foreign key (Approver_UserId) references Users(UserId)
);

Admittedly, this is not the only style for naming, so the answer is a a matter of (informed) opinion.  Many databases name the id column id, for instance, so you couldn't follow this convention.


问:
AngularJS: How to change the path after refresh the page
What I want: if the user reloads the page with his redirect to another page.

(Only when updating the page)

Example:
I'm on main/bla and reload the page and I'm redirected to the main/

```<code>window.onbeforeunload = function(e) {
 $state.go('main');
};
</code>```

Does not work for me.

答:
Check once if you are using proper injector in js controller or is there any other error on console.
Check for:

you have given proper state name $state.go('main'),it should defined in routing.

Should use injector $state in controller.

Body:
What I want: if the user reloads the page with his redirect to another page.

(Only when updating the page)

Example:
I'm on main/bla and reload the page and I'm redirected to the main/

window.onbeforeunload = function(e) {
 $state.go('main');
};

Does not work for me.


问:
Haskell, List as input for a function, How?
I've been given the following question in my coursework;

Define a function

```<code>flatten :: [(Char,Int)] -> String
</code>```

that flattens a list of pairs of characters and digits to a string. For example:

```<code>flatten [('a',5),('b',4),('c',2)]
"a5b4c2"
flatten [('d',9),('d',3)]
"d9d3"
</code>```

My problem is that whenever I attempt to define this function i get a type error relating the the [(Char, Int)] input. For example;

```<code>Couldn't match type '(Char, Int)' with '[Char]'
Expected type: [[Char]]
Actual type: [(Char, Int)]
</code>```

I've tried more ways of writing this definition in more ways than I can count, so I don't have any particular code to show, or any particular error ( I kept getting different ones...so many). All i have so far is;

```<code>flatten :: [(Char, Int)] -> String
flatten [] = []
</code>```

i figure my next line should go something like;

```<code>flatten ???? = concat (????)
</code>```

but I have no idea what to put in place of these question marks and Google search/class notes give no examples to follow.
any ideas?

答:
Well it is clear that in the case the list is not empty, it is of the form ((ca,cb):cs) with ca the Char, cb the Int and cs the remainder of the list [(Char,Int)].

In that case we can simply construct a string for that sequence ca:(show cb) with show :: Show a => a -> String we convert an integer to its String counterpart. Next we concatenate the flattening of remainder of the list to that string, so:

```<code>flatten ((ca,cb):cs) = ca:(show cb ++ flatten cs)
</code>```

Or in full:

```<code>flatten :: [(Char, Int)] -> String
flatten [] = []
flatten ((ca,cb):cs) = ca:(show cb ++ flatten cs)
</code>```

Body:
I've been given the following question in my coursework;

Define a function

flatten :: [(Char,Int)] -> String

that flattens a list of pairs of characters and digits to a string. For example:

flatten [('a',5),('b',4),('c',2)]
"a5b4c2"
flatten [('d',9),('d',3)]
"d9d3"

My problem is that whenever I attempt to define this function i get a type error relating the the [(Char, Int)] input. For example;

Couldn't match type '(Char, Int)' with '[Char]'
Expected type: [[Char]]
Actual type: [(Char, Int)]

I've tried more ways of writing this definition in more ways than I can count, so I don't have any particular code to show, or any particular error ( I kept getting different ones...so many). All i have so far is;

flatten :: [(Char, Int)] -> String
flatten [] = []

i figure my next line should go something like;

flatten ???? = concat (????)

but I have no idea what to put in place of these question marks and Google search/class notes give no examples to follow.
any ideas?

Body:
Well it is clear that in the case the list is not empty, it is of the form ((ca,cb):cs) with ca the Char, cb the Int and cs the remainder of the list [(Char,Int)].

In that case we can simply construct a string for that sequence ca:(show cb) with show :: Show a => a -> String we convert an integer to its String counterpart. Next we concatenate the flattening of remainder of the list to that string, so:

flatten ((ca,cb):cs) = ca:(show cb ++ flatten cs)

Or in full:

flatten :: [(Char, Int)] -> String
flatten [] = []
flatten ((ca,cb):cs) = ca:(show cb ++ flatten cs)


问:
Sort php array based on current time
I am currently using the following json data. (The key is a time hh:mm)

```<code> "chart": {
    "23:20": 11,
    "23:30": 11,
    "23:40": 11,
    "23:50": 16,
    "00:00": 16,
    "00:10": 14,
    "00:20": 11,
    "00:30": 12,
    "00:40": 14,
    "00:50": 10,
    "01:00": 8,
    "01:10": 12,
    "01:20": 15,
    "01:30": 13,
    "01:40": 11,
    "01:50": 8,
    "02:00": 8
 }
</code>```

https://pastebin.com/cp16Rr9w

I am then moving the data to a php array. I would like to sort the array, so it starts at the current server time and goes on from there.

At the moment i am using the following php (unsorted)

```<code>  <?php
    foreach ($data['chart'] as $key => $value){
        echo 'Time: '.$key.'Data: '.$value;
    }
  ?>
</code>```

Title: Sort php array based on current time

Body:
I am currently using the following json data. (The key is a time hh:mm)

 "chart": {
    "23:20": 11,
    "23:30": 11,
    "23:40": 11,
    "23:50": 16,
    "00:00": 16,
    "00:10": 14,
    "00:20": 11,
    "00:30": 12,
    "00:40": 14,
    "00:50": 10,
    "01:00": 8,
    "01:10": 12,
    "01:20": 15,
    "01:30": 13,
    "01:40": 11,
    "01:50": 8,
    "02:00": 8
 }

https://pastebin.com/cp16Rr9w

I am then moving the data to a php array. I would like to sort the array, so it starts at the current server time and goes on from there.

At the moment i am using the following php (unsorted)

  <?php
    foreach ($data['chart'] as $key => $value){
        echo 'Time: '.$key.'Data: '.$value;
    }
  ?>

Body:
Try it:

$data = json_decode('{"chart": {
    "23:20": 11,
    "23:30": 11,
    "23:40": 11,
    "23:50": 16,
    "00:00": 16,
    "00:10": 14,
    "00:20": 11,
    "00:30": 12,
    "00:40": 14,
    "00:50": 10,
    "01:00": 8,
    "01:10": 12,
    "01:20": 15,
    "01:30": 13,
    "01:40": 11,
    "01:50": 8,
    "02:00": 8
}}');

$data = (array) $data->chart;

function sort_time($a, $b) { return strtotime($a) > strtotime($b); }

uksort($data, 'sort_time' );

foreach ($data as $key => $value) {
    echo "$key: $value\n";
}


问:
Setting Up Apollo Server with subscriptions-transport-ws?
It seems like I have my server set up according to the Apollo docs at http://dev.apollodata.com/tools/apollo-server/setup.html. In my server/main.js file:

```<code>//SET UP APOLLO INCLUDING APOLLO PUBSUB
const executableSchema = makeExecutableSchema({
    typeDefs: Schema,
    resolvers: Resolvers,
    connectors: Connectors,
    logger: console,
});

const GRAPHQL_PORT = 8080;
const graphQLServer = express();

// `context` must be an object and can't be undefined when using connectors
graphQLServer.use('/graphql', bodyParser.json(), apolloExpress({
    schema: executableSchema,
    context: {}, //at least(!) an empty object
}));

graphQLServer.use('/graphiql', graphiqlExpress({
    endpointURL: '/graphql',
}));

graphQLServer.listen(GRAPHQL_PORT, () => console.log(
    `GraphQL Server is now running on http://localhost:${GRAPHQL_PORT}/graphql`
));
//SET UP APOLLO INCLUDING APOLLO PUBSUB
</code>```

It prints out "GraphQL Server is now running on http://localhost:8080/graphql" to the terminal log indicating that the server was successfully initialized.

But at the top of my main_layout component, when I run this code:

```<code>import { Client } from 'subscriptions-transport-ws';
const wsClient = new Client('ws://localhost:8080');
</code>```

...I get this console message:

WebSocket connection to 'ws://localhost:8080/' failed: Connection closed before receiving a handshake response

What am I missing?

答:
TL;DR: You can use graphql-up to quickly get a GraphQL server with subscriptions support up and ready. Here's a more detailed tutorial on using this in combination with Apollo and the websocket client subscriptions-transport-ws.

Obtain a GraphQL Server with one click

Let's say you want to build a Twitter clone based on this GraphQL Schema in IDL syntax:

```<code>type Tweet {
  id: ID!
  title: String!
  author: User! @relation(name: "Tweets")
}

type User {
  id: ID!
  name: String!
  tweets: [Tweet!]! @relation(name: "Tweets")
}
</code>```

Click this button to receive your own GraphQL API and then open the Playground, where you can add some tweets, query all tweets and also test out subscriptions.

Simple to use API

First, let's create a user that will be the author for all coming tweets. Run this mutation in the Playground:

```<code>mutation createUser {
  createUser(name: "Tweety") {
    id # copy this id for future mutations!
  }
}
</code>```

Here's how you query all tweets and their authors stored at your GraphQL server:

```<code>query allTweets {
  allTweets {
    id
    title
    createdAt
    author {
      id
      name
    }
  }
}
</code>```

Subscription support using websockets

Let's now subscribe to new tweets from "Tweety". This is the syntax:

```<code>subscription createdTweets {
  Message(filter: {
    mutation_in: [CREATED]
    node: {
      author: {
        name: "Tweety"
      }
    }
  }) {
    node {
      id
      text
      createdAt
      sentBy {
        id
        name
      }
    }
  }
}
</code>```

Now create a new tab in the Playground and create a new Tweet:

```<code>mutation createTweet {
  createTweet(
    title: "#GraphQL Subscriptions are awesome!"
    authorId: "<id-from-above>"
  ) {
    id
  }
}
</code>```

You should see a new event popping up in your other tab where you subscribed before.

Body:
It seems like I have my server set up according to the Apollo docs at http://dev.apollodata.com/tools/apollo-server/setup.html. In my server/main.js file:

//SET UP APOLLO INCLUDING APOLLO PUBSUB
const executableSchema = makeExecutableSchema({
    typeDefs: Schema,
    resolvers: Resolvers,
    connectors: Connectors,
    logger: console,
});

const GRAPHQL_PORT = 8080;
const graphQLServer = express();

// `context` must be an object and can't be undefined when using connectors
graphQLServer.use('/graphql', bodyParser.json(), apolloExpress({
    schema: executableSchema,
    context: {}, //at least(!) an empty object
}));

graphQLServer.use('/graphiql', graphiqlExpress({
    endpointURL: '/graphql',
}));

graphQLServer.listen(GRAPHQL_PORT, () => console.log(
    `GraphQL Server is now running on http://localhost:${GRAPHQL_PORT}/graphql`
));
//SET UP APOLLO INCLUDING APOLLO PUBSUB

It prints out "GraphQL Server is now running on http://localhost:8080/graphql" to the terminal log indicating that the server was successfully initialized.

But at the top of my main_layout component, when I run this code:

import { Client } from 'subscriptions-transport-ws';
const wsClient = new Client('ws://localhost:8080');

...I get this console message:

WebSocket connection to 'ws://localhost:8080/' failed: Connection closed before receiving a handshake response

What am I missing?

Body:
TL;DR: You can use graphql-up to quickly get a GraphQL server with subscriptions support up and ready. Here's a more detailed tutorial on using this in combination with Apollo and the websocket client subscriptions-transport-ws.

Obtain a GraphQL Server with one click

Let's say you want to build a Twitter clone based on this GraphQL Schema in IDL syntax:

type Tweet {
  id: ID!
  title: String!
  author: User! @relation(name: "Tweets")
}

type User {
  id: ID!
  name: String!
  tweets: [Tweet!]! @relation(name: "Tweets")
}

Click this button to receive your own GraphQL API and then open the Playground, where you can add some tweets, query all tweets and also test out subscriptions.

Simple to use API

First, let's create a user that will be the author for all coming tweets. Run this mutation in the Playground:

mutation createUser {
  createUser(name: "Tweety") {
    id # copy this id for future mutations!
  }
}

Here's how you query all tweets and their authors stored at your GraphQL server:

query allTweets {
  allTweets {
    id
    title
    createdAt
    author {
      id
      name
    }
  }
}

Subscription support using websockets

Let's now subscribe to new tweets from "Tweety". This is the syntax:

subscription createdTweets {
  Message(filter: {
    mutation_in: [CREATED]
    node: {
      author: {
        name: "Tweety"
      }
    }
  }) {
    node {
      id
      text
      createdAt
      sentBy {
        id
        name
      }
    }
  }
}

Now create a new tab in the Playground and create a new Tweet:

mutation createTweet {
  createTweet(
    title: "#GraphQL Subscriptions are awesome!"
    authorId: "<id-from-above>"
  ) {
    id
  }
}

You should see a new event popping up in your other tab where you subscribed before.