问:
How to load packages installed by `bundle` in webpack?
In a Ruby on Rails application, how can we require or import a package which was not installed via npm or yarn, but via bundle?

I tried:

```<code>//= require package-name
</code>```

But that doesn't seem to work with webpacker.

require("package-name") doesn't work either (because it is not found in node_modules).

答:
I have no webpack experience and no solution for your problem.

what about this

https://webpack.js.org/loaders/bundle-loader/

as I read in the documentation paths chapter

Paths

By default, Webpacker ships with simple conventions for where the JavaScript app files and compiled webpack bundles will go in your Rails app, but all these options are configurable from config/webpacker.yml file.

The configuration for what webpack is supposed to compile by default rests on the convention that every file in app/javascript/packs/*(default) or whatever path you set for source_entry_path in the webpacker.yml configuration is turned into their own output files (or entry points, as webpack calls it). Therefore you don't want to put anything inside packs directory that you do not want to be an entry file. As a rule of thumb, put all files you want to link in your views inside "packs" directory and keep everything else under app/javascript.

Suppose you want to change the source directory from app/javascript to frontend and output to assets/packs. This is how you would do it:

```<code># config/webpacker.yml
source_path: frontend
source_entry_path: packs
</code>```

public_output_path: assets/packs # outputs to => public/assets/packs
  Similarly you can also control and configure webpack-dev-server settings from config/webpacker.yml file:

```<code># config/webpacker.yml
development:
  dev_server:
    host: localhost
    port: 3035
</code>```

If you have hmr turned to true, then the stylesheet_pack_tag generates no output, as you will want to configure your styles to be inlined in your JavaScript for hot reloading. During production and testing, the stylesheet_pack_tag will create the appropriate HTML tags.

The asset-pipeline loads the files from the path defined with Rails.application.config.assets.paths

This is the output from my rails console

```<code>["/home/fabrizio/Documents/Sublime/Rails/surfcheck/app/assets/config",
 "/home/fabrizio/Documents/Sublime/Rails/surfcheck/app/assets/images",
 "/home/fabrizio/Documents/Sublime/Rails/surfcheck/app/assets/javascripts",
 "/home/fabrizio/Documents/Sublime/Rails/surfcheck/app/assets/stylesheets",
 "/home/fabrizio/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/font-awesome-rails-4.7.0.2/app/assets/fonts",
 "/home/fabrizio/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/font-awesome-rails-4.7.0.2/app/assets/stylesheets",
 "/home/fabrizio/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/jquery-rails-4.3.1/vendor/assets/javascripts",
 "/home/fabrizio/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/coffee-rails-4.2.2/lib/assets/javascripts",
 "/home/fabrizio/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/actioncable-5.1.4/lib/assets/compiled",
 "/home/fabrizio/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/actionview-5.1.4/lib/assets/compiled",
 "/home/fabrizio/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/turbolinks-source-5.0.3/lib/assets/javascripts",
 #<Pathname:/home/fabrizio/Documents/Sublime/Rails/surfcheck/node_modules>,
 #<Pathname:/home/fabrizio/Documents/Sublime/Rails/surfcheck/vendor>,
 "/home/fabrizio/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/bootstrap-sass-3.3.7/assets/stylesheets",
 "/home/fabrizio/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/bootstrap-sass-3.3.7/assets/javascripts",
 "/home/fabrizio/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/bootstrap-sass-3.3.7/assets/fonts",
 "/home/fabrizio/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/bootstrap-sass-3.3.7/assets/images"]
</code>```

When you do a require in your application.js or application.scss, sprockets will use the ruby require statement to search that file in the predefined paths.

In case of a GEM, it will find it in the .rbenv/version/yourversion folder.

My approach to solve this problem would be to include those files from the gem that you need for you front end app in the correct folder, so just visit the repository from the GEM and copy paste those file in the correct location.

I know this is not a solution to your problem, but I just wanted to help you out.

Bye
Fabrizio

Body:
In a Ruby on Rails application, how can we require or import a package which was not installed via npm or yarn, but via bundle?

I tried:

//= require package-name

But that doesn't seem to work with webpacker.

require("package-name") doesn't work either (because it is not found in node_modules).

Body:
I have no webpack experience and no solution for your problem.

what about this

https://webpack.js.org/loaders/bundle-loader/

as I read in the documentation paths chapter

Paths

By default, Webpacker ships with simple conventions for where the JavaScript app files and compiled webpack bundles will go in your Rails app, but all these options are configurable from config/webpacker.yml file.

The configuration for what webpack is supposed to compile by default rests on the convention that every file in app/javascript/packs/*(default) or whatever path you set for source_entry_path in the webpacker.yml configuration is turned into their own output files (or entry points, as webpack calls it). Therefore you don't want to put anything inside packs directory that you do not want to be an entry file. As a rule of thumb, put all files you want to link in your views inside "packs" directory and keep everything else under app/javascript.

Suppose you want to change the source directory from app/javascript to frontend and output to assets/packs. This is how you would do it:

# config/webpacker.yml
source_path: frontend
source_entry_path: packs

public_output_path: assets/packs # outputs to => public/assets/packs
  Similarly you can also control and configure webpack-dev-server settings from config/webpacker.yml file:

# config/webpacker.yml
development:
  dev_server:
    host: localhost
    port: 3035

If you have hmr turned to true, then the stylesheet_pack_tag generates no output, as you will want to configure your styles to be inlined in your JavaScript for hot reloading. During production and testing, the stylesheet_pack_tag will create the appropriate HTML tags.

The asset-pipeline loads the files from the path defined with Rails.application.config.assets.paths

This is the output from my rails console

["/home/fabrizio/Documents/Sublime/Rails/surfcheck/app/assets/config",
 "/home/fabrizio/Documents/Sublime/Rails/surfcheck/app/assets/images",
 "/home/fabrizio/Documents/Sublime/Rails/surfcheck/app/assets/javascripts",
 "/home/fabrizio/Documents/Sublime/Rails/surfcheck/app/assets/stylesheets",
 "/home/fabrizio/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/font-awesome-rails-4.7.0.2/app/assets/fonts",
 "/home/fabrizio/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/font-awesome-rails-4.7.0.2/app/assets/stylesheets",
 "/home/fabrizio/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/jquery-rails-4.3.1/vendor/assets/javascripts",
 "/home/fabrizio/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/coffee-rails-4.2.2/lib/assets/javascripts",
 "/home/fabrizio/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/actioncable-5.1.4/lib/assets/compiled",
 "/home/fabrizio/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/actionview-5.1.4/lib/assets/compiled",
 "/home/fabrizio/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/turbolinks-source-5.0.3/lib/assets/javascripts",
 #<Pathname:/home/fabrizio/Documents/Sublime/Rails/surfcheck/node_modules>,
 #<Pathname:/home/fabrizio/Documents/Sublime/Rails/surfcheck/vendor>,
 "/home/fabrizio/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/bootstrap-sass-3.3.7/assets/stylesheets",
 "/home/fabrizio/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/bootstrap-sass-3.3.7/assets/javascripts",
 "/home/fabrizio/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/bootstrap-sass-3.3.7/assets/fonts",
 "/home/fabrizio/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/bootstrap-sass-3.3.7/assets/images"]

When you do a require in your application.js or application.scss, sprockets will use the ruby require statement to search that file in the predefined paths.

In case of a GEM, it will find it in the .rbenv/version/yourversion folder.

My approach to solve this problem would be to include those files from the gem that you need for you front end app in the correct folder, so just visit the repository from the GEM and copy paste those file in the correct location.

I know this is not a solution to your problem, but I just wanted to help you out.

Bye
Fabrizio


来源: stackexchange

问:
How to hide view behind the view
I'm placing a textview over a line as textview have light color background the line behind the textview is visible, I want to hide that portion of line thats behind textview, how can i do that

Thanks in advance!

Like this

答:
You can either try it like following code

shape_line.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="line"
    >
    <solid android:color="#FFFFFF">
    </solid>
    <stroke
        android:width="1dp"
        android:color="#000000" />
    <size android:height="2dp" />
</shape>
</code>```

Add this to your drawable folder.
and in your layout add following layout

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="120dp"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:background="@drawable/shape_bg_line"
    tools:ignore="MissingConstraints">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:background="#FFFFFF"
        android:padding="5dp"
        android:text="Hello" />

</RelativeLayout>
</code>```

Here is the output :

ContentLicense: CC BY-SA 3.0

Title: How to hide view behind the view

Body:
You can either try it like following code

shape_line.xml

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="line"
    >
    <solid android:color="#FFFFFF">
    </solid>
    <stroke
        android:width="1dp"
        android:color="#000000" />
    <size android:height="2dp" />
</shape>

Add this to your drawable folder.
and in your layout add following layout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="120dp"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:background="@drawable/shape_bg_line"
    tools:ignore="MissingConstraints">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:background="#FFFFFF"
        android:padding="5dp"
        android:text="Hello" />

</RelativeLayout>

Here is the output :


问:
Printing from SAP via VBA
I have a script I put together that completes bulk shipments in SAP via VBA. At the end of each completed shipment, I want SAP to print the completed page as confirmation.

```<code>Sub STOMacro()

Dim App, Connection, session As Object
Set SapGuiAuto = GetObject("SAPGUI")
Set App = SapGuiAuto.GetScriptingEngine
Set Connection = App.Children(0)
Set session = Connection.Children(0)

If session Is Nothing Then
  Set session = Connection.Children(Int(ses))
End If

If MsgBox("Are you sure you want to acknowledge these STOs?", vbYesNo, "Complete STOs?") = vbNo Then
             Exit Sub
End If

OrderCounter = Range("A:A").Find("*", Range("A64999"), xlValues, xlWhole, xlByRows, xlPrevious).Row

For i = 1 To OrderCounter

Application.DisplayAlerts = False

STO = Range("A" & i).Value

Application.StatusBar = "Acknowledging STO " & i & " out of " & OrderCounter

session.findById("wnd[0]").maximize
session.findById("wnd[0]/tbar[0]/okcd").Text = "/nzvmonitor"
session.findById("wnd[0]").sendVKey 0
session.findById("wnd[0]/tbar[1]/btn[17]").press
session.findById("wnd[1]/usr/txtV-LOW").Text = "STOPrint"
session.findById("wnd[1]/usr/txtENAME-LOW").Text = ""
session.findById("wnd[1]/usr/txtV-LOW").CaretPosition = 14
session.findById("wnd[1]/tbar[0]/btn[8]").press
session.findById("wnd[0]/usr/ctxtS_DLVRY-LOW").Text = "" & STO & ""
session.findById("wnd[0]/usr/ctxtS_DLVRY-LOW").SetFocus
session.findById("wnd[0]/usr/ctxtS_DLVRY-LOW").CaretPosition = 10
session.findById("wnd[0]").sendVKey 8
session.findById("wnd[0]/usr/cntlZVR_OMONITOR_C1/shellcont/shell").currentCellColumn = ""
session.findById("wnd[0]/usr/cntlZVR_OMONITOR_C1/shellcont/shell").selectedRows = "0"
session.findById("wnd[0]/usr/cntlZVR_OMONITOR_C1/shellcont/shell").pressToolbarButton "RCPT"
session.findById("wnd[0]").sendVKey 3
session.findById("wnd[1]/usr/btnBUTTON_1").press
session.findById("wnd[1]").sendVKey 0
session.findById("wnd[0]/usr/cntlZVR_OMONITOR_C1/shellcont/shell").pressToolbarButton "&PRINT_BACK"
session.findById("wnd[1]").sendVKey 0
session.findById("wnd[1]").sendVKey 13
'This is where the print dialogue pops up but I can't interact with it

Next i
MsgBox ("All STOs acknowledged and printed.")
Application.StatusBar = ""

End Sub
</code>```

I can get SAP to open the print dialogue box but the user still has to manually click "ok" in order to actually print the pages. This is a minor inconvenience but I was wondering if it could.
Print dialogue

If anything, I'm fine with just using SendKeys to make the print dialogue get {Enter} sent to it but I don't know how to make SAP hook onto the box to send that command.

答:
For many years we have been using the following program code in a similar place:

```<code>. . .
dim Wshell as Object

set Wshell = CreateObject("WScript.Shell")

on error resume next
Do
 bWindowFound = Wshell.AppActivate("Print")
 Application.Wait (Now + TimeValue("0:00:01"))
Loop Until bWindowFound

bWindowFound = Wshell.AppActivate("Print")
if (bWindowFound) Then
Wshell.appActivate "Print"
 Application.Wait (Now + TimeValue("0:00:01"))
 Wshell.sendkeys "{ENTER}"
end if

bWindowFound = Wshell.AppActivate("Print")
if (bWindowFound) Then
 Wshell.appActivate "Print"
 Application.Wait (Now + TimeValue("0:00:01"))
 Wshell.sendkeys "{TAB}{ENTER}"
end if

bWindowFound = Wshell.AppActivate("Print")
if (bWindowFound) Then
 Wshell.appActivate "Print"
 Application.Wait (Now + TimeValue("0:00:01"))
 Wshell.sendkeys "{TAB}{TAB}{ENTER}"
end if
'It could be superfluous under certain circumstances.
session.findById("wnd[1]").Close

Application.Wait (Now + TimeValue("0:00:01"))

on error goto 0
. . .
</code>```

However, since you can not know where the cursor is currently located, all possibilities are carried out. But if you know it, you could leave something out.

Regards,
ScriptMan

Title: Printing from SAP via VBA

Body:
I have a script I put together that completes bulk shipments in SAP via VBA. At the end of each completed shipment, I want SAP to print the completed page as confirmation.

Sub STOMacro()

Dim App, Connection, session As Object
Set SapGuiAuto = GetObject("SAPGUI")
Set App = SapGuiAuto.GetScriptingEngine
Set Connection = App.Children(0)
Set session = Connection.Children(0)

If session Is Nothing Then
  Set session = Connection.Children(Int(ses))
End If

If MsgBox("Are you sure you want to acknowledge these STOs?", vbYesNo, "Complete STOs?") = vbNo Then
             Exit Sub
End If

OrderCounter = Range("A:A").Find("*", Range("A64999"), xlValues, xlWhole, xlByRows, xlPrevious).Row

For i = 1 To OrderCounter

Application.DisplayAlerts = False

STO = Range("A" & i).Value

Application.StatusBar = "Acknowledging STO " & i & " out of " & OrderCounter

session.findById("wnd[0]").maximize
session.findById("wnd[0]/tbar[0]/okcd").Text = "/nzvmonitor"
session.findById("wnd[0]").sendVKey 0
session.findById("wnd[0]/tbar[1]/btn[17]").press
session.findById("wnd[1]/usr/txtV-LOW").Text = "STOPrint"
session.findById("wnd[1]/usr/txtENAME-LOW").Text = ""
session.findById("wnd[1]/usr/txtV-LOW").CaretPosition = 14
session.findById("wnd[1]/tbar[0]/btn[8]").press
session.findById("wnd[0]/usr/ctxtS_DLVRY-LOW").Text = "" & STO & ""
session.findById("wnd[0]/usr/ctxtS_DLVRY-LOW").SetFocus
session.findById("wnd[0]/usr/ctxtS_DLVRY-LOW").CaretPosition = 10
session.findById("wnd[0]").sendVKey 8
session.findById("wnd[0]/usr/cntlZVR_OMONITOR_C1/shellcont/shell").currentCellColumn = ""
session.findById("wnd[0]/usr/cntlZVR_OMONITOR_C1/shellcont/shell").selectedRows = "0"
session.findById("wnd[0]/usr/cntlZVR_OMONITOR_C1/shellcont/shell").pressToolbarButton "RCPT"
session.findById("wnd[0]").sendVKey 3
session.findById("wnd[1]/usr/btnBUTTON_1").press
session.findById("wnd[1]").sendVKey 0
session.findById("wnd[0]/usr/cntlZVR_OMONITOR_C1/shellcont/shell").pressToolbarButton "&PRINT_BACK"
session.findById("wnd[1]").sendVKey 0
session.findById("wnd[1]").sendVKey 13
'This is where the print dialogue pops up but I can't interact with it

Next i
MsgBox ("All STOs acknowledged and printed.")
Application.StatusBar = ""

End Sub

I can get SAP to open the print dialogue box but the user still has to manually click "ok" in order to actually print the pages. This is a minor inconvenience but I was wondering if it could.
Print dialogue

If anything, I'm fine with just using SendKeys to make the print dialogue get {Enter} sent to it but I don't know how to make SAP hook onto the box to send that command.

Body:
For many years we have been using the following program code in a similar place:

. . .
dim Wshell as Object

set Wshell = CreateObject("WScript.Shell")

on error resume next
Do
 bWindowFound = Wshell.AppActivate("Print")
 Application.Wait (Now + TimeValue("0:00:01"))
Loop Until bWindowFound

bWindowFound = Wshell.AppActivate("Print")
if (bWindowFound) Then
Wshell.appActivate "Print"
 Application.Wait (Now + TimeValue("0:00:01"))
 Wshell.sendkeys "{ENTER}"
end if

bWindowFound = Wshell.AppActivate("Print")
if (bWindowFound) Then
 Wshell.appActivate "Print"
 Application.Wait (Now + TimeValue("0:00:01"))
 Wshell.sendkeys "{TAB}{ENTER}"
end if

bWindowFound = Wshell.AppActivate("Print")
if (bWindowFound) Then
 Wshell.appActivate "Print"
 Application.Wait (Now + TimeValue("0:00:01"))
 Wshell.sendkeys "{TAB}{TAB}{ENTER}"
end if
'It could be superfluous under certain circumstances.
session.findById("wnd[1]").Close

Application.Wait (Now + TimeValue("0:00:01"))

on error goto 0
. . .

However, since you can not know where the cursor is currently located, all possibilities are carried out. But if you know it, you could leave something out.

Regards,
ScriptMan


问:
Spring @RequestPart multipart/mixed Object errors
I am attempting to upload a file with additional parameters using RequestParts.  I have the file uploading correctly; however, when I try and add in the additional parameters I get an error in response.

My Controller:

```<code>@RequestMapping(value = "/v1/cases/{caseId}/file", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Success uploadFile(
        @RequestPart(value="file") MultipartFile file,
        @RequestPart(value="fileParameters") FileParameters fileParameters) throws FileNotFoundException, IOException {
</code>```

I have tried to POST to this 2 different ways with different errors:

1)

```<code>----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="file"; filename="myFile"
Content-Type:

----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="fileParameters"

{"filePassword":"testPassword", "configuration":{}, "target":null}
----WebKitFormBoundaryE19zNvXGzXaLvS5C
</code>```

this errors with:

```<code>The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method. See 'supportedMediaTypes' in 'additionalInfo' for a list of supported types
</code>```

2)

```<code>----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="file"; filename="myFile"
Content-Type:

----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="fileParamters[filePassword]"

testPassword
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="fileParamters[configuration]"

{}
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="fileParamters[target]"

null
----WebKitFormBoundaryE19zNvXGzXaLvS5C
</code>```

which returns the following error:

```<code>"rootExceptionClass": "org.springframework.web.multipart.support.MissingServletRequestPartException",
"rootExceptionMessage": "Required request part 'keyParameters' is not present."
</code>```

I'm assuming the first approach is the correct one; however, the application does support JSON, so I'm not sure what I am missing configuration wise.  Is there something I have to add to the request for this to work correctly, or am I missing something in a message converter.

Note: Not sure this matters but I am using Postman to test the endpoint.

答:
add

Content-Type: application/json;

under the line of

Content-Disposition: form-data; name="fileParameters"

to explicit how to resolve your parameters

see spring docs here

Body:
I am attempting to upload a file with additional parameters using RequestParts.  I have the file uploading correctly; however, when I try and add in the additional parameters I get an error in response.

My Controller:

@RequestMapping(value = "/v1/cases/{caseId}/file", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Success uploadFile(
        @RequestPart(value="file") MultipartFile file,
        @RequestPart(value="fileParameters") FileParameters fileParameters) throws FileNotFoundException, IOException {

I have tried to POST to this 2 different ways with different errors:

1)

----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="file"; filename="myFile"
Content-Type:

----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="fileParameters"

{"filePassword":"testPassword", "configuration":{}, "target":null}
----WebKitFormBoundaryE19zNvXGzXaLvS5C

this errors with:

The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method. See 'supportedMediaTypes' in 'additionalInfo' for a list of supported types

2)

----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="file"; filename="myFile"
Content-Type:

----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="fileParamters[filePassword]"

testPassword
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="fileParamters[configuration]"

{}
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="fileParamters[target]"

null
----WebKitFormBoundaryE19zNvXGzXaLvS5C

which returns the following error:

"rootExceptionClass": "org.springframework.web.multipart.support.MissingServletRequestPartException",
"rootExceptionMessage": "Required request part 'keyParameters' is not present."

I'm assuming the first approach is the correct one; however, the application does support JSON, so I'm not sure what I am missing configuration wise.  Is there something I have to add to the request for this to work correctly, or am I missing something in a message converter.

Note: Not sure this matters but I am using Postman to test the endpoint.


问:
Add a filter on a DbSet that is included on a related DbSet?
The following are some stuffs behind the scene.

```<code>public class User : BaseTransactionModel
{
    public Guid UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class Transaction
{

    public int TransactionId { get; set; }
    public string TransactionName { get; set; }
    public int TransactionHistoryId { get; set; }

    public virtual TransactionHistory TransactionHistory { get; set; }
}

public class TransactionHistory
{
    public int TransactionHistoryId { get; set; }
    public DateTime CreatedDateTime { get; set; }
    public Guid UserId { get; set; }
    public int TransactionId { get; set; }

    public virtual ICollection<User> Users { get; set; }
    public virtual ICollection<Transaction> Transactions { get; set; }
}

public class BaseTransactionModel
{

    public int TransactionHistoryId { get; set; }
    public int TransactionId { get; set; }

    public virtual TransactionHistory TransactionHistory { get; set; }
    public virtual Transaction Transaction { get; set; }
}
</code>```

With the above entities, I am trying to get all the Transactions from a User on a specified Date.

So I tried including both User and TransactionHistory on the Transaction DbSet:

```<code>Context.Transaction
    .Include(t => t.User)
    .Include(t => t.TransactionHistory)
    ...
</code>```

I wanted to add a where clause that filter the transaction from the date in transaction history entities:

```<code>Context.Transaction
    .Include(t => t.User)
    .Include(t => t.TransactionHistory)
    .Where(t => t.TransactionHistory.CreatedDateTime <= StartDateFilter && t.TransactionHistory.CreatedDateTime >= EndDateFilter)
</code>```

but could not able to do so. Since TransactionHistory is also a list of entity (or whatever it is called).

What could be the possible solution to get what I am trying to achieve ?

PS: I am new to EF and the title could be misleading. If so, feel free to update it.

答:
You might need to rethink your class design e.g.

```<code>public class User
    {
        public Guid UserId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public virtual ICollection<Transaction> TransactionHistory { get; set; }
    }

    public class Transaction
    {
        public int TransactionId { get; set; }
        public string TransactionName { get; set; }
        public DateTime CreatedDateTime { get; set; }
    }
</code>```

Then to get the transactions like you require your query could be something like this:

```<code> var result = Context.User
                .Where(u => u.UserId == myguid)
                .Select(t => new
                {
                    UserId = t.UserId,
                    Transactions = t.TransactionHistory.Where(x => x.CreatedDateTime >= StartDateFilter && x.CreatedDateTime <= EndDateFilter)
                })
                .ToList();
</code>```

Body:
The following are some stuffs behind the scene.

public class User : BaseTransactionModel
{
    public Guid UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class Transaction
{

    public int TransactionId { get; set; }
    public string TransactionName { get; set; }
    public int TransactionHistoryId { get; set; }

    public virtual TransactionHistory TransactionHistory { get; set; }
}

public class TransactionHistory
{
    public int TransactionHistoryId { get; set; }
    public DateTime CreatedDateTime { get; set; }
    public Guid UserId { get; set; }
    public int TransactionId { get; set; }

    public virtual ICollection<User> Users { get; set; }
    public virtual ICollection<Transaction> Transactions { get; set; }
}

public class BaseTransactionModel
{

    public int TransactionHistoryId { get; set; }
    public int TransactionId { get; set; }

    public virtual TransactionHistory TransactionHistory { get; set; }
    public virtual Transaction Transaction { get; set; }
}

With the above entities, I am trying to get all the Transactions from a User on a specified Date.

So I tried including both User and TransactionHistory on the Transaction DbSet:

Context.Transaction
    .Include(t => t.User)
    .Include(t => t.TransactionHistory)
    ...

I wanted to add a where clause that filter the transaction from the date in transaction history entities:

Context.Transaction
    .Include(t => t.User)
    .Include(t => t.TransactionHistory)
    .Where(t => t.TransactionHistory.CreatedDateTime <= StartDateFilter && t.TransactionHistory.CreatedDateTime >= EndDateFilter)

but could not able to do so. Since TransactionHistory is also a list of entity (or whatever it is called).

What could be the possible solution to get what I am trying to achieve ?

PS: I am new to EF and the title could be misleading. If so, feel free to update it.

Body:
You might need to rethink your class design e.g.

public class User
    {
        public Guid UserId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public virtual ICollection<Transaction> TransactionHistory { get; set; }
    }

    public class Transaction
    {
        public int TransactionId { get; set; }
        public string TransactionName { get; set; }
        public DateTime CreatedDateTime { get; set; }
    }

Then to get the transactions like you require your query could be something like this:

 var result = Context.User
                .Where(u => u.UserId == myguid)
                .Select(t => new
                {
                    UserId = t.UserId,
                    Transactions = t.TransactionHistory.Where(x => x.CreatedDateTime >= StartDateFilter && x.CreatedDateTime <= EndDateFilter)
                })
                .ToList();


问:
Laravel Database Seeder Class
Here is my DatabaseSeeder Class Code

```<code><?php

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {

        $this->call(
            AdminSeeder::class,
            CategorySeeder::class,
            UsersSeeder::class,);
    }
}
</code>```

My php Artisan Command is: php artisan db:seed
I want to migrate all Seeder class by one commad. but I can't do it. pls help me.

答:
You also call each seeder seperately.

```<code>$this->call('AdminSeeder');
$this->call('CategorySeeder');
$this->call('UsersSeeder');
</code>```

Edit for the downvoter, the call function can accept array or string.

```<code>/**
 * Seed the given connection from the given path.
 *
 * @param  array|string  $class
 * @param  bool  $silent
 * @return $this
 */
