问:
How to set date as type date in excel with apache poi?
I am using apache poi 3.8 to create an excel file. This excel file needs to contain some dates.

I am trying to write a date to the excel file with as format the excel type "date". But i always get a type "custom". I need to use the the type "date", so it will be localized based on the users settings.

I have tried the following:

Apache poi date format

Apache POI localized Date into Excel cell

But it doens't work.

This is the code that I have:

```<code>XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet("new sheet");

XSSFDataFormat df = wb.createDataFormat();
CellStyle cs = wb.createCellStyle();
cs.setDataFormat(df.getFormat("d-mmm-yy"));

XSSFCell cell = sheet.createRow(0).createCell(0);

Calendar c = Calendar.getInstance();
c.set(2012,3-1,18);
cell.setCellValue( c.getTime() );

cell.setCellStyle(cs);

// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("c:\\temp\\dates-sworkbook.xlsx");
wb.write(fileOut);
fileOut.close();
</code>```

Which format should I use?

Thanks

答:
I understand your problem. I resolved using DateUtil of Apache Poi.

```<code>Cell cell = yourRow.createCell(yourIndex);
cell.setCellValue(DateUtil.getExcelDate(yourDate);
</code>```

Enjoy !!

Body:
I am using apache poi 3.8 to create an excel file. This excel file needs to contain some dates.

I am trying to write a date to the excel file with as format the excel type "date". But i always get a type "custom". I need to use the the type "date", so it will be localized based on the users settings.

I have tried the following:

Apache poi date format

Apache POI localized Date into Excel cell

But it doens't work.

This is the code that I have:

XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet("new sheet");

XSSFDataFormat df = wb.createDataFormat();
CellStyle cs = wb.createCellStyle();
cs.setDataFormat(df.getFormat("d-mmm-yy"));

XSSFCell cell = sheet.createRow(0).createCell(0);

Calendar c = Calendar.getInstance();
c.set(2012,3-1,18);
cell.setCellValue( c.getTime() );

cell.setCellStyle(cs);

// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("c:\\temp\\dates-sworkbook.xlsx");
wb.write(fileOut);
fileOut.close();

Which format should I use?

Thanks

Body:
I understand your problem. I resolved using DateUtil of Apache Poi.

Cell cell = yourRow.createCell(yourIndex);
cell.setCellValue(DateUtil.getExcelDate(yourDate);

Enjoy !!


来源: stackexchange

问:
Tkinter text widget is wider than any other widget with grid
From tutorials, I have kind of been under the impression that grid just "kind of figures it out" for width, but it's clearly not the case when it comes to Text (I suppose when combined with list).

With the following code, listbox has is tiny and Text is absolutely massive (Width wise). I can make the listbox equal to the size of the Text by changing sticky="ew", but that's not what I want - I want a reasonable, equivalently styled "grid".

If I hardcode the size of the width, it's even more frustrating, because listbox width seems to equate to approximately 2/3 of Text width.

I've read up on rowconfigure and columnconfiugre, but this seems to actually do nothing with the below code (note - rowconfigure and columnconfigure are not in the below code, but I have tried them, perhaps I'm using them wrong).

Anyways, with the below code - can anyone explain to me how to make these more reasonably sized width wise, and also the same? Should I hardcode a width to Text and then set listbox to sticky="ew"? Seems counter intuitive to the grid layout concept.

```<code>class MainApplication(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        self.frame = tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent
        self.initialize()

    def initialize(self):

        self.lst_bx = tk.Listbox(self.parent, height = 15)
        self.lst_bx.grid(row=0, column=0, columnspan=2, padx=(10,10), sticky="w")

        self.exe_field = tk.Text(self.parent, height=15)
        self.exe_field.grid(row=1, column=0, columnspan=2, padx=(10,10), sticky="w")

        self.pick_exe_btn = tk.Button(
            self.parent, text="Choose Location", width=15
        )
        self.pick_exe_btn.grid(row=0, column=2)

if __name__ == "__main__":
    root = tk.Tk()
    #window_config(root)
    MainApplication(root).grid(stick="nesw")
    root.resizable(False, False)
    root.mainloop()
</code>```

I'm sorry for being such a noob, I swear I have searched this a lot before posting here - I just cannot find a straight answer on why ListBox is a completely different width from Text (and even moreso when I specify a width).

答:
The how tkinter calculates the dimensions tkinter.ListBox() and tkinter.Text() widgets is a little bit different from most of other widgets where it uses pixels. For these 2 specific widgets, the width is calculated in terms of characters whereas the height is assessed in terms of lines.

You did not set the width of self.lst_bx, so tkinter sets it by default to 20 characters.

You did not specify the width of self.exe_field either. So tkinter calculates this width based on the current default font size.

From 1) and 2) we can conclude that it is quite normal we can not expect from self.exe_field to have the same width as self.lst_bx. This means, you have no option other than hard coding them and visually check the GUI.

With minor changes of your code (mainly provided in the comments below your question) this is how I solved your issue:

```<code>import tkinter as tk

class MainApplication(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent
        self.initialize()

    def initialize(self):
        self.lst_bx = tk.Listbox(self, height = 15, width=70)
        self.lst_bx.grid(row=0, column=0, padx=(10,10), sticky="w")

        self.exe_field = tk.Text(self, height=15, width=80)
        self.exe_field.grid(row=1, column=0, padx=(10,10), sticky="w")

        self.pick_exe_btn = tk.Button(self, text="Choose Location", width=15)
        self.pick_exe_btn.grid(row=0, column=2, columnspan=2)

if __name__ == "__main__":
    root = tk.Tk()
    #window_config(root)
    MainApplication(root).grid(stick="nesw")
    root.resizable(False, False)
    root.mainloop()
</code>```

Note where I moved the columnspace option (it quite does not make a sens in the two places where you have set it previously). Note also that tkinter calculate the character somehow differently between the listbox and text widgets. Depending your operating system (and maybe machine also), you may have to change the 2 width dimensions I set to the widgets in questions.

Here is what I got on my machine:

ContentLicense: CC BY-SA 3.0

Body:
From tutorials, I have kind of been under the impression that grid just "kind of figures it out" for width, but it's clearly not the case when it comes to Text (I suppose when combined with list).

With the following code, listbox has is tiny and Text is absolutely massive (Width wise). I can make the listbox equal to the size of the Text by changing sticky="ew", but that's not what I want - I want a reasonable, equivalently styled "grid".

If I hardcode the size of the width, it's even more frustrating, because listbox width seems to equate to approximately 2/3 of Text width.

I've read up on rowconfigure and columnconfiugre, but this seems to actually do nothing with the below code (note - rowconfigure and columnconfigure are not in the below code, but I have tried them, perhaps I'm using them wrong).

Anyways, with the below code - can anyone explain to me how to make these more reasonably sized width wise, and also the same? Should I hardcode a width to Text and then set listbox to sticky="ew"? Seems counter intuitive to the grid layout concept.

class MainApplication(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        self.frame = tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent
        self.initialize()

    def initialize(self):

        self.lst_bx = tk.Listbox(self.parent, height = 15)
        self.lst_bx.grid(row=0, column=0, columnspan=2, padx=(10,10), sticky="w")

        self.exe_field = tk.Text(self.parent, height=15)
        self.exe_field.grid(row=1, column=0, columnspan=2, padx=(10,10), sticky="w")

        self.pick_exe_btn = tk.Button(
            self.parent, text="Choose Location", width=15
        )
        self.pick_exe_btn.grid(row=0, column=2)

if __name__ == "__main__":
    root = tk.Tk()
    #window_config(root)
    MainApplication(root).grid(stick="nesw")
    root.resizable(False, False)
    root.mainloop()

I'm sorry for being such a noob, I swear I have searched this a lot before posting here - I just cannot find a straight answer on why ListBox is a completely different width from Text (and even moreso when I specify a width).

Body:
The how tkinter calculates the dimensions tkinter.ListBox() and tkinter.Text() widgets is a little bit different from most of other widgets where it uses pixels. For these 2 specific widgets, the width is calculated in terms of characters whereas the height is assessed in terms of lines.

You did not set the width of self.lst_bx, so tkinter sets it by default to 20 characters.

You did not specify the width of self.exe_field either. So tkinter calculates this width based on the current default font size.

From 1) and 2) we can conclude that it is quite normal we can not expect from self.exe_field to have the same width as self.lst_bx. This means, you have no option other than hard coding them and visually check the GUI.

With minor changes of your code (mainly provided in the comments below your question) this is how I solved your issue:

import tkinter as tk

