问:
How to append Function directly to ID in jQuery?
I have one form where I have to display the same table thead multiple times. I thought a solution would be to write the thead in single function and call that function wherever I want in my project. For this I write one function:

```<code>function commonStructure() {
  return append('<thead>
    <tr>name</tr>
    <tr><address></tr>');
  }
</code>```

I am trying to call this function like:

```<code>$('#classA').commonStructure();
</code>```

This is not working for me. Please help me for the same issue.

答:
Your commonStructure function has nothing to do with jQuery. If you want to call it on a jQuery object you need to create it as a plugin. From there you need to amend your append() function to work on the element(s) contained in the jQuery object. If all you're doing is adding the content to the DOM, then you can use jQuery's own append() method - although prepend() would make more sense as you're attempting to create a header.

It's also worth noting that JS strings cannot contain line breaks. Either concatenate them over multiple lines or use template literals (as in the following example). In addition, your HTML is invalid. The content of the thead needs to be placed in td cells within the tr.

Putting it all together it should look something like this:

$.fn.commonStructure = function() {
  return this.prepend(`

name

address

`);
};

$('.foo').commonStructure();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table class="foo"></table>
<table class="foo"></table></code>```

Body:
I have one form where I have to display the same table thead multiple times. I thought a solution would be to write the thead in single function and call that function wherever I want in my project. For this I write one function:

function commonStructure() {
  return append('

name

<address>
');
  }

I am trying to call this function like:

$('#classA').commonStructure();

This is not working for me. Please help me for the same issue.

Body:
Your commonStructure function has nothing to do with jQuery. If you want to call it on a jQuery object you need to create it as a plugin. From there you need to amend your append() function to work on the element(s) contained in the jQuery object. If all you're doing is adding the content to the DOM, then you can use jQuery's own append() method - although prepend() would make more sense as you're attempting to create a header.

It's also worth noting that JS strings cannot contain line breaks. Either concatenate them over multiple lines or use template literals (as in the following example). In addition, your HTML is invalid. The content of the thead needs to be placed in td cells within the tr.

Putting it all together it should look something like this:

$.fn.commonStructure = function() {
  return this.prepend(`<thead>
    <tr><td>name</td></tr>
    <tr><td>address</td></tr>
  </thead>`);
};

$('.foo').commonStructure();

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table class="foo"></table>
<table class="foo"></table>


来源: stackexchange

问:
Xml Root.add value with Special Character( :)
I have an XML file
which is

```<code><?xml version="1.0" encoding="utf-8"?>
<urlset >

</urlset>
</code>```

I'm trying to add an XElement with special characters (:) code behind

```<code>string xmlpath = @"~/myxml.xml";
string path = Server.MapPath(xmlpath);
string title="SomeString"
XDocument doc = XDocument.Load(path);
XElement root = new XElement("url");
root.Add(new XElement("Video:title", "title"));//here is the problem i have Special char (:) which not allowed
doc.Element("urlset").Add(root);
</code>```

also i can't use &qoute; becuse it's contniue special char & Please i need help if any one can help i would be thankful thanks a lot for your time guys and thank a lot for giving time to read my queation

答:
I'm trying to add an XElement with special characters (:) code behind

Try using a XmlDocument which will allow creating an XmlElement with specified name and namespace.

```<code> string xmlpath = @"~/myxml.xml";
 string path = Server.MapPath(xmlpath);
 XmlDocument doc = new XmlDocument();

 doc.Load(path);
 var mainRoot = doc.DocumentElement; //urlset element
 var urlRoot = doc.CreateElement("url"); //create url element
 urlRoot.AppendChild(doc.CreateElement("Video:title","title")); //add element to the url element
 mainRoot.AppendChild(urlRoot); // add this new element to the main root of urlset
</code>```

Example Output:

```<code><?xml version="1.0" encoding="utf-8"?>
<urlset>
  <url>
    <Video:title xmlns:Video="title" />
  </url>
</urlset>
</code>```

Or if you just want a Video node with namespace of title...

```<code> urlRoot.AppendChild(doc.CreateElement("Video","title"));
</code>```

The output of this above:

```<code><?xml version="1.0" encoding="utf-8"?>
<urlset>
  <url>
    <Video xmlns="title"/>
  </url>
</urlset>
</code>```

Please let me know if this isn't your expected output.

ContentLicense: CC BY-SA 4.0

Body:
I have an XML file
which is

<?xml version="1.0" encoding="utf-8"?>
<urlset >

</urlset>

I'm trying to add an XElement with special characters (:) code behind

string xmlpath = @"~/myxml.xml";
string path = Server.MapPath(xmlpath);
string title="SomeString"
XDocument doc = XDocument.Load(path);
XElement root = new XElement("url");
root.Add(new XElement("Video:title", "title"));//here is the problem i have Special char (:) which not allowed
doc.Element("urlset").Add(root);

also i can't use &qoute; becuse it's contniue special char & Please i need help if any one can help i would be thankful thanks a lot for your time guys and thank a lot for giving time to read my queation

Body:
I'm trying to add an XElement with special characters (:) code behind

Try using a XmlDocument which will allow creating an XmlElement with specified name and namespace.

 string xmlpath = @"~/myxml.xml";
 string path = Server.MapPath(xmlpath);
 XmlDocument doc = new XmlDocument();

 doc.Load(path);
 var mainRoot = doc.DocumentElement; //urlset element
 var urlRoot = doc.CreateElement("url"); //create url element
 urlRoot.AppendChild(doc.CreateElement("Video:title","title")); //add element to the url element
 mainRoot.AppendChild(urlRoot); // add this new element to the main root of urlset

Example Output:

<?xml version="1.0" encoding="utf-8"?>
<urlset>
  <url>
    <Video:title xmlns:Video="title" />
  </url>
</urlset>

Or if you just want a Video node with namespace of title...

 urlRoot.AppendChild(doc.CreateElement("Video","title"));

The output of this above:

<?xml version="1.0" encoding="utf-8"?>
<urlset>
  <url>
    <Video xmlns="title"/>
  </url>
</urlset>

Please let me know if this isn't your expected output.


问:
MYSQL - Update row number for each group
I am trying to update the column sip_count so that it counts the number of rows with the same sip_id as shown below. None of the things that I have tried are worth posting. How do I do this?

Table

```<code>sip_id | sip   | sip_count
---------------------------
 1      |  1    | 2
 1      |  1    | 2
 2      |  1    | 3
 2      |  1    | 3
 2      |  1    | 3
 4      |  1    | 2
 4      |  1    | 2
 3      |  1    | 3
 3      |  1    | 3
 3      |  1    | 3
</code>```

Desired result

```<code> sip_id | sip   | sip_count
---------------------------
 1      |  1    | 1
 1      |  1    | 2
 2      |  1    | 1
 2      |  1    | 2
 2      |  1    | 3
 4      |  1    | 1
 4      |  1    | 2
 3      |  1    | 1
 3      |  1    | 2
 3      |  1    | 3
</code>```

Body:
I am trying to update the column sip_count so that it counts the number of rows with the same sip_id as shown below. None of the things that I have tried are worth posting. How do I do this?

Table

sip_id | sip   | sip_count
---------------------------
 1      |  1    | 2
 1      |  1    | 2
 2      |  1    | 3
 2      |  1    | 3
 2      |  1    | 3
 4      |  1    | 2
 4      |  1    | 2
 3      |  1    | 3
 3      |  1    | 3
 3      |  1    | 3

Desired result

 sip_id | sip   | sip_count
---------------------------
 1      |  1    | 1
 1      |  1    | 2
 2      |  1    | 1
 2      |  1    | 2
 2      |  1    | 3
 4      |  1    | 1
 4      |  1    | 2
 3      |  1    | 1
 3      |  1    | 2
 3      |  1    | 3

Body:
With mysql 8 you can use window function

SELECT
 `sip_id`, `sip`,
ROW_NUMBER() OVER(PARTITION BY `sip_id`) AS 'sip_count'
FROM sip_count

CREATE TABLE sip_count (
  `sip_id` INTEGER,
  `sip` INTEGER,
  `sip_count` INTEGER
);

INSERT INTO sip_count
  (`sip_id`, `sip`, `sip_count`)
VALUES
  ('1', '1', '2'),
  ('1', '1', '2'),
  ('2', '1', '3'),
  ('2', '1', '3'),
  ('2', '1', '3'),
  ('4', '1', '2'),
  ('4', '1', '2'),
  ('3', '1', '3'),
  ('3', '1', '3'),
  ('3', '1', '3');

✓

✓

SELECT
 `sip_id`, `sip`,
ROW_NUMBER() OVER(PARTITION BY `sip_id`) AS 'sip_count'
FROM sip_count

sip_id | sip | sip_count
-----: | --: | --------:
     1 |   1 |         1
     1 |   1 |         2
     2 |   1 |         1
     2 |   1 |         2
     2 |   1 |         3
     3 |   1 |         1
     3 |   1 |         2
     3 |   1 |         3
     4 |   1 |         1
     4 |   1 |         2

db<>fiddle here


问:
Install dll into the gac + .net 4.0
I want to add some .net 4.0 dlls to the gac, I know that the new gac is C:\Windows\Microsoft.NET\assembly

I cannot use the gacutil because visual studio in not installed on the deployment machine, and i cannot simply drag/drop the dll to the folder as i usually do in the previous versions.

How can I install the dlls to the GAC.

答:
It is part of Windows SDK and can be download separately at http://www.microsoft.com/downloads/en/details.aspx?FamilyID=6B6C21D2-2006-4AFA-9702-529FA782D63B. This installation will have gacutil.exe included. But first check it here: C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin you might have it installed

where is gacutil.exe?

UPDATE : Modified the link. Windows SDK for .Net 4.0

ContentLicense: CC BY-SA 3.0

Title: Install dll into the gac + .net 4.0


问:
What is neo4j closest feature to sql stored functions?
I'm new to neo4j and graph databases in general.

Given a complex Cypher query, that I don't want to store inside the application (or several applications), but keep centralized, what options are left to me?

In a SQL database I would use a stored function. Are UDF function the way to go in neo4j?
From the docs it seems to me that they're more a way to extend the database functionality by being able to access the graph internals, but I've just started studying them.

答:
Take a look at the custom functions and procedures available in the apoc library.

https://neo4j.com/docs/labs/apoc/current/cypher-execution/cypher-based-procedures-functions/

```<code>CALL apoc.custom.asProcedure('answer','RETURN 42 as answer')
</code>```

```<code>CALL custom.answer() YIELD row RETURN row.answer
</code>```

Body:
Take a look at the custom functions and procedures available in the apoc library.

https://neo4j.com/docs/labs/apoc/current/cypher-execution/cypher-based-procedures-functions/

CALL apoc.custom.asProcedure('answer','RETURN 42 as answer')

CALL custom.answer() YIELD row RETURN row.answer


问:
How to run a (insert) stored procedure without a entity class?
I am writing some code for my Spring Boot application and I am trying to incorporate a stored procedure. However, I am trying to find a way to run a insert Stored Procedure without needing an entity class. I have tried some ways before but I keep getting errors like java.lang.IllegalArgumentException: No @NamedStoredProcedureQuery was found with that name : InsertGPIP but I know it is because there is no entity associated with it.

Java:

```<code>    public void insertToGPIP(){

            StoredProcedureQuery query = entityManager.createNamedStoredProcedureQuery("InsertGPIP")
            .registerStoredProcedureParameter("appcode", String.class, ParameterMode.IN)
            .registerStoredProcedureParameter("guid", String.class, ParameterMode.IN)
            .registerStoredProcedureParameter("name", String.class, ParameterMode.IN)
            .registerStoredProcedureParameter("statuscode", String.class, ParameterMode.IN)
            .registerStoredProcedureParameter("assist", String.class, ParameterMode.IN)
            .registerStoredProcedureParameter("adid", String.class, ParameterMode.IN)
            .setParameter("appcode", "Rob")
            .setParameter("guid", "F38FJ47")
            .setParameter("name", "A Test")
            .setParameter("statuscode", "02")
            .setParameter("assist", "N")
            .setParameter("adid", "MyId");
            query.execute();

        }