public function call($class, $silent = false)
{
    $classes = Arr::wrap($class);
    foreach ($classes as $class) {
        if ($silent === false && isset($this->command)) {
            $this->command->getOutput()->writeln("<info>Seeding:</info> $class");
        }
        $this->resolve($class)->__invoke();
    }
    return $this;
}
</code>```

Title: Laravel Database Seeder Class

Body:
Here is my DatabaseSeeder Class Code

<?php

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {

        $this->call(
            AdminSeeder::class,
            CategorySeeder::class,
            UsersSeeder::class,);
    }
}

My php Artisan Command is: php artisan db:seed
I want to migrate all Seeder class by one commad. but I can't do it. pls help me.

Body:
You also call each seeder seperately.

$this->call('AdminSeeder');
$this->call('CategorySeeder');
$this->call('UsersSeeder');

Edit for the downvoter, the call function can accept array or string.

/**
 * Seed the given connection from the given path.
 *
 * @param  array|string  $class
 * @param  bool  $silent
 * @return $this
 */
public function call($class, $silent = false)
{
    $classes = Arr::wrap($class);
    foreach ($classes as $class) {
        if ($silent === false && isset($this->command)) {
            $this->command->getOutput()->writeln("<info>Seeding:</info> $class");
        }
        $this->resolve($class)->__invoke();
    }
    return $this;
}


问:
cloning a bitbucket project in AndroidStudio
I try to clone a project from Bitbucket into Android Studio. The project was originally published from Eclipse.

But I get the error:

Clone failed. Failed to start Git process.

What I have done so far:

Installed a Bitbucket plugin: https://bitbucket.org/dmitry_cherkas/jetbrains-bitbucket-connector/downloads (http://www.goprogramming.space/connecting-android-studio-project-with-bitbucket/)

Then VCS -> checkout from Version Control -> Bitbucket

I get a login screen.
I logged into Bitbucket and I could see the list of my projects (WOW!)
Then selecting a project and press ok. -> Clone failed. Failed to start Git process.

Any help on how I can clone a Bitbucket repository?

答:
For using BitBucket plugin you need to install git on your system too.

Install git on Linux using following command in terminal:

sudo apt-get install git

Windows & Mac OS X:

git tutorial | Install git


问:
Python: ValueError: invalid literal for int() with base 10: '"'
I'm creating code to get the average score in a CSV file.

CSV file looks like this:

```<code>5 Ser15