class MainApplication(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent
        self.initialize()

    def initialize(self):
        self.lst_bx = tk.Listbox(self, height = 15, width=70)
        self.lst_bx.grid(row=0, column=0, padx=(10,10), sticky="w")

        self.exe_field = tk.Text(self, height=15, width=80)
        self.exe_field.grid(row=1, column=0, padx=(10,10), sticky="w")

        self.pick_exe_btn = tk.Button(self, text="Choose Location", width=15)
        self.pick_exe_btn.grid(row=0, column=2, columnspan=2)

if __name__ == "__main__":
    root = tk.Tk()
    #window_config(root)
    MainApplication(root).grid(stick="nesw")
    root.resizable(False, False)
    root.mainloop()

Note where I moved the columnspace option (it quite does not make a sens in the two places where you have set it previously). Note also that tkinter calculate the character somehow differently between the listbox and text widgets. Depending your operating system (and maybe machine also), you may have to change the 2 width dimensions I set to the widgets in questions.

Here is what I got on my machine:


问:
AngularJS Calling Service from Controller Error
I am not sure why I am getting this error, could someone please explain this to me?

TypeError: Cannot read property 'getValueByName' of undefined
      at Object. (http://localhost:63342/Hardcore%20Gaming%20JS/scripts/MainApp.js:175:32)
      at Object.invoke (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js:4473:17)
      at extend.instance (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js:9093:34)
      at nodeLinkFn (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js:8205:36)
      at compositeLinkFn (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js:7637:13)
      at publicLinkFn (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js:7512:30)
      at link (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular-route.js:986:7)
      at invokeLinkFn (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js:8746:9)
      at nodeLinkFn (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js:8246:11)
      at compositeLinkFn (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js:7637:13)

I have created a service in order to store, update, and return the values of a parts list. I am trying to update the partsList after they click on the different radio buttons.

Also if you know how to make these selections persist through different view changes that would be awesome to know about as well.

Thanks!!

Here is my Service Code:

```<code>mainApp.service('MyService', function () {
    var partsList = [
        {name: "selected_computer_type", value: ''},
        {name: "selected_computer_size", value: ''},
        {name: "selected_computer_color", value: ''}
    ];

    //iterates through partslist, finds object that matches and sets the new value
    this.setValue = function (name, value) {
        for (var i = 0; i < partsList.length; i++)
            if (partsList[i].name == name) partsList[i].value = value;
    };

    this.getValueByName = function (name) {
        for (var i = 0; i < partsList.length; i++)
            if (partsList[i].name == name)
                return partsList[i].value;
        return "";
    };
});
</code>```

Here is my Controller Code:

```<code>mainApp.controller('controller_Computer_Type', ['$scope', function ($scope, MyService) {
    //Computer Type Selected
    $scope.current = MyService.getValueByName("selected_computer_type");

    //Updates the partsList
    $scope.change = function () {
        var value = $scope.current.toString();
        MyService.setValue("selected_computer_type", value);
    };

    //List of options for computer type
    $scope.types = [
        //TODO: update url images to reflect personal gaming and business profiles
        {name: 'Personal', value: 'personal', url: 'images/intel 700/ABFS_1_201706141903610053.jpg'},
        {name: 'Gaming', value: 'gaming', url: 'images/amd 500/83-230-100-02.jpg'},
        {name: 'Business', value: 'business', url: 'images/intel 500/83-101-369-z01.jpg'}
    ];
}]);
</code>```

Here is my View Code:

```<code><div ng-controller="controller_Computer_Type">

    <h2>Type of Computer</h2>

    <!--Radio Button Options Using Images-->
    <div class="row">
        <label class="col-sm-4" ng-repeat="option in types">
            <input type="radio" name="radio_type" ng-model="$parent.current" ng-change="change()" value="{{option.value}}" hidden/>
            <img class="img-thumbnail" src="{{option.url}}" alt="{{option.value}}">
            <img class="overlay" src="images/greenCheck.png">
        </label>
    </div>

    <!--Debugging purposes-->
    <p>Current RB - {{current}}</p>

    <p>Current DD - {{selectedItem.name}}</p>

    <p>Message - {{message}}</p>

</div>
</code>```

答:
U miss this

mainApp.controller('controller_Computer_Type', ['$scope','MyService', function ($scope, MyService)

Body:
I am not sure why I am getting this error, could someone please explain this to me?

TypeError: Cannot read property 'getValueByName' of undefined
      at Object. (http://localhost:63342/Hardcore%20Gaming%20JS/scripts/MainApp.js:175:32)
      at Object.invoke (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js:4473:17)
      at extend.instance (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js:9093:34)
      at nodeLinkFn (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js:8205:36)
      at compositeLinkFn (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js:7637:13)
      at publicLinkFn (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js:7512:30)
      at link (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular-route.js:986:7)
      at invokeLinkFn (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js:8746:9)
      at nodeLinkFn (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js:8246:11)
      at compositeLinkFn (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js:7637:13)

I have created a service in order to store, update, and return the values of a parts list. I am trying to update the partsList after they click on the different radio buttons.

Also if you know how to make these selections persist through different view changes that would be awesome to know about as well.

Thanks!!

Here is my Service Code:

mainApp.service('MyService', function () {
    var partsList = [
        {name: "selected_computer_type", value: ''},
        {name: "selected_computer_size", value: ''},
        {name: "selected_computer_color", value: ''}
    ];

    //iterates through partslist, finds object that matches and sets the new value
    this.setValue = function (name, value) {
        for (var i = 0; i < partsList.length; i++)
            if (partsList[i].name == name) partsList[i].value = value;
    };

    this.getValueByName = function (name) {
        for (var i = 0; i < partsList.length; i++)
            if (partsList[i].name == name)
                return partsList[i].value;
        return "";
    };
});

Here is my Controller Code:

mainApp.controller('controller_Computer_Type', ['$scope', function ($scope, MyService) {
    //Computer Type Selected
    $scope.current = MyService.getValueByName("selected_computer_type");

    //Updates the partsList
    $scope.change = function () {
        var value = $scope.current.toString();
        MyService.setValue("selected_computer_type", value);
    };

    //List of options for computer type
    $scope.types = [
        //TODO: update url images to reflect personal gaming and business profiles
        {name: 'Personal', value: 'personal', url: 'images/intel 700/ABFS_1_201706141903610053.jpg'},
        {name: 'Gaming', value: 'gaming', url: 'images/amd 500/83-230-100-02.jpg'},
        {name: 'Business', value: 'business', url: 'images/intel 500/83-101-369-z01.jpg'}
    ];
}]);

Here is my View Code:

Type of Computer

            <input type="radio" name="radio_type" ng-model="$parent.current" ng-change="change()" value="{{option.value}}" hidden/>

Current RB - {{current}}

Current DD - {{selectedItem.name}}

Message - {{message}}


问:
How to Use 1st Class Properties and Methods in 2nd Class?
I have two classes. Lets call them 'Class_A' and 'Class_B'. I want to use 'Class_A' properties and methods in 'Class B'. Like this...

```<code>$a = new Class_A;

class Class_B {

    function __construct() {

        $a->foo = 2;

        $a->magic();

    }

}
</code>```

Of course, it do not work. What is the best practice to deal with it?

'global' keyword?

Make properties and methods of 'Class_A' static?

Another way...?

答:
Dependency injection</p>

```<code>$a = new Class_A();

class Class_B {
    function __construct($x) {
          $x->foo = 2;
          $x->magic();
    }
}

$b = new Class_B($a);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have two classes. Lets call them 'Class_A' and 'Class_B'. I want to use 'Class_A' properties and methods in 'Class B'. Like this...

$a = new Class_A;

class Class_B {

    function __construct() {

        $a->foo = 2;

        $a->magic();

    }

}

Of course, it do not work. What is the best practice to deal with it?

'global' keyword?

Make properties and methods of 'Class_A' static?

Another way...?

Body:
Dependency injection

$a = new Class_A();

class Class_B {
    function __construct($x) {
          $x->foo = 2;
          $x->magic();
    }
}

$b = new Class_B($a);


问:
Use Inversion of Control to construct dependency with caller
Given the following ASP.NET Core controller :

```<code>public class MyController : Controller {
    public MyController(IDependency dependency) { this.dependency = dependency; }
}

public interface IDependency;

public class DependencyImplementation : IDependency {
    public DependencyImplementation(Controller controller) { ... }
}
</code>```

I want MyController to have a new instance of DependencyImplementation injected, constructed with the controller it's being passed to. Ideally using Ninject.

The non-IoC version would be:

```<code>public class MyController : Controller {
    public MyController() { this.dependency = new DependencyImplementation(this); }
}
</code>```

答:
This would cause circular dependency. Only idea I have is to introduce factory:

```<code>public interface IDependencyFactory
{
    IDependency Create(Controller controller);
}

public class MyController : Controller
{
    private IDependency dependency;

    public MyController(IDependencyFactory dependencyFactory)
    {
        this.dependency = dependencyFactory.Create(this);
    }
}

var kernel = new StandardKernel();
kernel.Bind<Controller>().To<MyController>();
kernel.Bind<IDependency>().To<DependencyImplementation>();
kernel.Bind<IDependencyFactory>().ToFactory();
var controller = kernel.Get<Controller>();
</code>```

Or maybe rather reconsider whole design.

Body:
Given the following ASP.NET Core controller :

public class MyController : Controller {
    public MyController(IDependency dependency) { this.dependency = dependency; }
}

public interface IDependency;

public class DependencyImplementation : IDependency {
    public DependencyImplementation(Controller controller) { ... }
}

I want MyController to have a new instance of DependencyImplementation injected, constructed with the controller it's being passed to. Ideally using Ninject.

The non-IoC version would be:

public class MyController : Controller {
    public MyController() { this.dependency = new DependencyImplementation(this); }
}

Body:
This would cause circular dependency. Only idea I have is to introduce factory:

public interface IDependencyFactory
{
    IDependency Create(Controller controller);
}

public class MyController : Controller
{
    private IDependency dependency;

    public MyController(IDependencyFactory dependencyFactory)
    {
        this.dependency = dependencyFactory.Create(this);
    }
}

var kernel = new StandardKernel();
kernel.Bind<Controller>().To<MyController>();
kernel.Bind<IDependency>().To<DependencyImplementation>();
kernel.Bind<IDependencyFactory>().ToFactory();
var controller = kernel.Get<Controller>();

Or maybe rather reconsider whole design.


问:
what kinda of SQL is it? TODATE(), TOCHAR(), isdateformat()
I am working on a aggregator and it contain build in functions which are I am not familiar with. Few are these I listed here, does anyone know what SQL format is it?

TODATE(string, in_format[, out_format])

ISDATEFORMAT(value[,date_format])

TOCHAR(numeric_value)

Also, here is how I use it, it does accepting my syntax, but it didn't return correct value.

```<code>count(where text_column != TODATE('date_format','YYYY-MM-DD', 'yyyymm'))
</code>```

答:
Finally I found out line of code that works:
sum(DECODE(text_column, DATETOCHAR('date_column','yyyy-mm-dd','yyyymm'),0,1))

So add on top of my original question. What type of SQL is function 'Datatochar'!?

Body:
I am working on a aggregator and it contain build in functions which are I am not familiar with. Few are these I listed here, does anyone know what SQL format is it?

TODATE(string, in_format[, out_format])

ISDATEFORMAT(value[,date_format])

TOCHAR(numeric_value)

Also, here is how I use it, it does accepting my syntax, but it didn't return correct value.

count(where text_column != TODATE('date_format','YYYY-MM-DD', 'yyyymm'))


问:
how connect to mssql named instance
I connected remote mssql default instance like

jdbc.url=jdbc:jtds:sqlserver://ip:port;databaseName=name

it succeed to connect and proceed in java source

I connected remote mssql named instance like

jdbc.url=jdbc:jtds:sqlserver://ip:port;databaseName=name

(surely I set port to instance in SQL server configuration management TCP/IP IPALL)

It succeed to connect, but not proceed well in java source like router error??

I think only reason is named instance

I don't write English well.. But, Help me..

答:
JDBC doesn't care about instance names, it doesn't use those. The instances are identified by port number.

You need to set up your named instance to allow TCP/IP protocol, assign it a port in TCP/IP IPall that's different from the default instance port), then restart the named instance. Then you use that port to connect to it throught JDBC.

Title: how connect to mssql named instance


问:
ASP.NET MVC ViewResult vs PartialViewResult
What is the difference between the controller result named ViewResult and PartialViewResult? More importantly, when is the PartialViewResult used?

答:
PartialViewResult is used to render a partialview (fx. just a user control). This is pretty nifty for AJAX stuff, i.e.

```<code><script type="text/javascript">
    $.get(
        "/MyController/MyAction",
        null,
        function (data) { $("#target").html(data) }
     );
</script>
</code>```

and action

```<code>public ActionResult MyAction()
{
    return PartialView("SomeView");
}
</code>```

where SomeView is a MVC User Control, e.g.:

```<code><div>
   <%= DateTime.Now.ToString() %>
</div>
</code>```

OwnerDisplayName: Diego Deberdt

LastEditorDisplayName: Diego Deberdt

Body:
PartialViewResult is used to render a partialview (fx. just a user control). This is pretty nifty for AJAX stuff, i.e.

<script type="text/javascript">
    $.get(
        "/MyController/MyAction",
        null,
        function (data) { $("#target").html(data) }
     );
</script>

and action

public ActionResult MyAction()
{
    return PartialView("SomeView");
}

where SomeView is a MVC User Control, e.g.:

<div>
   <%= DateTime.Now.ToString() %>
</div>

OwnerDisplayName: veggerby


问:
SQL command to extract schema of a SQLite table?
I can't decide if this is a dumb question or not but I'll take the risk. :)

I'm a fairly simple SQL user  - I understand CREATE/DROP tables and SELECT, INSERT, DELETE in their basic forms but not much more. What I'd like to know is if there's a way with SQL to request the schema of a table?

I have a PC app which uses SQLite and I'm writing a mobile client for it. I don't need all of the tables from the PC DB and not all columns from the tables. In SQLite Spy, I can right-click a table and select 'Show CREATE statement' which generates the SQL needed to recreate the table.

What I'd like to do (using code on the PC) to get the CREATE statement (or at least the schema) of the SQLite tables I need and then edit the strings to include only the columns I need. These could then be passed to my mobile app so it could create the 'subset' DB on the device. Is it possible?

EDIT: For anyone who comes after me looking for a similar answer. Thanks to dan04 pointing me in the right direction. The results of using...

```<code>SELECT * FROM sqlite_master
</code>```

... include a column called 'sql' which includes the CREATE statement. Just what I'm looking for. :)

答: It's stored in the sqlite_master table.

Body:
I can't decide if this is a dumb question or not but I'll take the risk. :)

I'm a fairly simple SQL user  - I understand CREATE/DROP tables and SELECT, INSERT, DELETE in their basic forms but not much more. What I'd like to know is if there's a way with SQL to request the schema of a table?

I have a PC app which uses SQLite and I'm writing a mobile client for it. I don't need all of the tables from the PC DB and not all columns from the tables. In SQLite Spy, I can right-click a table and select 'Show CREATE statement' which generates the SQL needed to recreate the table.

What I'd like to do (using code on the PC) to get the CREATE statement (or at least the schema) of the SQLite tables I need and then edit the strings to include only the columns I need. These could then be passed to my mobile app so it could create the 'subset' DB on the device. Is it possible?

EDIT: For anyone who comes after me looking for a similar answer. Thanks to dan04 pointing me in the right direction. The results of using...

SELECT * FROM sqlite_master

... include a column called 'sql' which includes the CREATE statement. Just what I'm looking for. :)

Body: It's stored in the sqlite_master table.


问:
What is the value type of the Map?
I have following code snippet:

```<code>  private def buildProps(host: => String)(config: => List[KafkaConfig]) =
    (config.map {
      case ClientId(value: String) =>
        (ProducerConfig.CLIENT_ID_CONFIG, value)
      case Acks(value: String) =>
        (ProducerConfig.ACKS_CONFIG, value)
      case Retries(value) =>
        (ProducerConfig.RETRIES_CONFIG, value)
      case BatchSize(value) =>
        (ProducerConfig.BATCH_SIZE_CONFIG, value)
      case LingerMs(value) =>
        (ProducerConfig.LINGER_MS_CONFIG, value)
      case BufferMemory(value) =>
        (ProducerConfig.BUFFER_MEMORY_CONFIG, value)
    } ++ List(
      (ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, host),
      (ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.ByteArraySerializer"),
      (ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.ByteArraySerializer"))
      ).toMap
</code>```

What is the type of the value from Map(String, ????)?
The type value of the case is very mixed:

```<code>final case class ClientId(value: String) extends KafkaConfig

final case class Acks(value: String) extends KafkaConfig

final case class Retries(value: java.lang.Integer) extends KafkaConfig

final case class BatchSize(value: java.lang.Integer) extends KafkaConfig

final case class LingerMs(value: java.lang.Integer) extends KafkaConfig

final case class BufferMemory(value: java.lang.Integer) extends KafkaConfig
</code>```

Some are Strings and another are Integers.

答:
I think it is AnyRef because that's what java class types usually roll up to.
Also, in java they meet at the object level.

https://www.scala-lang.org/old/node/71%3Fsize=_original.html#

Why cannot cast Integer to String in java?

Title: What is the value type of the Map?

Body:
I have following code snippet:

  private def buildProps(host: => String)(config: => List[KafkaConfig]) =
    (config.map {
      case ClientId(value: String) =>
        (ProducerConfig.CLIENT_ID_CONFIG, value)
      case Acks(value: String) =>
        (ProducerConfig.ACKS_CONFIG, value)
      case Retries(value) =>
        (ProducerConfig.RETRIES_CONFIG, value)
      case BatchSize(value) =>
        (ProducerConfig.BATCH_SIZE_CONFIG, value)
      case LingerMs(value) =>
        (ProducerConfig.LINGER_MS_CONFIG, value)
      case BufferMemory(value) =>
        (ProducerConfig.BUFFER_MEMORY_CONFIG, value)
    } ++ List(
      (ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, host),
      (ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.ByteArraySerializer"),
      (ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.ByteArraySerializer"))
      ).toMap

What is the type of the value from Map(String, ????)?
The type value of the case is very mixed:

final case class ClientId(value: String) extends KafkaConfig

final case class Acks(value: String) extends KafkaConfig

final case class Retries(value: java.lang.Integer) extends KafkaConfig

final case class BatchSize(value: java.lang.Integer) extends KafkaConfig

final case class LingerMs(value: java.lang.Integer) extends KafkaConfig

final case class BufferMemory(value: java.lang.Integer) extends KafkaConfig

Some are Strings and another are Integers.


问:
How to write SQL query into code-igniter formate
How to write below SQL query in to code-igniter </p>

```<code>SELECT
    `pm`.`id`,
    `pm`.`region`,
    `pm`.`port_name`,
    `pm`.`country`,
    `tbl_port_annual_throughput`.`YEAR`,
    `tbl_port_annual_throughput`.`TOTAL_THROUGHPUT`,
    `tbl_port_annual_throughput`.`status`
    FROM (`tbl_port_annual_throughput`)
    JOIN `port_master` pm
      ON `pm`.`id` = `tbl_port_annual_throughput`.`PORT_ID`
    WHERE `pm`.`country` = "100@Kenya"
    AND (
        (`tbl_port_annual_throughput`.`YEAR` =  '2014' AND `tbl_port_annual_throughput`.`status` =  'Confirmed')
        OR (`tbl_port_annual_throughput`.`YEAR` =  '2015' AND `tbl_port_annual_throughput`.`status` =  'Confirmed')
        OR (`tbl_port_annual_throughput`.`YEAR` =  '2016' AND `tbl_port_annual_throughput`.`status` =  'Confirmed')
    )
</code>```

答:
You can use the query builder class:

```<code>$this->db->select
$this->db->from
$this->db->join
</code>```

These kinds of methods can be used to do the same as you want in your query

You can find more here: Linkylink

Body:
How to write below SQL query in to code-igniter

SELECT
    `pm`.`id`,
    `pm`.`region`,
    `pm`.`port_name`,
    `pm`.`country`,
    `tbl_port_annual_throughput`.`YEAR`,
    `tbl_port_annual_throughput`.`TOTAL_THROUGHPUT`,
    `tbl_port_annual_throughput`.`status`
    FROM (`tbl_port_annual_throughput`)
    JOIN `port_master` pm
      ON `pm`.`id` = `tbl_port_annual_throughput`.`PORT_ID`
    WHERE `pm`.`country` = "100@Kenya"
    AND (
        (`tbl_port_annual_throughput`.`YEAR` =  '2014' AND `tbl_port_annual_throughput`.`status` =  'Confirmed')
        OR (`tbl_port_annual_throughput`.`YEAR` =  '2015' AND `tbl_port_annual_throughput`.`status` =  'Confirmed')
        OR (`tbl_port_annual_throughput`.`YEAR` =  '2016' AND `tbl_port_annual_throughput`.`status` =  'Confirmed')
    )

Body:
You can use the query builder class:

$this->db->select
$this->db->from
$this->db->join

These kinds of methods can be used to do the same as you want in your query

You can find more here: Linkylink


问:
How Temp Table works in Stored Procedures (global & local )
Image #1: I am creating a stored procedure for inserting records into #t1.
In the same session I am executing the Localtemp1 stored procedure for any number of times, and it works fine:

Image #2: again executing the stored procedure in another session & works fine as well:

Image #3: now creating stored procedure for inserting records into ##tt. For the first execution of globaltemp1 stored procedure, it works well:

Image #4: but when I executed it a second time, it is showing errors (does not exist in DB):

Image #5: then I closed the session where globaltemp stored procedure was created, and in a new session, I executed the stored procedure, and it works well for the first time:

Image #6: but when I execute it a second time, again it is showing errors (does not exist in DB):

What I know is scope of local temp & global temp, but in stored procedures, they were completely different

Can someone tell me

Execution of localtemp1 stored procedure for many times gives output but while executing globaltemp1 sp for the first time gives output and second time results in an error

As far as I know, after execution of stored procedure temptable gets dropped. Then why localtemp1 stored procedure is getting executed across all sessions and many number of times?

Why globaltemp1 stored procedure is executing once and for second time showing an error?

Final one, Globaltemp stored procedure shows output in another session for the first time only when created session was closed

I mean

56 ----> globaltemp sp was created

57 ----> to get o/p i need to close 56

58 ----> to get o?p i need to close 57   (  WHY ??? )

I am a beginner at SQL and please, someone make me understand because if I don't find logic & correct reason I could not dive into another topic.

答: Local temporary tables are visible only in the current session, and global temporary tables are visible to all sessions. Global temporary tables are automatically dropped when the session that created the table ends and all other tasks have stopped referencing them. The association between a task and a table is maintained only for the life of a single Transact-SQL statement. This means that a global temporary table is dropped at the completion of the last Transact-SQL statement that was actively referencing the table when the creating session ended.</p>


问:
How to execute Adobe javascript call in Jmeter
I am using the latest Jmeter ver. 3.3 and tried executing Adobe analytic JS call using JSR223 sampler but fails to show up in analytics dashboard.
Can anyone help me, need to trigger analytic call with load test.

Thanks,
A

答:
Looking into Adobe API Explorer given you have credentials, to wit API Username and Shared Secret (you can find them at your Account Information page) you should be able to execute necessary SOAP or REST request using JMeter's HTTP Request sampler.

You will also need HTTP Header Manager to send i.e. X-WSSE header, Content-Type header, etc.

See Testing SOAP/REST Web Services Using JMeter article for more information on configuring JMeter for simulating web service requests.


问:
Trigger AutoClosable on JVM Shutdown
TL;DR:
Is there a way to find out, that JVM-shutdown is only prevented from the threads started by my code? Is it for example possible to automatically trigger AutoCloseable.close() on Shutdown?

Context

I am building a library, that should be used by several customers. This means, besides providing a documentation, I can't enforce certain things.

Architecture

(I try to describe it as abstract as possible and avoid unnecessary details)

I have a "Manager" object (which is kind of a Factory), that is used to create a "Service" object, that in turn needs some data to work accordingly. Since that data is loaded from some "slow" backend service (which also might change from time to time), I use a separate (Daemon)-Thread that checks for updates and injects new data into that service as soon as available. (This also means that unless the first update, that service is simply in "noop mode". But that's ok.)

Now the "Updater" (which runs in my daemon thread) uses a library that again starts a thread when opening a connection and it's necessary to call "close" to ensure that this secondary thread is stopped - otherwise it is not possible, to shutdown the JVM properly.

As a safety-net I call the close() method inside the finalize() method of my "Manager" (which keeps a reference to all Updater instances). This is not 100% safe, since it's not predictable when GC runs (even more during shutdown!), but it's my only option.

Update: Here is some abstract example code that illustrates the architecture and the according problem

Problem

This architecture causes two possible pitfalls:

If the implementation does not keep a reference to the instance of the manager, it will be garbage collected at some point and trough the finalize method the necessary background updates will be stopped.

If the implementation keeps an instances of the manager, it must call the close method during the shutdown of the according system, otherwise the JVM can't terminate properly.

So my actual problem is the "potential unreliability" of the developers, which are using that library.

Does anyone have an idea how to build a solution, that could handle both pitfalls?
It would be nice to have some Auto-AutoCloseable ;) that is called during Shutdown (e.g by the DestroyJavaVM Thread or similar).

Solutions I tried unsuccessfully

Inside the Updater I am closing the "problematic" connection inside a "try-finally" block, but that daemon thread is not interrupted / stopped automatically as well.

I registered a Runtime.getRuntime().addShutdownHook(...) that would close all connections, but this shutdown hook is never called since a Shutdown is only initiated when all user-threads are stopped.

Update: Solved at my implementation, but not the problem

I solved my problem as I found that the third party library (RabbitMQ Client) offers a setThreadFactory method that I can use to ensure the spawned Threads are Daemon-Threads.
Good luck for me with my 3rd party library, but the described problem is still possible.

答:
Ok, I guess there is no good solution for that problem, but since I found that my 3rd party library gives the possibility to create Daemon-Threads, this is exactly what was necessary to fix it.

Maybe this is also a problem that should be solved on the "human level" by providing a good documentation and ensure a proper usage of AutoCloseable. A good developer should know how to deal with that.

From a technical point of view I found these possible solutions, which are just "safety nets" no one should rely on.

call "close()" inside the finalize method

I implemented a service, that can be used to register AutoClosable resources. It runs inside a Daemon-Thread and checks every few seconds, if it finds the JavaDestroyVM Thread and in such a case, closes all registered AutoClosables and stops itself.

Disclosure: If a system runs "outside of the main method" (the JavaDestroyVM Thread will run all the time), this is solution won't work.

Update: The RegisterAutoClosable-Service was a very ugly/hacky solution - I deleted it and plan to change the design, to avoid such situations, but finally it's the responsibility of the implementing developer to close opened resources properly.

Title: Trigger AutoClosable on JVM Shutdown

ContentLicense: CC BY-SA 4.0


问:
reactjs componentWillMount not calling every time when i open modal
i am displaying table data inside modal dialog, when i click table row to edit data it will open another modal dialog, here i am getting row data by using clicked row id inside componentWillMount(). but when i close edit modal dialog and try to edit other table row componentWillMount() will not called. so edit modal dialog is empty. why componentWillMount not calling every time?

答:
As Nir H already mentioned, Dialog component mounts into the dom only once, and then after you close it, becomes invisible (by changing the left position to -10000px) but still present inside the DOM.

So its clearly that componentWillMount and componentDidMount methods will be called only once. If you want to open Dialog component with different options every time, you can do the folloving:

Save ref to the Dialog component instanse in the parent component:

ref={instance => {this.RowDialog = instance}}

Then you can open Dialog by using it handleOpen method:

onRowClick = (event) => {
    this.RowDialog.handleOpen();
 }


问:
typescript compiling types under node_modules even after excluding them
While trying to compile my typescript source code, I see that the compiler is also trying to compile the types under my node_modules folder .
I am using typescript 2.6.1 and my tsconfig file is as below

```<code> {
  "compilerOptions": {
  "allowSyntheticDefaultImports":true,
  "outDir": "./dist",
  "mapRoot": "./dist",
  "module": "commonjs",
  "target": "es6",
  "sourceMap": true,
  "sourceRoot": "./source",
  "removeComments": false
},
"exclude": [
  "node_modules",
  "test"
],
  "include": [
  "source/*.ts"
]
}
</code>```

When I run the following comand "tsc -w -p tsconfig.json" I get the following error

```<code> node_modules/@types/es6-promise/index.d.ts(11,15): error TS2300: Duplicate identifier 'Promise'.
</code>```

答:
After reading this document, I got the answer
https://www.typescriptlang.org/docs/handbook/tsconfig-json.html

under section @types, typeRoots and types

They have mentioned

Specify "types": [] to disable automatic inclusion of @types packages.

The updated tsconfig.json is as follows

```<code>{
  "compilerOptions": {
   "allowSyntheticDefaultImports":true,
   "outDir": "./dist",
   "mapRoot": "./dist",
   "module": "commonjs",
   "target": "es6",
   "sourceMap": true,
   "sourceRoot": "./source",
   "removeComments": false,
   "types": []
 },
 "exclude": [
   "node_modules",
   "test"
 ],
 "include": [
   "source/*.ts"
 ]
}
</code>```

Body:
While trying to compile my typescript source code, I see that the compiler is also trying to compile the types under my node_modules folder .
I am using typescript 2.6.1 and my tsconfig file is as below

 {
  "compilerOptions": {
  "allowSyntheticDefaultImports":true,
  "outDir": "./dist",
  "mapRoot": "./dist",
  "module": "commonjs",
  "target": "es6",
  "sourceMap": true,
  "sourceRoot": "./source",
  "removeComments": false
},
"exclude": [
  "node_modules",
  "test"
],
  "include": [
  "source/*.ts"
]
}

When I run the following comand "tsc -w -p tsconfig.json" I get the following error

 node_modules/@types/es6-promise/index.d.ts(11,15): error TS2300: Duplicate identifier 'Promise'.

Body:
After reading this document, I got the answer
https://www.typescriptlang.org/docs/handbook/tsconfig-json.html

under section @types, typeRoots and types

They have mentioned

Specify "types": [] to disable automatic inclusion of @types packages.

The updated tsconfig.json is as follows

{
  "compilerOptions": {
   "allowSyntheticDefaultImports":true,
   "outDir": "./dist",
   "mapRoot": "./dist",
   "module": "commonjs",
   "target": "es6",
   "sourceMap": true,
   "sourceRoot": "./source",
   "removeComments": false,
   "types": []
 },
 "exclude": [
   "node_modules",
   "test"
 ],
 "include": [
   "source/*.ts"
 ]
}


问:
Can't use Bootstrap in PHP file
I'm fetching some data from a MySQL database onto a WebPage. I came up with a simple PHP page that queries the database and shows the query in the form of a table and it works just fine.

However, when I try to add bootstrap to the page and style it, the entire page stops working.

Here's my index.php

```<code><!DOCTYPE html>
<html>
<head>
<title>MakersBox</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<center>
<h1>Sensor Testing Dashboard</h1>
<div class="container">
<?php
echo "<table class='table table-hover' align=center>";
 echo "<thead><tr><th>Sensor Id</th><th>Temperature</th><th>Light</th><th>Last Updated</th></tr></thead>";

class TableRows extends RecursiveIteratorIterator {
    function __construct($it) {
        parent::__construct($it, self::LEAVES_ONLY);
    }

    function current() {
        return "<td>" . parent::current(). "</td>";
    }

    function beginChildren() {
        echo "<tr>";
    }

    function endChildren() {
        echo "</tr>" . "\n";
    }
}

$servername = "localhost";
$username = "root";
$password = "paanikiboond";
$dbname = "testbox1";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare("SELECT * FROM sensor ORDER BY LastUpdate DESC LIMIT 1");
    $stmt->execute();

    // set the resulting array to associative
    $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);

    foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
        echo $v;
    }
}
catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
</div>

$url1=$_SERVER['REQUEST_URI'];
header("Refresh: 3600 ; URL=$url1");
?>

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

Any idea what I may be doing wrong here?

答:
```<code></center><!--that where you forgot to add this as it needs to be closed off-->
</body>
</html>
</code>```

Also, you might be better off put Javascript on the bottom of the pages, Not sure if it will work.

Second things you need use Web developer tools to diagnosed this issues. it will help a lot. also, you might need to test out different browser if it's same issues or not.

Title: Can't use Bootstrap in PHP file

Body:
I'm fetching some data from a MySQL database onto a WebPage. I came up with a simple PHP page that queries the database and shows the query in the form of a table and it works just fine.

However, when I try to add bootstrap to the page and style it, the entire page stops working.

Here's my index.php

<!DOCTYPE html>

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

Sensor Testing Dashboard

<?php
echo "
";
 echo "

Sensor Id	Temperature	Light	Last Updated

";

class TableRows extends RecursiveIteratorIterator {
    function __construct($it) {
        parent::__construct($it, self::LEAVES_ONLY);
    }

    function current() {
        return "" . parent::current(). "	";
    }

    function beginChildren() {
        echo "
";
    }

    function endChildren() {
        echo "
" . "\n";
    }
}

$servername = "localhost";
$username = "root";
$password = "paanikiboond";
$dbname = "testbox1";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare("SELECT * FROM sensor ORDER BY LastUpdate DESC LIMIT 1");
    $stmt->execute();

    // set the resulting array to associative
    $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);

    foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
        echo $v;
    }
}
catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}
$conn = null;
echo "
";

$url1=$_SERVER['REQUEST_URI'];
header("Refresh: 3600 ; URL=$url1");
?>

Any idea what I may be doing wrong here?

Body:
</center><!--that where you forgot to add this as it needs to be closed off-->
</body>
</html>

Also, you might be better off put Javascript on the bottom of the pages, Not sure if it will work.

Second things you need use Web developer tools to diagnosed this issues. it will help a lot. also, you might need to test out different browser if it's same issues or not.


问:
Android Studio 3.1 Canary 3 - Gradle sync failed
For a unknown reason Android Studio 3.1 Canary 3 is bugged and stopped to work, I updated gradle to 3.1-alpha03 and it stopped working, no matter if I download the project again, already downloaded Android Studio again too.

I've already checkout old versions of the project, but this message still show:

```<code>Gradle sync failed: com.android.tools.idea.gradle.project.model.AndroidModuleModel.getSelectedVariant()Lcom/android/tools/idea/gradle/project/model/ide/android/IdeVariant; (8s 806ms)
</code>```

I've removed .idea folder, .gradle folder, did invalidate and restart

I don't know nothing more to do, cant run or use the IDE.

Edit:

Edit2:

New Projects doesnt work too

答:
It's a problem with Kotlin 1.1.60-release-Studio3.0-1 plugin.

Uninstall it from Android Studio and fetch an older version from here:
https://plugins.jetbrains.com/plugin/6954-kotlin

Body:
For a unknown reason Android Studio 3.1 Canary 3 is bugged and stopped to work, I updated gradle to 3.1-alpha03 and it stopped working, no matter if I download the project again, already downloaded Android Studio again too.

I've already checkout old versions of the project, but this message still show:

Gradle sync failed: com.android.tools.idea.gradle.project.model.AndroidModuleModel.getSelectedVariant()Lcom/android/tools/idea/gradle/project/model/ide/android/IdeVariant; (8s 806ms)

I've removed .idea folder, .gradle folder, did invalidate and restart

I don't know nothing more to do, cant run or use the IDE.

Edit:

Edit2:

New Projects doesnt work too


问:
Application Stops after i click an item on the app drawer
I am having a problem with  the framework which I have downloaded from the Github .
I have imported it in Android studio and I have made a few changes which consists on adding a new activity which can be launched from the app drawer .
I tried lunching the new activity like this

```<code>public void onClick(View v) {
    Intent intent = new Intent(getActivity(), WorkOrderActivity.class);
    startActivity(intent);
}
</code>```

It compiles but when I click it, that app stops the logcat shows :

```<code>11-15 09:39:52.681 3852-3874/? E/AndroidRuntime: FATAL EXCEPTION: ModernAsyncTask #1
                                             Process: com.odoo, PID: 3852
                                             java.lang.RuntimeException: An error occurred while executing doInBackground()
                                                 at android.support.v4.content.ModernAsyncTask$3.done(ModernAsyncTask.java:161)
                                                 at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
                                                 at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
                                                 at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                                                 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                                                 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                                                 at java.lang.Thread.run(Thread.java:841)
                                              Caused by: java.lang.IllegalArgumentException: Cannot bind argument at index 1 because the index is out of range.  The statement has 0 parameters.
                                                 at android.database.sqlite.SQLiteProgram.bind(SQLiteProgram.java:212)
                                                 at android.database.sqlite.SQLiteProgram.bindString(SQLiteProgram.java:166)
                                                 at android.database.sqlite.SQLiteProgram.bindAllArgsAsStrings(SQLiteProgram.java:200)
                                                 at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:47)
                                                 at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314)
                                                 at android.database.sqlite.SQLiteQueryBuilder.query(SQLiteQueryBuilder.java:400)
                                                 at android.database.sqlite.SQLiteQueryBuilder.query(SQLiteQueryBuilder.java:294)
                                                 at com.odoo.core.orm.provider.BaseModelProvider.query(BaseModelProvider.java:107)
                                                 at android.content.ContentProvider.query(ContentProvider.java:857)
                                                 at android.content.ContentProvider$Transport.query(ContentProvider.java:200)
                                                 at android.content.ContentResolver.query(ContentResolver.java:461)
                                                 at android.support.v4.content.ContentResolverCompatJellybean.query(ContentResolverCompatJellybean.java:33)
                                                 at android.support.v4.content.ContentResolverCompat$ContentResolverCompatImplJB.query(ContentResolverCompat.java:57)
                                                 at android.support.v4.content.ContentResolverCompat.query(ContentResolverCompat.java:125)
                                                 at android.support.v4.content.CursorLoader.loadInBackground(CursorLoader.java:59)
                                                 at android.support.v4.content.CursorLoader.loadInBackground(CursorLoader.java:37)
                                                 at android.support.v4.content.AsyncTaskLoader.onLoadInBackground(AsyncTaskLoader.java:299)
                                                 at android.support.v4.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:57)
                                                 at android.support.v4.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:45)
                                                 at android.support.v4.content.ModernAsyncTask$2.call(ModernAsyncTask.java:138)
                                                 at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                                                 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                                                 at java.lang.Thread.run(Thread.java:841)
</code>```

Does anyone have any idea what may be wrong .
Looking forward to your responses .

Best Regards

答:
If you are using Navigation Drawer then you should override this method

```<code>@Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.your_view_id) {
            //start your activity here
           }
}
</code>```

and if you set the click listener in your View then you should use

```<code>@Override
 public void onClick(View v) {
  switch (view.getId()){
   case R.id.your_view_id:
    Intent intent = new Intent(getActivity(), WorkOrderActivity.class);
    startActivity(intent);
    break;
 }
}
</code>```

Body:
I am having a problem with  the framework which I have downloaded from the Github .
I have imported it in Android studio and I have made a few changes which consists on adding a new activity which can be launched from the app drawer .
I tried lunching the new activity like this

public void onClick(View v) {
    Intent intent = new Intent(getActivity(), WorkOrderActivity.class);
    startActivity(intent);
}

It compiles but when I click it, that app stops the logcat shows :

11-15 09:39:52.681 3852-3874/? E/AndroidRuntime: FATAL EXCEPTION: ModernAsyncTask #1
                                             Process: com.odoo, PID: 3852
                                             java.lang.RuntimeException: An error occurred while executing doInBackground()
                                                 at android.support.v4.content.ModernAsyncTask$3.done(ModernAsyncTask.java:161)
                                                 at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
                                                 at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
                                                 at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                                                 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                                                 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                                                 at java.lang.Thread.run(Thread.java:841)
                                              Caused by: java.lang.IllegalArgumentException: Cannot bind argument at index 1 because the index is out of range.  The statement has 0 parameters.
                                                 at android.database.sqlite.SQLiteProgram.bind(SQLiteProgram.java:212)
                                                 at android.database.sqlite.SQLiteProgram.bindString(SQLiteProgram.java:166)
                                                 at android.database.sqlite.SQLiteProgram.bindAllArgsAsStrings(SQLiteProgram.java:200)
                                                 at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:47)
                                                 at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314)
                                                 at android.database.sqlite.SQLiteQueryBuilder.query(SQLiteQueryBuilder.java:400)
                                                 at android.database.sqlite.SQLiteQueryBuilder.query(SQLiteQueryBuilder.java:294)
                                                 at com.odoo.core.orm.provider.BaseModelProvider.query(BaseModelProvider.java:107)
                                                 at android.content.ContentProvider.query(ContentProvider.java:857)
                                                 at android.content.ContentProvider$Transport.query(ContentProvider.java:200)
                                                 at android.content.ContentResolver.query(ContentResolver.java:461)
                                                 at android.support.v4.content.ContentResolverCompatJellybean.query(ContentResolverCompatJellybean.java:33)
                                                 at android.support.v4.content.ContentResolverCompat$ContentResolverCompatImplJB.query(ContentResolverCompat.java:57)
                                                 at android.support.v4.content.ContentResolverCompat.query(ContentResolverCompat.java:125)
                                                 at android.support.v4.content.CursorLoader.loadInBackground(CursorLoader.java:59)
                                                 at android.support.v4.content.CursorLoader.loadInBackground(CursorLoader.java:37)
                                                 at android.support.v4.content.AsyncTaskLoader.onLoadInBackground(AsyncTaskLoader.java:299)
                                                 at android.support.v4.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:57)
                                                 at android.support.v4.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:45)
                                                 at android.support.v4.content.ModernAsyncTask$2.call(ModernAsyncTask.java:138)
                                                 at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                                                 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                                                 at java.lang.Thread.run(Thread.java:841)