</code>```

答:
From the NamedStoreProcedureQuery javadoc (bold is mine):

The NamedStoredProcedureQuery annotation can be applied to an entity
  or mapped superclass.

A mapped superclass has no table defined for it, only provides mapping information to be inherited by enties that extend it.

So you could have an empty abstract mapped superclass (@MappedSuperclass) as a container for the NamedStoredProcedureQuery annotations.

Body:
I am writing some code for my Spring Boot application and I am trying to incorporate a stored procedure. However, I am trying to find a way to run a insert Stored Procedure without needing an entity class. I have tried some ways before but I keep getting errors like java.lang.IllegalArgumentException: No @NamedStoredProcedureQuery was found with that name : InsertGPIP but I know it is because there is no entity associated with it.

Java:

    public void insertToGPIP(){

            StoredProcedureQuery query = entityManager.createNamedStoredProcedureQuery("InsertGPIP")
            .registerStoredProcedureParameter("appcode", String.class, ParameterMode.IN)
            .registerStoredProcedureParameter("guid", String.class, ParameterMode.IN)
            .registerStoredProcedureParameter("name", String.class, ParameterMode.IN)
            .registerStoredProcedureParameter("statuscode", String.class, ParameterMode.IN)
            .registerStoredProcedureParameter("assist", String.class, ParameterMode.IN)
            .registerStoredProcedureParameter("adid", String.class, ParameterMode.IN)
            .setParameter("appcode", "Rob")
            .setParameter("guid", "F38FJ47")
            .setParameter("name", "A Test")
            .setParameter("statuscode", "02")
            .setParameter("assist", "N")
            .setParameter("adid", "MyId");
            query.execute();

        }


问:
SwiftUI action when press on NavigationLink
I have a NavigationView with many NavigationLinks in SwiftUI for Mac.

Whenever I press a Navigation Item, the Navigation Detail is being displayed on the right. However, I have a custom styling for my active Navigation Items. When I press a Item, I want to call an action. I have tried onTapGesture() function on the NavigationLink, however it is not working correctly/ as expected.

Here is my code:

```<code> NavigationView {
        VStack{

            NavigationLink(destination: SecondContentView()) {
            VStack
            {
                Image("Calendar")
                    .resizable().frame(width:40, height: 40)
                    .colorMultiply(currentSelected == 0 ? Color(red: 57 / 255, green: 214 / 255, blue: 155 / 255) : Color(red: 255 / 255, green: 255 / 255, blue: 255 / 255))
                Text("Dates")
                    .foregroundColor(currentSelected == 0 ? Color(red: 57 / 255, green: 214 / 255, blue: 155 / 255) : Color(red: 255 / 255, green: 255 / 255, blue: 255 / 255))

            }
         }
         .buttonStyle(PlainButtonStyle())
         .padding(18)
         .background(currentSelected == 0 ? Color(.controlBackgroundColor) : Color(.clear))
         .zIndex(50)
         .onTapGesture {
            NSLog("Tapped Nav")
            self.currentSelected = 0
         }
</code>```

The log "Tapped Nav" is only output sometimes.. I think there is a problem with the image and text which is inside a navigation item. Is there a better way to call an action function, when I click on the item?

答:
Take in the account, that navigation link could be activated without
any "tap", programmatically, or from action menu etc.

If you have more than one navigation link, use the proper
initializer, which gives you some oportunity to do what you want to do

Currently we have three different initializers, especially the third one could help in your case.

```<code>/// A view that controls a navigation presentation.
@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
public struct NavigationLink<Label, Destination> : View where Label : View, Destination : View {

    /// Creates an instance that presents `destination`.
    public init(destination: Destination, @ViewBuilder label: () -> Label)

    /// Creates an instance that presents `destination` when active.
    public init(destination: Destination, isActive: Binding<Bool>, @ViewBuilder label: () -> Label)

    /// Creates an instance that presents `destination` when `selection` is set
    /// to `tag`.
    public init<V>(destination: Destination, tag: V, selection: Binding<V?>, @ViewBuilder label: () -> Label) where V : Hashable

    /// Declares the content and behavior of this view.
    public var body: some View { get }

    /// The type of view representing the body of this view.
    ///
    /// When you create a custom view, Swift infers this type from your
    /// implementation of the required `body` property.
    public typealias Body = some View
}
</code>```

The working example shows you, how to use it for "custom styling", but this could be extended for any use case (see the print out on debug window)

```<code>import SwiftUI

class Model: ObservableObject {
    @Published var selection: Int? {
        willSet {
            if let nv = newValue {
                selected = nv
                willChangeSelection?(selected)
            }
        }
    }
    var selected: Int = 0
    let willChangeSelection: ((Int) -> Void)?
    init( onSelection: ((Int)->Void)? ) {
        willChangeSelection = onSelection
        selection = 1
    }
}

struct ContentView: View {
    @ObservedObject var model = Model { i in
        print("selected:", i)
    }
    var body: some View {

        NavigationView {
            List {
                NavigationLink(destination: Detail(txt: "First"), tag: 1, selection: $model.selection) {
                    RowLabel(txt: "First", tag: 1, selected: model.selected)
                }
                NavigationLink(destination: Detail(txt: "Second"), tag: 2, selection: $model.selection) {
                    RowLabel(txt: "Second", tag: 2, selected: model.selected)
                }
                NavigationLink(destination: Detail(txt: "Third"), tag: 3, selection: $model.selection) {
                    RowLabel(txt: "Third", tag: 3, selected: model.selected)
                }
            }
            .frame(width: 200, height: 300)
            Detail(txt: "First")
        }.frame(width: 500)
    }
}

struct Detail: View {
    let txt: String
    var body: some View {
        VStack {
            Text(self.txt).font(.largeTitle)
        }.frame(width: 300)
    }
}

struct RowLabel: View {
    let txt: String
    let tag: Int
    let selected: Int
    var body: some View {
        Text(txt)
            .font(selected == tag ? .largeTitle: .footnote).padding(.leading, 10)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
</code>```

The resulting sample application in action

Body:
I have a NavigationView with many NavigationLinks in SwiftUI for Mac.

Whenever I press a Navigation Item, the Navigation Detail is being displayed on the right. However, I have a custom styling for my active Navigation Items. When I press a Item, I want to call an action. I have tried onTapGesture() function on the NavigationLink, however it is not working correctly/ as expected.

Here is my code:

 NavigationView {
        VStack{

            NavigationLink(destination: SecondContentView()) {
            VStack
            {
                Image("Calendar")
                    .resizable().frame(width:40, height: 40)
                    .colorMultiply(currentSelected == 0 ? Color(red: 57 / 255, green: 214 / 255, blue: 155 / 255) : Color(red: 255 / 255, green: 255 / 255, blue: 255 / 255))
                Text("Dates")
                    .foregroundColor(currentSelected == 0 ? Color(red: 57 / 255, green: 214 / 255, blue: 155 / 255) : Color(red: 255 / 255, green: 255 / 255, blue: 255 / 255))

            }
         }
         .buttonStyle(PlainButtonStyle())
         .padding(18)
         .background(currentSelected == 0 ? Color(.controlBackgroundColor) : Color(.clear))
         .zIndex(50)
         .onTapGesture {
            NSLog("Tapped Nav")
            self.currentSelected = 0
         }

The log "Tapped Nav" is only output sometimes.. I think there is a problem with the image and text which is inside a navigation item. Is there a better way to call an action function, when I click on the item?

Body:
Take in the account, that navigation link could be activated without
any "tap", programmatically, or from action menu etc.

If you have more than one navigation link, use the proper
initializer, which gives you some oportunity to do what you want to do

Currently we have three different initializers, especially the third one could help in your case.

/// A view that controls a navigation presentation.
@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
public struct NavigationLink<Label, Destination> : View where Label : View, Destination : View {

    /// Creates an instance that presents `destination`.
    public init(destination: Destination, @ViewBuilder label: () -> Label)

    /// Creates an instance that presents `destination` when active.
    public init(destination: Destination, isActive: Binding<Bool>, @ViewBuilder label: () -> Label)

    /// Creates an instance that presents `destination` when `selection` is set
    /// to `tag`.
    public init<V>(destination: Destination, tag: V, selection: Binding<V?>, @ViewBuilder label: () -> Label) where V : Hashable

    /// Declares the content and behavior of this view.
    public var body: some View { get }

    /// The type of view representing the body of this view.
    ///
    /// When you create a custom view, Swift infers this type from your
    /// implementation of the required `body` property.
    public typealias Body = some View
}

The working example shows you, how to use it for "custom styling", but this could be extended for any use case (see the print out on debug window)

import SwiftUI

class Model: ObservableObject {
    @Published var selection: Int? {
        willSet {
            if let nv = newValue {
                selected = nv
                willChangeSelection?(selected)
            }
        }
    }
    var selected: Int = 0
    let willChangeSelection: ((Int) -> Void)?
    init( onSelection: ((Int)->Void)? ) {
        willChangeSelection = onSelection
        selection = 1
    }
}

struct ContentView: View {
    @ObservedObject var model = Model { i in
        print("selected:", i)
    }
    var body: some View {

        NavigationView {
            List {
                NavigationLink(destination: Detail(txt: "First"), tag: 1, selection: $model.selection) {
                    RowLabel(txt: "First", tag: 1, selected: model.selected)
                }
                NavigationLink(destination: Detail(txt: "Second"), tag: 2, selection: $model.selection) {
                    RowLabel(txt: "Second", tag: 2, selected: model.selected)
                }
                NavigationLink(destination: Detail(txt: "Third"), tag: 3, selection: $model.selection) {
                    RowLabel(txt: "Third", tag: 3, selected: model.selected)
                }
            }
            .frame(width: 200, height: 300)
            Detail(txt: "First")
        }.frame(width: 500)
    }
}

struct Detail: View {
    let txt: String
    var body: some View {
        VStack {
            Text(self.txt).font(.largeTitle)
        }.frame(width: 300)
    }
}

struct RowLabel: View {
    let txt: String
    let tag: Int
    let selected: Int
    var body: some View {
        Text(txt)
            .font(selected == tag ? .largeTitle: .footnote).padding(.leading, 10)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

The resulting sample application in action


问:
How can I dynamically build a string and pass it to dplyr's mutate() function in R?
I asked a similar question before (Link). The given answer works fine. However, it turns out, that it does not fully apply to my use case.

Please consider the following minimal working example:

```<code>library(RSQLite)
library(dplyr)
library(dbplyr)
library(DBI)
library(stringr)

con <- DBI::dbConnect(RSQLite::SQLite(), path = ":memory:")

copy_to(con, mtcars, "mtcars", temporary = FALSE)

db <- tbl(con, "mtcars") %>%
    select(carb) %>%
    distinct(carb) %>%
    arrange(carb) %>%
    mutate(Q1=1, Q2=2, Q3=3, Q4=4) %>%
    collect()
</code>```

I am interested in dynamically building the string Q1=1, Q2=2, Q3=3, Q4=4 such that it could be Q1=1, Q2=2, ..., Qn = n.

One idea I had is to build the string like that:

```<code>n_par <- 4
str_c('Q', 1:n_par, ' = ', 1:n_par, collapse = ', ')
</code>```

such that n_par could be any positive number. However, due to dplyr's non-standard evaluation, I cannot make it work like that. However, this is exactly what I need.

Can somebody help?

答:
I recently read more about the topic and I found that the following code works quite nicely, causing dbplyr to write a cleaner SQL code.

```<code># Libraries

library(RSQLite)
library(dplyr)
library(dbplyr)
library(DBI)

# Example database

con <- DBI::dbConnect(RSQLite::SQLite(), path = ":memory:")

copy_to(con, mtcars, "mtcars", temporary = FALSE)

# Parameter for number of variables to be created

n <- 4

# Variable list

var <- list()
for(i in 1:n){
    j <- paste0("Q", i)
    var[[j]] <- i
}

# Query/computation

db <- tbl(con, "mtcars") %>%
    select(carb) %>%
    distinct(carb) %>%
    arrange(carb) %>%
    mutate(!!! var) %>%
    show_query() %>%
    collect()
</code>```

The trick was to build a list with proper names and to put it into the mutate() function using !!!. Furthermore, I read that parsing and evaluating strings should be avoided, so I switched to lists.

Body:
I asked a similar question before (Link). The given answer works fine. However, it turns out, that it does not fully apply to my use case.

Please consider the following minimal working example:

library(RSQLite)
library(dplyr)
library(dbplyr)
library(DBI)
library(stringr)

con <- DBI::dbConnect(RSQLite::SQLite(), path = ":memory:")

copy_to(con, mtcars, "mtcars", temporary = FALSE)

db <- tbl(con, "mtcars") %>%
    select(carb) %>%
    distinct(carb) %>%
    arrange(carb) %>%
    mutate(Q1=1, Q2=2, Q3=3, Q4=4) %>%
    collect()

I am interested in dynamically building the string Q1=1, Q2=2, Q3=3, Q4=4 such that it could be Q1=1, Q2=2, ..., Qn = n.

One idea I had is to build the string like that:

n_par <- 4
str_c('Q', 1:n_par, ' = ', 1:n_par, collapse = ', ')

such that n_par could be any positive number. However, due to dplyr's non-standard evaluation, I cannot make it work like that. However, this is exactly what I need.

Can somebody help?

Body:
I recently read more about the topic and I found that the following code works quite nicely, causing dbplyr to write a cleaner SQL code.

# Libraries

library(RSQLite)
library(dplyr)
library(dbplyr)
library(DBI)

# Example database

con <- DBI::dbConnect(RSQLite::SQLite(), path = ":memory:")

copy_to(con, mtcars, "mtcars", temporary = FALSE)

# Parameter for number of variables to be created

n <- 4

# Variable list

var <- list()
for(i in 1:n){
    j <- paste0("Q", i)
    var[[j]] <- i
}

# Query/computation

db <- tbl(con, "mtcars") %>%
    select(carb) %>%
    distinct(carb) %>%
    arrange(carb) %>%
    mutate(!!! var) %>%
    show_query() %>%
    collect()

The trick was to build a list with proper names and to put it into the mutate() function using !!!. Furthermore, I read that parsing and evaluating strings should be avoided, so I switched to lists.


问:
MFMailComposeViewController csv attachment not being attached, but showing inline instead
I am having a problem with sending csv attachments via MFMailComposeViewController.
Sometimes they come through just fine, but for other users they don't come through as attachments, but rather as text inline in the email (with
 instead of line returns.)  It's very strange.  Anybody know what I'm doing wrong?
Here is a snippet of my code:

```<code>MFMailComposeViewController *mailComposeViewController = [[MFMailComposeViewController alloc] init];
mailComposeViewController.mailComposeDelegate = self;

NSString *csv = @"foo,bar,blah,hello";
NSData *csvData = [csv dataUsingEncoding:NSUTF8StringEncoding];
[mailComposeViewController addAttachmentData:csvData mimeType:@"text/csv" fileName:@"testing.csv"];

[mailComposeViewController setSubject:@"testing sending csv attachment"];
[mailComposeViewController setMessageBody:@"csv file should be attached" isHTML:NO];
[self presentModalViewController:mailComposeViewController animated:YES];
</code>```

答:
Hi I put sample code for Creating CSV file and attach it with mail but make sure you have to add MessageUI.Framework and import its related header "MessageUI/MessageUI.h"
"MessageUI/MFMailComposeViewController.h" and deligate "MFMailComposeViewControllerDelegate"...I hope this wl useful for others  </p>

```<code>- (void)viewDidLoad {

arrCsv=[[NSArray alloc]initWithObjects:@"Hello",@"Hi",@"traun",@"fine",nil];
NSArray *paths = NSSearchPathForDirectoriesInDomains

(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *fileName = [NSString stringWithFormat:@"%@/try.csv", documentsDirectory];

[[arrCsv componentsJoinedByString:@","] writeToFile:fileName atomically:YES encoding:NSUTF8StringEncoding error:NULL];

 }

-(ibAction)btnMail   {

 NSArray *arrayPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *docDir = [arrayPaths objectAtIndex:0];
NSString *Path = [docDir stringByAppendingString:@"/CSVFile.csv"];
NSData *csvData = [NSData dataWithContentsOfFile:Path];
MFMailComposeViewController *controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
[controller setSubject:@"For csv file..."];
[controller setMessageBody:@"...csv file is hear.." isHTML:NO];
[controller addAttachmentData:csvData mimeType:@"text/csv" fileName:@"CSVFile.csv"];
[self presentModalViewController:controller animated:YES];
[controller release];

}

- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{   message.hidden = NO;
switch (result)
{
    case MFMailComposeResultCancelled:
        message.text = @"Result: canceled";
        break;
    case MFMailComposeResultSaved:
        message.text = @"Result: saved";
        break;
    case MFMailComposeResultSent:
        message.text = @"Result: sent";
        break;
    case MFMailComposeResultFailed:
        message.text = @"Result: failed";
        break;
    default:
        message.text = @"Result: not sent";
        break;
}
[self dismissModalViewControllerAnimated:YES];
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am having a problem with sending csv attachments via MFMailComposeViewController.
Sometimes they come through just fine, but for other users they don't come through as attachments, but rather as text inline in the email (with
 instead of line returns.)  It's very strange.  Anybody know what I'm doing wrong?
Here is a snippet of my code:

MFMailComposeViewController *mailComposeViewController = [[MFMailComposeViewController alloc] init];
mailComposeViewController.mailComposeDelegate = self;

NSString *csv = @"foo,bar,blah,hello";
NSData *csvData = [csv dataUsingEncoding:NSUTF8StringEncoding];
[mailComposeViewController addAttachmentData:csvData mimeType:@"text/csv" fileName:@"testing.csv"];

[mailComposeViewController setSubject:@"testing sending csv attachment"];
[mailComposeViewController setMessageBody:@"csv file should be attached" isHTML:NO];
[self presentModalViewController:mailComposeViewController animated:YES];

Body:
Hi I put sample code for Creating CSV file and attach it with mail but make sure you have to add MessageUI.Framework and import its related header "MessageUI/MessageUI.h"
"MessageUI/MFMailComposeViewController.h" and deligate "MFMailComposeViewControllerDelegate"...I hope this wl useful for others

- (void)viewDidLoad {

arrCsv=[[NSArray alloc]initWithObjects:@"Hello",@"Hi",@"traun",@"fine",nil];
NSArray *paths = NSSearchPathForDirectoriesInDomains

(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *fileName = [NSString stringWithFormat:@"%@/try.csv", documentsDirectory];

[[arrCsv componentsJoinedByString:@","] writeToFile:fileName atomically:YES encoding:NSUTF8StringEncoding error:NULL];

 }

-(ibAction)btnMail   {

 NSArray *arrayPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *docDir = [arrayPaths objectAtIndex:0];
NSString *Path = [docDir stringByAppendingString:@"/CSVFile.csv"];
NSData *csvData = [NSData dataWithContentsOfFile:Path];
MFMailComposeViewController *controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
[controller setSubject:@"For csv file..."];
[controller setMessageBody:@"...csv file is hear.." isHTML:NO];
[controller addAttachmentData:csvData mimeType:@"text/csv" fileName:@"CSVFile.csv"];
[self presentModalViewController:controller animated:YES];
[controller release];

}

- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{   message.hidden = NO;
switch (result)
{
    case MFMailComposeResultCancelled:
        message.text = @"Result: canceled";
        break;
    case MFMailComposeResultSaved:
        message.text = @"Result: saved";
        break;
    case MFMailComposeResultSent:
        message.text = @"Result: sent";
        break;
    case MFMailComposeResultFailed:
        message.text = @"Result: failed";
        break;
    default:
        message.text = @"Result: not sent";
        break;
}
[self dismissModalViewControllerAnimated:YES];
}


问:
Migrate full table to json/clob column in another table
I want to migrate the data from following table1:

NAME | Surname
-----+---------
Name1| Surname1
Name2| Surname2
```

<p>Into <strong>table2</strong>  as a clob (nclob,nvarchar(max),json.. etc.) column:</p>

<pre class="lang-none prettyprint-override"><code>NAME | JSON_COLUMN
-----+-------------------------------
NAME1| {Name: Name1,Surname: Surname1}
NAME2| {Name: Name2,Surname: Surname2}
</code>```

I wonder what is the best way to do this type of migration ?

Is there a function that can convert a table into json format so I can insert it into the new table?

Something like this:

```<code>insert into table2 (JSON_TABLE) select (table1 as json) from table1
</code>```

答:
In Oracle 12c and higher, You will need to convert the column values using JSON_OBJECT and then to CLOB and for proper JSON use FORMAT JSON (SQL string values 'true' and 'false' are converted to the JSON Boolean values true and false.)

Example:

```<code>SQL> WITH TABLE1 AS (
  2      SELECT 'Name1' NAME, 'Surname1' SURNAME FROM DUAL
  3      UNION ALL
  4      SELECT 'Name2', 'Surname2' FROM DUAL
  5  )
  6  SELECT
  7      NAME,
  8      TO_CLOB(JSON_OBJECT ( 'Name' VALUE NAME,
  9                    'Surname' VALUE SURNAME
 10                    FORMAT JSON )) AS "JSON_TABLE"
 11  FROM
 12      TABLE1;

NAME      |JSON_TABLE
----------|--------------------------------------------------
Name1     |{"Name":"Name1","Surname":Surname1}
Name2     |{"Name":"Name2","Surname":Surname2}

SQL>
</code>```

For Oracle 11g and lower, you need to create the JSON by yourself as follows:

```<code>SQL> WITH TABLE1 AS (
  2      SELECT 'Name1' NAME, 'Surname1' SURNAME FROM DUAL
  3      UNION ALL
  4      SELECT 'Name2', 'Surname2' FROM DUAL
  5  )
  6  SELECT
  7      NAME,
  8      to_clob('{"Name:"' || NAME || '","Surname":'||SURNAME || '}') as "JSON_TABLE"
  9  FROM
 10      TABLE1;

NAME      |JSON_TABLE
----------|--------------------------------------------------
Name1     |{"Name:"Name1","Surname":Surname1}
Name2     |{"Name:"Name2","Surname":Surname2}

SQL>
</code>```

Another option in Oracle 11g is to use sql*plus command-line interface as following:

```<code>set sqlformat json
</code>```

and then SELECT * FROM TABLE1 will generate the json format result but you need to export it to some file using spool and then load it into TABLE2. (Might be Lengthy approach)

Cheers!!

Body:
I want to migrate the data from following table1:

NAME | Surname
-----+---------
Name1| Surname1
Name2| Surname2

Into table2  as a clob (nclob,nvarchar(max),json.. etc.) column:

NAME | JSON_COLUMN
-----+-------------------------------
NAME1| {Name: Name1,Surname: Surname1}
NAME2| {Name: Name2,Surname: Surname2}

I wonder what is the best way to do this type of migration ?

Is there a function that can convert a table into json format so I can insert it into the new table?

Something like this:

insert into table2 (JSON_TABLE) select (table1 as json) from table1

Body:
In Oracle 12c and higher, You will need to convert the column values using JSON_OBJECT and then to CLOB and for proper JSON use FORMAT JSON (SQL string values 'true' and 'false' are converted to the JSON Boolean values true and false.)

Example:

SQL> WITH TABLE1 AS (
  2      SELECT 'Name1' NAME, 'Surname1' SURNAME FROM DUAL
  3      UNION ALL
  4      SELECT 'Name2', 'Surname2' FROM DUAL
  5  )
  6  SELECT
  7      NAME,
  8      TO_CLOB(JSON_OBJECT ( 'Name' VALUE NAME,
  9                    'Surname' VALUE SURNAME
 10                    FORMAT JSON )) AS "JSON_TABLE"
 11  FROM
 12      TABLE1;

NAME      |JSON_TABLE
----------|--------------------------------------------------
Name1     |{"Name":"Name1","Surname":Surname1}
Name2     |{"Name":"Name2","Surname":Surname2}

SQL>

For Oracle 11g and lower, you need to create the JSON by yourself as follows:

SQL> WITH TABLE1 AS (
  2      SELECT 'Name1' NAME, 'Surname1' SURNAME FROM DUAL
  3      UNION ALL
  4      SELECT 'Name2', 'Surname2' FROM DUAL
  5  )
  6  SELECT
  7      NAME,
  8      to_clob('{"Name:"' || NAME || '","Surname":'||SURNAME || '}') as "JSON_TABLE"
  9  FROM
 10      TABLE1;

NAME      |JSON_TABLE
----------|--------------------------------------------------
Name1     |{"Name:"Name1","Surname":Surname1}
Name2     |{"Name:"Name2","Surname":Surname2}

SQL>

Another option in Oracle 11g is to use sql*plus command-line interface as following:

set sqlformat json

and then SELECT * FROM TABLE1 will generate the json format result but you need to export it to some file using spool and then load it into TABLE2. (Might be Lengthy approach)

Cheers!!


问:
what is the difference between billing account and financial account in tmforum open-api account management service specs
I am just trying out the open-API specs provided by tmforum https://www.tmforum.org/open-apis/ and cannot seem to figure out the difference and actual purpose of the financial account resource mentioned in account management API specs. Can someone please elaborate?</p>

答: The financial account aggregates the amounts of one or more billing accounts owned by a given party. For example, as a customer, I may have multiple billing accounts (e.g. for broadband services for multiple properties) - the financial account is the aggregation of these billing accounts.</p>


问:
python while loop asks for input twice
i am trying to learn about the while loop and am trying to build something with it.
i have a function that will hold a choice that the user will make but every time i run it the script is asking for the input twice..
can someone please explain to me what is wrong with my code?
thanks in advance!! :)

code:

```<code>def choice():
    choice = int(input("what is your choice? "))
    valid_choice = False

    while not valid_choice:
        if choice >= 1 and choice <= 4:
            return choice
            valid_choice = True
        else:
            print("Please enter a valid response..")
            choice = int(input("what is your choice? "))
</code>```

答:
def beginning():
    while True:
        display_menu()
        choose = choice()
        if choose == 1: print("Your status")
        print(Michael.status())
        print()
        print("Banks's status:")
        print(Prod.status()) elif choose == 2: withraw = float(input("How much money do you want to withraw from the bank?: "))
        Prod.withrawl(withraw)
        Michael.withraw(withraw)
```

You were calling choice twice

Title: python while loop asks for input twice

Body:
i am trying to learn about the while loop and am trying to build something with it.
i have a function that will hold a choice that the user will make but every time i run it the script is asking for the input twice..
can someone please explain to me what is wrong with my code?
thanks in advance!! :)

code:

def choice():
    choice = int(input("what is your choice? "))
    valid_choice = False

    while not valid_choice:
        if choice >= 1 and choice <= 4:
            return choice
            valid_choice = True
        else:
            print("Please enter a valid response..")
            choice = int(input("what is your choice? "))

Body:
def beginning():
    while True:
        display_menu()
        choose = choice()
        if choose == 1: print("Your status")
        print(Michael.status())
        print()
        print("Banks's status:")
        print(Prod.status()) elif choose == 2: withraw = float(input("How much money do you want to withraw from the bank?: "))
        Prod.withrawl(withraw)
        Michael.withraw(withraw)

You were calling choice twice


问:
OpenCV - Image Stitching
I am using following code to stitch to input images. For an unknown
reason the output result is crap!
It seems that the homography matrix is wrong (or is affected wrongly)
because the transformed image is like an "exploited star"!
I have commented the part that I guess is the source of the problem
but I cannot realize it.
Any help or point is appriciated! </p>

<p>Have a nice day,
Ali </p>

```<code>void Stitch2Image(IplImage *mImage1, IplImage *mImage2)
{

    // Convert input images to gray
    IplImage* gray1 = cvCreateImage(cvSize(mImage1->width, mImage1->height), 8, 1);

    cvCvtColor(mImage1, gray1, CV_BGR2GRAY);
    IplImage* gray2 = cvCreateImage(cvSize(mImage2->width, mImage2->height), 8, 1);

    cvCvtColor(mImage2, gray2, CV_BGR2GRAY);
    // Convert gray images to Mat
    Mat img1(gray1);
    Mat img2(gray2);
    // Detect FAST keypoints and BRIEF features in the first image
    FastFeatureDetector detector(50);
    BriefDescriptorExtractor descriptorExtractor;
    BruteForceMatcher<L1<uchar> > descriptorMatcher;
    vector<KeyPoint> keypoints1;
    detector.detect( img1, keypoints1 );
    Mat descriptors1;
    descriptorExtractor.compute( img1, keypoints1, descriptors1 );

/* Detect FAST keypoints and BRIEF features in the second image*/

    vector<KeyPoint> keypoints2;
    detector.detect( img1, keypoints2 );
    Mat descriptors2;
    descriptorExtractor.compute( img2, keypoints2, descriptors2 );
    vector<DMatch> matches;
    descriptorMatcher.match(descriptors1, descriptors2, matches);
    if (matches.size()==0)
            return;
    vector<Point2f> points1, points2;
    for(size_t q = 0; q < matches.size(); q++)
    {
            points1.push_back(keypoints1[matches[q].queryIdx].pt);
            points2.push_back(keypoints2[matches[q].trainIdx].pt);
    }
    // Create the result image
    result = cvCreateImage(cvSize(mImage2->width * 2, mImage2->height), 8, 3);
    cvZero(result);

   // Copy the second image in the result image

    cvSetImageROI(result, cvRect(mImage2->width, 0, mImage2->width, mImage2->height));
    cvCopy(mImage2, result);
    cvResetImageROI(result);

  // Create warp image
    IplImage* warpImage = cvCloneImage(result);
    cvZero(warpImage);

  /************************** Is there anything wrong here!? *******************/
   // Find homography matrix
    Mat H = findHomography(Mat(points1), Mat(points2), 8, 3.0);
    CvMat HH = H; // Is this line converted correctly?
   // Transform warp image
    cvWarpPerspective(mImage1, warpImage, &HH);
  // Blend
    blend(result, warpImage);
  /*******************************************************************************/

    cvReleaseImage(&gray1);
    cvReleaseImage(&gray2);
    cvReleaseImage(&warpImage);
}
</code>```

答:
This is what I would suggest you to try, in this order:

1) Use CV_RANSAC option for homography. Refer http://opencv.willowgarage.com/documentation/cpp/calib3d_camera_calibration_and_3d_reconstruction.html

2) Try other descriptors, particularly SIFT or SURF which ship with OpenCV. For some images FAST or BRIEF descriptors are not discriminating enough. EDIT (Aug '12): The ORB descriptors, which are based on BRIEF, are quite good and fast!

3) Try to look at the Homography matrix (step through in debug mode or print it) and see if it is consistent.

4) If above does not give you a clue, try to look at the matches that are formed. Is it matching one point in one image with a number of points in the other image? If so the problem again should be with the descriptors or the detector.

My hunch is that it is the descriptors (so 1) or 2) should fix it).

Title: OpenCV - Image Stitching

Body:
I am using following code to stitch to input images. For an unknown
reason the output result is crap!
It seems that the homography matrix is wrong (or is affected wrongly)
because the transformed image is like an "exploited star"!
I have commented the part that I guess is the source of the problem
but I cannot realize it.
Any help or point is appriciated!

Have a nice day,
Ali

void Stitch2Image(IplImage *mImage1, IplImage *mImage2)
{

    // Convert input images to gray
    IplImage* gray1 = cvCreateImage(cvSize(mImage1->width, mImage1->height), 8, 1);

    cvCvtColor(mImage1, gray1, CV_BGR2GRAY);
    IplImage* gray2 = cvCreateImage(cvSize(mImage2->width, mImage2->height), 8, 1);

    cvCvtColor(mImage2, gray2, CV_BGR2GRAY);
    // Convert gray images to Mat
    Mat img1(gray1);
    Mat img2(gray2);
    // Detect FAST keypoints and BRIEF features in the first image
    FastFeatureDetector detector(50);
    BriefDescriptorExtractor descriptorExtractor;
    BruteForceMatcher<L1<uchar> > descriptorMatcher;
    vector<KeyPoint> keypoints1;
    detector.detect( img1, keypoints1 );
    Mat descriptors1;
    descriptorExtractor.compute( img1, keypoints1, descriptors1 );

/* Detect FAST keypoints and BRIEF features in the second image*/

    vector<KeyPoint> keypoints2;
    detector.detect( img1, keypoints2 );
    Mat descriptors2;
    descriptorExtractor.compute( img2, keypoints2, descriptors2 );
    vector<DMatch> matches;
    descriptorMatcher.match(descriptors1, descriptors2, matches);
    if (matches.size()==0)
            return;
    vector<Point2f> points1, points2;
    for(size_t q = 0; q < matches.size(); q++)
    {
            points1.push_back(keypoints1[matches[q].queryIdx].pt);
            points2.push_back(keypoints2[matches[q].trainIdx].pt);
    }
    // Create the result image
    result = cvCreateImage(cvSize(mImage2->width * 2, mImage2->height), 8, 3);
    cvZero(result);

   // Copy the second image in the result image

    cvSetImageROI(result, cvRect(mImage2->width, 0, mImage2->width, mImage2->height));
    cvCopy(mImage2, result);
    cvResetImageROI(result);

  // Create warp image
    IplImage* warpImage = cvCloneImage(result);
    cvZero(warpImage);

  /************************** Is there anything wrong here!? *******************/
   // Find homography matrix
    Mat H = findHomography(Mat(points1), Mat(points2), 8, 3.0);
    CvMat HH = H; // Is this line converted correctly?
   // Transform warp image
    cvWarpPerspective(mImage1, warpImage, &HH);
  // Blend
    blend(result, warpImage);
  /*******************************************************************************/

    cvReleaseImage(&gray1);
    cvReleaseImage(&gray2);
    cvReleaseImage(&warpImage);
}


问:
Removing margin from React Twitter Embed's TwitterTweetEmbed component
I'm using Material UI and have a TwitterTweetEmbed from React Twitter Embed that I can't figure out how to remove the top and bottom margins.

This is my current code:

```<code>const styles = theme => ({
  listItem: {
    padding: '0px',
  },
  tweetSize: {
    margin: 0,
  },
  tweet: {
    margin: 0,
  }
});

class TweetItem extends Component {

  render() {
    return (
      <ListItem className={this.props.classes.listItem}>
        <div className={this.props.classes.tweetSize}>
          <TwitterTweetEmbed className={this.props.classes.tweet} tweetId={blah} options={{ width: 'auto'}} />

        </div>
      </ListItem>
    );
  }
}

export default withStyles(styles)(TweetItem);
</code>```

Also, using the inspect tool in Chrome, I found that the margins appear here:

And this is what they look like on the page:

Is there a way to force those margins to 0, by any means necessary?

答:
A solution I found is just to add

```<code>marginTop: '-10px'
</code>```

to the listItem style.

Body:
I'm using Material UI and have a TwitterTweetEmbed from React Twitter Embed that I can't figure out how to remove the top and bottom margins.

This is my current code:

const styles = theme => ({
  listItem: {
    padding: '0px',
  },
  tweetSize: {
    margin: 0,
  },
  tweet: {
    margin: 0,
  }
});

class TweetItem extends Component {

  render() {
    return (
      <ListItem className={this.props.classes.listItem}>

          <TwitterTweetEmbed className={this.props.classes.tweet} tweetId={blah} options={{ width: 'auto'}} />

      </ListItem>
    );
  }
}

export default withStyles(styles)(TweetItem);

Also, using the inspect tool in Chrome, I found that the margins appear here:

And this is what they look like on the page:

Is there a way to force those margins to 0, by any means necessary?

Body:
A solution I found is just to add

marginTop: '-10px'

to the listItem style.


问:
In operator returns false
Why this statement returns false? It's really weird</p>

```<code>console.log("100038916831294" in ["100003748210938", "100038916831294"]);
</code>```

答:
The in operator in JavaScript compares indexes or property names in arrays instead of the value itself.

For example, if we write console.log(0 in ["abc","pqr"]); it will print true. However, if we use the value, like in console.log("abc" in ["abc","pqr"]); it will print false.

You can further read about it on https://www.w3schools.com/jsref/jsref_operators.asp.

Title: In operator returns false

Body:
Why this statement returns false? It's really weird

console.log("100038916831294" in ["100003748210938", "100038916831294"]);


问:
Multi-threading program taking longer than single thread (Java)
I have to write a program that reads all of the words from a file and determines how many times each word is used. I'm tasked to use multi-threading to speed the run time, but the single threaded program runs faster than the multi. I've tried researching a solution to this but a lot of the explanations are only confusing me more. I'm very new to using threads, and was wondering if anyone could point me in the right direction of fixing my code so that the overhead for creating the threads won't cause the program to run slower than the single thread.

```<code>public class Main
{
final static int THREADS = 4;
static HashMap<String, Integer> map = new HashMap<>();
static List<String> file = new ArrayList<String>();
static String filename = "D:\\yes.txt";
static int count;

public static void main(String args[]) throws Exception
{
    long startTime = System.nanoTime();
    Monitor m = new Monitor();
    final Queue<String> dataQueue = new ConcurrentLinkedQueue<>();

    try ( Scanner in = new Scanner(new File(filename)))
    {
                while ( in.hasNext() )
                {
                    dataQueue.add( in.next() );
                }
    }
    catch ( IOException e )
    {
        e.printStackTrace();
    }

    Thread T1 = new Thread( new WordCount(m, map, dataQueue ));
    Thread T2 = new Thread( new WordCount(m, map, dataQueue ));
    Thread T3 = new Thread( new WordCount(m, map, dataQueue ));
    Thread T4 = new Thread( new WordCount(m, map, dataQueue ));

    T1.start();
    T2.start();
    T3.start();
    T4.start();

     //wait for threads to end
       try {
       T1.join();
       T2.join();
       T3.join();
       T4.join();
    } catch ( Exception e) {
       System.out.println("Interrupted");
    }

    Set<String> keys = map.keySet();
    for (String key : keys)
    {
        System.out.println(key);
        System.out.println(map.get(key));
    }
    long endTime = System.nanoTime();
    System.out.println("Thread Took "+((endTime - startTime)/100000) + " ms");

}
}
</code>```

```<code>public class WordCount implements Runnable
{

    private Monitor m;
    private Queue<String> dataQueue;
    private HashMap<String, Integer> map;

    public WordCount(Monitor m, HashMap<String, Integer> map,Queue<String> dataQueue)
    {
        this.m = m;
        this.dataQueue = dataQueue;
        this.map = map;
    }

    @Override public void run()
    {
        while ( !dataQueue.isEmpty() )
        {
            String line = dataQueue.poll();
            m.keySet(map, line);
        }
    }
}
</code>```

```<code>public class Monitor
{
    public synchronized void keySet(HashMap<String, Integer> map, String word)
    {
        String[] words = filterIllegalTokens(word );
        String[] lowerCaseWords = mapToLowerCase( words );
         for ( String s : lowerCaseWords ) {

        if (map.containsKey(s))
        {
            map.put(s, map.get(s) + 1);

        }
        else
        {
            map.put(s, 1);
        }
         }
    }
    public  String[] filterIllegalTokens(String words)
    {
        List<String> filteredList = new ArrayList<>();

        if ( words.matches( "[a-zA-Z]+" ) ) {
                filteredList.add( words );
            }

        return filteredList.toArray( new String[filteredList.size()] );
    }
    public  String[] mapToLowerCase( String[] words )
    {
        String[] filteredList = new String[words.length];
        for ( int i = 0; i < words.length; i++ ) {
            filteredList[i] = words[i].toLowerCase();
        }
        return filteredList;
    }
}

</code>```

These are the three classes I have. Any tips or advice?

答:
A rule of thumbs says that you need one CPU core for the operating system, the others can be used for the program. So you need at least 5 CPU cores for optimal performance.

The overhead for creating these few threads does not really matter. That would become more relevant when you start dozens of threads withing milliseconds.

The main issue in your code is that you access data in a shared memory area for 90% of the total time. In this case we are talking about the ConcurrentLinkedQueue and the synchronized Monitor.keySet() method. While one thread access these objects, the other 3 threads must wait. When you run your program for a long time you might notice that only a fraction of your total CPU power is used.

To improve the performance I would recommend to split the job queue into 4 packets before you start the threads, so each thread can then process its own packet without waiting for other threads. Also each thread shall collect its result in an individual container. Then finally (after the threads are finished), you can combine the four results.

If your worker threads would be more complicated, your problem would be less hard. For example if the access to the containers would take only 10% of the overall time (while some calculation takes 90%) then the overhead of the thread synchronization would also be much less - relative to the total execution time.

Body:
I have to write a program that reads all of the words from a file and determines how many times each word is used. I'm tasked to use multi-threading to speed the run time, but the single threaded program runs faster than the multi. I've tried researching a solution to this but a lot of the explanations are only confusing me more. I'm very new to using threads, and was wondering if anyone could point me in the right direction of fixing my code so that the overhead for creating the threads won't cause the program to run slower than the single thread.

public class Main
{
final static int THREADS = 4;
static HashMap<String, Integer> map = new HashMap<>();
static List<String> file = new ArrayList<String>();
static String filename = "D:\\yes.txt";
static int count;

public static void main(String args[]) throws Exception
{
    long startTime = System.nanoTime();
    Monitor m = new Monitor();
    final Queue<String> dataQueue = new ConcurrentLinkedQueue<>();

    try ( Scanner in = new Scanner(new File(filename)))
    {
                while ( in.hasNext() )
                {
                    dataQueue.add( in.next() );
                }
    }
    catch ( IOException e )
    {
        e.printStackTrace();
    }

    Thread T1 = new Thread( new WordCount(m, map, dataQueue ));
    Thread T2 = new Thread( new WordCount(m, map, dataQueue ));
    Thread T3 = new Thread( new WordCount(m, map, dataQueue ));
    Thread T4 = new Thread( new WordCount(m, map, dataQueue ));

    T1.start();
    T2.start();
    T3.start();
    T4.start();

     //wait for threads to end
       try {
       T1.join();
       T2.join();
       T3.join();
       T4.join();
    } catch ( Exception e) {
       System.out.println("Interrupted");
    }

    Set<String> keys = map.keySet();
    for (String key : keys)
    {
        System.out.println(key);
        System.out.println(map.get(key));
    }
    long endTime = System.nanoTime();
    System.out.println("Thread Took "+((endTime - startTime)/100000) + " ms");

}
}

public class WordCount implements Runnable
{

    private Monitor m;
    private Queue<String> dataQueue;
    private HashMap<String, Integer> map;

    public WordCount(Monitor m, HashMap<String, Integer> map,Queue<String> dataQueue)
    {
        this.m = m;
        this.dataQueue = dataQueue;
        this.map = map;
    }

    @Override public void run()
    {
        while ( !dataQueue.isEmpty() )
        {
            String line = dataQueue.poll();
            m.keySet(map, line);
        }
    }
}

public class Monitor
{
    public synchronized void keySet(HashMap<String, Integer> map, String word)
    {
        String[] words = filterIllegalTokens(word );
        String[] lowerCaseWords = mapToLowerCase( words );
         for ( String s : lowerCaseWords ) {

        if (map.containsKey(s))
        {
            map.put(s, map.get(s) + 1);

        }
        else
        {
            map.put(s, 1);
        }
         }
    }
    public  String[] filterIllegalTokens(String words)
    {
        List<String> filteredList = new ArrayList<>();

        if ( words.matches( "[a-zA-Z]+" ) ) {
                filteredList.add( words );
            }

        return filteredList.toArray( new String[filteredList.size()] );
    }
    public  String[] mapToLowerCase( String[] words )
    {
        String[] filteredList = new String[words.length];
        for ( int i = 0; i < words.length; i++ ) {
            filteredList[i] = words[i].toLowerCase();
        }
        return filteredList;
    }
}

These are the three classes I have. Any tips or advice?


问:
Is there any extension in Visual Studio Code , which is similar to Tramp Mode in Emacs?
TRAMP (Transparent Remote Access, Multiple Protocols) is a package for editing remote files, similar to AngeFtp or efs. Whereas the others use FTP to connect to the remote host and to transfer the files, TRAMP uses a remote shell connection (rlogin, telnet, ssh). It can transfer the files using rcp or a similar program, or it can encode the file contents (using uuencode or base64) and transfer them right through the shell connection.</p>

答:
It seems like as of now there is at least one similar package to Tramp mode for VSCode.  I couldn't directly find in the documentation how you would open a remote shell inside VSCode, but it seems like it would have to be possible given the rest of the plugin.

https://code.visualstudio.com/docs/remote/ssh

https://code.visualstudio.com/blogs/2019/10/03/remote-ssh-tips-and-tricks

I have a terminal menu in VSCode that I can open up and directly ssh to stuff, so that seems to cover both sides of the "Tramp" mode usage


问:
Trying to create multiple unique short URLs
I want to make a post method that returns a list of shortened URLs when given a body containing multiple URLs in JSON.

This is my post method:

```<code>public class MyServices : Service
{
    public object Post(CreateShortUrlRequest request) //Post an array/list of URLs to the database and get a respective list of short URL
    {
        using (Task4URLEntities db = new Task4URLEntities())
        {
            var urls = new List<string>();
            foreach (string LongUrl in request.LongUrl)
            {
                var item = new ShortURLs
                {
                    LongUrl = LongUrl,
                    ShortUrl = GetUrl(),
                    DateCreated = DateTime.Now
                };
                urls.Add($"http://localhost/{item.ShortUrl}");
                db.ShortURLs.Add(item);
            }

            var campaign = new Campaign
            {
                CampaignName = request.CampaignName,
                Enddate = request.Enddate,
                Startdate = request.Startdate
            };

            db.Campaign.Add(campaign);

            try
            {
                db.SaveChanges();
            }
            catch (DbEntityValidationException ex)
            {
                foreach (var entityValidationErrors in ex.EntityValidationErrors)
                {
                    foreach (var validationError in entityValidationErrors.ValidationErrors)
                    {
                        Response.WriteAsync("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
                    }
                }
            }

            return new CreateShortUrlResponse
            {
                Response = urls,
                CampaignId = campaign.CampaignId
            };
        }
    }

    public string GetUrl()
    {
        var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        var stringChars = new char[5];
        var random = new Random();
        for (int i = 0; i < stringChars.Length; i++)
        {
            stringChars[i] = chars[random.Next(chars.Length)];
        }
        var finalString = new String(stringChars);
        return finalString;
    }

 }
</code>```

My problem is that when I send my post request on Postman for a list of URLs in JSON, I will get unique URLs as response for the first post if i click send again then I will get a response in which every returned short URL is the same.

How can I rectify this?

答:
I'm guessing that when you say "every returned short URL is the same" you mean that the CreateShortUrlResponse.Response property contains the exact same URL n number of times, where n is the number of URLs that you requested. I'm also assuming, based on that behavior, that this is a .NET Framework project, and not a .NET Core project.

If that's the case, then the problem is that creating new instances of Random in such a tight loop is resulting in each one being created with the exact same seed value. When you create an instance of Random in the .NET Framework with the empty constructor, it uses Environment.TickCount as the seed. So, if you create two instances of Random in rapid succession, they will both have the same seed and therefore generate the same values.

The documentation on Random speaks to this.

On the .NET Framework, initializing two random number generators in a tight loop or in rapid succession creates two random number generators that can produce identical sequences of random numbers. In most cases, this is not the developer's intent and can lead to performance issues, because instantiating and initializing a random number generator is a relatively expensive process.

Both to improve performance and to avoid inadvertently creating separate random number generators that generate identical numeric sequences, we recommend that you create one Random object to generate many random numbers over time, instead of creating new Random objects to generate one random number.

However, the Random class isn't thread safe. If you call Random methods from multiple threads, follow the guidelines discussed in the next section.

So, you might make the Random instance a member of the MyServices class instead of creating a new instance every time you call GetUrl.

```<code>public class MyServices : Service
{
    public object Post(CreateShortUrlRequest request) //Post an array/list of URLs to the database and get a respective list of short URL
    {
        using (Task4URLEntities db = new Task4URLEntities())
        {
            var urls = new List<string>();
            foreach (string LongUrl in request.LongUrl)
            {
                var item = new ShortURLs
                {
                    LongUrl = LongUrl,
                    ShortUrl = GetUrl(),
                    DateCreated = DateTime.Now
                };
                urls.Add($"http://localhost/{item.ShortUrl}");
                db.ShortURLs.Add(item);
            }

            var campaign = new Campaign
            {
                CampaignName = request.CampaignName,
                Enddate = request.Enddate,
                Startdate = request.Startdate
            };

            db.Campaign.Add(campaign);

            try
            {
                db.SaveChanges();
            }
            catch (DbEntityValidationException ex)
            {
                foreach (var entityValidationErrors in ex.EntityValidationErrors)
                {
                    foreach (var validationError in entityValidationErrors.ValidationErrors)
                    {
                        Response.WriteAsync("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
                    }
                }
            }

            return new CreateShortUrlResponse
            {
                Response = urls,
                CampaignId = campaign.CampaignId
            };
        }
    }

    public string GetUrl()
    {
        var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        var stringChars = new char[5];
        for (int i = 0; i < stringChars.Length; i++)
        {
            stringChars[i] = chars[_rng.Next(chars.Length)];
        }
        var finalString = new String(stringChars);
        return finalString;
    }
    private Random _rng = new Random();
 }
</code>```

Body:
I want to make a post method that returns a list of shortened URLs when given a body containing multiple URLs in JSON.

This is my post method:

public class MyServices : Service
{
    public object Post(CreateShortUrlRequest request) //Post an array/list of URLs to the database and get a respective list of short URL
    {
        using (Task4URLEntities db = new Task4URLEntities())
        {
            var urls = new List<string>();
            foreach (string LongUrl in request.LongUrl)
            {
                var item = new ShortURLs
                {
                    LongUrl = LongUrl,
                    ShortUrl = GetUrl(),
                    DateCreated = DateTime.Now
                };
                urls.Add($"http://localhost/{item.ShortUrl}");
                db.ShortURLs.Add(item);
            }

            var campaign = new Campaign
            {
                CampaignName = request.CampaignName,
                Enddate = request.Enddate,
                Startdate = request.Startdate
            };

            db.Campaign.Add(campaign);

            try
            {
                db.SaveChanges();
            }
            catch (DbEntityValidationException ex)
            {
                foreach (var entityValidationErrors in ex.EntityValidationErrors)
                {
                    foreach (var validationError in entityValidationErrors.ValidationErrors)
                    {
                        Response.WriteAsync("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
                    }
                }
            }

            return new CreateShortUrlResponse
            {
                Response = urls,
                CampaignId = campaign.CampaignId
            };
        }
    }

    public string GetUrl()
    {
        var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        var stringChars = new char[5];
        var random = new Random();
        for (int i = 0; i < stringChars.Length; i++)
        {
            stringChars[i] = chars[random.Next(chars.Length)];
        }
        var finalString = new String(stringChars);
        return finalString;
    }

 }

My problem is that when I send my post request on Postman for a list of URLs in JSON, I will get unique URLs as response for the first post if i click send again then I will get a response in which every returned short URL is the same.

How can I rectify this?

Body:
I'm guessing that when you say "every returned short URL is the same" you mean that the CreateShortUrlResponse.Response property contains the exact same URL n number of times, where n is the number of URLs that you requested. I'm also assuming, based on that behavior, that this is a .NET Framework project, and not a .NET Core project.

If that's the case, then the problem is that creating new instances of Random in such a tight loop is resulting in each one being created with the exact same seed value. When you create an instance of Random in the .NET Framework with the empty constructor, it uses Environment.TickCount as the seed. So, if you create two instances of Random in rapid succession, they will both have the same seed and therefore generate the same values.

The documentation on Random speaks to this.

On the .NET Framework, initializing two random number generators in a tight loop or in rapid succession creates two random number generators that can produce identical sequences of random numbers. In most cases, this is not the developer's intent and can lead to performance issues, because instantiating and initializing a random number generator is a relatively expensive process.

Both to improve performance and to avoid inadvertently creating separate random number generators that generate identical numeric sequences, we recommend that you create one Random object to generate many random numbers over time, instead of creating new Random objects to generate one random number.

However, the Random class isn't thread safe. If you call Random methods from multiple threads, follow the guidelines discussed in the next section.

So, you might make the Random instance a member of the MyServices class instead of creating a new instance every time you call GetUrl.

public class MyServices : Service
{
    public object Post(CreateShortUrlRequest request) //Post an array/list of URLs to the database and get a respective list of short URL
    {
        using (Task4URLEntities db = new Task4URLEntities())
        {
            var urls = new List<string>();
            foreach (string LongUrl in request.LongUrl)
            {
                var item = new ShortURLs
                {
                    LongUrl = LongUrl,
                    ShortUrl = GetUrl(),
                    DateCreated = DateTime.Now
                };
                urls.Add($"http://localhost/{item.ShortUrl}");
                db.ShortURLs.Add(item);
            }

            var campaign = new Campaign
            {
                CampaignName = request.CampaignName,
                Enddate = request.Enddate,
                Startdate = request.Startdate
            };

            db.Campaign.Add(campaign);

            try
            {
                db.SaveChanges();
            }
            catch (DbEntityValidationException ex)
            {
                foreach (var entityValidationErrors in ex.EntityValidationErrors)
                {
                    foreach (var validationError in entityValidationErrors.ValidationErrors)
                    {
                        Response.WriteAsync("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
                    }
                }
            }

            return new CreateShortUrlResponse
            {
                Response = urls,
                CampaignId = campaign.CampaignId
            };
        }
    }

    public string GetUrl()
    {
        var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        var stringChars = new char[5];
        for (int i = 0; i < stringChars.Length; i++)
        {
            stringChars[i] = chars[_rng.Next(chars.Length)];
        }
        var finalString = new String(stringChars);
        return finalString;
    }
    private Random _rng = new Random();
 }


问:
Mongoose - How to query subdocument by property value
I'm trying to get an array of unpaid orders. The order subdocument has a property isPaid which defines whether or not the order has been paid.

In my view, I want to display only orders which have not been paid.

Here is my schema:

```<code>var order = new Schema({
   content: [{
        product: {type: String, required: true},
        quantity: {type: Number},
        vatRate: {type: Number, required: true},
        price: {type: Number}
    }],
    isPaid: {type: Boolean, default: false},
    number: {type: Number}
});

var clientSchema = new Schema({
[...]
information: {
    code: {type: String, required: true},
    name: {type: String, required: true}
},
orders: [order],
[...]
});
</code>```

I started with, but without success

```<code>clientModel.find(
    {
       "information.code": clientCode,
       "orders.isPaid": false
    }, function (err, client) { ... });
</code>```

Then, I've done many tries, with $all, $elemMatch without success. Most of the time, it returns all the orders, paid or unpaid. I don't know why. I need some help, please :)

答:
.populate() allows you to specify a match query.
Example from another SO answer:

Users.find().populate({
  path: 'email',
  match: {
    type: 'Gmail'
  }
}).exec(function(err, users) {
  users = users.filter(function(user) {
    return user.email; // return only users with email matching 'type: "Gmail"' query
  });
});```

</code>```

Body:
I'm trying to get an array of unpaid orders. The order subdocument has a property isPaid which defines whether or not the order has been paid.

In my view, I want to display only orders which have not been paid.

Here is my schema:

var order = new Schema({
   content: [{
        product: {type: String, required: true},
        quantity: {type: Number},
        vatRate: {type: Number, required: true},
        price: {type: Number}
    }],
    isPaid: {type: Boolean, default: false},
    number: {type: Number}
});

var clientSchema = new Schema({
[...]
information: {
    code: {type: String, required: true},
    name: {type: String, required: true}
},
orders: [order],
[...]
});

I started with, but without success

clientModel.find(
    {
       "information.code": clientCode,
       "orders.isPaid": false
    }, function (err, client) { ... });

Then, I've done many tries, with $all, $elemMatch without success. Most of the time, it returns all the orders, paid or unpaid. I don't know why. I need some help, please :)


问:
Reuse a previously published datasource in a Power BI report
I have developed a Power BI report using Power BI Desktop, pointing to a private on premise development database as the datasource so that I was able to develop and test it easily. Then, I published it from my Power BI Desktop pbix to the work area of my customer.

As a result, the work area contains the published report and the dataset. Later, my customer has changed the dataset so that it now points to the correct on premise production database of their own. It works perfectly.

Now, I want to publish a new report for my customer using the previously published and reconfigured dataset. The problem is that I can't see any option in Power BI Desktop to have the report point to the published dataset, nor I can't see any option to avoid creating a new dataset each time I publish a report, nor any way to reconfigure from the web portal the new published report to point to the same dataset as the first one.

Is there any way to do this or any work around for this scenario? I think the most reasonable solution would be to be able to change the dataset of any report, so that the datasets of any report could be interchangeable.

Update:
I had already used connection specific parameters, but I'm not given rights to change the published dataset, so thats a dead end.

Another thing I have come up to is that in Power BI Desktop you cannot change the connection parameters values to those of production enviroment and publish the report if you can't access the target database from your computer, because PowerBI Desktop ask you to apply changes first, and when it tries to apply the values it tries to connect to the corresponding database and, obviously, ends with a network related error or timeout error trying to connect to the database server, therefore cancelling changes and returning to the starting point.

答:
It's always a good practice to use connection specific parameters to define the data source. This means that you do not enter server name directly, but specify it indirectly using a parameter. The same for the database name, if applicable.

If you are about to make a new report, cancel Get data dialog, define parameters as described bellow, and then in Get data specify the datasource using these parameters:

To modify an existing report, open Power Query Editor by clicking Edit Queries and in Manage Parameters define two new text parameters, lets name them ServerName and DatabaseName:

Set their current values to point to one of your data sources, e.g. SQLSERVER2016 and AdventureWorks2016. Then right click your query in the report and open Advanced Editor. Find the server name and database name in the M code:

and replace them with the parameters defined above, so the M code will look like this:

Now you can close and apply changes and your report should work as before. But now when you want to change the data source, do it using Edit Parameters:

and change the server and/or database name to point to the other data source, that you want to use for your report:

After changing parameter values, Power BI Desktop will ask you to apply the changes and reload the data from the new data source. To change the parameter values (i.e. the data source) of a report published in Power BI Service, go to dataset's settings and enter new server and/or database name:

If the server is on-premise, check the Gateway connection too, to make sure that it is configured properly to use the right gateway. You may also want to check the available gateways in Manage gateways:

After changing the data source, refresh your dataset to get the data from the new data source. With Power BI Pro account you can do this 8 times per 24 hours, while if the dataset is in a dedicated capacity, this limit is raised to 48 times per 24 hours.

This is a easy way to make your reports "switchable", e.g. for switching one report from DEV or QA to PROD environment, or as part of your disaster recovery plan, to automate switching all reports in some workgroup to another DR server. In your case, this will allow you (or your customers) to easily switch the datasource of the report.


问:
on heroku, celery beat database scheduler doesn’t run periodic tasks
I have an issue where django_celery_beat’s DatabaseScheduler doesn’t run periodic tasks. Or I should say where celery beat doesn’t find any tasks when the scheduler is DatabaseScheduler. In case I use the standard scheduler the tasks are executed regularly.

I setup celery on heroku by using a dyno for worker and one for beat (and one for web, obviously).

I know that beat and worker are connected to redis and to postgres for task results.

Every periodic task I run from django admin by selecting a task and “run selected task” gets executed.

However, it is about two days that I’m trying to figure out why there isn’t a way for beat/worker to find that I scheduled a task to execute every 10 seconds, or using a cron (even restarting beat and remot doesn’t change it).

I’m kind of desperate, and my next move would be to give redbeat a try.

Any help on how to how to troubleshoot this particular problem would be greatly appreciated. I suspect the problem is in the is_due method. I am using UTC (in celery and django), all cron are UTC based. All I see in the beat log is “writing entries..” every on and then.

I’ve tried changing celery version from 4.3 to 4.4 and django celery beat from 1.4.0 to 1.5.0 to 1.6.0

Any help would be greatly appreciated.

答:
In case it helps someone who's having or will have a similar trouble as ours: to recreate this issue, it is possible to create a task as simple as:

```<code>@app.task(bind=True)
def test(self, arg):

    print(kwargs.get("notification_id"))
</code>```

then, in django admin, enter the task editing and put something in the extra args field. Or, viceversa, the task could be

```<code>@app.task(bind=True)
def test(self, **kwargs):

    print(notification_id)
</code>```

And try to pass a positional argument. While locally this breaks, on Heroku's beat and worker dyno, this somehow slips away unnoticed, and django_celery_beats stop processing any task whatsoever in the future. The scheduler is completely broken by a "wrong" task.

Body:
In case it helps someone who's having or will have a similar trouble as ours: to recreate this issue, it is possible to create a task as simple as:

@app.task(bind=True)
def test(self, arg):

    print(kwargs.get("notification_id"))

then, in django admin, enter the task editing and put something in the extra args field. Or, viceversa, the task could be

@app.task(bind=True)
def test(self, **kwargs):

    print(notification_id)

And try to pass a positional argument. While locally this breaks, on Heroku's beat and worker dyno, this somehow slips away unnoticed, and django_celery_beats stop processing any task whatsoever in the future. The scheduler is completely broken by a "wrong" task.


问:
Load binary into stm32f103c8t6 with OpenOCD and arm-none-eabi-gdb
I tried to load binary that is compiled from rust code, but it doesn't work.

First, I downloaded Rust code from https://github.com/rust-embedded/discovery.
Then, I built it.

```<code># I am in the `src/05-led-roulette` directory
rustup target add thumbv7m-none-eabi
cargo build --target thumbv7m-none-eabi
</code>```

It was successfully compiled.

After that, I successfully connected with stm32f103c8t6 using OpenOCD.
Then, I run this command.

```<code>arm-none-eabi-gdb -q target/thumbv7m-none-eabi/debug/led-roulette
</code>```

But it seemed like it didn't finish reading.

```<code>Reading symbols from target/thumbv7m-none-eabi/debug/led-roulette...
(gdb)
</code>```

(not done?!)

After that, I tried loadcommand, but it returned following sentences.

```<code>Start address 0x0, load size 0
Transfer rate: 0 bits in <1 sec.
</code>```

I have no idea about why it doesn't work.

Please help me.

答:
After connecting openocd with the board don't forget to connect the debugger
arm-none-eabi-gdb with openocd.

```<code>> arm-none-eabi-gdb -se target/thumbv7em-none-eabi/release/your_binary
(gdb) target remote localhost:3333
</code>```

If all is OK in the terminal console where openocd is running you will see the message:

```<code>accepting 'gdb' connection on tcp/3333`
</code>```

and you should be able to start debugging.

To optimize connection setup you may create/update the .gdbinit file with the content:

```<code>target remote localhost:3333
</code>```

Body:
I tried to load binary that is compiled from rust code, but it doesn't work.

First, I downloaded Rust code from https://github.com/rust-embedded/discovery.
Then, I built it.

# I am in the `src/05-led-roulette` directory
rustup target add thumbv7m-none-eabi
cargo build --target thumbv7m-none-eabi

It was successfully compiled.

After that, I successfully connected with stm32f103c8t6 using OpenOCD.
Then, I run this command.

arm-none-eabi-gdb -q target/thumbv7m-none-eabi/debug/led-roulette

But it seemed like it didn't finish reading.

Reading symbols from target/thumbv7m-none-eabi/debug/led-roulette...
(gdb)

(not done?!)

After that, I tried loadcommand, but it returned following sentences.

Start address 0x0, load size 0
Transfer rate: 0 bits in <1 sec.

I have no idea about why it doesn't work.

Please help me.

Body:
After connecting openocd with the board don't forget to connect the debugger
arm-none-eabi-gdb with openocd.

> arm-none-eabi-gdb -se target/thumbv7em-none-eabi/release/your_binary
(gdb) target remote localhost:3333

If all is OK in the terminal console where openocd is running you will see the message:

accepting 'gdb' connection on tcp/3333`

and you should be able to start debugging.

To optimize connection setup you may create/update the .gdbinit file with the content:

target remote localhost:3333


问:
Which inliers is the RANSAC Algorithm using in cv2.FindHomography to find the homography matrix?
1) How is the RANSAC algorithm in OpenCV choosing an inlier over an outlier? I am presuming it calculates some total least square matching between the matched keypoints.

2)  I am fully aware that apart from the H matrix, the cv2.FindHomography also outputs the mask. And from this mask a matched keypoint which is a 1 is considered an inlier whilst a 0 is considered an outlier. But which inliers is the RANSAC algorithm choosing to find the final H homography outputted by cv2.FindHomography? Is it considering all of them to find the H matrix?

The documentation is not explaining these two questions properly.

答:
The ransacReprojThreshold argument in the findHomography docs describes inliers vs outliers:

For 1), RANSAC computes the error (vector norm) between the observed projection, dstPoint_i, and the projection of srcPoint_i computed with a candidate homography, H. Then it just does a simple threshold check. The user can set the ransacReprojThreshold to whatever value you find that works best for your data. If you're in pixel coordinates, you just set the maximum error in pixel distance for a point to be considered an inlier. Anything with greater error is considered an outlier.

For 2), the RANSAC algorithm will simply choose the H matrix that maximizes the number of inliers based on the threshold you set. So the mask it returns to you is the is the set with the greatest number of inliers.

Does that make sense? It doesn't look like it gives you a ton of options in terms of random sample sizes, number of iterations, etc. Here's the source, if you're interested.


问:
angular extending a class to change the inputs
So I'm building an org chart, extending a third party lib:

https://github.com/dabeng/ng-orgchart

and I'm trying to change which things are displayed in the chart. Here's some sample data:

```<code>  datasource = {
    'id': '1',
    'name': 'Lao Lao',
    'title': 'general manager',
    'routing' : 'abc'
    'children': [
      { 'id': '2', 'name': 'Bo Miao', 'title': 'department manager', 'routing': 'abd' },
      { 'id': '3', 'name': 'Su Miao', 'title': 'department manager', 'routing': 'bcd'}
     ]
   }
</code>```

I'm extending this class:

https://github.com/dabeng/ng-orgchart/blob/master/projects/ng-orgchart/src/lib/components/orgchart/chart-container/chart-container.component.ts

and trying to change one of the inputs like so:

```<code>export class OrgChartComponent extends OrgChartContainer {

  @Input() nodeContent = ['title', 'routing'];
</code>```

but I'm getting the following error:

```<code>Property 'nodeContent' in type 'OrgChartComponent' is not assignable to the same property in base type 'ChartContainerComponent'.
  Type 'string[]' is not assignable to type 'string'.
</code>```

How can I make this so that I can put multiple things from the data into nodeContent? I don't just want the title, I want the routing number to show up in there too.

答: The nodeContent property is string instead of Array of string in ChartContainerComponent (see github link you posted). Assign single string value in OrgChartComponent</p>

Body:
So I'm building an org chart, extending a third party lib:

https://github.com/dabeng/ng-orgchart

and I'm trying to change which things are displayed in the chart. Here's some sample data:

  datasource = {
    'id': '1',
    'name': 'Lao Lao',
    'title': 'general manager',
    'routing' : 'abc'
    'children': [
      { 'id': '2', 'name': 'Bo Miao', 'title': 'department manager', 'routing': 'abd' },
      { 'id': '3', 'name': 'Su Miao', 'title': 'department manager', 'routing': 'bcd'}
     ]
   }

I'm extending this class:

https://github.com/dabeng/ng-orgchart/blob/master/projects/ng-orgchart/src/lib/components/orgchart/chart-container/chart-container.component.ts

and trying to change one of the inputs like so:

export class OrgChartComponent extends OrgChartContainer {

  @Input() nodeContent = ['title', 'routing'];

but I'm getting the following error:

Property 'nodeContent' in type 'OrgChartComponent' is not assignable to the same property in base type 'ChartContainerComponent'.
  Type 'string[]' is not assignable to type 'string'.

How can I make this so that I can put multiple things from the data into nodeContent? I don't just want the title, I want the routing number to show up in there too.


问:
Is there a way to connect Wifi using PPPoE on Android?
Since I am newbie in Android, I don't know how to connect Android (2.1 on HTC Desire) with PPPoE using wifi connection.

So Please anybody know solution, then kindly help me.

答:
yes you can...
there is a App called WiFipppoe...

https://market.android.com/details?id=com.cnddu.wifipppoe


问:
How to share aggregate types (for ex. custom structures) between several sources in the same package
Let's suppose my server.go receives aggregate data, feeds the corresponding structure instance and passes if to a function in treatOne.go

Where to declare and to include such common types?

答:
The following can be done :

If server.go and treatOne.go belong to the same package, you can use the custom struct directly.

If server.go and treatOne.go do not belong to the same package, you can have the custom struct defined publicly in any of the files (depends on semantics of the struct). You can define a public custom struct by having the first letter capitalized.

If server.go and treatOne.go do not belong to the same package, you can have a third package which serves the custom struct purpose and define the custom struct in that package and make it publicly defined. This is a better way to go about it.

Hope it helps.


问:
Make Postgresql.Simple query results available to rest of .hs file
I have a sensor that puts values in a postgres table and im using postgresql-simple to read them out in my main :: IO () function with return queryResult after queryResult <- mapM_ print =<< (query_ conn "select sensor1 from lightbool" :: IO [Only String]).

I need to convert these values with another function (lightBoolHandler). It needs to take the contents of a query -- which are fake "bools" that are actually strings -- and produce safely typed Haskell [Bool].

How can i make the contents/result of that IO action availble to other parts of the .hs file?

Script snippet:

```<code>main :: IO ()
main = do
  conn <- connectPostgreSQL "host=myHost.rds.amazonaws.com port=5432 user=myUser password=myPw dbname=myDBName"
  queryResult <- mapM_ print =<< (query_ conn "select sensor1 from lightbool" :: IO [Only String])
  return queryResult

lightBoolHandler :: [Only String] -> [Bool]
lightBoolHandler list = ?
</code>```

For reference, if I run main in ghci, this is what I get:

```<code>Only {fromOnly = "TRUE"}
Only {fromOnly = "TRUE"}
Only {fromOnly = "TRUE"}
Only {fromOnly = "TRUE"}
Only {fromOnly = "FALSE"}
Only {fromOnly = "FALSE"}
</code>```

答:
No need to muddy the waters with a database example.  How do you pass values from one function to another in Haskell regardless of their source?  You pass the value as an argument in a function call.
 Consider:

```<code>main :: IO ()
main = do
  queryResult <- return ["True", "False"]
  mapM_ print queryResult
  let parsedResults = lightBoolHandler queryResult
  mapM_ print parsedResults

lightBoolHandler :: [String] -> [Bool]
lightBoolHandler = map read
</code>```

Side Notes

```<code>queryResult <- mapM_ print =<< ...
</code>```

Calling this a "result" is misleading.  Your mapM_ means "ignore the result and return ().  More, the result of print is not interesting.  presumably you would remove that part when developing and instead:

```<code>queryResult <- query ...
mapM_ print queryResult
let bools = lightBoolHandler queryResult
... use bools somehow ...
</code>```

Body:
I have a sensor that puts values in a postgres table and im using postgresql-simple to read them out in my main :: IO () function with return queryResult after queryResult <- mapM_ print =<< (query_ conn "select sensor1 from lightbool" :: IO [Only String]).

I need to convert these values with another function (lightBoolHandler). It needs to take the contents of a query -- which are fake "bools" that are actually strings -- and produce safely typed Haskell [Bool].

How can i make the contents/result of that IO action availble to other parts of the .hs file?

Script snippet:

main :: IO ()
main = do
  conn <- connectPostgreSQL "host=myHost.rds.amazonaws.com port=5432 user=myUser password=myPw dbname=myDBName"
  queryResult <- mapM_ print =<< (query_ conn "select sensor1 from lightbool" :: IO [Only String])
  return queryResult

lightBoolHandler :: [Only String] -> [Bool]
lightBoolHandler list = ?

For reference, if I run main in ghci, this is what I get:

Only {fromOnly = "TRUE"}
Only {fromOnly = "TRUE"}
Only {fromOnly = "TRUE"}
Only {fromOnly = "TRUE"}
Only {fromOnly = "FALSE"}
Only {fromOnly = "FALSE"}

Body:
No need to muddy the waters with a database example.  How do you pass values from one function to another in Haskell regardless of their source?  You pass the value as an argument in a function call.
 Consider:

main :: IO ()
main = do
  queryResult <- return ["True", "False"]
  mapM_ print queryResult
  let parsedResults = lightBoolHandler queryResult
  mapM_ print parsedResults

lightBoolHandler :: [String] -> [Bool]
lightBoolHandler = map read

Side Notes

queryResult <- mapM_ print =<< ...

Calling this a "result" is misleading.  Your mapM_ means "ignore the result and return ().  More, the result of print is not interesting.  presumably you would remove that part when developing and instead:

queryResult <- query ...
mapM_ print queryResult
let bools = lightBoolHandler queryResult
... use bools somehow ...


问:
TFS 2010 Upgrade Path to Azure DevOps Services - Circumvent or Not Circumvent?
I am preparing an upgrade of an on-premises TFS 2010 instance to the cloud-based Azure DevOps Services, using Microsoft's Data Migration Tool for Azure DevOps Migration to facilitate the collection database move to Azure DevOps Services. There are however a few key points or caveats to highlight relating to this proposed upgrade and these are listed below.

It will be an "In Place Upgrade", meaning we intend to use the existing "on-premises" hardware throughout the process.

Our TFS 2010 instance is hosted on a Windows Server 2008 R2 Enterprise server.

The Data Tier is implemented on a Microsoft SQL Server 2008 R2 instance.

Now, the Data Migration Guide recommends that to migrate to Azure DevOps Services, we first need to complete an upgrade from TFS 2010 to TFS 2013, as per the attached Upgrade path map. TFS 2013 however is not compatible with SQL Server 2008 R2 and requires SQL Server 2012 (Express, Standard, Enterprise).

On the other hand, TFS 2012 supports SQL Server 2008 R2 and can also then be upgraded directly to Azure DevOps Services, according to the Data Migration Tool's Recommended Upgrade Path. This, I believe will avoid the need to upgrade our current instance of SQL Server from SQL 2008 R2 to SQL Server 2012 (to upgrade to TFS 2013), in order to finally achieve our objective of upgrading to Azure DevOps Services.

Can anyone foresee any issues with this approach, or should we just bite the bullet and complete that SQL 2008 to SQL 2012 upgrade as suggested in the guide?

答:
You need to use supported hardware/software versions, end of story.

The premise under which you're operating is incorrect: The upgrade path is from TFS 2012 to Azure DevOps Server 2019, which is the last on-prem upgrade step before you can use the migration tool to migrate it. You can't use the migration tool on TFS 2012; you need to be using Azure DevOps Server 2019.