4 Ser15

3 Ser15
</code>```

1st column are the scores, the second are the usernames.

This is my code so far:

```<code>   def av():
    with open("SciMedreport.csv","r") as f:
        average = 0
        Sum = 0
        row_count = 0
        for row in f:
            column = row.split(',')
            i=(int(column[0]))
            Sum += i
            row_count += 1
        average = Sum / row_count
        return 'The average is:', average
  av()
</code>```

But this error appears...

```<code>  i=int(column[0])
ValueError: invalid literal for int() with base 10: '"'
</code>```

When I print the whole row to check, this appears:

```<code>def av():
with open("SciMedreport.csv","r") as f:
    average = 0
    Sum = 0
    row_count = 0
    for row in f:
        print(row)
av()
</code>```

This is the result:

```<code>5,Ser15
""

5,Ser15

""

4,Ser15
</code>```

Anyone know of a way to fix this, or an alternative way to work out the average??

答: when you try to split your row by ',' as there is none, whole string will be returned and trying to convert it into int() gives you the error, try splitting using ' '</p>

Body:
I'm creating code to get the average score in a CSV file.

CSV file looks like this:

5 Ser15

4 Ser15

3 Ser15

1st column are the scores, the second are the usernames.

This is my code so far:

   def av():
    with open("SciMedreport.csv","r") as f:
        average = 0
        Sum = 0
        row_count = 0
        for row in f:
            column = row.split(',')
            i=(int(column[0]))
            Sum += i
            row_count += 1
        average = Sum / row_count
        return 'The average is:', average
  av()

But this error appears...

  i=int(column[0])
ValueError: invalid literal for int() with base 10: '"'

When I print the whole row to check, this appears:

def av():
with open("SciMedreport.csv","r") as f:
    average = 0
    Sum = 0
    row_count = 0
    for row in f:
        print(row)
av()

This is the result:

5,Ser15
""

5,Ser15

""

4,Ser15

Anyone know of a way to fix this, or an alternative way to work out the average??


问:
Codeigneitor Error : Call to a member function result() on null
im trying get results through a for loop.but i am getting above error.what can be the reason?.I have db named news. it contains columns as id,title,description.

My controller

```<code>class news extends CI_Controller
{
    function  __construct() {

        parent::__construct();

        $this->load->helper('url');
        $this->load->database();
        $this->load->helper('form');
        $this->load->library('upload');
        $this->load->model('news_model');
    }

    function index(){

        $this->load->model('news_model');
        $this->data['NewsData'] = $this->news_model->get_news();
        $this->load->view('site/cms/news',$this->data);
    }

}
</code>```

Model

```<code>class news_model extends CI_Model
{
    public function __construct()
    {
        parent::__construct(); // Construct CI's core so that you can use it
        $this->load->database();

    }

     function get_news(){

        $this->db->select('*');
        $this->db->from('news');
        $news_details = $this->db->get();
        return $news_details;
    }
}
</code>```

View

```<code><?php if($NewsData->result() > 0){
                    foreach($NewsData->result() as $add){?>
<p><?php echo $add->title; ?></p>

 <?php }} ?>