Does anyone have any idea what may be wrong .
Looking forward to your responses .

Best Regards

Body:
If you are using Navigation Drawer then you should override this method

@Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.your_view_id) {
            //start your activity here
           }
}

and if you set the click listener in your View then you should use

@Override
 public void onClick(View v) {
  switch (view.getId()){
   case R.id.your_view_id:
    Intent intent = new Intent(getActivity(), WorkOrderActivity.class);
    startActivity(intent);
    break;
 }
}


问:
Laravel post request not works
I have Form in Laravel and when i submit the form to redirect another page("action = panel") with inputs's value. but problem is that when i enter in another's link it displays error. what is wrong?

This is form

this is another page when submit form

this is error when i enter in link again

this is form code:

```<code><form action="{{route('adminPanel')}}" class="form" method="POST">
    <p>Name:</p>
    <input type="text" name="name"><br>
    <p>Password:</p>
    <input type="password" name="password"><br>
    <input type="submit" name="submit" value="Enter As Admin" class="submit">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>
</code>```

this is routes:

```<code>Route::get('/', [

    'uses' => 'AdminController@getAdminIndex',

    'as' => 'index.admin'
]);
Route::post('/panel', [
    'uses' => 'AdminController@getAdminPanel',
    'as' => 'adminPanel'

]);
</code>```

