问:
Insert Operation is not working through Angular JS
I am trying to perform insert operation using Angular JS and mysql but it is working. Please check the below code and help me to find out the issues.

Following is the code of my index.html file

```<code><html ng-app="myapp">
   <head>
      <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
      <script src="js/bootstrap.min.js"></script>
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
   </head>
   <body ng-controller="formctrl" novalidate>
      <form ng-submit="submitStudentForm()">
         <input type="text" name="fname" ng-model="fname" placeholder="First Name"><br>
         <input type="text" name="lname" ng-model="lname" placeholder="Last Name"><br>
         <input type="submit" value="Submit" name="submit"/>
      </form>
      <script>
         var app = angular.module('myapp', []);
         app.controller('formctrl', function ($scope, $http) {
                 $scope.submitStudentForm = function () {
                     $http.post("add.php");
                 };
             }
         );

      </script>
   </body>
</html>
</code>```

Following is the code of add.php

```<code><?php
$conn = new mysqli("localhost", "root", "root", "test2");
if (isset($_POST['submit'])) {
    $submit = $_POST['submit'];
    $fname  = $_POST['fname'];
    $lname  = $_POST['lname'];
    $sql    = "INSERT into info(fname, lname)
    VALUES ('$fname', '$lname')";
    $result = mysqli_query($conn, $sql);
    if ($result) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
}
$conn->close();
?>
</code>```

答:
I bet u have no data to post on your http post. try editing on your http post:</p>

```<code>$http.post("add.php", {
'fname':$scope.fname,
'lname':$scope.lname})
</code>```

Body:
I am trying to perform insert operation using Angular JS and mysql but it is working. Please check the below code and help me to find out the issues.

Following is the code of my index.html file

      <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">

      <form ng-submit="submitStudentForm()">
         <input type="text" name="fname" ng-model="fname" placeholder="First Name">

         <input type="text" name="lname" ng-model="lname" placeholder="Last Name">

         <input type="submit" value="Submit" name="submit"/>
      </form>

Following is the code of add.php

<?php
$conn = new mysqli("localhost", "root", "root", "test2");
if (isset($_POST['submit'])) {
    $submit = $_POST['submit'];
    $fname  = $_POST['fname'];
    $lname  = $_POST['lname'];
    $sql    = "INSERT into info(fname, lname)
    VALUES ('$fname', '$lname')";
    $result = mysqli_query($conn, $sql);
    if ($result) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "
" . $conn->error;
    }
}
$conn->close();
?>

Body:
I bet u have no data to post on your http post. try editing on your http post:

$http.post("add.php", {
'fname':$scope.fname,
'lname':$scope.lname})


来源: stackexchange

问:
Can Intraweb + Delphi handle an authorize.net relay response using SIM?
We* have a web application, created by Delphi + Intraweb (for the front end/web code management) that manages an ordering process. It acquires ordering information, then sends a transaction request to authorize.net (essentially using their SIM sample code). This works beautifully, and the credit card order is processed.