</code>```

答:
Please correct your code using from below line.</p>

```<code><?php if($NewsData->num_rows() > 0){
       foreach($NewsData->result() as $add){?>
           <p><?php echo $add->title; ?></p>

       <?php }
} ?>
</code>```

Body:
im trying get results through a for loop.but i am getting above error.what can be the reason?.I have db named news. it contains columns as id,title,description.

My controller

class news extends CI_Controller
{
    function  __construct() {

        parent::__construct();

        $this->load->helper('url');
        $this->load->database();
        $this->load->helper('form');
        $this->load->library('upload');
        $this->load->model('news_model');
    }

    function index(){

        $this->load->model('news_model');
        $this->data['NewsData'] = $this->news_model->get_news();
        $this->load->view('site/cms/news',$this->data);
    }

}

Model

class news_model extends CI_Model
{
    public function __construct()
    {
        parent::__construct(); // Construct CI's core so that you can use it
        $this->load->database();

    }

     function get_news(){

        $this->db->select('*');
        $this->db->from('news');
        $news_details = $this->db->get();
        return $news_details;
    }
}

View

<?php if($NewsData->result() > 0){
                    foreach($NewsData->result() as $add){?>

<?php echo $add->title; ?>

 <?php }} ?>

Body:
Please correct your code using from below line.

<?php if($NewsData->num_rows() > 0){
       foreach($NewsData->result() as $add){?>
           <p><?php echo $add->title; ?></p>

       <?php }
} ?>


问:
What is the difference between state and props in React?
I was watching a Pluralsight course on React and the instructor stated that props should not be changed. I'm now reading an article (uberVU/react-guide) on props vs. state and it says

Both props and state changes trigger a render update.

Later in the article it says:

Props (short for properties) are a Component's configuration, its options if you may. They are received from above and immutable.

So props can change but they should be immutable?

When should you use props and when should you use state?

If you have data that a React component needs, should it be passed through props or setup in the React component via getInitialState?

答:
In general, state of one component(parent) is prop for the child component.

State resides within a component where as props are passed from parent to
child.

Props are generally immutable.

```<code>class Parent extends React.Component {
    constructor() {
        super();
        this.state = {
            name : "John",
        }
    }
    render() {
        return (
            <Child name={this.state.name}>
        )
    }
}

class Child extends React.Component {
    constructor() {
        super();
    }

    render() {
        return(
            {this.props.name}
        )
    }
}
</code>```

In the above code, we have a parent class(Parent) which has name as its state which is passed to the child component(Child class) as a prop and the child component renders it using {this.props.name}

Body:
In general, state of one component(parent) is prop for the child component.

State resides within a component where as props are passed from parent to
child.

Props are generally immutable.

class Parent extends React.Component {
    constructor() {
        super();
        this.state = {
            name : "John",
        }
    }
    render() {
        return (
            <Child name={this.state.name}>
        )
    }
}

class Child extends React.Component {
    constructor() {
        super();
    }

    render() {
        return(
            {this.props.name}
        )
    }
}

In the above code, we have a parent class(Parent) which has name as its state which is passed to the child component(Child class) as a prop and the child component renders it using {this.props.name}


问:
Having a block of code wait to run at a certain time in iOS
Let's say I have a view controller with code that I want to execute at a certain time, say 2:00pm. What I want to happen is that if the user opens the view controller at 1:58pm, that the code will wait and continuously check the time, executing itself at exactly 2:00pm. Is there a way to do this in Swift 4, perhaps with a timer?</p>

答:
You can figure out the number of seconds between your future date and now and use either GCD or Timer to setup your future event:

```<code>let futureDate = ISO8601DateFormatter().date(from: "2018-1-1T00:00:00Z" )!
DispatchQueue.main.asyncAfter(deadline: .now() + futureDate.timeIntervalSinceNow) {
    print("Its the future!")
}
</code>```

or

```<code>let futureDate = ISO8601DateFormatter().date(from: "2018-1-1T00:00:00Z" )!
let timer = Timer.scheduledTimer(withTimeInterval: futureDate.timeIntervalSinceNow, repeats: false) {
    print("Its the future!")
}
</code>```

Timer is easier to cancel and reschedule:

```<code>timer.invalidate()
</code>```

Body:
You can figure out the number of seconds between your future date and now and use either GCD or Timer to setup your future event:

let futureDate = ISO8601DateFormatter().date(from: "2018-1-1T00:00:00Z" )!
DispatchQueue.main.asyncAfter(deadline: .now() + futureDate.timeIntervalSinceNow) {
    print("Its the future!")
}

or

let futureDate = ISO8601DateFormatter().date(from: "2018-1-1T00:00:00Z" )!
let timer = Timer.scheduledTimer(withTimeInterval: futureDate.timeIntervalSinceNow, repeats: false) {
    print("Its the future!")
}

Timer is easier to cancel and reschedule:

timer.invalidate()


问:
Displaying options for two select
friends. Faced such a question. I have two select, in each select of the city they are taken from the database, and in the second select  - the city that is != To the city from the first select. Help me, pleasee..)
Code</p>

```<code>       <form action="{{route('countDistance')}}" method="post">
    <div class="starter-template">
<select class="selectpicker" name="from" id="from">

@foreach($deps as $depart)
<option>{!!$depart->City!!}</option>
@endforeach
</select>
<select class="selectpicker" name="to" id="to">

@foreach($deps as $depart)
<option>{!!$depart->City!!}</option>
@endforeach
</select>
   <button type="submit" class="btn btn-info">Count »</button>
   {{ csrf_field() }}
    </div>
    </form>
</code>```

答:
I used jquery to accomplish this. For that I had to add first option saying 'Please select' for both. On change of #from select box, I hid the option with the same text from #to select box. And before hiding any option, showed all, so that previously hidden option may be available now.</p>

```<code>   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

    <form action="{{route('countDistance')}}" method="post">
    <div class="starter-template">
    <select class="selectpicker" name="from" id="from">

    <option>Please select</option>
    @foreach($deps as $depart)
    <option>{!!$depart->City!!}</option>
    @endforeach

    </select>
    <select class="selectpicker" name="to" id="to">

    <option>Please select</option>
    @foreach($deps as $depart)
    <option>{!!$depart->City!!}</option>
    @endforeach

    </select>
    <button type="submit" class="btn btn-info">Count »</button>
    {{ csrf_field() }}
    </div>
    </form>

<script>

$(document).ready(function() {

    $("#from").change(function() {
        // first show all from #to
        $("#to > option").each(function() {
            $(this).show();
        });

        console.log($("#from").val());
        var toHide = $("#from").val();
        $("#to option:contains('" + toHide + "')").hide();
    });
});

</script>
</code>```

Title: Displaying options for two select

Body:
friends. Faced such a question. I have two select, in each select of the city they are taken from the database, and in the second select  - the city that is != To the city from the first select. Help me, pleasee..)
Code

       <form action="{{route('countDistance')}}" method="post">

<select class="selectpicker" name="from" id="from">

@foreach($deps as $depart)
<option>{!!$depart->City!!}</option>
@endforeach
</select>
<select class="selectpicker" name="to" id="to">

@foreach($deps as $depart)
<option>{!!$depart->City!!}</option>
@endforeach
</select>
   <button type="submit" class="btn btn-info">Count »</button>
   {{ csrf_field() }}

    </form>

Body:
I used jquery to accomplish this. For that I had to add first option saying 'Please select' for both. On change of #from select box, I hid the option with the same text from #to select box. And before hiding any option, showed all, so that previously hidden option may be available now.

   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

    <form action="{{route('countDistance')}}" method="post">
    <div class="starter-template">
    <select class="selectpicker" name="from" id="from">

    <option>Please select</option>
    @foreach($deps as $depart)
    <option>{!!$depart->City!!}</option>
    @endforeach

    </select>
    <select class="selectpicker" name="to" id="to">

    <option>Please select</option>
    @foreach($deps as $depart)
    <option>{!!$depart->City!!}</option>
    @endforeach

    </select>
    <button type="submit" class="btn btn-info">Count &raquo;</button>
    {{ csrf_field() }}
    </div>
    </form>

<script>

$(document).ready(function() {

    $("#from").change(function() {
        // first show all from #to
        $("#to > option").each(function() {
            $(this).show();
        });

        console.log($("#from").val());
        var toHide = $("#from").val();
        $("#to option:contains('" + toHide + "')").hide();
    });
});

</script>


问:
Only one expression can be specified in the select list when the sub-query is not introduced with EXISTS
```<code>SELECT
  ( Select
COUNT(t2.ID) as Total_HH_Memebers_Primary,t1.SETTLEMENT_ID
from
PScData t1
INNER JOIN
PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
WHERE  EXISTS (SELECT 1
               FROM   PScData t1
               WHERE  t1.SETTLEMENT_ID = SETTLEMENT_ID
                AND t2.EDUCATION_LEVEL = 5
               HAVING Count(*) > 1)
               Group By t1.SETTLEMENT_ID
) col1

  , (Select
COUNT(t2.ID) as Total_HH_Memebers_Secondary,t1.SETTLEMENT_ID
from
PScData t1
INNER JOIN
PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
 WHERE  EXISTS (SELECT 1
               FROM   PScData t1
               WHERE  t1.SETTLEMENT_ID = SETTLEMENT_ID
                AND t2.EDUCATION_LEVEL = 10
              HAVING Count(*) > 1)
               Group By t1.SETTLEMENT_ID

) col2
</code>```

Here is my query, i want to get two different results based on "WHERE" condition from same table in the form of columns when i do this its giving this error .can somebody how to it correctly?

答:
I have accepted the above answer and i have found another method for it as well:

Both methods are feasible,the method that i have found is given below:

```<code>WITH EDU_LEVEL AS
(SELECT t1.SETTLEMENT_ID,t2.EDUCATION_LEVEL from
PScData t1
INNER JOIN
PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
)

SELECT  SETTLEMENT_ID,
(Select COUNT(*) FROM EDU_LEVEL    WHERE  SETTLEMENT_ID = T.SETTLEMENT_ID AND EDUCATION_LEVEL = 5 ) Total_HH_Memebers_Primary,
(Select COUNT(*) FROM EDU_LEVEL    WHERE  SETTLEMENT_ID = T.SETTLEMENT_ID AND EDUCATION_LEVEL = 10 ) Total_HH_Memebers_Secondary