this is controller:

```<code>class AdminController extends Controller
{
    public function getAdminIndex(){
        return view('admin/index');
    }
    public function getAdminPanel(Request $request){
        return view('admin/admin', ['name' => $request->name]);
    }
}
</code>```

答: Try to use the following statement in form as {{ csrf_field() }}</p>

Title: Laravel post request not works

Body:
I have Form in Laravel and when i submit the form to redirect another page("action = panel") with inputs's value. but problem is that when i enter in another's link it displays error. what is wrong?

This is form

this is another page when submit form

this is error when i enter in link again

this is form code:

<form action="{{route('adminPanel')}}" class="form" method="POST">

Name:

    <input type="text" name="name">

Password:

    <input type="password" name="password">

    <input type="submit" name="submit" value="Enter As Admin" class="submit">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>

this is routes:

Route::get('/', [

    'uses' => 'AdminController@getAdminIndex',

    'as' => 'index.admin'
]);
Route::post('/panel', [
    'uses' => 'AdminController@getAdminPanel',
    'as' => 'adminPanel'

]);

this is controller:

class AdminController extends Controller
{
    public function getAdminIndex(){
        return view('admin/index');
    }
    public function getAdminPanel(Request $request){
        return view('admin/admin', ['name' => $request->name]);
    }
}