However, when authorize.net sends the form post back to the relay response url (http://developer.authorize.net/guides/SIM/Receipt_Options/Relay_Response.htm), the Intraweb app blows up. I can see, using TamperData, that the form data is being sent correctly. She can see that her program opens a database connection, then times out.

I've exhausted my google-fu, and haven't found any examples of Intraweb code being able to accept incoming form posts. (That's probably all we really need. If we could get the data into the Intraweb/Delphi world, we could then manage the rest.)

The Intraweb documentation suggests that IW will accept params passed on a URL, but doesn't mention accepting POST data.

The authorize.net community forum has an asked/answered post, that says basically "Sorry, we don't have any Delphi code samples, ask your vendor."

Intraweb Tech Support hasn't been able to help her. (I think they haven't responded to the request from several weeks ago, but I'm not certain.)

I suggested that she create a test application stub that mimicked the authorize.net form post, to be sure that the form objects were being properly created. (I don't really understand what's happening under the covers of the drag-n-drop form fields, but I poured over the generated source code to try to figure this out.) But a form POST is a form POST, right? I mean, it's HTTP, not magic. But there were two problems with that. 1.) Intraweb seems to force form field names to all CAPS. 2.) She says that IW won't accept underscores as a part of the form field name. And of course, we're stuck with what authorize.net sends, lower-case, underscore separated, and all.

Do you have any insights, pointers to sample code, or advice to chuck it all and move to another solution? We'd greatly appreciate any of the above.

*We = an old-skool Delphi programmer/DBA who knows Delphi inside out but Intraweb "automagically works" and me, a Java programmer and occasional PHP hacker on the other side of the country, who's allergic to visual IDE's but trying to interpret teh Internets & the mysteries of HTTP for her. For this particular problem, we appear to be less than the sum of our parts.

答:
Thanks to pointers from @ioan, we've got a SOAP solution up and running. It took my colleague a bit of trial and error to write the Pascal code, but she passed it on to me to post in case it saves anyone else some time. Here's what she ended up with:

```<code>procedure TfrmSOAP.btnGetUnsettledReportClick(Sender: TObject);
var
  X : ServiceSoap;
  MyAuthentication : MerchantAuthenticationType;
  MyRequest : GetUnsettledTransactionListRequestType;
  aResponse : GetUnsettledTransactionListResponseType;
  msg : string;
  i : integer;
begin
  inherited;
  //Call the service
  X := GetServiceSoap(false);
  //create some variables/parameters to pass back and forth
  MyAuthentication := MerchantAuthenticationType.Create;
  MyRequest := GetUnsettledTransactionListRequestType.Create;
  aResponse := GetUnsettledTransactionListResponseType.Create;
  try
    //assign values to the MerchantAuthenticationType parameter
    MyAuthentication.name_ := APILoginTest;
    MyAuthentication.transactionKey := TransKeyTest;
    //request a list of unsettled transactions
    aResponse := X.GetUnsettledTransactionList(MyAuthentication, MyRequest);
    //check to see if the request was successful
    if aResponse.resultCode <> messagetypeenum(0) then
        begin
          ShowMsg('Error');
          ShowMsg(aResponse.messages[0].text);
        end;
    //step through the list, and display i, InvoiceNo, and LastName.
    for i := 0 to high(aResponse.transactions) do
       msg := msg + IntToStr(i) + ') ' + aResponse.transactions[i].invoiceNumber
              + '  '+ aResponse.transactions[i].lastName + #13;
    ShowMsg(msg);
  finally
    MyRequest.Free;
    MyAuthentication.Free;
    aResponse.Free;
  end;
end;
</code>```

She also sends the reminder to be sure you're using the right info when running tests vs. production: "I was using the URL in the downloaded WSDL.  Which is for production accounts.  You must use a different one for test accounts. So I kept getting an empty list, and thought it was error in my code, not getting a response."

Thanks again for all of the help and suggestions!

ContentLicense: CC BY-SA 2.5

Body:
Thanks to pointers from @ioan, we've got a SOAP solution up and running. It took my colleague a bit of trial and error to write the Pascal code, but she passed it on to me to post in case it saves anyone else some time. Here's what she ended up with:

procedure TfrmSOAP.btnGetUnsettledReportClick(Sender: TObject);
var
  X : ServiceSoap;
  MyAuthentication : MerchantAuthenticationType;
  MyRequest : GetUnsettledTransactionListRequestType;
  aResponse : GetUnsettledTransactionListResponseType;
  msg : string;
  i : integer;
begin
  inherited;
  //Call the service
  X := GetServiceSoap(false);
  //create some variables/parameters to pass back and forth
  MyAuthentication := MerchantAuthenticationType.Create;
  MyRequest := GetUnsettledTransactionListRequestType.Create;
  aResponse := GetUnsettledTransactionListResponseType.Create;
  try
    //assign values to the MerchantAuthenticationType parameter
    MyAuthentication.name_ := APILoginTest;
    MyAuthentication.transactionKey := TransKeyTest;
    //request a list of unsettled transactions
    aResponse := X.GetUnsettledTransactionList(MyAuthentication, MyRequest);
    //check to see if the request was successful
    if aResponse.resultCode <> messagetypeenum(0) then
        begin
          ShowMsg('Error');
          ShowMsg(aResponse.messages[0].text);
        end;
    //step through the list, and display i, InvoiceNo, and LastName.
    for i := 0 to high(aResponse.transactions) do
       msg := msg + IntToStr(i) + ') ' + aResponse.transactions[i].invoiceNumber
              + '  '+ aResponse.transactions[i].lastName + #13;
    ShowMsg(msg);
  finally
    MyRequest.Free;
    MyAuthentication.Free;
    aResponse.Free;
  end;
end;

She also sends the reminder to be sure you're using the right info when running tests vs. production: "I was using the URL in the downloaded WSDL.  Which is for production accounts.  You must use a different one for test accounts. So I kept getting an empty list, and thought it was error in my code, not getting a response."

Thanks again for all of the help and suggestions!

ContentLicense: CC BY-SA 3.0


问:
Long polling in minute or single scheduler for a task - Approach for a notification system
I have a requirement in which, I will plan multiple tasks for certain interval. And for each task a notification has to be pushed at certain interval of time.
I have two approaches, Either to write a single scheduler which will poll at each one minute and push the notification accordingly. Or I can schedule initialize a scheduler for each task. With the former method the solution is pretty much simple, with the later I can get more control on the scheduler, for instance I can put initial delay for each task specifically(Which is a requirement), then stop an individual task, resume etc. So far I am proceeding with the latter method. But I would like to know If it could be better to use so many scheduler in a single application. Or is it better to go with a single scheduler with 1 minute polling?. On an average I will have about 200+ tasks live at a time. Or for this can I depend on any other library?

So far my code
Sheduler which is an ExecutorService

```<code>       //Constructor
            public TaskScheduler(String taskName) {
                this.taskName = taskName;
                this.taskResult = new TaskResult();
                this.taskResult.setStartTime(getNewDate());
                scheduledExecutorService = Executors.newScheduledThreadPool(1);
//DB Operation
            }

    // To stop an individual task
                public TaskResult stop() throws InterruptedException {
                    try {
                        System.out.println("Stopping : " + this.taskName);
                        this.taskResult.setTaskName(this.taskName);
                        this.taskResult.setEndTime(new Date());
                        scheduledFuture.cancel(false);
                        scheduledExecutorService.shutdown();
//DB Operation
                        System.out.println("Stopping : finished - " + this.taskName + " @ "+ new Date());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return this.taskResult;
                }

        //Portion to add task
            public TaskScheduler schedule(Runnable task, long initialDelay, long frequency) throws Exception{
                this.taskResult.setFrequencyInSeconds(frequency);
                scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(task, initialDelay, frequency, TimeUnit.SECONDS);
                return this;
            }
</code>```

Task thread with business logic

```<code>        public class TaskModel implements Runnable {
            private String taskName;

            public TaskModel() {

            }

            public TaskModel(String taskName) {
                this.taskName = taskName;
            }

            @Override
            public void run() {
//     DB operations
    .
    .
</code>```

答:
It is better to use a single scheduler, but you don't need to write your own scheduler for this. You could use single instance Executors.newScheduledThreadPool(1) with some number of threads to schedule all your tasks.

Think about the following code:

```<code>class TaskScheduler {
    private ScheduledExecutorService scheduledExecutorService;

    public TaskScheduler(int threads) {
        this.scheduledExecutorService = Executors.newScheduledThreadPool(threads);
    }

    //Portion to add task
    public TaskExecutionContext schedule(String taskName, Runnable task, long initialDelay, long frequency) {
        TaskExecutionContext context = new TaskExecutionContext(taskName);
        context.getTaskResult().setFrequencyInSeconds(frequency);
        ScheduledFuture scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(task, initialDelay, frequency, TimeUnit.SECONDS);
        context.setScheduledFuture(scheduledFuture);
        return context;
    }
}

class TaskExecutionContext {
    private String taskName;
    private TaskResult taskResult;

    private ScheduledFuture scheduledFuture;

    public TaskExecutionContext(String taskName) {
        this.taskName = taskName;
        this.taskResult = new TaskResult();
        this.taskResult.setTaskName(taskName);
        this.taskResult.setStartTime(new Date());
        //DB Operation on creation
    }

    public TaskResult stop() {
        try {
            System.out.println("Stopping : " + this.taskName);
            this.taskResult.setTaskName(this.taskName);
            this.taskResult.setEndTime(new Date());
            scheduledFuture.cancel(false);
//DB Operation on stopping
            System.out.println("Stopping : finished - " + this.taskName + " @ " + new Date());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return this.taskResult;
    }

    public TaskResult getTaskResult() {
        return this.taskResult;
    }

    public void setScheduledFuture(ScheduledFuture scheduledFuture) {
        this.scheduledFuture = scheduledFuture;
    }
}
</code>```

If you need some extra operations on scheduling, creation and stopping tasks - probably, it's better to have separate TaskExecutionContext, which will perform all your needs.

Create a context when you need to schedule a task and pass it to scheduler.

ContentLicense: CC BY-SA 4.0

Body:
I have a requirement in which, I will plan multiple tasks for certain interval. And for each task a notification has to be pushed at certain interval of time.
I have two approaches, Either to write a single scheduler which will poll at each one minute and push the notification accordingly. Or I can schedule initialize a scheduler for each task. With the former method the solution is pretty much simple, with the later I can get more control on the scheduler, for instance I can put initial delay for each task specifically(Which is a requirement), then stop an individual task, resume etc. So far I am proceeding with the latter method. But I would like to know If it could be better to use so many scheduler in a single application. Or is it better to go with a single scheduler with 1 minute polling?. On an average I will have about 200+ tasks live at a time. Or for this can I depend on any other library?

So far my code
Sheduler which is an ExecutorService

       //Constructor
            public TaskScheduler(String taskName) {
                this.taskName = taskName;
                this.taskResult = new TaskResult();
                this.taskResult.setStartTime(getNewDate());
                scheduledExecutorService = Executors.newScheduledThreadPool(1);
//DB Operation
            }

    // To stop an individual task
                public TaskResult stop() throws InterruptedException {
                    try {
                        System.out.println("Stopping : " + this.taskName);
                        this.taskResult.setTaskName(this.taskName);
                        this.taskResult.setEndTime(new Date());
                        scheduledFuture.cancel(false);
                        scheduledExecutorService.shutdown();
//DB Operation
                        System.out.println("Stopping : finished - " + this.taskName + " @ "+ new Date());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return this.taskResult;
                }

        //Portion to add task
            public TaskScheduler schedule(Runnable task, long initialDelay, long frequency) throws Exception{
                this.taskResult.setFrequencyInSeconds(frequency);
                scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(task, initialDelay, frequency, TimeUnit.SECONDS);
                return this;
            }

Task thread with business logic

        public class TaskModel implements Runnable {
            private String taskName;

            public TaskModel() {

            }

            public TaskModel(String taskName) {
                this.taskName = taskName;
            }

            @Override
            public void run() {
//     DB operations
    .
    .

Body:
It is better to use a single scheduler, but you don't need to write your own scheduler for this. You could use single instance Executors.newScheduledThreadPool(1) with some number of threads to schedule all your tasks.

Think about the following code:

class TaskScheduler {
    private ScheduledExecutorService scheduledExecutorService;

    public TaskScheduler(int threads) {
        this.scheduledExecutorService = Executors.newScheduledThreadPool(threads);
    }

    //Portion to add task
    public TaskExecutionContext schedule(String taskName, Runnable task, long initialDelay, long frequency) {
        TaskExecutionContext context = new TaskExecutionContext(taskName);
        context.getTaskResult().setFrequencyInSeconds(frequency);
        ScheduledFuture scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(task, initialDelay, frequency, TimeUnit.SECONDS);
        context.setScheduledFuture(scheduledFuture);
        return context;
    }
}

class TaskExecutionContext {
    private String taskName;
    private TaskResult taskResult;

    private ScheduledFuture scheduledFuture;

    public TaskExecutionContext(String taskName) {
        this.taskName = taskName;
        this.taskResult = new TaskResult();
        this.taskResult.setTaskName(taskName);
        this.taskResult.setStartTime(new Date());
        //DB Operation on creation
    }

    public TaskResult stop() {
        try {
            System.out.println("Stopping : " + this.taskName);
            this.taskResult.setTaskName(this.taskName);
            this.taskResult.setEndTime(new Date());
            scheduledFuture.cancel(false);
//DB Operation on stopping
            System.out.println("Stopping : finished - " + this.taskName + " @ " + new Date());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return this.taskResult;
    }

    public TaskResult getTaskResult() {
        return this.taskResult;
    }

    public void setScheduledFuture(ScheduledFuture scheduledFuture) {
        this.scheduledFuture = scheduledFuture;
    }
}

If you need some extra operations on scheduling, creation and stopping tasks - probably, it's better to have separate TaskExecutionContext, which will perform all your needs.

Create a context when you need to schedule a task and pass it to scheduler.


问:
router.post can't pass data
```<code>$.post($gameNetwork._serverURL+'/addfriend',
{username:"r",tusername:"w"}).done(function (data) {
console.log("finished");
 });

Account.statics.

    friend = function(name,tname,cb) {

        return this.findOneAndUpdate(

        { 'username':  name },

        { $push: {'friendlist': tname}},

        { upsert: true, new: true},

        cb);

    };
</code>```

route

```<code>router.post('/addfriend',  function(req, res) {

//Account.findByName(req.body.username, function(err, account){
    Account.friend(req.body.username,req.body.tusername, function(err, account){
 if (err) {
      return res.status(203).json({
        err: err.msg
      });}
    if (!account) {
      return res.status(203).json({
        err: "Invalid username"
      });}
        var tname = req.body.tusername;

    var profile = {
        tname : tname,
      name: account.username,
      email: account.email,
      id: account._id,
      rank: account.rank
    };  });
</code>```

this code should enter "w" in to the field 'friendlist' in Mongodb,  but I got null instead of w.

how can I get "w" into the field 'friendlist' in Mongodb.
Any help is appreciated
Thanks in advance

答:
router in an ExpressJS router?

If yes did you set the bodyParser middleware?

If not, set it like this

```<code>const express = require('express')
const bodyParser = require('body-parser')

const app = express()

// parse application/json
app.use(bodyParser.json())
</code>```

You can also try to stringify the body in the ajax request like described here

Title: router.post can't pass data

Body:
$.post($gameNetwork._serverURL+'/addfriend',
{username:"r",tusername:"w"}).done(function (data) {
console.log("finished");
 });

Account.statics.

    friend = function(name,tname,cb) {

        return this.findOneAndUpdate(

        { 'username':  name },

        { $push: {'friendlist': tname}},

        { upsert: true, new: true},

        cb);

    };

route

router.post('/addfriend',  function(req, res) {

//Account.findByName(req.body.username, function(err, account){
    Account.friend(req.body.username,req.body.tusername, function(err, account){
 if (err) {
      return res.status(203).json({
        err: err.msg
      });}
    if (!account) {
      return res.status(203).json({
        err: "Invalid username"
      });}
        var tname = req.body.tusername;

    var profile = {
        tname : tname,
      name: account.username,
      email: account.email,
      id: account._id,
      rank: account.rank
    };  });

this code should enter "w" in to the field 'friendlist' in Mongodb,  but I got null instead of w.

how can I get "w" into the field 'friendlist' in Mongodb.
Any help is appreciated
Thanks in advance

Body:
router in an ExpressJS router?

If yes did you set the bodyParser middleware?

If not, set it like this

const express = require('express')
const bodyParser = require('body-parser')

const app = express()

// parse application/json
app.use(bodyParser.json())

You can also try to stringify the body in the ajax request like described here


问:
Unable to load app preview in iTunes connect
Has anyone been able to load an app preview video in iTunes connect?  I receive an error every time, saying "Your file could not be loaded.  Please try again."

Any workaround to this, that you're aware of?

答:
I use ffmpeg to modify videos so they are accepted in iTunes connect (modify as you need):

```<code># Reduce frame rate from 60 to 30
ffmpeg -y -r 30 -i input.mp4 -strict -2 output-almost.mp4
ffmpeg -y -i output-almost.mp4 -filter:v "setpts=0.5*PTS"  -strict -2 output.mp4
rm -f output-almost.mp4

# Trim video
# From second 10, take 30 seconds
ffmpeg -i input.mp4 -strict -2 -ss 10 -t 30 -async 1 output.mp4

# Set codec, bitrate, etc....
ffmpeg -i input.mp4 -c:v libx264 -profile:v baseline -level 4.0 -pix_fmt yuv420p -c:a aac -ac 2 -b:a 256k -b:v 10M  -movflags faststart -strict -2 output.mp4
</code>```

Also, sometimes when I press "save" in iTunes connect, after I uploaded the video, I get an error. But, then I change the tab to see another screenshots size, then I go back, press save again, and... it's saved without any error (awesome Apple...)

Body:
I use ffmpeg to modify videos so they are accepted in iTunes connect (modify as you need):

# Reduce frame rate from 60 to 30
ffmpeg -y -r 30 -i input.mp4 -strict -2 output-almost.mp4
ffmpeg -y -i output-almost.mp4 -filter:v "setpts=0.5*PTS"  -strict -2 output.mp4
rm -f output-almost.mp4

# Trim video
# From second 10, take 30 seconds
ffmpeg -i input.mp4 -strict -2 -ss 10 -t 30 -async 1 output.mp4

# Set codec, bitrate, etc....
ffmpeg -i input.mp4 -c:v libx264 -profile:v baseline -level 4.0 -pix_fmt yuv420p -c:a aac -ac 2 -b:a 256k -b:v 10M  -movflags faststart -strict -2 output.mp4

Also, sometimes when I press "save" in iTunes connect, after I uploaded the video, I get an error. But, then I change the tab to see another screenshots size, then I go back, press save again, and... it's saved without any error (awesome Apple...)


问:
Custom font loads on defining @font-face or when used in font-family
As the title says, I have a lot of custom fonts to be referenced on a site where I will have different pages using a few of the fonts at once and not all.

I don't want to impact the site performance so want to know whether the browser loads the font files on defining the @font-face itself or waits for it to be first used in a font-family

答: On analyzing the network tab, it looks like the font files are not loaded unless and until one does not use them in the font-family thus it is safe to use as many declarations as @font-face without slowing down the site.


问:
Can I rely on the using statement to close my MySQL connections?
I have an ASP.NET website that uses mysql as it's database. I notice there are a lot of connections "sleeping" when I show a full process list. Today we had some errors "The timeout period elapsed prior to obtaining a connection from the pool.". If the processes are "sleeping" then are they still open from the code? All MySQL connections in the code are in using statements. Can I rely on the using statement to properly close connections?

Edit Code:
I am using this class to create my connection:

```<code>public class DbAccess
{
    public static MySqlConnection OpenConnection(string connectionStringName)
    {
        string connectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
        if (string.IsNullOrEmpty(connectionString))
        {
            throw new ArgumentException("Connection string " + connectionStringName + " does not exist.");
        }
        MySqlConnection connection = new MySqlConnection(connectionString);
        connection.Open();
        return connection;
    }
}
</code>```

Then I am calling it like this:

```<code>using (MySqlConnection connection = DbAccess.OpenConnection(connectionString))
{
    //Code Here
}
</code>```

Some additional info: Resetting MySql did not make the errors go away, but resetting my app pool did..

答:
hope this could be of any help: MySqlConnection really not close
and
Using MySQLConnection in C# does not close properly
and this one
http://social.msdn.microsoft.com/Forums/en/adodotnetdataproviders/thread/c57c0432-c27b-45ab-81ca-b2df76c911ef</p>

Body:
I have an ASP.NET website that uses mysql as it's database. I notice there are a lot of connections "sleeping" when I show a full process list. Today we had some errors "The timeout period elapsed prior to obtaining a connection from the pool.". If the processes are "sleeping" then are they still open from the code? All MySQL connections in the code are in using statements. Can I rely on the using statement to properly close connections?

Edit Code:
I am using this class to create my connection:

public class DbAccess
{
    public static MySqlConnection OpenConnection(string connectionStringName)
    {
        string connectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
        if (string.IsNullOrEmpty(connectionString))
        {
            throw new ArgumentException("Connection string " + connectionStringName + " does not exist.");
        }
        MySqlConnection connection = new MySqlConnection(connectionString);
        connection.Open();
        return connection;
    }
}

Then I am calling it like this:

using (MySqlConnection connection = DbAccess.OpenConnection(connectionString))
{
    //Code Here
}

Some additional info: Resetting MySql did not make the errors go away, but resetting my app pool did..


问:
lzma is failed to createobjectfunc for rar using c++
There is failed to CreateObject by passing

rar(clsid = 23170F69-40C1-278A-1000-000110030000)

the lzma sdk is lzma1900. the testing dll(7zra.dll) is compiled by vs2008 nmake in "lzma1900\CPP\7zip\Bundles\Format7zR".

How to compile the lzma to extract .rar file? any idea is much appreciated.

it's ok by passing 7z(23170F69-40C1-278A-1000-000110070000).

```<code>DEFINE_GUID(CLSID_CFormatRar,
  0x23170F69, 0x40C1, 0x278A, 0x10, 0x00, 0x00, 0x01, 0x10, 0x03, 0x00, 0x00);

#define kDllName "7zra.dll"

int MY_CDECL main(int numArgs, const char *args[])
{
NT_CHECK

  NDLL::CLibrary lib;
  if (!lib.Load(NDLL::GetModuleDirPrefix() + FTEXT(kDllName)))
  {
    PrintError("Can not load 7-zip library");
    return 1;
  }

  Func_CreateObject createObjectFunc = (Func_CreateObject)lib.GetProc("CreateObject");
  if (!createObjectFunc)
  {
    PrintError("Can not get CreateObject");
    return 1;
  }

//the code context extracts from lzma1900\CPP\7zip\UI\Client7z\Client7z.cpp
//always failed if set rar
CMyComPtr<IInArchive> archive;
    if (createObjectFunc(&CLSID_CFormatRar, &IID_IInArchive, (void **)&archive) != S_OK)
    {
      PrintError("Can not get class object");
      return 1;
    }

  //...
}
</code>```

答:
figure it out.lzma sdk doesn't contain rar unpack code, 7z1900 source code is ok.

the target dll is complied from 7z1900\CPP\7zip\Bundles\Format7zF

Body:
There is failed to CreateObject by passing

rar(clsid = 23170F69-40C1-278A-1000-000110030000)

the lzma sdk is lzma1900. the testing dll(7zra.dll) is compiled by vs2008 nmake in "lzma1900\CPP\7zip\Bundles\Format7zR".

How to compile the lzma to extract .rar file? any idea is much appreciated.

it's ok by passing 7z(23170F69-40C1-278A-1000-000110070000).

DEFINE_GUID(CLSID_CFormatRar,
  0x23170F69, 0x40C1, 0x278A, 0x10, 0x00, 0x00, 0x01, 0x10, 0x03, 0x00, 0x00);

#define kDllName "7zra.dll"

int MY_CDECL main(int numArgs, const char *args[])
{
NT_CHECK

  NDLL::CLibrary lib;
  if (!lib.Load(NDLL::GetModuleDirPrefix() + FTEXT(kDllName)))
  {
    PrintError("Can not load 7-zip library");
    return 1;
  }

  Func_CreateObject createObjectFunc = (Func_CreateObject)lib.GetProc("CreateObject");
  if (!createObjectFunc)
  {
    PrintError("Can not get CreateObject");
    return 1;
  }

//the code context extracts from lzma1900\CPP\7zip\UI\Client7z\Client7z.cpp
//always failed if set rar
CMyComPtr<IInArchive> archive;
    if (createObjectFunc(&CLSID_CFormatRar, &IID_IInArchive, (void **)&archive) != S_OK)
    {
      PrintError("Can not get class object");
      return 1;
    }

  //...
}


问:
How to display Greek letters using sympy.printing.mathml
I use Python's Sympy module.

The Sympy module has a library called sympy.printing.mathml, which converts formulas into mathml.

However, I could not convert Greek letters such as α and β to mathml.

How can I solve this problem if I want to insert Greek letters into the formula?

ーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーー

I want to get mathml like example2 from python's formula like example1.

example1

```<code>S=abs(a)*(β-α)^3/6
</code>```

example2

```<code><math><mi>S</mi><mo>=</mo><mstyle displaystyle='true'><mfrac><mrow><mo>|</mo><mi>a</mi><mo>|</mo><mo><!--FUNCTION APPLICATION--></mo><mo>(</mo><mo>β</mo><mo>-</mo><mo>α</mo><msup><mo>)</mo><mn>3</mn></msup></mrow><mrow><mn>6</mn></mrow></mfrac></mstyle></math>
</code>```

I executed the following code.

```<code>from sympy import *
from sympy.printing.mathml import mathml
print(mathml(S=abs(a)*(β-α)^3/6,printer='presentation'))
</code>```

答:
In a terminal that supported copy/paste of Greek characters, I was able to create a variable with Greek name, e.g. beta = Symbol('beta') where beta was a literal Greek character. The output of the formula you gave -- using ** instead of ^ is identical to the code generated when the symbols for alpha and beta are imported from abc:

```<code>>>> from sympy.abc import alpha, beta
>>> print(mathml(abs(a)*(beta-alpha)**3/6, printer='presentation'))
<mrow><mfrac><mrow><msup><mfenced><mrow><mrow><mo>-</mo><mi>α</
o>+</mo><mi>β</mi></mrow></mfenced><mn>3</mn></msup><mo>&Invisi
o><mrow><mfenced close="|" open="|"><mi>a</mi></mfenced></mrow></mro
</mfrac></mrow>
</code>```

Body:
I use Python's Sympy module.

The Sympy module has a library called sympy.printing.mathml, which converts formulas into mathml.

However, I could not convert Greek letters such as α and β to mathml.

How can I solve this problem if I want to insert Greek letters into the formula?

ーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーー

I want to get mathml like example2 from python's formula like example1.

example1

S=abs(a)*(β-α)^3/6

example2

<math><mi>S</mi><mo>=</mo><mstyle displaystyle='true'><mfrac><mrow><mo>|</mo><mi>a</mi><mo>|</mo><mo></mo><mo>(</mo><mo>β</mo><mo>-</mo><mo>α</mo><msup><mo>)</mo><mn>3</mn></msup></mrow><mrow><mn>6</mn></mrow></mfrac></mstyle></math>

I executed the following code.

from sympy import *
from sympy.printing.mathml import mathml
print(mathml(S=abs(a)*(β-α)^3/6,printer='presentation'))

Body:
In a terminal that supported copy/paste of Greek characters, I was able to create a variable with Greek name, e.g. beta = Symbol('beta') where beta was a literal Greek character. The output of the formula you gave -- using ** instead of ^ is identical to the code generated when the symbols for alpha and beta are imported from abc:

>>> from sympy.abc import alpha, beta
>>> print(mathml(abs(a)*(beta-alpha)**3/6, printer='presentation'))
<mrow><mfrac><mrow><msup><mfenced><mrow><mrow><mo>-</mo><mi>&#945;</
o>+</mo><mi>&#946;</mi></mrow></mfenced><mn>3</mn></msup><mo>&Invisi
o><mrow><mfenced close="|" open="|"><mi>a</mi></mfenced></mrow></mro
</mfrac></mrow>


问:
Android shrink and grow sequential animation
I want to make a sequential animation in which two buttons shrink until they disappear and then they grow again to their original size.
When I run it the buttons simply disappear without any animations

```<code><?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/accelerate_decelerate_interpolator"
    android:fillAfter="true">

    <scale
        android:fromXScale="1"
        android:toXScale="0"
        android:fromYScale="1"
        android:toYScale="0"
        android:duration="400"
        android:pivotX="50%"
        android:pivotY="50%"
        />

    <scale
        android:startOffset="700"
        android:fromXScale="0"
        android:toXScale="1"
        android:fromYScale="0"
        android:toYScale="1"
        android:duration="400"
        android:pivotX="50%"
        android:pivotY="50%"
     />

</set>
</code>```

```<code>Animation sgAnimation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.shrink_grow);
btPrimary.startAnimation(sgAnimation);
btSecondary.startAnimation(sgAnimation);
</code>```

答:
```<code>val scaleDown = ObjectAnimator.ofPropertyValuesHolder(
    view,
    PropertyValuesHolder.ofFloat("scaleX", 0.5f),
    PropertyValuesHolder.ofFloat("scaleY", 0.5f)
)
scaleDown.duration = 2000
scaleDown.repeatMode = ValueAnimator.REVERSE
scaleDown.repeatCount = ValueAnimator.INFINITE
scaleDown.start()
</code>```

Demo

Body:
I want to make a sequential animation in which two buttons shrink until they disappear and then they grow again to their original size.
When I run it the buttons simply disappear without any animations

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/accelerate_decelerate_interpolator"
    android:fillAfter="true">

    <scale
        android:fromXScale="1"
        android:toXScale="0"
        android:fromYScale="1"
        android:toYScale="0"
        android:duration="400"
        android:pivotX="50%"
        android:pivotY="50%"
        />

    <scale
        android:startOffset="700"
        android:fromXScale="0"
        android:toXScale="1"
        android:fromYScale="0"
        android:toYScale="1"
        android:duration="400"
        android:pivotX="50%"
        android:pivotY="50%"
     />

</set>

Animation sgAnimation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.shrink_grow);
btPrimary.startAnimation(sgAnimation);
btSecondary.startAnimation(sgAnimation);

Body:
val scaleDown = ObjectAnimator.ofPropertyValuesHolder(
    view,
    PropertyValuesHolder.ofFloat("scaleX", 0.5f),
    PropertyValuesHolder.ofFloat("scaleY", 0.5f)
)
scaleDown.duration = 2000
scaleDown.repeatMode = ValueAnimator.REVERSE
scaleDown.repeatCount = ValueAnimator.INFINITE
scaleDown.start()

Demo


问:
What is the most EVIL code you have ever seen in a production enterprise environment?
What is the most evil or dangerous code fragment you have ever seen in a production environment at a company?  I've never encountered production code that I would consider to be deliberately malicious and evil, so I'm quite curious to see what others have found.

The most dangerous code I have ever seen was a stored procedure two linked-servers away from our core production database server.  The stored procedure accepted any NVARCHAR(8000) parameter and executed the parameter on the target production server via an double-jump sp_executeSQL command.  That is to say, the sp_executeSQL command executed another sp_executeSQL command in order to jump two linked servers.  Oh, and the linked server account had sysadmin rights on the target production server.

答:
I think that it was a program which loaded a loop into the general purpose registers of a pdp-10 and then executed the code in those registers.

You could do that on a pdp-10.  That doesn't mean that you should.

EDIT:  at least this is to the best of my (sometimes quite shabby) recollection.

OwnerDisplayName: InnerJoin

LastEditorDisplayName: Noah


问:
How to find a servlet object by name?
OK, completely noob to JSP here. I need to find the code that handles a form submission, but I did a text search and can't find it at all.

I have this in my web.xml

```<code><servlet-mapping>
    <servlet-name>myservlet</servlet-name>
    <url-pattern>/flow.htm</url-pattern>
</servlet-mapping>
</code>```

The flow.htm is where the form is posting to. How do I locate the java code that handles the post?

答:
Find the following entry in the same file :

```<code><servlet>
    <servlet-name>myservlet</servlet-name>
    <servlet-class>the.class.of.the.servlet.handling.the.Request</servlet-class>
</servlet>
</code>```

It will give you the class name of the servlet.

Title: How to find a servlet object by name?

Body:
OK, completely noob to JSP here. I need to find the code that handles a form submission, but I did a text search and can't find it at all.

I have this in my web.xml

<servlet-mapping>
    <servlet-name>myservlet</servlet-name>
    <url-pattern>/flow.htm</url-pattern>
</servlet-mapping>

The flow.htm is where the form is posting to. How do I locate the java code that handles the post?

Body:
Find the following entry in the same file :

<servlet>
    <servlet-name>myservlet</servlet-name>
    <servlet-class>the.class.of.the.servlet.handling.the.Request</servlet-class>
</servlet>

It will give you the class name of the servlet.


问:
Debezium kafka connect connector not updating successfully
I am trying to CDC using Debezium and Kafka. I have registered a connector with 3 tables in table.whitelist property and it is working properly. Here is the configuration of running connector.

```<code>{"name":"xoom-eds-extactor","config":{"connector.class":"io.debezium.connector.mysql.MySqlConnector","database.user":"debezium","database.server.id":"1","database.hostname":"qa514dtc001.ord.qa001.xoom.com","database.password":"xoom123","database.history.kafka.bootstrap.servers":"eds-kafka1:9092","database.history.kafka.topic":"dbhistory.inventory","name":"xoom-eds-extactor","database.server.name":"MySQL-Database-Docker","database.port":"3306","include.schema.changes":"true","table.whitelist":"xoom_eds_extraction_src_db_mock.postal_code_mock,xoom_eds_extraction_src_db_mock.account_number_mock,xoom_eds_extraction_src_db_mock.credit_card_number_mock,xoom_eds_extraction_src_db_mock.ip_address_details_mock,xoom_eds_extraction_src_db_mock.university_details_mock"},"tasks":[{"connector":"xoom-eds-extactor","task":0}],"type":"source"}
</code>```

Now I want to update the connector and add two more tables from the same database. I am using the following command and config file to update the connector.

Command :

```<code>curl -X PUT -H "Content-Type: application/json" --data @xoom-eds-extactor-conf.json "http://eds-kafka1:8083/connectors/xoom-eds-extactor/config"
</code>```

Config json :

```<code>{
   "name":"xoom-eds-extactor",
   "connector.class":"io.debezium.connector.mysql.MySqlConnector",
   "database.hostname":"qa514dtc001.ord.qa001.xoom.com",
   "database.port":"3306",
   "database.user":"debezium",
   "database.password":"xoom123",
   "database.server.id":"1",
   "database.server.name":"MySQL-Database-Docker",
   "database.history.kafka.bootstrap.servers":"eds-kafka1:9092",
   "database.history.kafka.topic":"dbhistory.inventory",
   "include.schema.changes":"true",
"table.whitelist":"xoom_eds_extraction_src_db_mock.postal_code_mock,xoom_eds_extraction_src_db_mock.account_number_mock,xoom_eds_extraction_src_db_mock.credit_card_number_mock,xoom_eds_extraction_src_db_mock.ip_address_details_mock,xoom_eds_extraction_src_db_mock.university_details_mock"
}
</code>```

This executes successfully but when I list the Kafka topics only the last 3 topics are present 2 new topics are not added.

```<code>MySQL-Database-Docker
MySQL-Database-Docker.xoom_eds_extraction_src_db_mock.account_number_mock
MySQL-Database-Docker.xoom_eds_extraction_src_db_mock.credit_card_number_mock
MySQL-Database-Docker.xoom_eds_extraction_src_db_mock.postal_code_mock
__consumer_offsets
connect-configs
connect-offsets
connect-status
dbhistory.inventory
</code>```

Can anyone out there help me with this? Thanks in advance.

答:
As far as I know, there was an old pending PR related to this issue and it should have been fixed in 0.9.1 release. But if you are using some old version you can simply follow these steps.

Add the new tables, but don't write to them yet

Shut down the connector

Change the filter configuration and set snapshot mode to "schema_only_recovery"

Delete (or rename) the existing DB history topic

Restart the connector; this will re-create the internal history of the DB schema and then continue streaming from the previously recorded offset

Begin writing to the new tables

At least this is what we do(we are still using 0.8.2).

Source : debezium-google-group.

Body:
I am trying to CDC using Debezium and Kafka. I have registered a connector with 3 tables in table.whitelist property and it is working properly. Here is the configuration of running connector.

{"name":"xoom-eds-extactor","config":{"connector.class":"io.debezium.connector.mysql.MySqlConnector","database.user":"debezium","database.server.id":"1","database.hostname":"qa514dtc001.ord.qa001.xoom.com","database.password":"xoom123","database.history.kafka.bootstrap.servers":"eds-kafka1:9092","database.history.kafka.topic":"dbhistory.inventory","name":"xoom-eds-extactor","database.server.name":"MySQL-Database-Docker","database.port":"3306","include.schema.changes":"true","table.whitelist":"xoom_eds_extraction_src_db_mock.postal_code_mock,xoom_eds_extraction_src_db_mock.account_number_mock,xoom_eds_extraction_src_db_mock.credit_card_number_mock,xoom_eds_extraction_src_db_mock.ip_address_details_mock,xoom_eds_extraction_src_db_mock.university_details_mock"},"tasks":[{"connector":"xoom-eds-extactor","task":0}],"type":"source"}

Now I want to update the connector and add two more tables from the same database. I am using the following command and config file to update the connector.

Command :

curl -X PUT -H "Content-Type: application/json" --data @xoom-eds-extactor-conf.json "http://eds-kafka1:8083/connectors/xoom-eds-extactor/config"

Config json :

{
   "name":"xoom-eds-extactor",
   "connector.class":"io.debezium.connector.mysql.MySqlConnector",
   "database.hostname":"qa514dtc001.ord.qa001.xoom.com",
   "database.port":"3306",
   "database.user":"debezium",
   "database.password":"xoom123",
   "database.server.id":"1",
   "database.server.name":"MySQL-Database-Docker",
   "database.history.kafka.bootstrap.servers":"eds-kafka1:9092",
   "database.history.kafka.topic":"dbhistory.inventory",
   "include.schema.changes":"true",
"table.whitelist":"xoom_eds_extraction_src_db_mock.postal_code_mock,xoom_eds_extraction_src_db_mock.account_number_mock,xoom_eds_extraction_src_db_mock.credit_card_number_mock,xoom_eds_extraction_src_db_mock.ip_address_details_mock,xoom_eds_extraction_src_db_mock.university_details_mock"
}

This executes successfully but when I list the Kafka topics only the last 3 topics are present 2 new topics are not added.

MySQL-Database-Docker
MySQL-Database-Docker.xoom_eds_extraction_src_db_mock.account_number_mock
MySQL-Database-Docker.xoom_eds_extraction_src_db_mock.credit_card_number_mock
MySQL-Database-Docker.xoom_eds_extraction_src_db_mock.postal_code_mock
__consumer_offsets
connect-configs
connect-offsets
connect-status
dbhistory.inventory

Can anyone out there help me with this? Thanks in advance.


问:
How to trim only white space but not \n in Java
I have a string like

String str = " hello world\n "

when I call str.trim(),
it returns

"hello world"

However, I need the string looks like

"hello world\n"

How could I do it for only remove leading and trailing white space in a string?

答:
Here's what I'd do.

```<code>private static Pattern pat = Pattern.compile("[\t ]*(.*?)[\t ]*", Pattern.DOTALL);

public static String stripWhiteStuff(String str) {
    Matcher m = pat.matcher(str);
    return m.matches()? m.group(1) : str;
}

public static void main(String... args) {

    String str = "  Hello\n\t ";
    System.out.println(">" + stripWhiteStuff(str) + "<");
}
</code>```

Result:

```<code>>Hello
<
</code>```

Body:
Here's what I'd do.

private static Pattern pat = Pattern.compile("[\t ]*(.*?)[\t ]*", Pattern.DOTALL);

public static String stripWhiteStuff(String str) {
    Matcher m = pat.matcher(str);
    return m.matches()? m.group(1) : str;
}

public static void main(String... args) {

    String str = "  Hello\n\t ";
    System.out.println(">" + stripWhiteStuff(str) + "<");
}

Result:

>Hello
<


问:
Django: optimizing many to many query
I have Post and Tag models:

```<code>class Tag(models.Model):
    """ Tag for blog entry """
    title           = models.CharField(max_length=255, unique=True)

class Post(models.Model):
    """ Blog entry """
    tags            = models.ManyToManyField(Tag)
    title           = models.CharField(max_length=255)
    text            = models.TextField()
</code>```

I need to output the list of blog entries and a set of tags for each post. I would like to be able to do this with just two queries, using this workflow:

Get the list of posts

Get the list of tags used in those posts

Link tags to posts in python

I am having the trouble with the last step, here is the code I came up with, but in gives me 'Tag' object has no attribute 'post__id'

```<code>#getting posts
posts = Post.objects.filter(published=True).order_by('-added')[:20]
#making a disc, like {5:<post>}
post_list = dict([(obj.id, obj) for obj in posts])
#gathering ids to list
id_list = [obj.id for obj in posts]

#tags used in given posts
objects = Tag.objects.select_related('post').filter(post__id__in=id_list)
relation_dict = {}
for obj in objects:
    #Here I get: 'Tag' object has no attribute 'post__id'
    relation_dict.setdefault(obj.post__id, []).append(obj)

for id, related_items in relation_dict.items():
    post_list[id].tags = related_items
</code>```

Can you see an error there? how can I solve this task using django ORM, or I will have to write a custom SQL?

EDIT:

I was able to solve this with raw query:

```<code>objects = Tag.objects.raw("""
    SELECT
        bpt.post_id,
        t.*
    FROM
        blogs_post_tags AS bpt,
        blogs_tag AS t
    WHERE
        bpt.post_id IN (""" + ','.join(id_list) + """)
        AND t.id = bpt.tag_id
""")
relation_dict = {}
for obj in objects:
    relation_dict.setdefault(obj.post_id, []).append(obj)
</code>```

I would be greatfull to anyone who would point on how to avoid it.

答:
If you must have it it in two queries, I think you'll need custom SQL:

```<code>def custom_query(posts):
  from django.db import connection
  query = """
  SELECT "blogs_post_tags"."post_id", "blogs_tag"."title"
  FROM "blogs_post_tags"
  INNER JOIN "blogs_tags" ON ("blogs_post_tags"."tag_id"="blogs_tags"."id")
  WHERE "blogs_post_tags"."post_id" in %s
  """
  cursor=connection.cursor()
  cursor.execute(query,[posts,])
  results = {}
  for id,title in cursor.fetchall():
    results.setdefault(id,[]).append(title)
  return results

recent_posts = Post.objects.filter(published=True).order_by('-added')[:20]
post_ids = recent_posts.values_list('id',flat=True)
post_tags = custom_query(post_ids)
</code>```

recent_posts is your Post QuerySet, should cache from one query.

post_tags is a mapping of post id to tag titles, from one query.

Title: Django: optimizing many to many query

Body:
I have Post and Tag models:

class Tag(models.Model):
    """ Tag for blog entry """
    title           = models.CharField(max_length=255, unique=True)

class Post(models.Model):
    """ Blog entry """
    tags            = models.ManyToManyField(Tag)
    title           = models.CharField(max_length=255)
    text            = models.TextField()

I need to output the list of blog entries and a set of tags for each post. I would like to be able to do this with just two queries, using this workflow:

Get the list of posts

Get the list of tags used in those posts

Link tags to posts in python

I am having the trouble with the last step, here is the code I came up with, but in gives me 'Tag' object has no attribute 'post__id'

#getting posts
posts = Post.objects.filter(published=True).order_by('-added')[:20]
#making a disc, like {5:<post>}
post_list = dict([(obj.id, obj) for obj in posts])
#gathering ids to list
id_list = [obj.id for obj in posts]

#tags used in given posts
objects = Tag.objects.select_related('post').filter(post__id__in=id_list)
relation_dict = {}
for obj in objects:
    #Here I get: 'Tag' object has no attribute 'post__id'
    relation_dict.setdefault(obj.post__id, []).append(obj)

for id, related_items in relation_dict.items():
    post_list[id].tags = related_items

Can you see an error there? how can I solve this task using django ORM, or I will have to write a custom SQL?

EDIT:

I was able to solve this with raw query:

objects = Tag.objects.raw("""
    SELECT
        bpt.post_id,
        t.*
    FROM
        blogs_post_tags AS bpt,
        blogs_tag AS t
    WHERE
        bpt.post_id IN (""" + ','.join(id_list) + """)
        AND t.id = bpt.tag_id
""")
relation_dict = {}
for obj in objects:
    relation_dict.setdefault(obj.post_id, []).append(obj)

I would be greatfull to anyone who would point on how to avoid it.

Body:
If you must have it it in two queries, I think you'll need custom SQL:

def custom_query(posts):
  from django.db import connection
  query = """
  SELECT "blogs_post_tags"."post_id", "blogs_tag"."title"
  FROM "blogs_post_tags"
  INNER JOIN "blogs_tags" ON ("blogs_post_tags"."tag_id"="blogs_tags"."id")
  WHERE "blogs_post_tags"."post_id" in %s
  """
  cursor=connection.cursor()
  cursor.execute(query,[posts,])
  results = {}
  for id,title in cursor.fetchall():
    results.setdefault(id,[]).append(title)
  return results

recent_posts = Post.objects.filter(published=True).order_by('-added')[:20]
post_ids = recent_posts.values_list('id',flat=True)
post_tags = custom_query(post_ids)

recent_posts is your Post QuerySet, should cache from one query.

post_tags is a mapping of post id to tag titles, from one query.


问:
Binary search not working because of index?
I am looking at this binary search

I modified it a bit to the index, but cannot get it working

```<code>function bs1(a, tar, l, h) {
  // pass index, so equal
  if (h > l) {
    // not m = (h+l)/2
    // l+diff
    //let m = l + Math.floor( (h - l) / 2 );
    let m = Math.floor( (h + l) / 2 );

    if (a[m] == tar)
      return m;

    // tar... a[m]....
    if (a[m] > tar)
        return bs1(a, tar, l, m - 1);

    // a[m]..tar...
    return bs1(a, tar, m + 1, h);
  }

  return -1;
}

arr = [1, 2, 3, 4, 5, 6, 7];
tar = 5;
out = bs1(arr, tar, 0, arr.length);
console.log(out);
</code>```

What I want to do is:

pass arr.length, instead of arr.length-1

use if (h > l) {, instead of if (h >= l) {

Is it possible?

答:
Try this(made small change) -> returns index 4, is this expected fiddle</p>

```<code>function bs1(a, tar, l, h) {

  // pass index, so equal
  if (h > l) {
    // not m = (h+l)/2
    // l+diff
    //let m = l + Math.floor( (h - l) / 2 );
    let m = Math.floor( (h + l) / 2 );

    if (a[m] == tar)
      return m;

    // tar... a[m]....
    if (a[m] > tar)
        return bs1(a, tar, l, m);

    // a[m]..tar...
    return bs1(a, tar, m + 1, h);
  }

  return -1;
}

arr = [1, 2, 3, 4, 5, 6, 7];
tar = 5;
out = bs1(arr, tar, 0, arr.length);
console.log(out);
</code>```

Body:
I am looking at this binary search

I modified it a bit to the index, but cannot get it working

function bs1(a, tar, l, h) {
  // pass index, so equal
  if (h > l) {
    // not m = (h+l)/2
    // l+diff
    //let m = l + Math.floor( (h - l) / 2 );
    let m = Math.floor( (h + l) / 2 );

    if (a[m] == tar)
      return m;

    // tar... a[m]....
    if (a[m] > tar)
        return bs1(a, tar, l, m - 1);

    // a[m]..tar...
    return bs1(a, tar, m + 1, h);
  }

  return -1;
}

arr = [1, 2, 3, 4, 5, 6, 7];
tar = 5;
out = bs1(arr, tar, 0, arr.length);
console.log(out);

What I want to do is:

pass arr.length, instead of arr.length-1

use if (h > l) {, instead of if (h >= l) {

Is it possible?

Body:
Try this(made small change) -> returns index 4, is this expected fiddle

function bs1(a, tar, l, h) {

  // pass index, so equal
  if (h > l) {
    // not m = (h+l)/2
    // l+diff
    //let m = l + Math.floor( (h - l) / 2 );
    let m = Math.floor( (h + l) / 2 );

    if (a[m] == tar)
      return m;

    // tar... a[m]....
    if (a[m] > tar)
        return bs1(a, tar, l, m);

    // a[m]..tar...
    return bs1(a, tar, m + 1, h);
  }

  return -1;
}

arr = [1, 2, 3, 4, 5, 6, 7];
tar = 5;
out = bs1(arr, tar, 0, arr.length);
console.log(out);


问:
Stack Overflow Error while using JPanel.setLocation with an StretchIcon (ImageIcon) in it
Trying to make a movable object with JPanel, which has a ImageIcon which will automaticly stretch when I resize it.
Now, when I run the application, it activates properly and shows the image.
However when I press a button it shows the following error message:

```<code>Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError
    at java.awt.Component.setLocation(Unknown Source)
    at tutorial.GridPanel.move(GridPanel.java:51)
    at java.awt.Component.setLocation(Unknown Source)
    at tutorial.GridPanel.move(GridPanel.java:51)
    at java.awt.Component.setLocation(Unknown Source)
    at tutorial.GridPanel.move(GridPanel.java:51)
    (continue many times)
</code>```

Found that it is maybe a king of indirect recursion? thing, but I just cannot find what is causing it. Following is the class GridPanel I wrote for the JPanel.

package tutorial;

import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JPanel;

import darrylbu.icon.StretchIcon;

public class GridPanel extends JPanel
{
    private BufferedImage image;

    GridPanel() {}
    GridPanel(String path)
    {
        setLayout(null);
        try
        {
            image = ImageIO.read(new File(path));
        }catch(IOException e)
        {
            System.out.println(e);
        }

        addKeyListener(new KeyAdapter()
        {
            public void keyPressed(KeyEvent e)
            {
                System.out.println(e.getKeyChar());
                move(10, 10);
            }
        });
    }

    @Override
        protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        StretchIcon icon = new StretchIcon(image);
        icon.paintIcon(this, g, 0, 0);
    }

    public void move(int x, int y)
    {
        super.setLocation(getX() + x, getY() + y);
    }
}

```

答:
Here:

```<code>public void setLocation(int x, int y)
{
  move (x, y);
}
</code>```

That is the source code for Component.setLocation(). As you can see: that method calls move(). You panel overrides move() to call setLocation(). There we go: your recursion is not "indirect", it is right there.

So obviously: do not call setLocation() from your move() method! So your whole approach is flawed at this point.

Body:
Trying to make a movable object with JPanel, which has a ImageIcon which will automaticly stretch when I resize it.
Now, when I run the application, it activates properly and shows the image.
However when I press a button it shows the following error message:

Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError
    at java.awt.Component.setLocation(Unknown Source)
    at tutorial.GridPanel.move(GridPanel.java:51)
    at java.awt.Component.setLocation(Unknown Source)
    at tutorial.GridPanel.move(GridPanel.java:51)
    at java.awt.Component.setLocation(Unknown Source)
    at tutorial.GridPanel.move(GridPanel.java:51)
    (continue many times)

Found that it is maybe a king of indirect recursion? thing, but I just cannot find what is causing it. Following is the class GridPanel I wrote for the JPanel.

package tutorial;

import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JPanel;

import darrylbu.icon.StretchIcon;

public class GridPanel extends JPanel
{
    private BufferedImage image;

    GridPanel() {}
    GridPanel(String path)
    {
        setLayout(null);
        try
        {
            image = ImageIO.read(new File(path));
        }catch(IOException e)
        {
            System.out.println(e);
        }

        addKeyListener(new KeyAdapter()
        {
            public void keyPressed(KeyEvent e)
            {
                System.out.println(e.getKeyChar());
                move(10, 10);
            }
        });
    }

    @Override
        protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        StretchIcon icon = new StretchIcon(image);
        icon.paintIcon(this, g, 0, 0);
    }

    public void move(int x, int y)
    {
        super.setLocation(getX() + x, getY() + y);
    }
}

Body:
Here:

public void setLocation(int x, int y)
{
  move (x, y);
}

That is the source code for Component.setLocation(). As you can see: that method calls move(). You panel overrides move() to call setLocation(). There we go: your recursion is not "indirect", it is right there.

So obviously: do not call setLocation() from your move() method! So your whole approach is flawed at this point.


问:
How to resolve the Botkit.slackbot is not a function error for my code while trying to build a slackbot using botkit?
I am trying to make a slackbot using botkit and I have written a code however I get the following error when I try to run it-

```<code>TypeError: Botkit.slackbot is not a function
    at Object.<anonymous> (E:\Postman Projects\botkitBot\mybot\index.js:27:27)
    at Module._compile (internal/modules/cjs/loader.js:701:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
    at Module.load (internal/modules/cjs/loader.js:600:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
    at Function.Module._load (internal/modules/cjs/loader.js:531:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
</code>```

This is the part in the code where I get the error:

```<code>const controller = Botkit.slackbot({
     debug: false,
     //include "log: false" to disable logging
});
</code>```

I tried installing yeoman and slack adapter but its still not working.
It seems like its not a very common problem as its not acknowledged anywhere.
Please do help. It is the very basic step and I can't proceed if this doesn't work.

答:
check the version of package installed by using this command

```<code>npm list botkit
</code>```

it seems like new version has changed the specification if it shows 4.0 , try to uninstall it

```<code>npm uninstall botkit
</code>```

and install the specific version which has this function in specification

```<code>npm install botkit@0.6
</code>```

Body:
I am trying to make a slackbot using botkit and I have written a code however I get the following error when I try to run it-

TypeError: Botkit.slackbot is not a function
    at Object.<anonymous> (E:\Postman Projects\botkitBot\mybot\index.js:27:27)
    at Module._compile (internal/modules/cjs/loader.js:701:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
    at Module.load (internal/modules/cjs/loader.js:600:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
    at Function.Module._load (internal/modules/cjs/loader.js:531:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)

This is the part in the code where I get the error:

const controller = Botkit.slackbot({
     debug: false,
     //include "log: false" to disable logging
});

I tried installing yeoman and slack adapter but its still not working.
It seems like its not a very common problem as its not acknowledged anywhere.
Please do help. It is the very basic step and I can't proceed if this doesn't work.

Body:
check the version of package installed by using this command

npm list botkit

it seems like new version has changed the specification if it shows 4.0 , try to uninstall it

npm uninstall botkit

and install the specific version which has this function in specification

npm install botkit@0.6


问:
Problem on distributing traffic from public load balancer to nginx
I am trying to distribute requests that comes to load-balancer to azure scale set instances.

I created a scale set using a linux vm image. In image, Nginx is already installed in the vm. Nginx config is shown below:

```<code>server {
    listen 80 default_server;

    server_name _;

    return 301 https://$host$request_uri;
}

server {

    listen 443;
    listen [::]:443;
    server_name 127.0.0.1 127.0.0.1 *.cloudapp.azure.com;
    ssl_certificate /usr/local/etc/ssl/certs/certi/domain-crt.txt;
    ssl_certificate_key /usr/local/etc/ssl/certs/certi/domain-key.txt;
    ssl on;
    ssl_session_cache builtin:1000 shared:SSL:10m;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers HIGH:!aNULL:!eNULL:!EXPORT:!CAMELLIA:!DES:!MD5:!PSK:!RC4;
    ssl_prefer_server_ciphers on;
    access_log /var/log/nginx/access.log;
    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass https://127.0.0.1:9000;
        proxy_redirect http:// https://;
    }

}
</code>```

Another application(XYZ) is running in port 9000. So, Nginx is routing the request to port 9000. The application(XYZ) then consumes request and returns a response.

Now, I created a scale set with public load balancer. The load balancer rule is to listen to port 80 and send to backend port 80.

To check the health of instances, I am sending a tcpProbe(PORT 80, Interval 5, Unhealthy threshold 4).

There is a public IP address associated with loadbalancer.

However, even after hitting public ip address (or DNS name) in browser, I cannot see the application running in port 9000.

I am new to Azure and Nginx and having a tough time implementing it. All I want to do is run multiple instances of my vm image using scale set and loadbalancer.

The resources that were created  while creating scale set are pip, vnet, scaleset, lb,nsg.

How do I distribute traffic from load-balancer to nginx? Any hint, suggestion on how I can debug it.

答:
The traffic flow is as follows:

Client on port 80 --> LB(80) --> Nginx (80) redirect to port 443 with location header
Client on port443 --> LB(443) --> Nginx (443) another redirection to port 9000 (Not sure if it is a internal redirection)

So all you need to do is to create a LB rule on port 443 and port 9000 if it is redirection to the client so the flow remains intact.

Body:
I am trying to distribute requests that comes to load-balancer to azure scale set instances.

I created a scale set using a linux vm image. In image, Nginx is already installed in the vm. Nginx config is shown below:

server {
    listen 80 default_server;

    server_name _;

    return 301 https://$host$request_uri;
}

server {

    listen 443;
    listen [::]:443;
    server_name 127.0.0.1 127.0.0.1 *.cloudapp.azure.com;
    ssl_certificate /usr/local/etc/ssl/certs/certi/domain-crt.txt;
    ssl_certificate_key /usr/local/etc/ssl/certs/certi/domain-key.txt;
    ssl on;
    ssl_session_cache builtin:1000 shared:SSL:10m;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers HIGH:!aNULL:!eNULL:!EXPORT:!CAMELLIA:!DES:!MD5:!PSK:!RC4;
    ssl_prefer_server_ciphers on;
    access_log /var/log/nginx/access.log;
    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass https://127.0.0.1:9000;
        proxy_redirect http:// https://;
    }

}

Another application(XYZ) is running in port 9000. So, Nginx is routing the request to port 9000. The application(XYZ) then consumes request and returns a response.

Now, I created a scale set with public load balancer. The load balancer rule is to listen to port 80 and send to backend port 80.

To check the health of instances, I am sending a tcpProbe(PORT 80, Interval 5, Unhealthy threshold 4).

There is a public IP address associated with loadbalancer.

However, even after hitting public ip address (or DNS name) in browser, I cannot see the application running in port 9000.

I am new to Azure and Nginx and having a tough time implementing it. All I want to do is run multiple instances of my vm image using scale set and loadbalancer.

The resources that were created  while creating scale set are pip, vnet, scaleset, lb,nsg.

How do I distribute traffic from load-balancer to nginx? Any hint, suggestion on how I can debug it.


问:
strptime string to datetime object conversion
I have a Python2.7 script with a variable date= "21/05/2019" that works fine.
I need the date variable to be datetime.now - 60 days.

However the output must be like time.struct_time(tm_year=2019, tm_mon=5, tm_mday=28, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=148, tm_isdst=-1)

datetime.datetime.now() with strptime won't work.

```<code>import datetime, time
from datetime import timedelta

N = 60
#pre_create_date = datetime.datetime.today() - datetime.timedelta(days=N)
pre_create_date = "28/04/2019"

# Sort out date format
pre_create_date = time.strptime(pre_create_date, "%d/%m/%Y")

print pre_create_date
</code>```

I expect to be able to use datetime.datetime.today() - datetime.timedelta(days=N) but the output to be a datetime object.

Edit:

It looks like I haven't explained myself very well. Sorry about that.

The script is:

```<code>import datetime, time
from datetime import timedelta

N = 60
#pre_create_date = datetime.datetime.today() - datetime.timedelta(days=N)
pre_create_date = "28/04/2019"

# Sort out date format
pre_create_date = time.strptime(pre_create_date, "%d/%m/%Y")

print pre_create_date
</code>```

Output:

```<code>time.struct_time(tm_year=2019, tm_mon=4, tm_mday=28, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=118, tm_isdst=-1)
</code>```

Script using datetime.now - datetime.timedelta:

```<code>import datetime, time
from datetime import timedelta

N = 60
pre_create_date = datetime.datetime.today() - datetime.timedelta(days=N)

print pre_create_date
</code>```

Output:

```<code>2019-03-31 21:09:25.183459
</code>```

Expected output:

```<code>time.struct_time(tm_year=2019, tm_mon=3, tm_mday=31, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=118, tm_isdst=-1)
</code>```

答:
you have syntax problem, change print pre_create_date to print (pre_create_date) to start with and you are assigning a string to pre_create_date try to get it in date format, and use pre_create_date = pre_create_date.strftime("%Y.%m.%d %H:%M:%S.%f") or any format as you you like,

good luck.

Body:
I have a Python2.7 script with a variable date= "21/05/2019" that works fine.
I need the date variable to be datetime.now - 60 days.

However the output must be like time.struct_time(tm_year=2019, tm_mon=5, tm_mday=28, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=148, tm_isdst=-1)

datetime.datetime.now() with strptime won't work.

import datetime, time
from datetime import timedelta

N = 60
#pre_create_date = datetime.datetime.today() - datetime.timedelta(days=N)
pre_create_date = "28/04/2019"

# Sort out date format
pre_create_date = time.strptime(pre_create_date, "%d/%m/%Y")

print pre_create_date

I expect to be able to use datetime.datetime.today() - datetime.timedelta(days=N) but the output to be a datetime object.

Edit:

It looks like I haven't explained myself very well. Sorry about that.

The script is:

import datetime, time
from datetime import timedelta

N = 60
#pre_create_date = datetime.datetime.today() - datetime.timedelta(days=N)
pre_create_date = "28/04/2019"

# Sort out date format
pre_create_date = time.strptime(pre_create_date, "%d/%m/%Y")

print pre_create_date

Output:

time.struct_time(tm_year=2019, tm_mon=4, tm_mday=28, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=118, tm_isdst=-1)

Script using datetime.now - datetime.timedelta:

import datetime, time
from datetime import timedelta

N = 60
pre_create_date = datetime.datetime.today() - datetime.timedelta(days=N)

print pre_create_date

Output:

2019-03-31 21:09:25.183459

Expected output:

time.struct_time(tm_year=2019, tm_mon=3, tm_mday=31, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=118, tm_isdst=-1)


问:
Select data where condition matches and if none, then select all?

select * from (values
    ('dept1','user1'),
    ('dept2','user2'),
    ('dept3','user3'),
    ('dept4','user4')
    )table1([department],[user])
where [user] = @id
```

<p>scenario1:
     @id = 'user1'</p>

```dept1
```

<p>scenario2:
    @id = 'user5'</p>

```dept1
dept2
dept3
dept4
```

<p>this is what it looks like from a noobish query</p>

<pre class="lang-sql prettyprint-override"><code>declare @id varchar(12) = 'user1'
declare @var int = (select count(*) from table1 where [user] = @id)

select * from table1 where [user] = @id or @var = 0
</code>```

答:
you can try this:

```<code>DECLARE @id varchar(12) = 'user1'

IF EXISTS(SELECT COUNT(*) FROM table1 WHERE [user] = @id)
BEGIN
SELECT * FROM table1 WHERE [user] = @id
END
ELSE
BEGIN
SELECT * FROM table1
END
</code>```

you can also read more about "EXISTS" syntax on:
https://learn.microsoft.com/en-us/sql/t-sql/language-elements/exists-transact-sql?view=sql-server-2017

Body:
select * from (values
    ('dept1','user1'),
    ('dept2','user2'),
    ('dept3','user3'),
    ('dept4','user4')
    )table1([department],[user])
where [user] = @id

scenario1:
     @id = 'user1'

dept1

scenario2:
    @id = 'user5'

dept1
dept2
dept3
dept4

this is what it looks like from a noobish query

declare @id varchar(12) = 'user1'
declare @var int = (select count(*) from table1 where [user] = @id)

select * from table1 where [user] = @id or @var = 0

Body:
you can try this:

DECLARE @id varchar(12) = 'user1'

IF EXISTS(SELECT COUNT(*) FROM table1 WHERE [user] = @id)
BEGIN
SELECT * FROM table1 WHERE [user] = @id
END
ELSE
BEGIN
SELECT * FROM table1
END

you can also read more about "EXISTS" syntax on:
https://learn.microsoft.com/en-us/sql/t-sql/language-elements/exists-transact-sql?view=sql-server-2017


问:
Apply Undo Redo on elements that can dragable (drag and drop)
I want to implement functionality on the svgElements that can be dragged with javascript how could I do this...

I have implemented this with mouse up

When mouse up occurs, I save the x and y position, object id, object type (circle, rect, etc.)

Can any one tell...is this good way to implement?

答:
cwolves describes a good structure for the undo/redo functionality.

You are correct, that during mouse-up, you'll want to store the history, but you'll also want to store the original location of the object(s) being manipulated during mouse-down so you'll have have it when you undo the move.

If you end up taking it a step further, and allowing scaling, then you'll want to store the complete original transform e.g. "translate(10,10) scale(1.2,1.2) rotate(90)", for history, but also so that you'll have a baseline to apply the drag-scaling action to.


问:
No way to make Work persistent across reboots?
So I know WorkManager utilizes JobScheduler on supported APIs but there doesnt seem to be any way to make WorkManager work persistent across reboots? Is the only option to request the BOOT_COMPLETED permission and reschedule jobs?

答: WorkManager is actually used to persist deferrable tasks even after your app exits and the device restarts, please refer to the docs. It uses JobScheduler for api 23 and above and broadcastReceiver and AlarmManger on api 14 to 22. You can use constraints to check battery status, network coverage ...etc depending your particular usecase. You just have to be careful not to remove or rename your existing classes after they are added in the queue because WorkManager uses it's internal database to store those classes and your app will crash if you remove them or rename them.</p>


问:
What's the better way to join string to value of an element of the dictionary?
Find a better way to solve my question~

Here is my tableData and tableColumns:

tableData:

```<code>  [{
    "A":[{"id":0,"name":"aName1"}],
    "B":[{"id":0,"name":"bName1"},{"id":2,"name":"bName2"}],
    "C":[{"id":0,"name":"cName1"},{"id":2,"name":"cName2"}，{"id":3,"name":"cName3"}],
  }]
</code>```

tableCoulumns:

```<code>  [
    {"key":"A", "title":"test1"},
    {"key":"B", "title":"test2"},
    {"key":"C", "title":"test3"}
  ]
</code>```

<el-table :data="tableData">
   <el-table-column v-for="column in tableCoulumns" :prop="column.key" :label="column.title">
      <template scope="scope">

1 && scope.row[column.key].length<=2">

2">

       </template>
   </el-table-column>
</el-table>
```

expected results:

答:
```<code>  scope.row[column.key].map(it => it.name).join(", ")
</code>```

The above will work for any number of columns.

Body:
Find a better way to solve my question~

Here is my tableData and tableColumns:

tableData:

  [{
    "A":[{"id":0,"name":"aName1"}],
    "B":[{"id":0,"name":"bName1"},{"id":2,"name":"bName2"}],
    "C":[{"id":0,"name":"cName1"},{"id":2,"name":"cName2"}，{"id":3,"name":"cName3"}],
  }]

tableCoulumns:

  [
    {"key":"A", "title":"test1"},
    {"key":"B", "title":"test2"},
    {"key":"C", "title":"test3"}
  ]

<el-table :data="tableData">
   <el-table-column v-for="column in tableCoulumns" :prop="column.key" :label="column.title">
      <template scope="scope">

1 && scope.row[column.key].length<=2">

2">

       </template>
   </el-table-column>
</el-table>

expected results:

Body:
  scope.row[column.key].map(it => it.name).join(", ")

The above will work for any number of columns.


问:
Bootstrap is not working even though included
Hi Guys I have a problem about bootstrap bootstrap.min.css  jquery.min.js and   bootstrap.min.js are already included in my project but I cannot use well well-sm class and when I add manually by links this time divs engage you can see in the picture. where is the problem I don't understand?

my code :

```<code>@model xx.Web.Models.MiniRepairViewModel
@{
    Layout = null;
}
<div class="pageWrapper">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
    @Html.Action("Breadcrumb", "Manage")
    <div class="TextBody">
        <div class="container">
            @Html.Action("LeftMenu", "Manage") //menu engage
            <div class="col-threeQuarters">
     @using (Ajax.BeginForm("MiniRepairServiceAdd", "Ajax", new AjaxOptions { OnSuccess = "jsFilt", OnFailure = "OnFailure" }))
                {
                    <ul class="Form">
                        <li class="oneColumsFull">
                            @Html.DropDownListFor(x => x.GetCityModel.a, (IEnumerable<SelectListItem>)ViewBag.CitiesList, "select", new { name = "x", id = "y" })
                        </li>
                        <li id="ilce" class="twoColumsFull" style="display:none;">
                        </li>
                        <li class="oneColums"><input type="text" name="serviceName" id="serviceName" placeholder="Service"></li>

                        <li class="button"><input class=".bh-sl-reset" id="reset" type="button" value="clear" onclick="javascript: window.location.reload();"></li>
                        <li class="button"><input type="submit" value="search" name="search"></li>
                    </ul>
                }
                <div id="myDiv" class="well well-sm"> </div> //not working
            </div>
        </div>
    </div>
</div>
</code>```

答:
This is because you are not loading your bootstrap cdn at right place. You should load all your scripts files inside your head tag as @yashwardhan said.

this mean:

Go to your code, find  tag and load all your scripts and css file just before this tag.

```<code><head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</head>
</code>```

and use the right bootstrap syntax. colThreeQuarters is not a bootstrap class

Why you should do this, is explained here:-
Where should I put

Body:
Hi Guys I have a problem about bootstrap bootstrap.min.css  jquery.min.js and   bootstrap.min.js are already included in my project but I cannot use well well-sm class and when I add manually by links this time divs engage you can see in the picture. where is the problem I don't understand?

my code :

@model xx.Web.Models.MiniRepairViewModel
@{
    Layout = null;
}

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">

    @Html.Action("Breadcrumb", "Manage")

            @Html.Action("LeftMenu", "Manage") //menu engage

     @using (Ajax.BeginForm("MiniRepairServiceAdd", "Ajax", new AjaxOptions { OnSuccess = "jsFilt", OnFailure = "OnFailure" }))
                {

                            @Html.DropDownListFor(x => x.GetCityModel.a, (IEnumerable<SelectListItem>)ViewBag.CitiesList, "select", new { name = "x", id = "y" })

<input type="text" name="serviceName" id="serviceName" placeholder="Service">

<input class=".bh-sl-reset" id="reset" type="button" value="clear" onclick="javascript: window.location.reload();">

<input type="submit" value="search" name="search">

                }

 //not working

Body:
This is because you are not loading your bootstrap cdn at right place. You should load all your scripts files inside your head tag as @yashwardhan said.

this mean:

Go to your code, find </head> tag and load all your scripts and css file just before this tag.

<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</head>

and use the right bootstrap syntax. colThreeQuarters is not a bootstrap class

Why you should do this, is explained here:-
Where should I put <script> tags in HTML markup?


答:
I am not sure if colThreeQuarters is a bootstrap class, the actual class is col

```<code><div class="container">
   <div class="row">
      <div class="col-md-9> // 3quarters
      </div>
   </div>
</div>
</code>```

Title: Bootstrap is not working even though included

Body:
I am not sure if colThreeQuarters is a bootstrap class, the actual class is col

<div class="container">
   <div class="row">
      <div class="col-md-9> // 3quarters
      </div>
   </div>
</div>


问:
Can not export AVMutableComposition with AVAssetExportSession
Here is part of composition creation:

```<code>  AVMutableComposition* mixComposition = [[AVMutableComposition alloc] init];

  for (NSDictionary *track in tracks) {
    NSURL *url = [[NSURL alloc] initWithString:track[@"url"]];
    AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:url options:nil];
    AVMutableCompositionTrack *firstTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio
                                                                        preferredTrackID:kCMPersistentTrackID_Invalid];

    [firstTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, urlAsset.duration)
                        ofTrack:[[urlAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0]
                         atTime:kCMTimeZero
                          error:nil];
  }
  [self persist:mixComposition for:songId];
</code>```

Then i wish to persist collection in directory so i do not have to download it each time

Output of composition looks like this:

"AVMutableCompositionTrack: 0x1c4a276a0 trackID = 1, mediaType = soun, editCount = 1",
     "AVMutableCompositionTrack: 0x1c4a28560 trackID = 2, mediaType = soun, editCount = 1"...,

```<code>- (void)persist:(AVMutableComposition *) composition
            for:(NSString *) songId {

  NSLog(@"%@", composition);

  AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]
                                         initWithAsset:composition
                                         presetName:AVAssetExportPresetAppleM4A];
  NSString *path = [NSHomeDirectory() stringByAppendingPathComponent: songId];
  NSURL *url = [NSURL fileURLWithPath: path];
  exportSession.outputURL = url;
  exportSession.shouldOptimizeForNetworkUse = YES;
  exportSession.outputFileType = AVFileTypeAppleM4A;

  //   perform the export
  [exportSession exportAsynchronouslyWithCompletionHandler:^{

    if (AVAssetExportSessionStatusCompleted == exportSession.status) {
      NSLog(@"AVAssetExportSessionStatusCompleted");
      NSLog(@"Path : %@", url);
    } else if (AVAssetExportSessionStatusFailed == exportSession.status) {
      // a failure may happen because of an event out of your control
      // for example, an interruption like a phone call comming in
      // make sure and handle this case appropriately
      NSLog(@"%@", exportSession.error);

    } else {
      NSLog(@"Export Session Status: %ld", (long)exportSession.status);
    }
  }];

}
</code>```

The error i get:

Error Domain=AVFoundationErrorDomain Code=-11800 "The operation could
  not be completed" UserInfo={NSLocalizedFailureReason=An unknown error
  occurred (-12780), NSLocalizedDescription=The operation could not be
  completed, NSUnderlyingError=0x1c0a409f0 {Error
  Domain=NSOSStatusErrorDomain Code=-12780 "(null)"}}

答:
the path you use must content type of your file need to export, it's look like:

```<code>    let directory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
    let audioTypeOutput = ".m4a"//type of your file, mp3, m4a for audio
    let exportPath = directory?.appendingPathComponent(name + audioTypeOutput)
</code>```

hope this help!

Body:
Here is part of composition creation:

  AVMutableComposition* mixComposition = [[AVMutableComposition alloc] init];

  for (NSDictionary *track in tracks) {
    NSURL *url = [[NSURL alloc] initWithString:track[@"url"]];
    AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:url options:nil];
    AVMutableCompositionTrack *firstTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio
                                                                        preferredTrackID:kCMPersistentTrackID_Invalid];

    [firstTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, urlAsset.duration)
                        ofTrack:[[urlAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0]
                         atTime:kCMTimeZero
                          error:nil];
  }
  [self persist:mixComposition for:songId];

Then i wish to persist collection in directory so i do not have to download it each time

Output of composition looks like this:

"AVMutableCompositionTrack: 0x1c4a276a0 trackID = 1, mediaType = soun, editCount = 1",
     "AVMutableCompositionTrack: 0x1c4a28560 trackID = 2, mediaType = soun, editCount = 1"...,

- (void)persist:(AVMutableComposition *) composition
            for:(NSString *) songId {

  NSLog(@"%@", composition);

  AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]
                                         initWithAsset:composition
                                         presetName:AVAssetExportPresetAppleM4A];
  NSString *path = [NSHomeDirectory() stringByAppendingPathComponent: songId];
  NSURL *url = [NSURL fileURLWithPath: path];
  exportSession.outputURL = url;
  exportSession.shouldOptimizeForNetworkUse = YES;
  exportSession.outputFileType = AVFileTypeAppleM4A;

  //   perform the export
  [exportSession exportAsynchronouslyWithCompletionHandler:^{

    if (AVAssetExportSessionStatusCompleted == exportSession.status) {
      NSLog(@"AVAssetExportSessionStatusCompleted");
      NSLog(@"Path : %@", url);
    } else if (AVAssetExportSessionStatusFailed == exportSession.status) {
      // a failure may happen because of an event out of your control
      // for example, an interruption like a phone call comming in
      // make sure and handle this case appropriately
      NSLog(@"%@", exportSession.error);

    } else {
      NSLog(@"Export Session Status: %ld", (long)exportSession.status);
    }
  }];

}

The error i get:

Error Domain=AVFoundationErrorDomain Code=-11800 "The operation could
  not be completed" UserInfo={NSLocalizedFailureReason=An unknown error
  occurred (-12780), NSLocalizedDescription=The operation could not be
  completed, NSUnderlyingError=0x1c0a409f0 {Error
  Domain=NSOSStatusErrorDomain Code=-12780 "(null)"}}

Body:
the path you use must content type of your file need to export, it's look like:

    let directory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
    let audioTypeOutput = ".m4a"//type of your file, mp3, m4a for audio
    let exportPath = directory?.appendingPathComponent(name + audioTypeOutput)

hope this help!


问:
On refreshing page browser showing script
Once I am going to refresh pages rather than main route, browser showing script/code instead of ui. Web app made using reactjs v16. I am looking for solutions. Could you please help me?

page after refresh

```<code>import React, { Component } from 'react';

    class DashboardContainer extends Component {

        constructor(props) {
            super(props);

        }

        render() {
            return (
                <div className="right_col quick-settings" role="main">
    Dashboard
                </div>
            )
        }

    }

    export default DashboardContainer;
</code>```

答:
I think you omitted the angle bracket(<>) by mistake when you used Dashborard component. Try this:

import React, { Component } from 'react';

class DashboardContainer extends Component {

constructor(props) {
    super(props);

}

render() {
    return (

            <Dashboard />

    )
  }
}

export default DashboardContainer;
```

Body:
Once I am going to refresh pages rather than main route, browser showing script/code instead of ui. Web app made using reactjs v16. I am looking for solutions. Could you please help me?

page after refresh

import React, { Component } from 'react';

    class DashboardContainer extends Component {

        constructor(props) {
            super(props);

        }

        render() {
            return (

    Dashboard

            )
        }

    }

    export default DashboardContainer;

Body:
I think you omitted the angle bracket(<>) by mistake when you used Dashborard component. Try this:

import React, { Component } from 'react';

class DashboardContainer extends Component {

constructor(props) {
    super(props);

}

render() {
    return (
        <div className="right_col quick-settings" role="main">
            <Dashboard />
        </div>
    )
  }
}

export default DashboardContainer;