FROM EDU_LEVEL AS T
Group By SETTLEMENT_ID
</code>```

Body:
SELECT
  ( Select
COUNT(t2.ID) as Total_HH_Memebers_Primary,t1.SETTLEMENT_ID
from
PScData t1
INNER JOIN
PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
WHERE  EXISTS (SELECT 1
               FROM   PScData t1
               WHERE  t1.SETTLEMENT_ID = SETTLEMENT_ID
                AND t2.EDUCATION_LEVEL = 5
               HAVING Count(*) > 1)
               Group By t1.SETTLEMENT_ID
) col1

  , (Select
COUNT(t2.ID) as Total_HH_Memebers_Secondary,t1.SETTLEMENT_ID
from
PScData t1
INNER JOIN
PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
 WHERE  EXISTS (SELECT 1
               FROM   PScData t1
               WHERE  t1.SETTLEMENT_ID = SETTLEMENT_ID
                AND t2.EDUCATION_LEVEL = 10
              HAVING Count(*) > 1)
               Group By t1.SETTLEMENT_ID

) col2

Here is my query, i want to get two different results based on "WHERE" condition from same table in the form of columns when i do this its giving this error .can somebody how to it correctly?

Body:
I have accepted the above answer and i have found another method for it as well:

Both methods are feasible,the method that i have found is given below:

WITH EDU_LEVEL AS
(SELECT t1.SETTLEMENT_ID,t2.EDUCATION_LEVEL from
PScData t1
INNER JOIN
PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
)

SELECT  SETTLEMENT_ID,
(Select COUNT(*) FROM EDU_LEVEL    WHERE  SETTLEMENT_ID = T.SETTLEMENT_ID AND EDUCATION_LEVEL = 5 ) Total_HH_Memebers_Primary,
(Select COUNT(*) FROM EDU_LEVEL    WHERE  SETTLEMENT_ID = T.SETTLEMENT_ID AND EDUCATION_LEVEL = 10 ) Total_HH_Memebers_Secondary

FROM EDU_LEVEL AS T
Group By SETTLEMENT_ID


问:
Unit testing BLE application in IOS (Swift)
We've developed an app that connects to a BLE dongle and everything is working thru the BLE connection.

Now we decided to add Unit testing ( And Yes, i know it is much better to do TDD and not this way but this is the situation)

In the app everything is working, but when i'm trying to develop the unit tests i can't go pass the connection phase (GAT) i'm not getting the connection working an in any case the tests go thru one after the other and don't stop to wait for the connection to happen and authentication and nothing)

```<code>func testConnect() {
    if viewController == nil {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        viewController = storyboard.instantiateViewController(withIdentifier: "ViewController") as? ViewController

        if let vc = viewController {
            _ = vc.view
        }
    }

    viewController?.connectBluetooth();
}

func testAuthenticateByPin() {
    delay(5) {
        var error: NSError? = nil

        self.datConnection?.connect("ABCDEFG", withError: &error)
        XCTAssertNotNil(error, "Connect Error: \(String(describing: error))")
        print("Connection: \(String(describing: error))")

        self.datConnection?.authenticate(byPIN: "AD$FGR#", withError: &error)
        XCTAssertNotNil(error, "Error: \(String(describing: error))")
        print("Auth: \(String(describing: error))")
    }
}

func delay(_ delay:Double, closure:@escaping ()->()) {
    let when = DispatchTime.now() + delay
    DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
}
</code>```

Any one knows how to create a BLE unit test and how to create a Delay between unit tests?

答:
I use expectations for my network operation tests in Objective-C.

You create an expectation and at the end of the test case, wait for it to become fulfilled. When you get the connection notification or whatever you have to wait for, call fulfill(). The wait uses a timeout and if the notification never comes (connection never takes place), the test will fail with the non-fulfilled expectation.

From a sample from Apple's website (here) which is already in Swift:

```<code>func testDownloadWebData() {
    // Create an expectation for a background download task.
    let expectation = XCTestExpectation(description: "Download apple.com home page")
    // Create a URL for a web page to be downloaded.
    let url = URL(string: "https://apple.com")!
    // Create a background task to download the web page.
    let dataTask = URLSession.shared.dataTask(with: url) { (data, _, _) in
        // Make sure we downloaded some data.
        XCTAssertNotNil(data, "No data was downloaded.")
        // Fulfill the expectation to indicate that the background task has finished successfully.
        expectation.fulfill()
    }

    // Start the download task.
    dataTask.resume()
    // Wait until the expectation is fulfilled, with a timeout of 10 seconds.
    wait(for: [expectation], timeout: 10.0)
}
</code>```

Body:
We've developed an app that connects to a BLE dongle and everything is working thru the BLE connection.

Now we decided to add Unit testing ( And Yes, i know it is much better to do TDD and not this way but this is the situation)

In the app everything is working, but when i'm trying to develop the unit tests i can't go pass the connection phase (GAT) i'm not getting the connection working an in any case the tests go thru one after the other and don't stop to wait for the connection to happen and authentication and nothing)

func testConnect() {
    if viewController == nil {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        viewController = storyboard.instantiateViewController(withIdentifier: "ViewController") as? ViewController

        if let vc = viewController {
            _ = vc.view
        }
    }

    viewController?.connectBluetooth();
}

func testAuthenticateByPin() {
    delay(5) {
        var error: NSError? = nil

        self.datConnection?.connect("ABCDEFG", withError: &error)
        XCTAssertNotNil(error, "Connect Error: \(String(describing: error))")
        print("Connection: \(String(describing: error))")

        self.datConnection?.authenticate(byPIN: "AD$FGR#", withError: &error)
        XCTAssertNotNil(error, "Error: \(String(describing: error))")
        print("Auth: \(String(describing: error))")
    }
}

func delay(_ delay:Double, closure:@escaping ()->()) {
    let when = DispatchTime.now() + delay
    DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
}

Any one knows how to create a BLE unit test and how to create a Delay between unit tests?

Body:
I use expectations for my network operation tests in Objective-C.

You create an expectation and at the end of the test case, wait for it to become fulfilled. When you get the connection notification or whatever you have to wait for, call fulfill(). The wait uses a timeout and if the notification never comes (connection never takes place), the test will fail with the non-fulfilled expectation.

From a sample from Apple's website (here) which is already in Swift:

func testDownloadWebData() {
    // Create an expectation for a background download task.
    let expectation = XCTestExpectation(description: "Download apple.com home page")
    // Create a URL for a web page to be downloaded.
    let url = URL(string: "https://apple.com")!
    // Create a background task to download the web page.
    let dataTask = URLSession.shared.dataTask(with: url) { (data, _, _) in
        // Make sure we downloaded some data.
        XCTAssertNotNil(data, "No data was downloaded.")
        // Fulfill the expectation to indicate that the background task has finished successfully.
        expectation.fulfill()
    }

    // Start the download task.
    dataTask.resume()
    // Wait until the expectation is fulfilled, with a timeout of 10 seconds.
    wait(for: [expectation], timeout: 10.0)
}


问:
check duplicate numbers with bool function in matrix c++
I created a matrix[10][10] with random numbers

```<code>for (int i = 0; i < 10; i++)
{
    for (int j = 0; j < 10; j++)
    {
        matrix[i][j] = rand() % 100 ;

    }
}
</code>```

But I need to use bool function for check duplicate numbers and if its same use random again.How can i do it?

答:
An efficient way to test for duplicates is to store the elements that have been inserted into the matrix in a std::vector and to use to std::find. This allows to check whether a newly generated random number is already included in the previously stored elements or not. If it is found, then another random number should be generated and the test repeated.

```<code>#include <iostream>
#include <cstdlib>
#include <vector>
#include <algorithm>

bool alreadySelected(int n, int nvalues, int values[][10]) {
  std::vector<int> v(&values[0][0], &values[0][0] + nvalues );
  return (std::find(v.begin(), v.end(), n) != v.end());
}

int main() {
  int matrix[10][10];
  for (int i = 0; i < 10; i++) {
    int n;
    bool dupe;
    for (int j = 0; j < 10; j++) {
    int nvalues = i * 10 + j;
    do {
      n = std::rand() % 100 ;
      dupe = alreadySelected( n, nvalues, matrix );
    } while ( dupe );
    matrix[i][j] = n;
    std::cout << matrix[i][j] << " ";
   }
   std::cout << "\n";
  }
}
</code>```

A much simpler way to generate such a matrix would be to use std::random_shuffle.

Body:
I created a matrix[10][10] with random numbers

for (int i = 0; i < 10; i++)
{
    for (int j = 0; j < 10; j++)
    {
        matrix[i][j] = rand() % 100 ;

    }
}

But I need to use bool function for check duplicate numbers and if its same use random again.How can i do it?

Body:
An efficient way to test for duplicates is to store the elements that have been inserted into the matrix in a std::vector and to use to std::find. This allows to check whether a newly generated random number is already included in the previously stored elements or not. If it is found, then another random number should be generated and the test repeated.

#include <iostream>
#include <cstdlib>
#include <vector>
#include <algorithm>

bool alreadySelected(int n, int nvalues, int values[][10]) {
  std::vector<int> v(&values[0][0], &values[0][0] + nvalues );
  return (std::find(v.begin(), v.end(), n) != v.end());
}

int main() {
  int matrix[10][10];
  for (int i = 0; i < 10; i++) {
    int n;
    bool dupe;
    for (int j = 0; j < 10; j++) {
    int nvalues = i * 10 + j;
    do {
      n = std::rand() % 100 ;
      dupe = alreadySelected( n, nvalues, matrix );
    } while ( dupe );
    matrix[i][j] = n;
    std::cout << matrix[i][j] << " ";
   }
   std::cout << "\n";
  }
}

A much simpler way to generate such a matrix would be to use std::random_shuffle.


问:
Visualization of raw RGB image data with 24bits using opencv
I would like to process a raw image using OpenCV. As far I know, it is not possible to open raw image using OpenCV.
I fllowed the instaction.

My raw picture is RGB with 24bits (the first 3 bytes represents the color values of red, green and blue in the same pixel).

My aim is to be able to process my picture using OpenCV functions.

How should I reshape my raw data?
I thought of (3, 1280, 1080) based on what i saw in the internet

How could I visualized the three pictures as "normal" picture? and how could I visualized he three pictures separably?

As small example I tried to reshape the bytes I read using:

```<code>a = np.arange(18).reshape(3,2,3, order='F')

a: [[[ 0  6 12]
     [ 3  9 15]]
    [[ 1  7 13]
     [ 4 10 16]]
    [[ 2  8 14]
     [ 5 11 17]]]