问:
can't import name 'Post'
i can't import a class Post in my django models,when i try to runserver, its returns importError:cannot import name "Post",i have been on this for some days now,please help me..thanks

this is my class models for Post

```<code>from .models import Post,  Comment

class Post(models.Model):
     objects = models.Manager()
     published = PublishedManager()

     def get_absolute_url(self):
         return reverse('blog:post_detail',args=[self.publish.year,self.publish.strftime('%m'), self.publish.strftime('%d'),self.slug])

    STATUS_CHOICES = (('draft', 'Draft'),('published', 'Published'),)
    title = models.CharField(max_length=250)
    slug = models.SlugField(max_length=250,
    unique_for_date='publish')
    author = models.ForeignKey(User,
    related_name='blog_posts')
    body = models.TextField()
    publish = models.DateTimeField(default=timezone.now)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    status = models.CharField(max_length=10,
    choices=STATUS_CHOICES,default='draft')
class Meta:
     ordering = ('-publish',)
     def __unicode__(self):
         return self.title
</code>```

And this also my class model for Comment

```<code>from .models import Post,  Comment

class Comment(models.Model):
    post = models.ForeignKey(Post, related_name='comments')
    name = models.CharField(max_length=80)
    email = models.EmailField()
    body = models.TextField()
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    active = models.BooleanField(default=True)
class Meta:
    ordering = ('created',)
    def __unicode__(self):
     return 'Comment by {} on {}'.format(self.name, self.post)
</code>```