</code>```

答:
OpenCV is able to read NetPBM (Wikipedia entry for NetPBM)  format images, see PPM Example on linked page.

So you could just put a P6 (i.e. binary RGB) NetPBM header on the front of your image like this, then OpenCV can open it:

```<code>{ printf "P6\n1280 1080\n255\n" ; cat YourImage.raw ; } > result.ppm
</code>```

If you are unfortunate enough to be on Windows, you can probably do it something like this:

```<code>echo "P6"          > header.txt
echo "1280 1080"  >> header.txt
echo "255"        >> header.txt
copy /b header.txt+YourImage.raw result.ppm
</code>```

Alternatively, if you are on Linux, you probably have ImageMagick, and it is available for macOS and Windows too. So, at the command line in Terminal, you could convert your image to a PNG like tis:

```<code>convert -depth 8 -size 1280x1080 rgb:YourImage.raw result.png
</code>```

You can then separate the individual channels and append them beside each other with

```<code>convert result.png -separate +append 3channels.png   # or use `-append` instead
</code>```

Or, with auto-level contrast:

```<code>convert result.png -separate +append -auto-level 3channels.png
</code>```

Body:
I would like to process a raw image using OpenCV. As far I know, it is not possible to open raw image using OpenCV.
I fllowed the instaction.

My raw picture is RGB with 24bits (the first 3 bytes represents the color values of red, green and blue in the same pixel).

My aim is to be able to process my picture using OpenCV functions.

How should I reshape my raw data?
I thought of (3, 1280, 1080) based on what i saw in the internet

How could I visualized the three pictures as "normal" picture? and how could I visualized he three pictures separably?

As small example I tried to reshape the bytes I read using:

a = np.arange(18).reshape(3,2,3, order='F')

a: [[[ 0  6 12]
     [ 3  9 15]]
    [[ 1  7 13]
     [ 4 10 16]]
    [[ 2  8 14]
     [ 5 11 17]]]

Body:
OpenCV is able to read NetPBM (Wikipedia entry for NetPBM)  format images, see PPM Example on linked page.

So you could just put a P6 (i.e. binary RGB) NetPBM header on the front of your image like this, then OpenCV can open it:

{ printf "P6\n1280 1080\n255\n" ; cat YourImage.raw ; } > result.ppm

If you are unfortunate enough to be on Windows, you can probably do it something like this:

echo "P6"          > header.txt
echo "1280 1080"  >> header.txt
echo "255"        >> header.txt
copy /b header.txt+YourImage.raw result.ppm

Alternatively, if you are on Linux, you probably have ImageMagick, and it is available for macOS and Windows too. So, at the command line in Terminal, you could convert your image to a PNG like tis:

convert -depth 8 -size 1280x1080 rgb:YourImage.raw result.png

You can then separate the individual channels and append them beside each other with

convert result.png -separate +append 3channels.png   # or use `-append` instead

Or, with auto-level contrast:

convert result.png -separate +append -auto-level 3channels.png


问:
just another tagcloud question
i have an act:

```<code>public class Act
{
    public Act()
    {
        this.Tags = new List<Tag>();
    }

    public string Id {get; set;}

    public string Name { get; set; }

    public IList<Tag> Tags { get; set; }

}
</code>```

Tag is just:

```<code>public class Tag
{
    public string Name { get; set; }

    public string LfmUrl { get; set; }
}
</code>```

I want to be able to query the DB and get a list of TagCount back which shows the name of the tag and the number of times it appears.

So far I have this:

```<code>public class Tags_ByTagCloud : AbstractIndexCreationTask
{
    public override IndexDefinition CreateIndexDefinition()
    {
        return new IndexDefinition<Act, TagAndCount>
                   {
                       Map = docs => from doc in docs
                                     from tag in doc.Tags
                                     select new
                                                {
                                                    Name = tag.Name,
                                                    Count = 1
                                                },
                       Reduce = results => from result in results
                                           group result by result.TagName
                                           into g
                                           select new
                                                      {
                                                          Name = g.Key,
                                                          Count = g.Sum(x => x.Count)
                                                      },
                       SortOptions = {{x => x.Count, SortOptions.Int}}
                   }.ToIndexDefinition(DocumentStore.Conventions);
    }
}
</code>```

Which happily outputs nothing. I know there are thousands of acts each with at least a few tags. Any ideas?

I ideally want to pass in a list of act ids to query this against. So, given a list of acts, what are the tags and how many times does
each occur?

答: Just had to change all TagName to match Name and it mapped nicely</p>

ContentLicense: CC BY-SA 2.5

Title: just another tagcloud question

Body:
i have an act:

public class Act
{
    public Act()
    {
        this.Tags = new List<Tag>();
    }

    public string Id {get; set;}

    public string Name { get; set; }

    public IList<Tag> Tags { get; set; }

}

Tag is just:

public class Tag
{
    public string Name { get; set; }

    public string LfmUrl { get; set; }
}

I want to be able to query the DB and get a list of TagCount back which shows the name of the tag and the number of times it appears.

So far I have this:

public class Tags_ByTagCloud : AbstractIndexCreationTask
{
    public override IndexDefinition CreateIndexDefinition()
    {
        return new IndexDefinition<Act, TagAndCount>
                   {
                       Map = docs => from doc in docs
                                     from tag in doc.Tags
                                     select new
                                                {
                                                    Name = tag.Name,
                                                    Count = 1
                                                },
                       Reduce = results => from result in results
                                           group result by result.TagName
                                           into g
                                           select new
                                                      {
                                                          Name = g.Key,
                                                          Count = g.Sum(x => x.Count)
                                                      },
                       SortOptions = {{x => x.Count, SortOptions.Int}}
                   }.ToIndexDefinition(DocumentStore.Conventions);
    }
}

Which happily outputs nothing. I know there are thousands of acts each with at least a few tags. Any ideas?

I ideally want to pass in a list of act ids to query this against. So, given a list of acts, what are the tags and how many times does
each occur?


问:
How to use single print function to print multiple lines?
I just started learning Python3 and I got to the part where I started using arithmetic operations, I am trying to break the result into multiple lines, I used sep='/n' and /n, but I gives this error (positional argument follows keyword argument) I know it maybe a noob question but I can't figure out how to do it or what to search for in Google.

```<code>x=22
y=18
print('x+y=', x+y, 'x-y=', x-y)
</code>```

The result I get is this:
x+y= 40 x-y= 4.

I want it to be displayed like this:

x+y= 40

x-y= 4

答:
What about:

```<code>x=22
y=18
print('x+y =', x+y, '\nx-y =', x-y)
</code>```

or (better IMHO):

```<code>x=22
y=18
print('x+y = %d\nx-y = %d' % (x+y, x-y))
</code>```

(the latter using formatting features).

Body:
I just started learning Python3 and I got to the part where I started using arithmetic operations, I am trying to break the result into multiple lines, I used sep='/n' and /n, but I gives this error (positional argument follows keyword argument) I know it maybe a noob question but I can't figure out how to do it or what to search for in Google.

x=22
y=18
print('x+y=', x+y, 'x-y=', x-y)

The result I get is this:
x+y= 40 x-y= 4.

I want it to be displayed like this:

x+y= 40

x-y= 4

Body:
What about:

x=22
y=18
print('x+y =', x+y, '\nx-y =', x-y)

or (better IMHO):

x=22
y=18
print('x+y = %d\nx-y = %d' % (x+y, x-y))

(the latter using formatting features).


问:
SBT fails to resolve dependency for jersey-container-grizzly2-http 2.5.1
I am fairly new to Scala and SBT. I would like to implement a REST server using Jersey JAX-RS and Scala, but have faced the first hurdle trying to configure SBT. I was planning to use the Grizzly HTTP Server. The build.sbt is as follows:

```<code>name := "scala-jersey-server"

version := "1.0"

scalaVersion := "2.10.3"