答: Why are you trying to import the Post and Comment models into the same file where they are defined? There is no reason to do that; delete those import lines.</p>

Title: can't import name 'Post'

Body:
i can't import a class Post in my django models,when i try to runserver, its returns importError:cannot import name "Post",i have been on this for some days now,please help me..thanks

this is my class models for Post

from .models import Post,  Comment

class Post(models.Model):
     objects = models.Manager()
     published = PublishedManager()

     def get_absolute_url(self):
         return reverse('blog:post_detail',args=[self.publish.year,self.publish.strftime('%m'), self.publish.strftime('%d'),self.slug])

    STATUS_CHOICES = (('draft', 'Draft'),('published', 'Published'),)
    title = models.CharField(max_length=250)
    slug = models.SlugField(max_length=250,
    unique_for_date='publish')
    author = models.ForeignKey(User,
    related_name='blog_posts')
    body = models.TextField()
    publish = models.DateTimeField(default=timezone.now)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    status = models.CharField(max_length=10,
    choices=STATUS_CHOICES,default='draft')
class Meta:
     ordering = ('-publish',)
     def __unicode__(self):
         return self.title

And this also my class model for Comment

from .models import Post,  Comment

class Comment(models.Model):
    post = models.ForeignKey(Post, related_name='comments')
    name = models.CharField(max_length=80)
    email = models.EmailField()
    body = models.TextField()
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    active = models.BooleanField(default=True)
class Meta:
    ordering = ('created',)
    def __unicode__(self):
     return 'Comment by {} on {}'.format(self.name, self.post)


问:
Flink Monitoring: Capture statistics for more than 5 min
I am new to Flink community and I am trying to do a experimental study to capture performance of Flink for streaming data.
For this, I am trying to collect statistics of running jobs over a few hours. However, using Flink’s UI I can only see the statistics for the last 5 minutes.
I tried to hit the Rest API but that does not contain the data of statistics other than bytes read/written.

The metrics provided in the UI under Task Metrics are very helpful but do not scale beyond 5 min. Is there a way in which I can capture the entire history of metrics.

答:
You can configure a metrics reporter to record all the metrics that you are interested in over any period of time.

Flink 1.3 comes with reporters for JMX, Ganglia, Graphite, StatsD, and DataDog. The documentation describes to to configure a reporter.


问:
How to replace spring property placeholders in a simple java program
I am working with Java and spring boot apps. I have a property file which needs to be added as environmental variables for a docker image at run time. Some of the properties are filtered through the existing Environment when they are used via placeholders as below.

```<code>app.name=MyApp
app.description=${app.name} is a Spring Boot application
</code>```

I am writing a sample java file to read this property file and create a map object with some filtered properties. In this process how can I replace the placeholders with the actual property values?

I have tried looking for a key and replacing using getProperty method. But I would like to avoid looking up hard coded property key names in order to avoid maintenance difficulties.
Thanks in advance.

答:
Replace the named token with numbered token and use the MessageFormat class of Java SE.  It allows you to do exactly what you ask for.

Assuming props contains all the properties loaded from your file.

```<code>MessageFormat.format((String) props.get("app.description"),((String) props.get("app.name"));
</code>```

Here your property shall be :

app.description={0} is a Spring Boot application

Else you will need to write a custom

Body:
I am working with Java and spring boot apps. I have a property file which needs to be added as environmental variables for a docker image at run time. Some of the properties are filtered through the existing Environment when they are used via placeholders as below.

app.name=MyApp
app.description=${app.name} is a Spring Boot application

I am writing a sample java file to read this property file and create a map object with some filtered properties. In this process how can I replace the placeholders with the actual property values?

I have tried looking for a key and replacing using getProperty method. But I would like to avoid looking up hard coded property key names in order to avoid maintenance difficulties.
Thanks in advance.

Body:
Replace the named token with numbered token and use the MessageFormat class of Java SE.  It allows you to do exactly what you ask for.

Assuming props contains all the properties loaded from your file.

MessageFormat.format((String) props.get("app.description"),((String) props.get("app.name"));

Here your property shall be :

app.description={0} is a Spring Boot application

Else you will need to write a custom


问:
How to make a reusable view cells for UITableViewCell and UICollectionViewCell ? I've tried to sublassing UIView for the cell but it's not working
I want to reuse my UITableViewCell to my UICollectionViewCell.

Until now, I always use 2 xibs, 1 for UITableViewCell and 1 for UICollectionViewCell and I think it's kinda waste.

I've tried to subclassing UIView for the cell but it's not working.

答:
A way to do this is by using reusable views. Here is a Github project that can help: NibDesignable

You can also do this without using the project I mentioned, but it does make it easier. You then create a UIView with a View nib and put all your UI into this as well as any code for setting the UI components. Then you create your UITableViewCell and UICollectionViewCell and then just use the view that you created. You can also use prototype cells in a Storyboard for CollectionView or TableView if you prefer.


问:
c++ array problems with Zeshan
In this program, I am trying that when I write name DK, I see "Correct
        Password" answer. But I always see "Incorrect Password", whether I write
        DK or MK or any other name. Can someone please guide me? Please try to
        explain
        in easy words. I started learning c++ like a week ago. Thanks</p>

```<code>#include <iostream>
using namespace std;
int main ()
{
    using namespace std;
    char name [6];
    cout << " Enter your name: ";
    cin >> name;

    if (name == "DK")
    {
         cout << " Correct password";
    }
    else
    {
          cout << " Incorrect password.";
    }
    return 0;
}
</code>```

答:
char name[6] is an array of chars. Thus name returns the address of the first element of the array. name == "DK" compares the address of the first element with with the address of the string literal "DK". That's not what you want. You should either use std::string instead of char arrays or you can use std::strcmp from <cstring> to compare char arrays. I recommend std::strings because they're easier to handle. Examples with std::strings are posted by other users.

An example with cstrings:

```<code>#include <iostream>
#include <cstring>
using namespace std;

int main ()
{
    char name [6];
    cout << " Enter your name: ";
    cin >> name;

    if (strcmp(name, "DK") == 0)
    {
        cout << " Correct password";
    }
    else
    {
        cout << " Incorrect password.";
    }
    return 0;
}
</code>```

Title: c++ array problems with Zeshan

Body:
In this program, I am trying that when I write name DK, I see "Correct
        Password" answer. But I always see "Incorrect Password", whether I write
        DK or MK or any other name. Can someone please guide me? Please try to
        explain
        in easy words. I started learning c++ like a week ago. Thanks

#include <iostream>
using namespace std;
int main ()
{
    using namespace std;
    char name [6];
    cout << " Enter your name: ";
    cin >> name;

    if (name == "DK")
    {
         cout << " Correct password";
    }
    else
    {
          cout << " Incorrect password.";
    }
    return 0;
}

Body:
char name[6] is an array of chars. Thus name returns the address of the first element of the array. name == "DK" compares the address of the first element with with the address of the string literal "DK". That's not what you want. You should either use std::string instead of char arrays or you can use std::strcmp from <cstring> to compare char arrays. I recommend std::strings because they're easier to handle. Examples with std::strings are posted by other users.

An example with cstrings:

#include <iostream>
#include <cstring>
using namespace std;

int main ()
{
    char name [6];
    cout << " Enter your name: ";
    cin >> name;

    if (strcmp(name, "DK") == 0)
    {
        cout << " Correct password";
    }
    else
    {
        cout << " Incorrect password.";
    }
    return 0;
}


问:
Why a catch block cant be of type Object?
I am new to JAVA i am preparing for my OCP JP certification.

I have this doubt regarding exception handling

```<code>try{
        assert(false):"HI";
    }
catch(Throwable e){}
</code>```

I know assert should not be handled but i am using this just for example. From what i know
Object->Throwable ->Exception and Error

If i have Throwable or Exception or Error in the catch block it works but when i have object which is super class of all, eclipse shows me a compile time error.

Any reason why i cant have Object in catch block?

答:
Everyone is saying that only throwable and its child class come into the catch block parenthesis which is right .
Now ,your doubt is :- why object cant be there why is it designed that way ?
i am breaking your question into 2 parts :-
1) why is it designed in that way ?
Answer :-because , we can only throw throwable class and its child class . So , it is designed to catch only these type of object only .
2) why we cannot use Object class reference at the place of throwable or Exception Or Error ?

Answer :- It is very simple brother . throwable class is child class of Object class .ok . Now , we know that a Parent class can hold the reference of its child class but a child class can not hold the reference of its Parent class . Object class is parent class and throwable is child class and Catch block only accept throwable type . so , you can write throwable or Exception Or Error in catch block because throwable class is able to hold the reference of own and its subclasses . but throwable class can not hold the reference of its own Parent class i.e Object class . child class can not hold the reference of Parent class . I think this is the reason due to which we can not write Object type reference in catch block .

Body:
I am new to JAVA i am preparing for my OCP JP certification.

I have this doubt regarding exception handling

try{
        assert(false):"HI";
    }
catch(Throwable e){}

I know assert should not be handled but i am using this just for example. From what i know
Object->Throwable ->Exception and Error

If i have Throwable or Exception or Error in the catch block it works but when i have object which is super class of all, eclipse shows me a compile time error.

Any reason why i cant have Object in catch block?


问:
I want to export data from a BLE112 dongle on BLE GUI to a csv or other similar type file
I have a device connected to my Bluegiga BLE112 dongle that sends temperature measurements every second. I am using BLE GUI to connect to and receive the data. I would like to store all the measurements in a csv file so I can import it into another program and analyze it. I have already enabled indications, so the data shows up and updates in the 'raw' column as shown:

but I cannot figure out how to store or export that data.