libraryDependencies += "org.glassfish.jersey.containers" % "jersey-container-grizzly2-http" % "2.5.1"
</code>```

Running sbt update fails with the following messages

```<code>[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  ::          UNRESOLVED DEPENDENCIES         ::
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  :: org.glassfish.hk2#hk2-utils;2.5.1: not found
[warn]  :: org.glassfish.hk2#hk2-locator;2.5.1: not found
[warn]  :: javax.validation#validation-api;${javax.validation.version}: not found
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
</code>```

Looking at the pom.xml for hk2-api, it shows dependency on hk2-utils using the ${project.version} variable, but I'd have expected version 2.2.0-b21 of hk2-utils to be requested by SBT not 2.5.1 (which is JAX-RS version).

```<code><dependency>
   <groupId>org.glassfish.hk2</groupId>
   <artifactId>hk2-utils</artifactId>
   <version>${project.version}</version>
</dependency>
</code>```

Is this a problem with the configuration of hk2-api's pom.xml, is SBT using an incorrect version or something else?

答:
**I tried the above .sbt file but it was not excluding the jars and was still giving the same ERROR.

So modified the build file. below sample it could create a build successfully.**

```<code>name := "KafkaSparkCouchReadWrite"

organization := "my.clairvoyant"

version := "1.0.0-SNAPSHOT"

scalaVersion := "2.11.11"

libraryDependencies ++= Seq(
  "org.apache.spark" %% "spark-core" % "2.1.0",
  "org.apache.spark" %% "spark-streaming" % "2.1.0",
  "org.apache.spark" %% "spark-sql" % "2.1.0",
  "com.couchbase.client" %% "spark-connector" % "2.1.0",
  "org.glassfish.hk2" % "hk2-utils" % "2.2.0-b27",
  "org.glassfish.hk2" % "hk2-locator" % "2.2.0-b27",
  "javax.validation" % "validation-api" % "1.1.0.Final"
).map(_.excludeAll(ExclusionRule("org.glassfish.hk2"),ExclusionRule("javax.validation")))
</code>```

Body:
I am fairly new to Scala and SBT. I would like to implement a REST server using Jersey JAX-RS and Scala, but have faced the first hurdle trying to configure SBT. I was planning to use the Grizzly HTTP Server. The build.sbt is as follows:

name := "scala-jersey-server"

version := "1.0"

scalaVersion := "2.10.3"

libraryDependencies += "org.glassfish.jersey.containers" % "jersey-container-grizzly2-http" % "2.5.1"

Running sbt update fails with the following messages

[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  ::          UNRESOLVED DEPENDENCIES         ::
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  :: org.glassfish.hk2#hk2-utils;2.5.1: not found
[warn]  :: org.glassfish.hk2#hk2-locator;2.5.1: not found
[warn]  :: javax.validation#validation-api;${javax.validation.version}: not found
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::

Looking at the pom.xml for hk2-api, it shows dependency on hk2-utils using the ${project.version} variable, but I'd have expected version 2.2.0-b21 of hk2-utils to be requested by SBT not 2.5.1 (which is JAX-RS version).

<dependency>
   <groupId>org.glassfish.hk2</groupId>
   <artifactId>hk2-utils</artifactId>
   <version>${project.version}</version>
</dependency>

Is this a problem with the configuration of hk2-api's pom.xml, is SBT using an incorrect version or something else?

Body:
**I tried the above .sbt file but it was not excluding the jars and was still giving the same ERROR.

So modified the build file. below sample it could create a build successfully.**

name := "KafkaSparkCouchReadWrite"

organization := "my.clairvoyant"

version := "1.0.0-SNAPSHOT"

scalaVersion := "2.11.11"

libraryDependencies ++= Seq(
  "org.apache.spark" %% "spark-core" % "2.1.0",
  "org.apache.spark" %% "spark-streaming" % "2.1.0",
  "org.apache.spark" %% "spark-sql" % "2.1.0",
  "com.couchbase.client" %% "spark-connector" % "2.1.0",
  "org.glassfish.hk2" % "hk2-utils" % "2.2.0-b27",
  "org.glassfish.hk2" % "hk2-locator" % "2.2.0-b27",
  "javax.validation" % "validation-api" % "1.1.0.Final"
).map(_.excludeAll(ExclusionRule("org.glassfish.hk2"),ExclusionRule("javax.validation")))


问:
Save the data into a database and return another value from database using PHP
I want the text (Name of a person) entered in an input field to be saved on mysql database in the column name with a unique id which is a number( auto increment)

After saving the text into the database i want to get the automatically generated id from the database and append it to the url. And want the user to be forwarded to that url

For eg:

User enters John

Save john to db with a unique id

Get the unique id of john

Append the id to url ( http://example.com?id=1234)

Forward the user to the url http://example.com?id=1234

Print the name to the page http://example.com?id=1234

答:
U can use the normal php code to insert the data to mysql
ex:

```<code><?php
    if($_SERVER["REQUEST_METHOD"] == "POST") {
    $servername="localhost";
    $username="root";
    $password="";
    $db="login";
    //connection
    $conn=new mysqli($servername,$username,$password,$db);
    //fetch from form
    $myusername = mysqli_real_escape_string($conn,$_POST['usernam']);
    $mypassword = mysqli_real_escape_string($conn,$_POST['password']);
    $myemail=mysqli_real_escape_string($conn,$_POST['email']);
    $sql=$conn->query("INSERT INTO su values('$myusername','$mypassword','$myemail',0)");

    }
?>
</code>```

This inserts the data into mysql and the sql design needs to be done in such a way that it has an extra column to keep the generated ID

Once the data is entered fetch the details from this column append that to the URL and it will automatically redirect to the specified page with ur id

Example to fetch data from mysql using php:

```<code> $sql = "SELECT * FROM accounts where username='$myusername' ";
$result = $conn->query($sql);
    $row = mysqli_fetch_assoc($result);
</code>```

Now u can use $row['tablename'] to fetch the value from the database

Body:
U can use the normal php code to insert the data to mysql
ex:

<?php
    if($_SERVER["REQUEST_METHOD"] == "POST") {
    $servername="localhost";
    $username="root";
    $password="";
    $db="login";
    //connection
    $conn=new mysqli($servername,$username,$password,$db);
    //fetch from form
    $myusername = mysqli_real_escape_string($conn,$_POST['usernam']);
    $mypassword = mysqli_real_escape_string($conn,$_POST['password']);
    $myemail=mysqli_real_escape_string($conn,$_POST['email']);
    $sql=$conn->query("INSERT INTO su values('$myusername','$mypassword','$myemail',0)");

    }
?>

This inserts the data into mysql and the sql design needs to be done in such a way that it has an extra column to keep the generated ID

Once the data is entered fetch the details from this column append that to the URL and it will automatically redirect to the specified page with ur id

Example to fetch data from mysql using php:

 $sql = "SELECT * FROM accounts where username='$myusername' ";
$result = $conn->query($sql);
    $row = mysqli_fetch_assoc($result);

Now u can use $row['tablename'] to fetch the value from the database


问:
Compare current time with specific time when some event occures
In the code below, only the else part is ever getting executed. What should I do to execute the if part?

```<code>private void Form_Load(object sender, EventArgs e)
{
    // Current Time is 11:47:00 AM
    DateTime CurrentTime = System.DateTime.Now;
    DateTime StartTime = Convert.ToDateTime("10:15:00 AM");
    DateTime Stoptime = Convert.ToDateTime("02:29:57 PM");
    DateTime CloseTime = Convert.ToDateTime("02:59:57 PM");

    if (StartTime > CurrentTime && CurrentTime < Stoptime)
    {
        // CODE
    }
    else
    {
        // CODE
    }
}
</code>```

答:
```<code>public static Boolean IsTimeBetween(DateTime refer, DateTime begin, DateTime end, Boolean inclusive = true)
{
    DateTime from = new DateTime(refer.Year, refer.Month, refer.Day, begin.Hour, begin.Minute, begin.Second, begin.Millisecond);
    DateTime to = new DateTime(refer.Year, refer.Month, refer.Day, end.Hour, end.Minute, end.Second, end.Millisecond);

    if (inclusive)
        return ((from <= refer) && (to >= refer));

    return ((from < refer) && (to > refer));
}
</code>```

This will never get you wrong:

```<code>Boolean between = IsTimeBetween(CurrentTime, StartTime, StopTime);
</code>```

Body:
In the code below, only the else part is ever getting executed. What should I do to execute the if part?

private void Form_Load(object sender, EventArgs e)
{
    // Current Time is 11:47:00 AM
    DateTime CurrentTime = System.DateTime.Now;
    DateTime StartTime = Convert.ToDateTime("10:15:00 AM");
    DateTime Stoptime = Convert.ToDateTime("02:29:57 PM");
    DateTime CloseTime = Convert.ToDateTime("02:59:57 PM");

    if (StartTime > CurrentTime && CurrentTime < Stoptime)
    {
        // CODE
    }
    else
    {
        // CODE
    }
}

Body:
public static Boolean IsTimeBetween(DateTime refer, DateTime begin, DateTime end, Boolean inclusive = true)
{
    DateTime from = new DateTime(refer.Year, refer.Month, refer.Day, begin.Hour, begin.Minute, begin.Second, begin.Millisecond);
    DateTime to = new DateTime(refer.Year, refer.Month, refer.Day, end.Hour, end.Minute, end.Second, end.Millisecond);

    if (inclusive)
        return ((from <= refer) && (to >= refer));

    return ((from < refer) && (to > refer));
}

This will never get you wrong:

Boolean between = IsTimeBetween(CurrentTime, StartTime, StopTime);


问:
Groovy: Check if text contains a string more than one time
I want to check if the word "test" appears more than 1 time in the logs.
The following code just checks if the word 'test' appears more than 0 times in the string. (it just checks if the logs contain the word).

```<code> if (env.logs.contains('test')) {
      xxx
}
</code>```

What do I have to change to let this part of code check for more than one appearances of the word test?

答:
Using matcher:</p>

```<code>def match = (env.logs =~ /test/)
assert match.size() > 1
</code>```

Body:
I want to check if the word "test" appears more than 1 time in the logs.
The following code just checks if the word 'test' appears more than 0 times in the string. (it just checks if the logs contain the word).

 if (env.logs.contains('test')) {
      xxx
}

What do I have to change to let this part of code check for more than one appearances of the word test?

Body:
Using matcher:

def match = (env.logs =~ /test/)
assert match.size() > 1


问:
How can I select a record from MySQL that is older than 10min?
How do I select a record from MySQL that is older than 10min?</p>

答: SELECT record FROM act_0223 WHERE valid < NOW() - INTERVAL 10 MINUTE

ContentLicense: CC BY-SA 4.0


问:
What is a spring service annotation?
I understand that @Service is used to mark a class as a business logic class. Why is it useful for spring? I can already use @Component to mark a class as a bean. I understand that @Service is more specific than @Component, but how?

答:
Consider @Component annotation as a Swiss Knife.  It can act as cutting knife, as an opener, as a scissor, etc.

Similarly, your Component can act as a Repository, as Business Logic class or as a controller.

Now, @Service is a just one of the versions of @Component, say a knife.

Spring process @Service similar to @Component, since @Service interface itself is annotated with @Component.

From Spring docs.:

```<code>@Target(value=TYPE)
@Retention(value=RUNTIME)
@Documented
@Component
public @interface Service
</code>```

Indicates that an annotated class is a "Service" (e.g. a business
  service facade).

Why to differentiate both of them?

To apply the basic rule of programming: Your code should be easily readable.

Yes, you can use @Component annotation everywhere and it will work fine but for the better understanding of the code, it is preferred to use the respective special types of annotations like @Service in our case.

The other benefit is ease of debugging. Once you know the error, you need not hope from one component class to another, checking it time whether that class is service, repository or controller.

Title: What is a spring service annotation?

Body:
Consider @Component annotation as a Swiss Knife.  It can act as cutting knife, as an opener, as a scissor, etc.

Similarly, your Component can act as a Repository, as Business Logic class or as a controller.

Now, @Service is a just one of the versions of @Component, say a knife.

Spring process @Service similar to @Component, since @Service interface itself is annotated with @Component.

From Spring docs.:

@Target(value=TYPE)
@Retention(value=RUNTIME)
@Documented
@Component
public @interface Service

Indicates that an annotated class is a "Service" (e.g. a business
  service facade).

Why to differentiate both of them?

To apply the basic rule of programming: Your code should be easily readable.

Yes, you can use @Component annotation everywhere and it will work fine but for the better understanding of the code, it is preferred to use the respective special types of annotations like @Service in our case.

The other benefit is ease of debugging. Once you know the error, you need not hope from one component class to another, checking it time whether that class is service, repository or controller.


问:
Find the longest array within an object (within another object) in javascript
I have an object of objects. Within those objects are arrays, that have more objects.
Below is the structure.

I want to find out what the longest array of objects is within the parent object.
So in my example below:

For ObjectOne - the longest array is B.

For ObjectTwo, the longest array is C.

```<code>mainobj = {
    ObjectOne: {
        A: [
             { x: 'd', y: 'e'},
             { x: 'd', y: 2}
           ],
        B: [
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'}
           ],
        C: [
             { x: 'd', y: 'e'}
           ]
    },
    ObjectTwo:{
        A: [
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'}
           ],
        B: [
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'}
           ],
        C: [
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'}
           ]
    }
}
</code>```

I can do this:

```<code>var size = Object.values(mainobj).length
</code>```

but I don't know how to get deeper than that. For instance, this doesn't work:

```<code>var size = Object.values(mainobj)[0].length
</code>```

This question is pretty similar, but I can't figure out how to apply it.
I appreciate the help!

答:
You can convert your objet to keep only arrays which have the max length:

var    mainObj =   {
                    1:{
                            A: [
                                        { x: 'd', y: 'e'},
                                        { x: 'd', y: 2}
                                    ],
                            B: [
                                        { x: 'd', y: 'e'},
                                        { x: 'd', y: 'e'},
                                        { x: 'd', y: 'e'},
                                        { x: 'd', y: 'e'}
                                    ],
                            C: [
                                        { x: 'd', y: 'e'}
                                    ]
                        },
                    2:{
                            A: [
                                        { x: 'd', y: 'e'},
                                        { x: 'd', y: 'e'},
                                        { x: 'd', y: 'e'}
                                    ],
                            B: [
                                        { x: 'd', y: 'e'},
                                        { x: 'd', y: 'e'}
                                    ],
                            C: [
                                        { x: 'd', y: 'e'},
                                        { x: 'd', y: 'e'},
                                        { x: 'd', y: 'e'},
                                        { x: 'd', y: 'e'},
                                        { x: 'd', y: 'e'}
                                    ]
                        }
                };

var res = {};

Object.keys(mainObj).forEach(key => {
    var maxLength = 0, nameOfmaxLenghtArray, maxLenghtArray;
    Object.keys(mainObj[key]).forEach(arrayName => {
        if (mainObj[key][arrayName].length > maxLength) {
            maxLengthArrayName = arrayName;
            maxLenghtArray = mainObj[key][arrayName];
            maxLength = mainObj[key][arrayName].length;
        }
    });
    res[key] = { [maxLengthArrayName ]: maxLenghtArray};
});

console.log('res: ', res);

// You can then access the max length array for each sub-object of mainobj:

var subObject = '1';
var maxLengthArrayName = Object.keys(res[subObject])[0];
var maxLengthArray = Object.values(res[subObject])[0];

console.log(`max length array name for sub-object ${subObject}: `, maxLengthArrayName);
console.log(`max length array for sub-object ${subObject}: `, maxLengthArray );```

Body:
I have an object of objects. Within those objects are arrays, that have more objects.
Below is the structure.

I want to find out what the longest array of objects is within the parent object.
So in my example below:

For ObjectOne - the longest array is B.

For ObjectTwo, the longest array is C.

mainobj = {
    ObjectOne: {
        A: [
             { x: 'd', y: 'e'},
             { x: 'd', y: 2}
           ],
        B: [
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'}
           ],
        C: [
             { x: 'd', y: 'e'}
           ]
    },
    ObjectTwo:{
        A: [
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'}
           ],
        B: [
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'}
           ],
        C: [
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'}
           ]
    }
}

I can do this:

var size = Object.values(mainobj).length

but I don't know how to get deeper than that. For instance, this doesn't work:

var size = Object.values(mainobj)[0].length

This question is pretty similar, but I can't figure out how to apply it.
I appreciate the help!


问:
RabbitMQ for IoT using Federated Plugin?
I am confused about RabbitMQ and the federated plugin.  Therefore, I seem unable to set it up to work.

Let's say I have 'n' number of raspberry pi s  (rpi1, rpi2, rpi3... rpin)

I want them all to send messages to a cloud server (c1).

They will have intermittent connections to the internet so I want them all to queue their messages locally before sending to the server.  Then when they come online to send their messages to c1 so that I can retrieve them off a queue.  I want all of the messages to go to one queue.

I set up rabbitmq on all of the hosts.

Here is what I have done:

I configure upstreams on all of the raspberry pi s

```<code>rabbitmqctl set_parameter federation-upstream my-upstream '{"uri":"amqp://user:pwd@c1.foo.com","expires":3600000}'
rabbitmqctl set_policy --apply-to exchanges federate-me "^amq\." '{"federation-upstream-set":"all"}'
</code>```

The exchanges seem to set themselves up on the server

I cannot seem to figure out how to add a message to a rpi queue and have it show up on the server.

What am I missing?

Is federation what I want?

what do I have to do on c1 to get it to take incoming messages and drop them into a queue?

what do I have to do on the rpi s to have them send their messages to the server

Is this a good path for what I am attempting?

Totally lost.  Thanks for your help!!

答:
From the use case you're describing, federation seems like the right path for you.

From the documentation:

The federation plugin uses AMQP 0-9-1 to communicate between brokers, and is designed to tolerate intermittent connectivity.

The issue with your setup is that you've done the configuration on the upstream nodes, while it should be done on the federated node:

A federated exchange links to other exchanges (called upstream exchanges). Logically (see next item), messages published to the upstream exchanges are copied to the federated exchange, as though they were published directly to it. The upstream exchanges do not need to be reconfigured and they do not have to be on the same broker or in the same cluster.

So no action on the rpis, configuration is on c1.

Create an upstream in c1 for each of the rpis

Create a federation upstream set with all the upstreams you have created

Add a policy to link the target exchanges on the rpis to the exchanges on c1, referencing the federation upstream set you have defined (as the "all" one refers to all the upstreams, that could be fitting for your use case of course, just find it cleaner to be specific)

Body:
I am confused about RabbitMQ and the federated plugin.  Therefore, I seem unable to set it up to work.

Let's say I have 'n' number of raspberry pi s  (rpi1, rpi2, rpi3... rpin)

I want them all to send messages to a cloud server (c1).

They will have intermittent connections to the internet so I want them all to queue their messages locally before sending to the server.  Then when they come online to send their messages to c1 so that I can retrieve them off a queue.  I want all of the messages to go to one queue.

I set up rabbitmq on all of the hosts.

Here is what I have done:

I configure upstreams on all of the raspberry pi s

rabbitmqctl set_parameter federation-upstream my-upstream '{"uri":"amqp://user:pwd@c1.foo.com","expires":3600000}'
rabbitmqctl set_policy --apply-to exchanges federate-me "^amq\." '{"federation-upstream-set":"all"}'

The exchanges seem to set themselves up on the server

I cannot seem to figure out how to add a message to a rpi queue and have it show up on the server.

What am I missing?

Is federation what I want?

what do I have to do on c1 to get it to take incoming messages and drop them into a queue?

what do I have to do on the rpi s to have them send their messages to the server

Is this a good path for what I am attempting?

Totally lost.  Thanks for your help!!


问:
How to add pdf_ui_utils in angular 4 typescript project
I'm trying to add text selection in PDFJS using the method renderTextLayer.

Base from this you need to add ui_util.js, though I'm not sure how to add it in an existing Angular 4 Typescript project.

I tried adding it in angular-cli.json like below

```<code>"scripts": [
  "../node_modules/pdfjs-dist/lib/web/ui_utils.js"
]
</code>```

But it doesn't seem to work. Any help will be highly appreciated.

Thanks

答:
Your import to angurla-cli.json looks correct. To use external libraries you also need the typings for the library to make it available in your editor.

For that you have two possibilities:

Import the typings from DefinitelyTyped - if available

Make the library visible in your project by adding some code to typings.d.ts. I have described in a different thread how that can be done.

Hope this helps.

Body:
I'm trying to add text selection in PDFJS using the method renderTextLayer.

Base from this you need to add ui_util.js, though I'm not sure how to add it in an existing Angular 4 Typescript project.

I tried adding it in angular-cli.json like below

"scripts": [
  "../node_modules/pdfjs-dist/lib/web/ui_utils.js"
]

But it doesn't seem to work. Any help will be highly appreciated.

Thanks


问:
How to configure package.json to run eslint script
I am using eslint as a linter for my react project and I would like it to check all of my .js files.

I am able to do this through the script:

```<code>"lint": "eslint back/*.js && eslint backTest/*.js && eslint front/actions/*.js"
</code>```

how can I get it to examine every .js file recursively, something like:

```<code>"lint": "eslint -r *.js"
</code>```

This would save me having to type out each file individually.

答:
eslint . --ext .js to lint files with the .js extension.

The . targets files in the current directory and all subdirectories.

To include other file extensions,
eslint . --ext .js,.jsx or eslint . --ext .js --ext .jsx.

The eslint documentation covers this option.

Body:
I am using eslint as a linter for my react project and I would like it to check all of my .js files.

I am able to do this through the script:

"lint": "eslint back/*.js && eslint backTest/*.js && eslint front/actions/*.js"

how can I get it to examine every .js file recursively, something like:

"lint": "eslint -r *.js"

This would save me having to type out each file individually.


问:
How to get data from two tables of a call (function) double-use true or false?
I have a function, responsible for knowing if a user made the purchase correctly (complete) or if the status of the purchase is (incomplete).

This function is with a single query.

```<code>function checkOrderComplete($con,$id_product,$id_user){
  $res = false; // the default result
  $stmt = $con->prepare("SELECT status FROM order WHERE id_product=? AND id_user=? AND status=? limit 1");
  $stmt->bind_param("iis",$id_product,$id_user,$status);
  $status='complete';
  $stmt->execute();

  $stmt->store_result();

  if ($stmt->num_rows ===1){
    $res = true;
  } else {
    $res = false;
  }
  return $res;

}
</code>```

Now I have added a new table called order_details

```<code>id_order_product  order_date  id_product  quantity  price   id_order
       1             -----          2        1       10.00     18
       2             -----          6        1       50.00     18
</code>```

Order

```<code>id_order id_user  status
  18        3    complete
</code>```

So what I want to achieve is the same functioning of the function you can realize before, it took into account the status of the purchase if it was completed or not, and the id of the product, and the id of the user who made the purchase.

Then perform the following procedure but it shows me errors in the $stmt->bind_param("isi",$id_user,$status,$id_product);

The query:

```<code>$stmt = $con->prepare("SELECT order.status, order.id_user, order_details.id_product FROM order inner join order_details ON order.id_user=? order.status=? order_details.id_product=? LIMIT 1");
</code>```

How do I obtain the same values mentioned from the two tables?

答:
Your JOIN is not not properly formatted.  The way to define a JOIN is to use the ON keyword to define what fields should be equal to perform the JOIN.  Like so:

```<code>SELECT order.status,
       order.id_user,
       order_details.id_product
FROM order
INNER JOIN order_details ON order_details.id_order = order.id_order
WHERE order.id_user = ?
  AND order.status = ?
  AND order_details.id_product = ?
</code>```

Then bind your parameters as required.

Body:
I have a function, responsible for knowing if a user made the purchase correctly (complete) or if the status of the purchase is (incomplete).

This function is with a single query.

function checkOrderComplete($con,$id_product,$id_user){
  $res = false; // the default result
  $stmt = $con->prepare("SELECT status FROM order WHERE id_product=? AND id_user=? AND status=? limit 1");
  $stmt->bind_param("iis",$id_product,$id_user,$status);
  $status='complete';
  $stmt->execute();

  $stmt->store_result();

  if ($stmt->num_rows ===1){
    $res = true;
  } else {
    $res = false;
  }
  return $res;

}

Now I have added a new table called order_details

id_order_product  order_date  id_product  quantity  price   id_order
       1             -----          2        1       10.00     18
       2             -----          6        1       50.00     18

Order

id_order id_user  status
  18        3    complete

So what I want to achieve is the same functioning of the function you can realize before, it took into account the status of the purchase if it was completed or not, and the id of the product, and the id of the user who made the purchase.

Then perform the following procedure but it shows me errors in the $stmt->bind_param("isi",$id_user,$status,$id_product);

The query:

$stmt = $con->prepare("SELECT order.status, order.id_user, order_details.id_product FROM order inner join order_details ON order.id_user=? order.status=? order_details.id_product=? LIMIT 1");

How do I obtain the same values mentioned from the two tables?

Body:
Your JOIN is not not properly formatted.  The way to define a JOIN is to use the ON keyword to define what fields should be equal to perform the JOIN.  Like so:

SELECT order.status,
       order.id_user,
       order_details.id_product
FROM order
INNER JOIN order_details ON order_details.id_order = order.id_order
WHERE order.id_user = ?
  AND order.status = ?
  AND order_details.id_product = ?

Then bind your parameters as required.