答:
Unless BLE GUI has changed significantly (I haven't used it in about 1-2 years), you can't do anything like this.

You'd need to write your own app or laptop/desktop communication and parser/save.

HOWEVER! One option you could use that I used to do is try out my BLE Log parser:
http://www.sureshjoshi.com/development/summer-of-bluegiga-code/
http://www.sureshjoshi.com/development/blegui-log-parsing-and-filtering/

I wrote a little tool a couple years ago which would parse data coming from the log, and place it all in one place, so I could copy and use that elsewhere (I was using it for tracking advertising data on multiple devices).

NOTE: I haven't touched that code since that blog was written - no idea if it'll work.


问:
How do you split a multilinestring into x lines of equal length in R
If you have a multilinestring:

```<code>multiline <- MULTILINESTRING ((12.573769564824442 55.67932019039465, 12.573664593749626 55.67929917900955, 12.572916898811318 55.679149506755245, 12.5722100725459 55.679011254788364, 12.572044628054563 55.678978898110536))
</code>```

Is there a smart way to, split that into X lines of equal length?

```<code>lines_of_equal_length <- cool_function(multiline)
</code>```

Or do you have to code such a function all the way from zero, e.g. by calculating the length of the line, and then dividing the length by X, and then running along the line and cleaving it ever y meters?

答:
I found a nice blog post that goes over it in detail, Segmentation of spatial lines. Basically you convert your multilinestring into spatial lines, and then in the blog a lot of nice functions are described that do the magic.

Converting to spatial lines:

```<code>library(rgeos)
spatialLines <- readWKT(multiline)
</code>```

Function 1: Creates a line segment

```<code>CreateSegment <- function(coords, from, to) {
    distance <- 0
    coordsOut <- c()
    biggerThanFrom <- F
    for (i in 1:(nrow(coords) - 1)) {
        d <- sqrt((coords[i, 1] - coords[i + 1, 1])^2 + (coords[i, 2] - coords[i +
            1, 2])^2)
        distance <- distance + d
        if (!biggerThanFrom && (distance > from)) {
            w <- 1 - (distance - from)/d
            x <- coords[i, 1] + w * (coords[i + 1, 1] - coords[i, 1])
            y <- coords[i, 2] + w * (coords[i + 1, 2] - coords[i, 2])
            coordsOut <- rbind(coordsOut, c(x, y))
            biggerThanFrom <- T
        }
        if (biggerThanFrom) {
            if (distance > to) {
                w <- 1 - (distance - to)/d
                x <- coords[i, 1] + w * (coords[i + 1, 1] - coords[i, 1])
                y <- coords[i, 2] + w * (coords[i + 1, 2] - coords[i, 2])
                coordsOut <- rbind(coordsOut, c(x, y))
                break
            }
            coordsOut <- rbind(coordsOut, c(coords[i + 1, 1], coords[i + 1,
                2]))
        }
    }
    return(coordsOut)
}
</code>```

Function 2: Creates line segments

```<code>CreateSegments <- function(coords, length = 0, n.parts = 0) {
    stopifnot((length > 0 || n.parts > 0))
    # calculate total length line
    total_length <- 0
    for (i in 1:(nrow(coords) - 1)) {
        d <- sqrt((coords[i, 1] - coords[i + 1, 1])^2 + (coords[i, 2] - coords[i +
            1, 2])^2)
        total_length <- total_length + d
    }

    # calculate stationing of segments
    if (length > 0) {
        stationing <- c(seq(from = 0, to = total_length, by = length), total_length)
    } else {
        stationing <- c(seq(from = 0, to = total_length, length.out = n.parts),
            total_length)
    }

    # calculate segments and store the in list
    newlines <- list()
    for (i in 1:(length(stationing) - 1)) {
        newlines[[i]] <- CreateSegment(coords, stationing[i], stationing[i +
            1])
    }
    return(newlines)
}
</code>```

Function 3: Merges to last line segments

```<code>MergeLast <- function(lst) {
    l <- length(lst)
    lst[[l - 1]] <- rbind(lst[[l - 1]], lst[[l]])
    lst <- lst[1:(l - 1)]
    return(lst)
}
</code>```

Function 4: Puts it all toghether and can cut a spatial lines into either n-1 lines or into lines of certain lengths

```<code>SegmentSpatialLines <- function(sl, length = 0, n.parts = 0, merge.last = FALSE) {
    stopifnot((length > 0 || n.parts > 0))
    id <- 0
    newlines <- list()
    sl <- as(sl, "SpatialLines")
    for (lines in sl@lines) {
        for (line in lines@Lines) {
            crds <- line@coords
            # create segments
            segments <- CreateSegments(coords = crds, length, n.parts)
            if (merge.last && length(segments) > 1) {
                # in case there is only one segment, merging would result into error
                segments <- MergeLast(segments)
            }
            # transform segments to lineslist for SpatialLines object
            for (segment in segments) {
                newlines <- c(newlines, Lines(list(Line(unlist(segment))), ID = as.character(id)))
                id <- id + 1
            }
        }
    }
    return(SpatialLines(newlines))
}
</code>```

Again, all credit goes to the creator of the functions: Creator

Body:
If you have a multilinestring:

multiline <- MULTILINESTRING ((12.573769564824442 55.67932019039465, 12.573664593749626 55.67929917900955, 12.572916898811318 55.679149506755245, 12.5722100725459 55.679011254788364, 12.572044628054563 55.678978898110536))

Is there a smart way to, split that into X lines of equal length?

lines_of_equal_length <- cool_function(multiline)

Or do you have to code such a function all the way from zero, e.g. by calculating the length of the line, and then dividing the length by X, and then running along the line and cleaving it ever y meters?

Body:
I found a nice blog post that goes over it in detail, Segmentation of spatial lines. Basically you convert your multilinestring into spatial lines, and then in the blog a lot of nice functions are described that do the magic.

Converting to spatial lines:

library(rgeos)
spatialLines <- readWKT(multiline)

Function 1: Creates a line segment

CreateSegment <- function(coords, from, to) {
    distance <- 0
    coordsOut <- c()
    biggerThanFrom <- F
    for (i in 1:(nrow(coords) - 1)) {
        d <- sqrt((coords[i, 1] - coords[i + 1, 1])^2 + (coords[i, 2] - coords[i +
            1, 2])^2)
        distance <- distance + d
        if (!biggerThanFrom && (distance > from)) {
            w <- 1 - (distance - from)/d
            x <- coords[i, 1] + w * (coords[i + 1, 1] - coords[i, 1])
            y <- coords[i, 2] + w * (coords[i + 1, 2] - coords[i, 2])
            coordsOut <- rbind(coordsOut, c(x, y))
            biggerThanFrom <- T
        }
        if (biggerThanFrom) {
            if (distance > to) {
                w <- 1 - (distance - to)/d
                x <- coords[i, 1] + w * (coords[i + 1, 1] - coords[i, 1])
                y <- coords[i, 2] + w * (coords[i + 1, 2] - coords[i, 2])
                coordsOut <- rbind(coordsOut, c(x, y))
                break
            }
            coordsOut <- rbind(coordsOut, c(coords[i + 1, 1], coords[i + 1,
                2]))
        }
    }
    return(coordsOut)
}

Function 2: Creates line segments

CreateSegments <- function(coords, length = 0, n.parts = 0) {
    stopifnot((length > 0 || n.parts > 0))
    # calculate total length line
    total_length <- 0
    for (i in 1:(nrow(coords) - 1)) {
        d <- sqrt((coords[i, 1] - coords[i + 1, 1])^2 + (coords[i, 2] - coords[i +
            1, 2])^2)
        total_length <- total_length + d
    }

    # calculate stationing of segments
    if (length > 0) {
        stationing <- c(seq(from = 0, to = total_length, by = length), total_length)
    } else {
        stationing <- c(seq(from = 0, to = total_length, length.out = n.parts),
            total_length)
    }

    # calculate segments and store the in list
    newlines <- list()
    for (i in 1:(length(stationing) - 1)) {
        newlines[[i]] <- CreateSegment(coords, stationing[i], stationing[i +
            1])
    }
    return(newlines)
}

Function 3: Merges to last line segments

MergeLast <- function(lst) {
    l <- length(lst)
    lst[[l - 1]] <- rbind(lst[[l - 1]], lst[[l]])
    lst <- lst[1:(l - 1)]
    return(lst)
}

Function 4: Puts it all toghether and can cut a spatial lines into either n-1 lines or into lines of certain lengths

SegmentSpatialLines <- function(sl, length = 0, n.parts = 0, merge.last = FALSE) {
    stopifnot((length > 0 || n.parts > 0))
    id <- 0
    newlines <- list()
    sl <- as(sl, "SpatialLines")
    for (lines in sl@lines) {
        for (line in lines@Lines) {
            crds <- line@coords
            # create segments
            segments <- CreateSegments(coords = crds, length, n.parts)
            if (merge.last && length(segments) > 1) {
                # in case there is only one segment, merging would result into error
                segments <- MergeLast(segments)
            }
            # transform segments to lineslist for SpatialLines object
            for (segment in segments) {
                newlines <- c(newlines, Lines(list(Line(unlist(segment))), ID = as.character(id)))
                id <- id + 1
            }
        }
    }
    return(SpatialLines(newlines))
}

Again, all credit goes to the creator of the functions: Creator


问:
Xcode links a Third Party framework in my Framework and includes it's symbols
I am building a Framework and the code there uses a Third party framework. When I compile my Framework it seems to contain all the symbols from the Third party framework. If I don't add the third party framework to Linked Frameworks and Libraries I get compiler errors about undefined symbols.

On the other hand, when I add the third party framework to Linked Frameworks and Libraries it compiles fine. However, in a sample app when I link both my framework and the third party one I get the following runtime warnings: Class is implemented in both, One of the two will be used. Which one is undefined.

My question is how do I build my framework with a dependency on another framework without actually linking it? I want to do all the linking on the app level.

答:
I wasn’t able to achieve this behavior building dynamic frameworks. However, as I built my framework as static, the framework compiled fine and did not include third party framework symbols. All the linking with the third party framework has to be done on the app level.

I have seen many questions on stack overflow like this with no definite answer. I hope my finding would help.


问:
MongoDB .find in many collections at once
Can I do find in many the same collections at once?

I have several identical collections that are collected by day. I need to do a search in a few days.

Example:

collectionname_20171110
collectionname_20171111
collectionname_20171112
collectionname_20171112
etc

Is there any method?

$lookup it's not what I need, I do not "join" data from one collection with other.

Sorry for my English.

答: That is not possible. The find API works on a collection. You can try to handle on application side to throw db.collection.find() in parallel and merge the result.


问:
Where is defined path to database.yml in rails?
Where is defined path to database.yml in rails?

I am about worked project. In development it equal to config in same folder where is app folder. In production deployed by capistrano it equal ~/sites/shared/config.

Is it convention? Where it is documented?

答:
It is hardcoded to be <app-root>/config/database.yml. In production environment where you store it in a shared folder, you must create a symlink that points to that shared file.

```<code> <app-root>/config/database.yml -> ~/sites/shared/config/database.yml
</code>```

Or you could symlink the whole config directory, if you wanted.

Body:
It is hardcoded to be <app-root>/config/database.yml. In production environment where you store it in a shared folder, you must create a symlink that points to that shared file.

 <app-root>/config/database.yml -> ~/sites/shared/config/database.yml

Or you could symlink the whole config directory, if you wanted.


问:
docker api client/server version mismatch?
docker version showing correct api version for both client and server when i run inside python it is throwing error as below.

# docker version
Client:
 Version:         1.12.6
 API version:     1.24
 Package version: docker-1.12.6-48.git0fdc778.el7.x86_64
 Go version:      go1.8.3
 Git commit:      0fdc778/1.12.6
 Built:           Thu Jul 20 00:06:39 2017
 OS/Arch:         linux/amd64

Server:
 Version:         1.12.6
 API version:     1.24
 Package version: docker-1.12.6-48.git0fdc778.el7.x86_64
 Go version:      go1.8.3
 Git commit:      0fdc778/1.12.6
 Built:           Thu Jul 20 00:06:39 2017
 OS/Arch:         linux/amd64
# ```
</div>
</div>
</p>

<p>But when i run with python it is throwing error as below.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code> # python
Python 2.7.5 (default, Aug 29 2016, 10:12:21)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import docker
>>> client = docker.APIClient(base_url='unix://var/run/docker.sock')
>>> print client.version()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/site-packages/docker/api/daemon.py", line 177, in version
    return self._result(self._get(url), json=True)
  File "/usr/lib/python2.7/site-packages/docker/api/client.py", line 226, in _result
    self._raise_for_status(response)
  File "/usr/lib/python2.7/site-packages/docker/api/client.py", line 222, in _raise_for_status
    raise create_api_error_from_http_exception(e)
  File "/usr/lib/python2.7/site-packages/docker/errors.py", line 31, in create_api_error_from_http_exception
    raise cls(e, response=response, explanation=explanation)
docker.errors.APIError: 400 Client Error: Bad Request ("client is newer than server (client API version: 1.30, server API version: 1.24)")
>>></code>```

答:
It says API of your docker python package doesn’t match the docker engine server API. You should install a docker python package compatible with 1.24 or update your docker engine API to 1.30.

Additionally, you can try assigning new value to your docker client as follows:

client = docker.DockerClient(base_url='unix://var/run/docker.sock', version="1.24")

OR

client = docker.APIClient(base_url='unix://var/run/docker.sock', version="1.24")

Body:
docker version showing correct api version for both client and server when i run inside python it is throwing error as below.

# docker version
Client:
 Version:         1.12.6
 API version:     1.24
 Package version: docker-1.12.6-48.git0fdc778.el7.x86_64
 Go version:      go1.8.3
 Git commit:      0fdc778/1.12.6
 Built:           Thu Jul 20 00:06:39 2017
 OS/Arch:         linux/amd64

Server:
 Version:         1.12.6
 API version:     1.24
 Package version: docker-1.12.6-48.git0fdc778.el7.x86_64
 Go version:      go1.8.3
 Git commit:      0fdc778/1.12.6
 Built:           Thu Jul 20 00:06:39 2017
 OS/Arch:         linux/amd64
#

But when i run with python it is throwing error as below.

 # python
Python 2.7.5 (default, Aug 29 2016, 10:12:21)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import docker
>>> client = docker.APIClient(base_url='unix://var/run/docker.sock')
>>> print client.version()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/site-packages/docker/api/daemon.py", line 177, in version
    return self._result(self._get(url), json=True)
  File "/usr/lib/python2.7/site-packages/docker/api/client.py", line 226, in _result
    self._raise_for_status(response)
  File "/usr/lib/python2.7/site-packages/docker/api/client.py", line 222, in _raise_for_status
    raise create_api_error_from_http_exception(e)
  File "/usr/lib/python2.7/site-packages/docker/errors.py", line 31, in create_api_error_from_http_exception
    raise cls(e, response=response, explanation=explanation)
docker.errors.APIError: 400 Client Error: Bad Request ("client is newer than server (client API version: 1.30, server API version: 1.24)")
>>>


问:
cap "no such file or directory /usr/bin/env npm" although it is really here
I'm having this weird cap error when running the task returns :

```<code>INFO[f0017d58] Running /usr/bin/env npm install --silent on default
DEBUG[f0017d58] Command: cd /var/www/myapp/releases/20141208112620 && /usr/bin/env npm       install --silent
DEBUG[f0017d58]     /usr/bin/env:
DEBUG[f0017d58]     npm
DEBUG[f0017d58]     : No such file or directory
DEBUG[f0017d58]
cap aborted!
</code>```

Where this works just fine (with the same user) when i'm logged in through ssh :

```<code>vagrant@localhost:~$ cd /var/www/myapp/releases/20141208112620 && /usr/bin/env npm    install --silent
grunt-contrib-uglify@0.3.3 node_modules/grunt-contrib-uglify
├── grunt-lib-contrib@0.6.1 (zlib-browserify@0.0.1)
├── chalk@0.4.0 (has-color@0.1.7, ansi-styles@1.0.0, strip-ansi@0.1.1)
└── uglify-js@2.4.15 (uglify-to-browserify@1.0.2, async@0.2.10, optimist@0.3.7, source-map@0.1.34)
</code>```

So there's something weird that i can't identify.

Thanks for your help.

Edit: so yeah, I found out the origin of the actual issue.
When I log-in (via vagrant ssh) I get a different env than the one I get with cap.
Basically I can call npm from CLI when logged in and this will find it in /usr/local/node/node-default/bin/npm, while cap can't, since none of this is in the path it's using (or something like that)

答:
Below fixe took care of the problem

deploy.rb

```<code>set :nvm_node, 'v8.9.1'

set :nvm_map_bins, %w{node npm}
</code>```

Gemfile

```<code>gem 'capistrano-nvm'
</code>```

Capfile

```<code>require 'capistrano/nvm'
</code>```

Body:
I'm having this weird cap error when running the task returns :

INFO[f0017d58] Running /usr/bin/env npm install --silent on default
DEBUG[f0017d58] Command: cd /var/www/myapp/releases/20141208112620 && /usr/bin/env npm       install --silent
DEBUG[f0017d58]     /usr/bin/env:
DEBUG[f0017d58]     npm
DEBUG[f0017d58]     : No such file or directory
DEBUG[f0017d58]
cap aborted!

Where this works just fine (with the same user) when i'm logged in through ssh :

vagrant@localhost:~$ cd /var/www/myapp/releases/20141208112620 && /usr/bin/env npm    install --silent
grunt-contrib-uglify@0.3.3 node_modules/grunt-contrib-uglify
├── grunt-lib-contrib@0.6.1 (zlib-browserify@0.0.1)
├── chalk@0.4.0 (has-color@0.1.7, ansi-styles@1.0.0, strip-ansi@0.1.1)
└── uglify-js@2.4.15 (uglify-to-browserify@1.0.2, async@0.2.10, optimist@0.3.7, source-map@0.1.34)

So there's something weird that i can't identify.

Thanks for your help.

Edit: so yeah, I found out the origin of the actual issue.
When I log-in (via vagrant ssh) I get a different env than the one I get with cap.
Basically I can call npm from CLI when logged in and this will find it in /usr/local/node/node-default/bin/npm, while cap can't, since none of this is in the path it's using (or something like that)

Body:
Below fixe took care of the problem

deploy.rb

set :nvm_node, 'v8.9.1'

set :nvm_map_bins, %w{node npm}

Gemfile

gem 'capistrano-nvm'

Capfile

require 'capistrano/nvm'