问:
Update a table column with some values in SQL Server
I need some help or guidance on this.

I have this situation where I don't have a primary key in the first table:

```<code>County,
Gender,
EconomyName,
HighestEducation,
HighestEducationCount,
EconomyCount
</code>```

In a second table, I have

```<code>County,
Gender,
HighestEducation,
HighestEducationCount
</code>```

I want to update the first table (HighestEducaiion, HighestEducationCount) from the second table value.

How to do this without a key? Here is the sample data, EconStat,EduStatu is blank in table 1.

```<code>County  Year    Gender  AgeDetails      EconStat    EducStatu   AgeCnt  EconCnt EduCnt
Carlow  2006    Male    Total persons                           20193   0       0
Carlow  2006    Male    Total whose                             17215   0       0
Carlow  2006    Male    Under 15 years                          2179    0       0
Carlow  2006    Male    15 years                                1366    0       0
Carlow  2006    Male    16 years                                2369    0       0
Carlow  2006    Male    17 years                                1767    0       0
Carlow  2006    Male    18 years                                2485    0       0
</code>```

In the second table

```<code>County  Year    Gender  EducStatu                                   EduCnt
Carlow  2006    Male    Total education ceased and not ceased       20193
Carlow  2006    Male    Total whose full-time education has ceased  17215
Carlow  2006    Male    Primary (incl. no formal education)         3536
Carlow  2006    Male    Lower secondary                             4408
</code>```

Note : always less data In the second table
Result should look like this

County  Year    Gender  AgeDetails      EconStat    EducStatu               AgeCnt  EconCnt EduCnt
Carlow  2006    Male    Total persons       Total education ceased and not ceased   20193   0   20193
Carlow  2006    Male    Total whose         Total whose full-time education has ceased  17215   0   17215
Carlow  2006    Male    Under 15 years      Primary (incl. no formal education) 2179    0   3536
Carlow  2006    Male    15 years            Lower secondary         1366    0   4408
Carlow  2006    Male    16 years                            2369    0   0
Carlow  2006    Male    17 years                            1767    0   0
Carlow  2006    Male    18 years                            2485    0   0

答:
The combination of County, Year and Gender columns are not unique. In your sample data, they have the exact same set of values for all rows in both the columns. So you cannot do any operations based on them. </p>

<p>In your second column, you are left with two columns - EducStatu, and EduCnt. From the data, EducStatu is the column that differentiates rows in the second table (in addition to the combination of the first three columns in that table). But you have mentioned that EduStatu is blank in the first table. So you don't have any link (through columns) between the first and second tables. From the data you have given here, there is no way to pragmatically summarize the data in second table to meaningful data in the first table. Unless you have more columns in both tables, you are out of luck. </p>

Body:
I need some help or guidance on this.

I have this situation where I don't have a primary key in the first table:

County,
Gender,
EconomyName,
HighestEducation,
HighestEducationCount,
EconomyCount

In a second table, I have

County,
Gender,
HighestEducation,
HighestEducationCount

I want to update the first table (HighestEducaiion, HighestEducationCount) from the second table value.

How to do this without a key? Here is the sample data, EconStat,EduStatu is blank in table 1.

County  Year    Gender  AgeDetails      EconStat    EducStatu   AgeCnt  EconCnt EduCnt
Carlow  2006    Male    Total persons                           20193   0       0
Carlow  2006    Male    Total whose                             17215   0       0
Carlow  2006    Male    Under 15 years                          2179    0       0
Carlow  2006    Male    15 years                                1366    0       0
Carlow  2006    Male    16 years                                2369    0       0
Carlow  2006    Male    17 years                                1767    0       0
Carlow  2006    Male    18 years                                2485    0       0

In the second table

County  Year    Gender  EducStatu                                   EduCnt
Carlow  2006    Male    Total education ceased and not ceased       20193
Carlow  2006    Male    Total whose full-time education has ceased  17215
Carlow  2006    Male    Primary (incl. no formal education)         3536
Carlow  2006    Male    Lower secondary                             4408

Note : always less data In the second table
Result should look like this

County  Year    Gender  AgeDetails      EconStat    EducStatu               AgeCnt  EconCnt EduCnt
Carlow  2006    Male    Total persons       Total education ceased and not ceased   20193   0   20193
Carlow  2006    Male    Total whose         Total whose full-time education has ceased  17215   0   17215
Carlow  2006    Male    Under 15 years      Primary (incl. no formal education) 2179    0   3536
Carlow  2006    Male    15 years            Lower secondary         1366    0   4408
Carlow  2006    Male    16 years                            2369    0   0
Carlow  2006    Male    17 years                            1767    0   0
Carlow  2006    Male    18 years                            2485    0   0

Body:
The combination of County, Year and Gender columns are not unique. In your sample data, they have the exact same set of values for all rows in both the columns. So you cannot do any operations based on them.

In your second column, you are left with two columns - EducStatu, and EduCnt. From the data, EducStatu is the column that differentiates rows in the second table (in addition to the combination of the first three columns in that table). But you have mentioned that EduStatu is blank in the first table. So you don't have any link (through columns) between the first and second tables. From the data you have given here, there is no way to pragmatically summarize the data in second table to meaningful data in the first table. Unless you have more columns in both tables, you are out of luck.


来源: stackexchange

问:
Multiple-target cross-browser drag& drop file upload
We're investigating if it's possible to have the following: A webpage with multiple 'folders' to which a user can drag & drop a files. It's meant to be used as an interface to upload scanned documents to an archive.

For example, we would have page that states: 'Quotes', 'Invoices' & 'Misc'. Depending on the sort of document the user would drag & drop the file from the local file system to one of these three folders. It should then upload the file to the correct folder on the web server.

Is this possible, and if it is, any existing solutions using ASP.NET?

答: You could use a silverlight app or a java applet, but those are the only solutions that I know of...  The users would obviously need to have silverlight or the jre installed.</p>

ContentLicense: CC BY-SA 2.5


问:
Kotlin in xml onClick not work
I learning kotlin, and now for me not cearly some moment. I have xml

```<code><ImageView
                    android:id="@+id/aries"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="10dp"
                    android:tag="1"
                    android:onClick="clickItemHoro"
                    android:src="@drawable/aries" />
</code>```

and fragment

```<code>class ChooseYourHoroscope : Fragment(){

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.fragment_welcome_old, container, false)

        return view;
    }

    fun clickItemHoro(v: View?){
        Log.e("clickItemHoro", v!!.tag.toString())
    }

}
</code>```

when i click button i have error:

Could not find method clickItemHoro(View) in a parent or ancestor
  Context for android:onClick attribute defined on view class
  android.support.v7.widget.AppCompatImageView with id 'aries'

why it happen? Code vary simple, but it not work, i cant understand why

答:
In Gradle file add

```<code>apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
</code>```

then activity add

```<code>   import kotlinx.android.synthetic.main.activity_main.*
</code>```

ContentLicense: CC BY-SA 3.0

Title: Kotlin in xml onClick not work

Body:
I learning kotlin, and now for me not cearly some moment. I have xml

<ImageView
                    android:id="@+id/aries"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="10dp"
                    android:tag="1"
                    android:onClick="clickItemHoro"
                    android:src="@drawable/aries" />

and fragment

class ChooseYourHoroscope : Fragment(){

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.fragment_welcome_old, container, false)

        return view;
    }

    fun clickItemHoro(v: View?){
        Log.e("clickItemHoro", v!!.tag.toString())
    }

}

when i click button i have error:

Could not find method clickItemHoro(View) in a parent or ancestor
  Context for android:onClick attribute defined on view class
  android.support.v7.widget.AppCompatImageView with id 'aries'

why it happen? Code vary simple, but it not work, i cant understand why

Body:
In Gradle file add

apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

then activity add

   import kotlinx.android.synthetic.main.activity_main.*


问:
Error Having From using Inner Join Query while connecting 3 three tables
I m trying to join three tables while using the join queries but when execute the code I have a face a syntax error in the FROM clause. I have write the snippet please suggest what is the error in my code.</p>

```<code> SELECT u.UserID, t.UserName,u.email, d.debit,d.credit,d.hand_on_cash
  FROM userdetails u JOIN usertable t  JOIN userdata d
  WHERE u.UserID=t.UserID
   AND u.UserID=d.UserID
  ORDER BY u.UserID,t.UserID
</code>```

答:
You are mixing old style and new style join syntax.  You should use the latter:

```<code>SELECT
    u.UserID,
    t.UserName,
    u.email,
    d.debit,
    d.credit,
    d.hand_on_cash
FROM userdetails u
INNER JOIN usertable t
    ON u.UserID = t.UserID
INNER JOIN userdata d
    ON u.UserID = d.UserID
ORDER BY
    u.UserID,
    t.UserID
</code>```

If you really wanted to use the old school Oracle style join, it would look like this:

```<code>SELECT
    u.UserID,
    t.UserName,
    u.email,
    d.debit,
    d.credit,
    d.hand_on_cash
FROM userdetails u, usertable t, userdata d   -- commas in the FROM clause
WHERE                                         -- not nice, but it should run
    u.UserID = t.UserID AND
    u.UserID = d.UserID                       -- the ON condition appears here
ORDER BY
    u.UserID,
    t.UserID
</code>```

Body:
I m trying to join three tables while using the join queries but when execute the code I have a face a syntax error in the FROM clause. I have write the snippet please suggest what is the error in my code.

 SELECT u.UserID, t.UserName,u.email, d.debit,d.credit,d.hand_on_cash
  FROM userdetails u JOIN usertable t  JOIN userdata d
  WHERE u.UserID=t.UserID
   AND u.UserID=d.UserID
  ORDER BY u.UserID,t.UserID

Body:
You are mixing old style and new style join syntax.  You should use the latter:

SELECT
    u.UserID,
    t.UserName,
    u.email,
    d.debit,
    d.credit,
    d.hand_on_cash
FROM userdetails u
INNER JOIN usertable t
    ON u.UserID = t.UserID
INNER JOIN userdata d
    ON u.UserID = d.UserID
ORDER BY
    u.UserID,
    t.UserID

If you really wanted to use the old school Oracle style join, it would look like this:

SELECT
    u.UserID,
    t.UserName,
    u.email,
    d.debit,
    d.credit,
    d.hand_on_cash
FROM userdetails u, usertable t, userdata d   -- commas in the FROM clause
WHERE                                         -- not nice, but it should run
    u.UserID = t.UserID AND
    u.UserID = d.UserID                       -- the ON condition appears here
ORDER BY
    u.UserID,
    t.UserID


问:
Vue-material stepper submit
How can I submit a vue material stepper?
I tried wrapping the md-stepper tag with a form tag like:

```<code><form @submit="onSubmit">
  <md-stepper md-vertical class="stepper">
    ...
  </md-stepper>
</form>
</code>```

But it is not working

So my question is how do i use the 'FINISH' button as a submit button or what's the right way to submit that form.

Thanks!

答:
Simply bind your onSubmit handler to the completed event on the stepper component...

```<code><md-stepper @completed="onSubmit" md-vertical class="stepper">
  ...
</md-stepper>
</code>```

There's no need for a <form>.

Title: Vue-material stepper submit

Body:
How can I submit a vue material stepper?
I tried wrapping the md-stepper tag with a form tag like:

<form @submit="onSubmit">
  <md-stepper md-vertical class="stepper">
    ...
  </md-stepper>
</form>

But it is not working

So my question is how do i use the 'FINISH' button as a submit button or what's the right way to submit that form.

Thanks!

Body:
Simply bind your onSubmit handler to the completed event on the stepper component...

<md-stepper @completed="onSubmit" md-vertical class="stepper">
  ...
</md-stepper>

There's no need for a <form>.


问:
what is the meaning of $ in typescript
I am learning Angular 2 with Typescript .
I came across an example which has quite confused me . Here it goes

In

component.ts

```<code>getValidation(state:any, thingName?: string) {
  let thing: string = state.path || thingName;
  let messages : string[] = [];
  messages.push(`You must enter a **${thing}**`);
}
</code>```

What is the significance of using $ and {} in the above example, until now I always used this.thing to use any variable?

答: What you're referring to our template literals in JavaScript (TypeScript is a typed superset of JavaScript*). It's a way to refer to variable defined outside of everything you have defined within the backticks.  So ${variable} is simply the way to reference it is all.

ContentLicense: CC BY-SA 4.0

Title: what is the meaning of $ in typescript

Body:
I am learning Angular 2 with Typescript .
I came across an example which has quite confused me . Here it goes

In

component.ts

getValidation(state:any, thingName?: string) {
  let thing: string = state.path || thingName;
  let messages : string[] = [];
  messages.push(`You must enter a **${thing}**`);
}

What is the significance of using $ and {} in the above example, until now I always used this.thing to use any variable?


问:
How to redirect to previous page using own back button?
I am using ng-routing in application in angularjs. I have my own back button. I want to go back to previous page from where I have redirected to this page? Kindly help me?

答: You can use history.back() on click of your back button. this will redirect to your previous page using browser's history.


问:
Array equation explanation
I would appreciate if someone could explain why the output of this code:

```<code>*a, b = [1, 2, 3, 4]
a[b-2] + b
</code>```

is 7. Could anyone please break it down line by line so I understand what's going on here? How does this become 7?

答:
To break anything down line by line one could use REPL:

```<code>*a, b = [1, 2, 3, 4]
#⇒ [1, 2, 3, 4]

a
#⇒ [1, 2, 3]

b
#⇒ 4
</code>```

Using splat operator, we have decomposed the original array to new array and the single value. Now everything is crystal clear: a[b-2] which is a[2], which is in turn 3 (check a array.) and b is still 4.

```<code>3 + 4
#⇒ 7
</code>```

Title: Array equation explanation

Body:
I would appreciate if someone could explain why the output of this code:

*a, b = [1, 2, 3, 4]
a[b-2] + b

is 7. Could anyone please break it down line by line so I understand what's going on here? How does this become 7?

Body:
To break anything down line by line one could use REPL:

*a, b = [1, 2, 3, 4]
#⇒ [1, 2, 3, 4]

a
#⇒ [1, 2, 3]

b
#⇒ 4

Using splat operator, we have decomposed the original array to new array and the single value. Now everything is crystal clear: a[b-2] which is a[2], which is in turn 3 (check a array.) and b is still 4.

3 + 4
#⇒ 7


问:
"undefined" function declared in another file?
I'm trying to write a basic go program that calls a function on a different file, but a part of the same package. However, it returns:

```<code>undefined: NewEmployee
</code>```

Here is the source code:

main.go:

```<code>package main

func main() {
emp := NewEmployee()
}
</code>```

employee.go:

```<code>package main

type Employee struct {
    name string
    age int
}

func NewEmployee() *Employee {
    p := &Employee{}
    return p
}

func PrintEmployee (p *Employee)  {
    return "Hello world!"
}
</code>```

答:
I just had the same problem in GoLand (which is Intellij IDEA for Go) and worked out a solution. You need to change the Run kind from File to Package or Directory. You can choose this from a drop-down if you go into Run/Edit Configurations.

Eg: for package ~/go/src/a_package, use a Package path of a_package and a Directory of ~/go/src/a_package and Run kind of Package or Directory.

Body:
I'm trying to write a basic go program that calls a function on a different file, but a part of the same package. However, it returns:

undefined: NewEmployee

Here is the source code:

main.go:

package main

func main() {
emp := NewEmployee()
}

employee.go:

package main

type Employee struct {
    name string
    age int
}

func NewEmployee() *Employee {
    p := &Employee{}
    return p
}

func PrintEmployee (p *Employee)  {
    return "Hello world!"
}


Title: Array equation explanation

Body:
*a, b = [1, 2, 3, 4] it means  a = [1,2,3] and b = 4 when you do a[b-2] + b it will be

                +-----------------------+
a[b-2]   + b    |        a[2]           |
a[4-2]   + 4    |          |            |
a[2]     + 4    |  a[1, 2, 3]           |
3        + 4    |    0  1  2 -> index   |
= 7             +-----------------------+


问:
Correct way to retrieve token for FCM - iOS 10 Swift 3
i had implement Firebase with FirebaseAuth/FCM etc and did sent notification successfully through Firebase Console.

However i would need to push the notification from my own app server.

i am wondering below which way is correct way to retrieve the registration id for the device:-

1) retrieve registration id token from didRegisterForRemoteNotificationWithDeviceToken

```<code>func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    var token = ""

    for i in 0..<deviceToken.count {
        token += String(format: "%02.2hhx", arguments: [deviceToken[i]])
    }

    print("Registration succeeded!")
    print("Token: ", token)
    Callquery(token)

}
</code>```

2) Retrieve Registration token from firebase (Based on Firebase document which retrieve the current registration token)

```<code>let token = FIRInstanceID.instanceID().token()!
</code>```

i was using the first way, the push notification is not being received even the registration id is stored on my app server database accordingly and i get this CURL session result :-

```<code>{"multicast_id":6074293608087656831,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
</code>```

i had also tried the second way and get fatal error while running the app as below:-

appreciated if anyone could point me the right way, thanks!

答:
FCM Device Token swift3

```<code>    let fcmDeviceToken = FIRInstanceID.instanceID().token()
    print("FCM token: \(fcmDeviceToken ?? "")")
</code>```

Body:
i had implement Firebase with FirebaseAuth/FCM etc and did sent notification successfully through Firebase Console.

However i would need to push the notification from my own app server.

i am wondering below which way is correct way to retrieve the registration id for the device:-

1) retrieve registration id token from didRegisterForRemoteNotificationWithDeviceToken

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    var token = ""

    for i in 0..<deviceToken.count {
        token += String(format: "%02.2hhx", arguments: [deviceToken[i]])
    }

    print("Registration succeeded!")
    print("Token: ", token)
    Callquery(token)

}

2) Retrieve Registration token from firebase (Based on Firebase document which retrieve the current registration token)

let token = FIRInstanceID.instanceID().token()!

i was using the first way, the push notification is not being received even the registration id is stored on my app server database accordingly and i get this CURL session result :-

{"multicast_id":6074293608087656831,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}

i had also tried the second way and get fatal error while running the app as below:-

appreciated if anyone could point me the right way, thanks!

Body:
FCM Device Token swift3

    let fcmDeviceToken = FIRInstanceID.instanceID().token()
    print("FCM token: \(fcmDeviceToken ?? "")")


问:
How to display YouTube like black title box?
I want to view black title box instead of regular title box like  and I think there is readymade HTML tag for this as far I know because i have seen it somewhere else but couldn't remember at all! Please help me if you know the tag for this.

Above share button you can see a black box titled Share. I want to view that!

答:
These are Bootstrap tooltips. You can find the documentation here : Bootstrap Tooltips.

If you include Bootstrap library you get easily modifiable and editable tooltips and many more things.


问:
Undefined class constant 'TYPE_LIST' yii2-widget-depdrop
I'm using yii2 in local server but I face error like this

```<code>Undefined class constant 'TYPE_LIST'
...
...
'type' => DepDrop::TYPE_LIST
...
...
</code>```

So, I check vendor/kartik-v/yii2-widget-depdrop/DepDrop.php

There is no const TYPE_LIST but when I check thus file in production server there is const TYPE_LIST = 3

Package version is yii2-widget-depdrop 1.0.4 for both server, production and local

But when I check official package repo https://github.com/kartik-v/yii2-widget-depdrop/blob/master/DepDrop.php

There is no const TYPE_LIST

How I can fix this error?

Thanks in advance

答:
You are looking to the wrong component

for depdrop the type is

type: int the type of dropdown list to be generated. Should be one of
  the following values:

1 or DepDrop::TYPE_DEFAULT: render a default HTML select using
  \yii\helpers\Html::dropDownList.

2 or DepDrop::TYPE_SELECT2: render advanced Select2 using
  \kartik\widgets\Select2 widget.

If not set the type will default to 1 or DepDrop::TYPE_DEFAULT.

for sortable type is

The Sortable widget allows you to configure the following properties:
  type: string, the type of the sortable widget. Defaults to
  Sortable::TYPE_LIST. Should be one of

Sortable::TYPE_LIST or list

Sortable::TYPE_GRID or grid

http://demos.krajee.com/sortable

http://demos.krajee.com/widget-details/depdrop

Body:
I'm using yii2 in local server but I face error like this

Undefined class constant 'TYPE_LIST'
...
...
'type' => DepDrop::TYPE_LIST
...
...

So, I check vendor/kartik-v/yii2-widget-depdrop/DepDrop.php

There is no const TYPE_LIST but when I check thus file in production server there is const TYPE_LIST = 3

Package version is yii2-widget-depdrop 1.0.4 for both server, production and local

But when I check official package repo https://github.com/kartik-v/yii2-widget-depdrop/blob/master/DepDrop.php

There is no const TYPE_LIST

How I can fix this error?

Thanks in advance


问:
Inner join update set postgresql
So I want to make the product between the sum of the number of days that a prisoner has worked and the multiplication coefficient for the specific task.
I tried this code:

```<code>UPDATE prisoners
    SET nr_days_equaled = (SELECT COALESCE (multiplication_coefficient*SUM(nr_days_worked),0)
                           FROM prisoners pr
                              INNER JOIN timesheets_prisoners tp ON pr.idprisoner= tp.idprisoner
                              INNER JOIN nomenclature_activities_prisoners nap ON pp.idactivity=nap.idactivity)
</code>```

But I get the following error:

column "nap.multiplication_coefficient" must appear in the GROUP BY clause or be used in an aggregate function

What can I do? Any ideas?

答:
Welcome to StackOverflow.

When using any aggregate function (SUM, COUNT, MIN MAX etc.) together with any other field in your select statement, you must GROUP By the other fields selected.  So in your case the compiler wants:

```<code>UPDATE prisoners
SET nr_days_equaled =
(SELECT COALESCE (multiplication_coefficient*SUM(nr_days_worked),0)
FROM prisoners pr INNER JOIN timesheets_prisoners tp
ON pr.idprisoner= tp.idprisoner
INNER JOIN nomenclature_activities_prisoners nap
ON pp.idactivity=nap.idactivity GROUP BY multiplication_coefficient)
</code>```

However, without seeing the inner structure of your tables, I suspect that this is not really what you want.  My suspicion is that you really need

```<code>SET nr_days_equaled =
(SELECT COALESCE (SUM(multiplication_coefficient*nr_days_worked),0)
FROM prisoners pr INNER JOIN timesheets_prisoners tp
ON pr.idprisoner= tp.idprisoner
INNER JOIN nomenclature_activities_prisoners nap
ON pp.idactivity=nap.idactivity)
</code>```

The difference is that this version allows for different multiplication_coefficients for different work, but still sums the total.  I stress that I am not sure.  Please test by converting this to a SELECT statement before issuing the UPDATE.

EDIT

Having seen the structure, what you need is:

```<code>UPDATE prisoners
SET nr_days_equaled = SubQ.sumdaysmult
FROM
(SELECT pr.idprisoner, COALESCE (ppnap.sumdaysmult, 0) AS sumdaysmult FROM
FROM prisoners pr LEFT JOIN (SELECT tp.idprisoner, SUM(tp.nr_days_worked
* nap.multiplication_coefficient) as sumdaysmult
FROM timesheets_prisoners tp
INNER JOIN nomenclature_activities_prisoners nap
ON tp.idactivity=nap.idactivity GROUP BY tp.idprisoner) tpnap
ON tpnap.idprisoner = pr.idprisoner) AS SubQ
WHERE SubQ.idprisoner = prisoners.idprisoner
</code>```

Title: Inner join update set postgresql

Body:
So I want to make the product between the sum of the number of days that a prisoner has worked and the multiplication coefficient for the specific task.
I tried this code:

UPDATE prisoners
    SET nr_days_equaled = (SELECT COALESCE (multiplication_coefficient*SUM(nr_days_worked),0)
                           FROM prisoners pr
                              INNER JOIN timesheets_prisoners tp ON pr.idprisoner= tp.idprisoner
                              INNER JOIN nomenclature_activities_prisoners nap ON pp.idactivity=nap.idactivity)

But I get the following error:

column "nap.multiplication_coefficient" must appear in the GROUP BY clause or be used in an aggregate function

What can I do? Any ideas?

Body:
Welcome to StackOverflow.

When using any aggregate function (SUM, COUNT, MIN MAX etc.) together with any other field in your select statement, you must GROUP By the other fields selected.  So in your case the compiler wants:

UPDATE prisoners
SET nr_days_equaled =
(SELECT COALESCE (multiplication_coefficient*SUM(nr_days_worked),0)
FROM prisoners pr INNER JOIN timesheets_prisoners tp
ON pr.idprisoner= tp.idprisoner
INNER JOIN nomenclature_activities_prisoners nap
ON pp.idactivity=nap.idactivity GROUP BY multiplication_coefficient)

However, without seeing the inner structure of your tables, I suspect that this is not really what you want.  My suspicion is that you really need

SET nr_days_equaled =
(SELECT COALESCE (SUM(multiplication_coefficient*nr_days_worked),0)
FROM prisoners pr INNER JOIN timesheets_prisoners tp
ON pr.idprisoner= tp.idprisoner
INNER JOIN nomenclature_activities_prisoners nap
ON pp.idactivity=nap.idactivity)

The difference is that this version allows for different multiplication_coefficients for different work, but still sums the total.  I stress that I am not sure.  Please test by converting this to a SELECT statement before issuing the UPDATE.

EDIT

Having seen the structure, what you need is:

UPDATE prisoners
SET nr_days_equaled = SubQ.sumdaysmult
FROM
(SELECT pr.idprisoner, COALESCE (ppnap.sumdaysmult, 0) AS sumdaysmult FROM
FROM prisoners pr LEFT JOIN (SELECT tp.idprisoner, SUM(tp.nr_days_worked
* nap.multiplication_coefficient) as sumdaysmult
FROM timesheets_prisoners tp
INNER JOIN nomenclature_activities_prisoners nap
ON tp.idactivity=nap.idactivity GROUP BY tp.idprisoner) tpnap
ON tpnap.idprisoner = pr.idprisoner) AS SubQ
WHERE SubQ.idprisoner = prisoners.idprisoner


答:
when you assign array like this,

```<code>*a, b = [1, 2, 3, 4]
</code>```

then it will assign

```<code>a = [1,2,3]
</code>```

and b = 4

Now when you tried to print a[b-2] + b

```<code>a[b - 2] = 3
b = 4
3 + 4 = 7
</code>```

for more understanding use rails console and run line by line.

Title: Array equation explanation

Body:
when you assign array like this,

*a, b = [1, 2, 3, 4]

then it will assign

a = [1,2,3]

and b = 4

Now when you tried to print a[b-2] + b

a[b - 2] = 3
b = 4
3 + 4 = 7

for more understanding use rails console and run line by line.


问:
using xsd.exe to generate c# files, getting error and warnings
This is the command i'm running:

```<code>xsd.exe -c -l:c# D:\Documents\DEV\SARPilot\Docs\schemas\06-141r2\06-141r2.xsd
</code>```

These are the errors i'm getting:

```<code>Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 2.0.50727.3038]
Copyright (C) Microsoft Corporation. All rights reserved.
Schema validation warning: Undefined complexType 'http://www.opengis.net/sps/0:ParameterDescriptorType' is used as a base for comp
lex type extension. Line 617, position 2.
Schema validation warning: Undefined complexType 'http://www.opengis.net/ows:GetCapabilitiesType' is used as a base for complex ty
pe extension. Line 23, position 2.
Schema validation warning: Undefined complexType 'http://www.opengis.net/ows:CapabilitiesBaseType' is used as a base for complex t
ype extension. Line 35, position 2.
Schema validation warning: The 'http://www.opengis.net/gml:Point' element is not declared. Line 869, position 2.
Schema validation warning: The 'http://www.opengis.net/gml:Polygon' element is not declared. Line 870, position 2.
Schema validation warning: The 'http://www.opengis.net/gml:Rectangle' element is not declared. Line 871, position 2.
Schema validation warning: The 'http://www.opengis.net/sps/0:Parameter' element is not declared. Line 381, position 2.
Schema validation warning: The 'http://www.opengis.net/sps/0:ID' element is not declared. Line 451, position 2.

Warning: Schema could not be validated. Class generation may fail or may produce incorrect results.

Error: Error generating classes for schema 'D:\Documents\DEV\SARPilot\Docs\schemas\06-141r2\06-141r2'.
  - The datatype 'http://www.opengis.net/ows:GetCapabilitiesType' is missing.

If you would like more help, please type "xsd /?".

C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin>
</code>```

The XSD file was copy/pasted from Appendix A in the following document:
http://services.eoportal.org/portal/documents/06-141r2_Ordering_Services_for_Earth_Observation_Products_0.9.2.pdf

答:
The XML Schema included in the PDF document you linked has references to several other XSD files using the <import> element. You will need to download these additional schema files and make sure that the path references in the <import> elements are pointing to the correct locations on your local computer.

If you are still getting errors, it is because xsd.exe could not follow up on external references. To solve this issue, specify all the required XSD files directly on the command line as follows:

xsd.exe /c MySchema.xsd Import01.xsd Import02.xsd Include01.xsd Include02.xsd

where Import01.xsd, Import02.xsd, Include01.xsd and Include02.xsd are XSD files referenced via import and include elements in MySchema.xsd.

Body:
This is the command i'm running:

xsd.exe -c -l:c# D:\Documents\DEV\SARPilot\Docs\schemas\06-141r2\06-141r2.xsd

These are the errors i'm getting:

Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 2.0.50727.3038]
Copyright (C) Microsoft Corporation. All rights reserved.
Schema validation warning: Undefined complexType 'http://www.opengis.net/sps/0:ParameterDescriptorType' is used as a base for comp
lex type extension. Line 617, position 2.
Schema validation warning: Undefined complexType 'http://www.opengis.net/ows:GetCapabilitiesType' is used as a base for complex ty
pe extension. Line 23, position 2.
Schema validation warning: Undefined complexType 'http://www.opengis.net/ows:CapabilitiesBaseType' is used as a base for complex t
ype extension. Line 35, position 2.
Schema validation warning: The 'http://www.opengis.net/gml:Point' element is not declared. Line 869, position 2.
Schema validation warning: The 'http://www.opengis.net/gml:Polygon' element is not declared. Line 870, position 2.
Schema validation warning: The 'http://www.opengis.net/gml:Rectangle' element is not declared. Line 871, position 2.
Schema validation warning: The 'http://www.opengis.net/sps/0:Parameter' element is not declared. Line 381, position 2.
Schema validation warning: The 'http://www.opengis.net/sps/0:ID' element is not declared. Line 451, position 2.

Warning: Schema could not be validated. Class generation may fail or may produce incorrect results.

Error: Error generating classes for schema 'D:\Documents\DEV\SARPilot\Docs\schemas\06-141r2\06-141r2'.
  - The datatype 'http://www.opengis.net/ows:GetCapabilitiesType' is missing.

If you would like more help, please type "xsd /?".

C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin>

The XSD file was copy/pasted from Appendix A in the following document:
http://services.eoportal.org/portal/documents/06-141r2_Ordering_Services_for_Earth_Observation_Products_0.9.2.pdf


问:
Override static method in graph extension
I don't think this is possible but thought I would ask anyway.

There is a method on the PX.Objects.AR.ARStatementPrint graph that I want to override.

Its declaration is as follows

```<code>public static void PrintStatements(PrintParameters filter,  List<DetailsResult> list, bool markOnly)
{
}
</code>```

I want to override this is my graph extension but I get errors saying cannot find the method to override in the graph etc when I use the [PXOverride]

Can you only override virtual methods with [PXOverride]?

答: As of right now, one can only override virtual methods with [PXOverride].</p>

Body:
I don't think this is possible but thought I would ask anyway.

There is a method on the PX.Objects.AR.ARStatementPrint graph that I want to override.

Its declaration is as follows

public static void PrintStatements(PrintParameters filter,  List<DetailsResult> list, bool markOnly)
{
}

I want to override this is my graph extension but I get errors saying cannot find the method to override in the graph etc when I use the [PXOverride]

Can you only override virtual methods with [PXOverride]?


问:
Java Thread: Run method cannot throw checked exception
In Java thread, the 'run' method cannot throw a 'checked exception'. I came across this in the Core Java (vol 1)  book. Can someone please explain the reasoning behind it? </p>

答:
The more obvious solution to the previous answers is that if you throw a checked exception, you are not correctly implementing run() as specified in the runnable interface.

It won't even compile:

```<code>run() in TestClass cannot implement run() in java.lang.Runnable;
overridden method does not throw java.lang.Exception
</code>```

Body:
The more obvious solution to the previous answers is that if you throw a checked exception, you are not correctly implementing run() as specified in the runnable interface.

It won't even compile:

run() in TestClass cannot implement run() in java.lang.Runnable;
overridden method does not throw java.lang.Exception


问:
How to access child of a component in jest in a react/redux app
I like to test a component inside Connect in a Redux app:

```<code>this.component = TestUtils.renderIntoDocument(<Provider store={store}><Header path={this.path} /></Provider>);
</code>```

I have no idea about how to access Header inside Provider...(since I can not stop through in a debugger when running the jest from CLI.

So when I tried to get a child inside Header

```<code>      const path = findDOMNode(self.component.refs.pathElemSpan);
      console.log("path="+path)
</code>```

I got undefined on path

Any suggestion?

thanks

答:
Are you looking for this ? </p>

```<code>function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

function App() {
  return (
    <div>
      <Welcome name="Sara" />
      <Welcome name="Cahal" />
      <Welcome name="Edite" />
    </div>
  );
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);
</code>```

Body:
I like to test a component inside Connect in a Redux app:

this.component = TestUtils.renderIntoDocument(<Provider store={store}></Provider>);

I have no idea about how to access Header inside Provider...(since I can not stop through in a debugger when running the jest from CLI.

So when I tried to get a child inside Header

      const path = findDOMNode(self.component.refs.pathElemSpan);
      console.log("path="+path)

I got undefined on path

Any suggestion?

thanks

Body:
Are you looking for this ?

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

function App() {
  return (
    <div>
      <Welcome name="Sara" />
      <Welcome name="Cahal" />
      <Welcome name="Edite" />
    </div>
  );
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);


问:
Difference between classes in Java vs JavaScript?
I have some experience with C# and Java, but I'm trying to learn javascript/node.js. I can't quite figure out what the problem is with this code.

So I have my main.js file, and it has this code:

```<code>const MyClass = require("./MyClass");
let myclass = new MyClass("my string!");

myclass.repeatString();
</code>```

The MyClass it's calling has this code:

```<code>class MyClass {
    constructor(myString) {
        this.myString = myString;
    }

    repeatString() {
        console.log(myString);
    }
}

module.exports = MyClass;
</code>```

When I try to run this, I get ReferenceError: myString is not defined when it tries to execute that repeatString() method. What am I doing wrong/what's the right way to do this?

答: To print myString varible use console.log(this.myString);

Body:
I have some experience with C# and Java, but I'm trying to learn javascript/node.js. I can't quite figure out what the problem is with this code.

So I have my main.js file, and it has this code:

const MyClass = require("./MyClass");
let myclass = new MyClass("my string!");

myclass.repeatString();

The MyClass it's calling has this code:

class MyClass {
    constructor(myString) {
        this.myString = myString;
    }

    repeatString() {
        console.log(myString);
    }
}

module.exports = MyClass;

When I try to run this, I get ReferenceError: myString is not defined when it tries to execute that repeatString() method. What am I doing wrong/what's the right way to do this?


问:
How to update service worker cache in PWA?
I use service worker with sw-toolbox library. My PWA caches everything except API queries (images, css, js, html). But what if some files will be changed someday. Or what if service-worker.js will be changed.
How application should know about changes in files?

My service-worker.js:

```<code>'use strict';
importScripts('./build/sw-toolbox.js');

self.toolbox.options.cache = {
  name: 'ionic-cache'
};

// pre-cache our key assets
self.toolbox.precache(
  [
    './build/main.js',
    './build/main.css',
    './build/polyfills.js',
    'index.html',
    'manifest.json'
  ]
);

// dynamically cache any other local assets
self.toolbox.router.any('/*', self.toolbox.cacheFirst);

// for any other requests go to the network, cache,
// and then only use that cached resource if your user goes offline
self.toolbox.router.default = self.toolbox.networkFirst;
</code>```

I don't know what is the usual method to update cache in PWA. Maybe PWA should send AJAX request in background and check UI version?

答:
I dealt with services workers without using any library and the solution I ended up coming up with involved a bit of server side code and some client side. The strategy in a nutshell

Firstly the variables you will need and where:

On the server side have a "service worker version" variable (Put this in a database or config file if you are using something like php that will update immediately on the server side without requiring a redeploy. Let's call it serverSWVersion

On one of the javascript files you cache (I have a javascript file dedicated to this) have a global variable that will also be the "service worker version". Let's call it clientSWVersion

Now how to use the two:

Whenever a person lands on the page make an ajax call to your server to get the serverSWVersion value. Compare this with the clientSWVersion value.

If the values are different that means your web app version is not
the latest.

If this is the case then unregister the service worker and refresh the page so that the service worker will be re registered and the new files will be cached.

What to actually do when new file is available

Update the serviceSWVersion and clientSWVersion variables and upload to server where applicable.

When a person visits again then the service worker should be re registered and all the cached files will be retrieved.

I have provided a php server side based code that I used while I was implementing this strategy. It should show you the principles. Just drop the "Exercise" folder in a htdocs of a php server and it should work without you having to do anything else. I hope you find it useful... And remember you could just use a database instead of a config file to store the server side service worker variable if you are using some other server instead of php:

Zip file with code:
ServiceWorkerExercise.zip

Body:
I use service worker with sw-toolbox library. My PWA caches everything except API queries (images, css, js, html). But what if some files will be changed someday. Or what if service-worker.js will be changed.
How application should know about changes in files?

My service-worker.js:

'use strict';
importScripts('./build/sw-toolbox.js');

self.toolbox.options.cache = {
  name: 'ionic-cache'
};

// pre-cache our key assets
self.toolbox.precache(
  [
    './build/main.js',
    './build/main.css',
    './build/polyfills.js',
    'index.html',
    'manifest.json'
  ]
);

// dynamically cache any other local assets
self.toolbox.router.any('/*', self.toolbox.cacheFirst);

// for any other requests go to the network, cache,
// and then only use that cached resource if your user goes offline
self.toolbox.router.default = self.toolbox.networkFirst;

I don't know what is the usual method to update cache in PWA. Maybe PWA should send AJAX request in background and check UI version?


问:
Runtime of triple nested for loops
I'm currently going through "Cracking the coding interview" textbook and I'm reviewing Big-O and runtime. One of the examples were as such:

Print all positive integer solutions to the equation a^3 + b^3 = c^3 + d^3 where a, b, c, d are integers between 1 and 1000.

The psuedo code solution provided is:

```<code>n = 1000;
for c from 1 to n
  for d from 1 to n
    result = c^3 + d^3
    append (c,d) to list at value map[result]

for each result, list in map
  for each pair1 in list
    for each pair2 in list
      print pair1, pair2

The runtime is O(N^2)
</code>```

I'm not sure how O(N^2) is obtained and after extensive googling and trying to figure out why, I still have no idea. My rational is as following:

Top half is O(N^2) because the outer loop goes to n and inner loop executes n times each.

The bottom half I'm not sure how to calculate, but I got O(size of map) * O(size of list) * O(size of list) = O(size of map) * O(size of list^2).

O(N^2) + O(size of map) * O(size of list^2)

The 2 for loops adding the pairs to the list of the map = O(N) * O(N) b/c it's 2 for loops running N times.

The outer for loop for iterating through the map = O(2N-1) = O(N) b/c the size of the map is 2N - 1 which is essentially N.

The 2 for loops for iterating through the pairs of each list = O(N) * O(N) b/c each list is <= N

Total runtime: O(N^2) + O(N) * O(N^2) = O(N^3)

Not sure what I'm missing here

Could someone help me figure out how O(N^2) is obtained or why my solution is incorrect. Sorry if my explanation is a bit confusing. Thanks

答:
Based on the first part of the solution, sum(size of lists) == N. This means that the second part (nested loop) cannot be more complex then O(N^2). As you said, the complexity is O(size of map)*O(size of list^2), but it should rather be:

O(size of map)*(O(size of list1^2) + O(size of list2^2) + ... )

This means, that in the worst-case scenario we will get a map of size 1, and one list of size N, and the resulting complexity of O(1)*O((N-1)^2) <==> O(N^2)

In other scenarios the complexity will be lower. For instance if we have map of 2 elements, then we will get 2 lists with the total size of N. So the result will then be:

O(2)*( O(size of list1^2) + O(size of list2^2)), where (size of list1)+(size of list2) == N

and we know from basic maths that X^2 + Y^2 <= (X+Y)^2 for positive numbers.

Title: Runtime of triple nested for loops

Body:
I'm currently going through "Cracking the coding interview" textbook and I'm reviewing Big-O and runtime. One of the examples were as such:

Print all positive integer solutions to the equation a^3 + b^3 = c^3 + d^3 where a, b, c, d are integers between 1 and 1000.

The psuedo code solution provided is:

n = 1000;
for c from 1 to n
  for d from 1 to n
    result = c^3 + d^3
    append (c,d) to list at value map[result]

for each result, list in map
  for each pair1 in list
    for each pair2 in list
      print pair1, pair2

The runtime is O(N^2)

I'm not sure how O(N^2) is obtained and after extensive googling and trying to figure out why, I still have no idea. My rational is as following:

Top half is O(N^2) because the outer loop goes to n and inner loop executes n times each.

The bottom half I'm not sure how to calculate, but I got O(size of map) * O(size of list) * O(size of list) = O(size of map) * O(size of list^2).

O(N^2) + O(size of map) * O(size of list^2)

The 2 for loops adding the pairs to the list of the map = O(N) * O(N) b/c it's 2 for loops running N times.

The outer for loop for iterating through the map = O(2N-1) = O(N) b/c the size of the map is 2N - 1 which is essentially N.

The 2 for loops for iterating through the pairs of each list = O(N) * O(N) b/c each list is <= N

Total runtime: O(N^2) + O(N) * O(N^2) = O(N^3)

Not sure what I'm missing here

Could someone help me figure out how O(N^2) is obtained or why my solution is incorrect. Sorry if my explanation is a bit confusing. Thanks


问:
What is the point of this line of code?
I found this line of code in the Virtuemart plugin for Joomla on line 2136 in administrator/components/com_virtuemart/classes/ps_product.php</p>

```<code>eval ("\$text_including_tax = \"$text_including_tax\";");
</code>```

答: I'm guessing that it's a funky way of forcing $text_including_tax to be a string and not a number.</p>

OwnerDisplayName: mk

Title: What is the point of this line of code?

Body:
I found this line of code in the Virtuemart plugin for Joomla on line 2136 in administrator/components/com_virtuemart/classes/ps_product.php

eval ("\$text_including_tax = \"$text_including_tax\";");

OwnerDisplayName: Glomek


问:
Is it possible to develop a database app in Visual Studio 2010 for Microsoft SQL Server, then use MySQL instead?
The dev tools for SQL in Visual Studio are great.

Is it possible to develop an app for Microsoft SQL Server, and then deploy a MySQL-compatible database instead?

The dev tools for Microsoft SQL Server are really nice (i.e. LINQ support), but a MySQL-compatible column database has better performance for huge datasets.

答:
You can write your code for SQL Server and then switch to Devart LinqConnect.

For example, you can create a LINQ to SQL model using Entity Developer (in VS integration mode or in standalone mode), then change the connection to the MySQL-specific one and run Update Database from Model wizard (don't forget to select the Regenerate Storage check box).

As a result, you will obtain a MySQL database, having structure identical to the SQL Server one.


问:
table index for DISTINCT values
In my stored procedure, I need "Unique" values of one of the columns. I am not sure if I should and if I should, what type of Index I should apply on the table for better performance. No being very specific, the same case happens when I retrieve distinct values of multiple columns.
The column is of String(NVARCHAR) type.

e.g.

select DISTINCT Column1 FROM Table1;

OR

select DISTINCT Column1, Column2, Column3 FROM Table1;

答:
An index on these specific columns could improve performance by a bit, but just because it will require SQL Server to scan less data (just these specific columns, nothing else). Other than that - a SCAN will always be done. An option would be to create indexed view if you need distinct values from that table.

```<code>CREATE VIEW Test
WITH SCHEMABINDING
AS
SELECT Column1, COUNT_BIG(*) AS UselessColumn
FROM Table1
GROUP BY Column1;
GO
CREATE UNIQUE CLUSTERED INDEX PK_Test ON Test (Column1);
GO
</code>```

And then you can query it like that:

```<code>SELECT *
FROM Test WITH (NOEXPAND);
</code>```

NOEXPAND is a hint needed for SQL Server to not expand query in a view and treat it as a table. Note: this is needed for non Enterprise version of SQL Server only.

Title: table index for DISTINCT values

Body:
An index on these specific columns could improve performance by a bit, but just because it will require SQL Server to scan less data (just these specific columns, nothing else). Other than that - a SCAN will always be done. An option would be to create indexed view if you need distinct values from that table.

CREATE VIEW Test
WITH SCHEMABINDING
AS
SELECT Column1, COUNT_BIG(*) AS UselessColumn
FROM Table1
GROUP BY Column1;
GO
CREATE UNIQUE CLUSTERED INDEX PK_Test ON Test (Column1);
GO

And then you can query it like that:

SELECT *
FROM Test WITH (NOEXPAND);

NOEXPAND is a hint needed for SQL Server to not expand query in a view and treat it as a table. Note: this is needed for non Enterprise version of SQL Server only.


问:
Iterating over a mongodb cursor serially (waiting for callbacks before moving to next document)
Using mongoskin, I can do a query like this, which will return a cursor:

```<code>myCollection.find({}, function(err, resultCursor) {
      resultCursor.each(function(err, result) {

      }
}
</code>```

However, I'd like to call some async functions for each document, and only move on to the next item on the cursor after this has called back (similar to the eachSeries structure in the async.js module).  E.g:

```<code>myCollection.find({}, function(err, resultCursor) {
      resultCursor.each(function(err, result) {

            externalAsyncFunction(result, function(err) {
               //externalAsyncFunction completed - now want to move to next doc
            });

      }
}
</code>```

How could I do this?

Thanks

UPDATE:

I don't wan't to use toArray() as this is a large batch operation, and the results might not fit in memory in one go.

答:
A more modern approach that uses async/await:

```<code>const cursor = db.collection("foo").find({});
while(await cursor.hasNext()) {
  const doc = await cursor.next();
  // process doc here
}
</code>```

Notes:

This may be even more simple to do when async iterators arrive.

You'll probably want to add try/catch for error checking.

The containing function should be async or the code should be wrapped in (async function() { ... })() since it uses await.

If you want, add await new Promise(resolve => setTimeout(resolve, 1000)); (pause for 1 second) at the end of the while loop to show that it does process docs one after the other.

Body:
Using mongoskin, I can do a query like this, which will return a cursor:

myCollection.find({}, function(err, resultCursor) {
      resultCursor.each(function(err, result) {

      }
}

However, I'd like to call some async functions for each document, and only move on to the next item on the cursor after this has called back (similar to the eachSeries structure in the async.js module).  E.g:

myCollection.find({}, function(err, resultCursor) {
      resultCursor.each(function(err, result) {

            externalAsyncFunction(result, function(err) {
               //externalAsyncFunction completed - now want to move to next doc
            });

      }
}

How could I do this?

Thanks

UPDATE:

I don't wan't to use toArray() as this is a large batch operation, and the results might not fit in memory in one go.

Body:
A more modern approach that uses async/await:

const cursor = db.collection("foo").find({});
while(await cursor.hasNext()) {
  const doc = await cursor.next();
  // process doc here
}

Notes:

This may be even more simple to do when async iterators arrive.

You'll probably want to add try/catch for error checking.

The containing function should be async or the code should be wrapped in (async function() { ... })() since it uses await.

If you want, add await new Promise(resolve => setTimeout(resolve, 1000)); (pause for 1 second) at the end of the while loop to show that it does process docs one after the other.


问:
Defining a duplicate row by the first 20 characters of a cell
I am running a basic de-duplication script for a Google spreadsheet and have hit  roadblock. I want to base whether or not a row is a duplicate on only the first 20 characters in the columns I have defined, not the entire contents of the column.

I ran multiple searches and haven't found anything even close. I keep coming up with ways to remove the first X characters, but that doesn't do me any good.

Any help is greatly appreciated.

function removeDuplicates() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var data = sheet.getDataRange().getValues();
  var newData = new Array();
  for(i in data){
    var row = data[i];
    var duplicate = false;
    for(j in newData){
      if(row[0] == newData[j][0] && row[4] == newData[j][4]){
  duplicate = true;
}
    }
    if(!duplicate){
      newData.push(row);
    }
  }
  sheet.clearContents();
  sheet.getRange(1, 1, newData.length, newData[0].length).setValues(newData);
}```

答:
You were nearly there, If you could compare first 20 characters of column B of your spreadsheet with saved array, you can find duplicates.

substring() is the function you need to use

Read more: https://www.w3schools.com/jsref/jsref_substring.asp

```<code>function removeDuplicates()
{
  var sheet = SpreadsheetApp.getActiveSheet();
  var data = sheet.getDataRange().getValues();
  var newData = new Array();
  for(var i in data)
  {
    var row = data[i];
    var duplicate = false;
    for(var j in newData)
    {
    //row[1]=> column B value
      if(row[1].substring(0,20) == newData[j][1].substring(0,20)){
        duplicate = true;
      }
    }
    if(!duplicate){
      newData.push(row);
    }
  }
  sheet.clearContents();
  sheet.getRange(1, 1, newData.length, newData[0].length).setValues(newData);
}
</code>```

Body:
You were nearly there, If you could compare first 20 characters of column B of your spreadsheet with saved array, you can find duplicates.

substring() is the function you need to use

Read more: https://www.w3schools.com/jsref/jsref_substring.asp

function removeDuplicates()
{
  var sheet = SpreadsheetApp.getActiveSheet();
  var data = sheet.getDataRange().getValues();
  var newData = new Array();
  for(var i in data)
  {
    var row = data[i];
    var duplicate = false;
    for(var j in newData)
    {
    //row[1]=> column B value
      if(row[1].substring(0,20) == newData[j][1].substring(0,20)){
        duplicate = true;
      }
    }
    if(!duplicate){
      newData.push(row);
    }
  }
  sheet.clearContents();
  sheet.getRange(1, 1, newData.length, newData[0].length).setValues(newData);
}


问:
SQL return selected result to EF
In Entity Framework, I tried executing these two queries:

Query #1:

```<code>var deptInput = new SqlParameter("@DepartmentName", deptString);
var departmentTable = Database.Users.FromSql("EXECUTE dbo.
[ViewEmployeeListByDepartment] @DepartmentName", deptInput).ToList();
</code>```

Query #2:

```<code>var deptInput = new SqlParameter("@DepartmentName", deptString);
var departmentTable = Database.Database.ExecuteSqlCommand("EXECUTE dbo.
[ViewEmployeeListByDepartment] @DepartmentName", deptInput);
</code>```

And this is my stored procedure in SQL Server:

```<code>Declare @CounterForEmployees int
Declare @NumberOfEmployees int
Declare @TableCount int = 1

Declare @DepartmentTable TABLE(
    Id nvarchar(450),
    UserName nvarchar(256),
    Display_Name nvarchar(256),
    Direct_Supervisor nvarchar(256),
    Ranking int
);

SET @NumberOfEmployees = (SELECT Count(*)
                          FROM dbo.[User]
                          WHERE Department = @DepartmentName)
SET @CounterForEmployees = 0

--Get the HOD of the Department First
INSERT INTO @DepartmentTable
    SELECT
        Id, UserName, Display_Name, Direct_Supervisor, ''
    FROM
        [ASEAppraisalDB].[dbo].[User]
    WHERE
        Department = @DepartmentName AND
        UserName IN (SELECT Distinct(Head_Of_Department)
                     FROM [ASEAppraisalDB].[dbo].[User]
                     WHERE Department = @DepartmentName)

UPDATE @DepartmentTable
SET Ranking = @TableCount
WHERE Ranking = 0
.
.
.
.
.
.
.
.
SELECT * FROM @DepartmentTable
</code>```

When I execute the first one, it returns a error message saying there is missing column from the dbo.[User] table inside @DepartmentTable. The dbo.[User] table has some columns I did not select into @DepartmentTable.

When I execute the second one, it returns only a number (which is the number of employees). It seems that the second query has only selected the part that counts the employee. The number of employee is only needed for my other parts of my code for calculations for a while loop. I do not need to return it to the EF.

I only want the result from select * from @DepartmentTable to be returned to Entity Framework. In the parameter of the stored procedure in SQL Server Object Explorer, it also says that it returns integer shown below:

How do I fix this? Also Which query is more efficient and more 'correct' to use?

答:
when you map you stored procedure to your .edmx fle in enfity framework create a complex type.

first click on Generate column Information then click on Create New Complex Type

I will be yielding the result from complex type.
Since i am using a repository pattern i have created a generic function for executing stored procedure in my code which takes name of stored procedure as string and list of sql parameter.

```<code>public List<T> ExecuteStoredProc(string StoredProcName, List<SqlParameter> parameters)
    {
        List<T> list = null;
        try
        {

            if (!string.IsNullOrEmpty(StoredProcName))
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("Exec ");
                sb.Append(StoredProcName);

                foreach (SqlParameter item in parameters)
                {
                    if (list == null)
                    {
                        sb.Append(" @");
                        list = new List<T>();
                    }
                    else
                    {
                        sb.Append(", @");
                    }
                    sb.Append(item.ParameterName);
                    if (item.Direction == System.Data.ParameterDirection.Output)
                    {
                        sb.Append(" OUT");
                    }
                }

                list = Context.Database.SqlQuery<T>(sb.ToString(), parameters.Cast<object>().ToArray()).ToList();
            }

        }
        catch (SqlException ex)
        {
            //RAISERROR() has limitation of 255 characters, so complete error message is being passed through output parameter : @ErrorMessage
            if (parameters != null && parameters.Count > 0)
            {
                SqlParameter param = parameters.FirstOrDefault(a => a.Direction == ParameterDirection.Output && a.ParameterName == Constants.Constant.ParamErrorMessage);
                if (param != null)
                {
                    string errorMessage = Convert.ToString(param.Value);
                    if (!string.IsNullOrEmpty(errorMessage))
                    {
                        throw new JcomSqlException(errorMessage, ex);
                    }
                }
            }

            throw new JcomSqlException(ex.Message, ex);
        }
        return list;
    }

    Then use it with your repository

       List<GetDepartmentDetails_Result> getDepts(string deptName)
    {
        List<SqlParameter> spm = new List<SqlParameter>()
        {
            new SqlParameter() { ParameterName="@DepartmentName", Value=deptName}
        };
        var result = this.UnitOfWork.GetRepository<GetDepartmentDetails_Result>().ExecuteStoredProc("GetDepartmentDetails", spm);
        return result;

    }
</code>```

Title: SQL return selected result to EF

Body:
In Entity Framework, I tried executing these two queries:

Query #1:

var deptInput = new SqlParameter("@DepartmentName", deptString);
var departmentTable = Database.Users.FromSql("EXECUTE dbo.
[ViewEmployeeListByDepartment] @DepartmentName", deptInput).ToList();

Query #2:

var deptInput = new SqlParameter("@DepartmentName", deptString);
var departmentTable = Database.Database.ExecuteSqlCommand("EXECUTE dbo.
[ViewEmployeeListByDepartment] @DepartmentName", deptInput);

And this is my stored procedure in SQL Server:

Declare @CounterForEmployees int
Declare @NumberOfEmployees int
Declare @TableCount int = 1

Declare @DepartmentTable TABLE(
    Id nvarchar(450),
    UserName nvarchar(256),
    Display_Name nvarchar(256),
    Direct_Supervisor nvarchar(256),
    Ranking int
);

SET @NumberOfEmployees = (SELECT Count(*)
                          FROM dbo.[User]
                          WHERE Department = @DepartmentName)
SET @CounterForEmployees = 0

--Get the HOD of the Department First
INSERT INTO @DepartmentTable
    SELECT
        Id, UserName, Display_Name, Direct_Supervisor, ''
    FROM
        [ASEAppraisalDB].[dbo].[User]
    WHERE
        Department = @DepartmentName AND
        UserName IN (SELECT Distinct(Head_Of_Department)
                     FROM [ASEAppraisalDB].[dbo].[User]
                     WHERE Department = @DepartmentName)

UPDATE @DepartmentTable
SET Ranking = @TableCount
WHERE Ranking = 0
.
.
.
.
.
.
.
.
SELECT * FROM @DepartmentTable

When I execute the first one, it returns a error message saying there is missing column from the dbo.[User] table inside @DepartmentTable. The dbo.[User] table has some columns I did not select into @DepartmentTable.

When I execute the second one, it returns only a number (which is the number of employees). It seems that the second query has only selected the part that counts the employee. The number of employee is only needed for my other parts of my code for calculations for a while loop. I do not need to return it to the EF.

I only want the result from select * from @DepartmentTable to be returned to Entity Framework. In the parameter of the stored procedure in SQL Server Object Explorer, it also says that it returns integer shown below:

How do I fix this? Also Which query is more efficient and more 'correct' to use?

Body:
when you map you stored procedure to your .edmx fle in enfity framework create a complex type.

first click on Generate column Information then click on Create New Complex Type

I will be yielding the result from complex type.
Since i am using a repository pattern i have created a generic function for executing stored procedure in my code which takes name of stored procedure as string and list of sql parameter.

public List<T> ExecuteStoredProc(string StoredProcName, List<SqlParameter> parameters)
    {
        List<T> list = null;
        try
        {

            if (!string.IsNullOrEmpty(StoredProcName))
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("Exec ");
                sb.Append(StoredProcName);

                foreach (SqlParameter item in parameters)
                {
                    if (list == null)
                    {
                        sb.Append(" @");
                        list = new List<T>();
                    }
                    else
                    {
                        sb.Append(", @");
                    }
                    sb.Append(item.ParameterName);
                    if (item.Direction == System.Data.ParameterDirection.Output)
                    {
                        sb.Append(" OUT");
                    }
                }

                list = Context.Database.SqlQuery<T>(sb.ToString(), parameters.Cast<object>().ToArray()).ToList();
            }

        }
        catch (SqlException ex)
        {
            //RAISERROR() has limitation of 255 characters, so complete error message is being passed through output parameter : @ErrorMessage
            if (parameters != null && parameters.Count > 0)
            {
                SqlParameter param = parameters.FirstOrDefault(a => a.Direction == ParameterDirection.Output && a.ParameterName == Constants.Constant.ParamErrorMessage);
                if (param != null)
                {
                    string errorMessage = Convert.ToString(param.Value);
                    if (!string.IsNullOrEmpty(errorMessage))
                    {
                        throw new JcomSqlException(errorMessage, ex);
                    }
                }
            }

            throw new JcomSqlException(ex.Message, ex);
        }
        return list;
    }

    Then use it with your repository

       List<GetDepartmentDetails_Result> getDepts(string deptName)
    {
        List<SqlParameter> spm = new List<SqlParameter>()
        {
            new SqlParameter() { ParameterName="@DepartmentName", Value=deptName}
        };
        var result = this.UnitOfWork.GetRepository<GetDepartmentDetails_Result>().ExecuteStoredProc("GetDepartmentDetails", spm);
        return result;

    }


答: You should use group by using nap.multiplication_coefficient</p>

Title: Inner join update set postgresql

Body:
So I want to make the product between the sum of the number of days that a prisoner has worked and the multiplication coefficient for the specific task.
I tried this code:

UPDATE prisoners
    SET nr_days_equaled = (SELECT COALESCE (multiplication_coefficient*SUM(nr_days_worked),0)
                           FROM prisoners pr
                              INNER JOIN timesheets_prisoners tp ON pr.idprisoner= tp.idprisoner
                              INNER JOIN nomenclature_activities_prisoners nap ON pp.idactivity=nap.idactivity)

But I get the following error:

column "nap.multiplication_coefficient" must appear in the GROUP BY clause or be used in an aggregate function

What can I do? Any ideas?


问:
jasmine getFixtures is not a function
I'm developing some unitTests using Jasmine. I'm currently working on Windows8.1 and when I run my test I get following error message.

TypeError: jasmine.getFixtures() is not a function

This is the code that I'm using. I don't know what I must change in order to do this work.

Karma.conf.js

```<code>//More configuration entries
 ...........
  files: [
// app-specific code
'src/app/app.js',

// 3rd-party resources
'node_modules/angular-mocks/angular-mocks.js',

// test files
'test/unit/**/*.js',

//fixture to serve mockData in Tests
{ pattern: 'test/unit/mock-data/*.json' }
]
</code>```

Here is the piece of code from my test.

```<code>it('Should load my fixture', function(){
    jasmine.getFixtures().fixturesPath = 'HpIpsUi/test/unit/mock-data';
    var json = readFixtures('diagnostics.json');
    var result = JSON.parse(json);
    expect(result).toBeDefined();1
})
</code>```

It's not recognizing my call to the function jasmine.getFictures().

Thank you for your help

答:
Have you included the jasmine-query library? It's defined there, not in the jasmine library.

Said jasmine-query.js needs to be downloaded, and added as file, because it's not installable with npm yet.

Title: jasmine getFixtures is not a function

Body:
I'm developing some unitTests using Jasmine. I'm currently working on Windows8.1 and when I run my test I get following error message.

TypeError: jasmine.getFixtures() is not a function

This is the code that I'm using. I don't know what I must change in order to do this work.

Karma.conf.js

//More configuration entries
 ...........
  files: [
// app-specific code
'src/app/app.js',

// 3rd-party resources
'node_modules/angular-mocks/angular-mocks.js',

// test files
'test/unit/**/*.js',

//fixture to serve mockData in Tests
{ pattern: 'test/unit/mock-data/*.json' }
]

Here is the piece of code from my test.

it('Should load my fixture', function(){
    jasmine.getFixtures().fixturesPath = 'HpIpsUi/test/unit/mock-data';
    var json = readFixtures('diagnostics.json');
    var result = JSON.parse(json);
    expect(result).toBeDefined();1
})

It's not recognizing my call to the function jasmine.getFictures().

Thank you for your help


问:
wants to populate two drop down boxes on previous selected option
I am working on a very old coded project but it is running perfectly  on selected option.The coder populate one hidden drop down which is dynamic like this.

```<code>            <td class="hidden isagentname"><strong>
              <select name="agentnamee">
                <option value="">Please AgentName</option>
                  <?php $i = 0; while($i < $buyerCodeNum){ ?>
                <option value="<?php echo
                  mysql_result($buyerCode,$i,"name"); ?>"><?php echo
                  mysql_result($buyerCode,$i,"name"); ?>
                </option>
                  <?php $i++;}?>
              </select>
              <a href="#" class="remove" rel="agentname">remove</a>
              </strong>
            </td>
</code>```

now i want to populate two hidden drop down boxes on  selected option from first drop down box

i tried this but it is not working

```<code>using two <td> under one select tag
</code>```

kindly genius coders help me

答:
<!DOCTYPE html>

<select id='purpose'>
<option value="1">Personal use</option>
<option value="2">Business use</option>
<option value="3">Passing on to a client</option>
</select>

Business Name

 <select name="agentnamee" id="agentName">
 <option value="0">Please AgentName</option>
  <option value="1">zzz</option>
  <option value="2">xxx</option>
   <option value="3">yyy</option>

                    </select>
                    remove
      <select name="agentID" id="agentID">
 <option value="0">Please AgentID</option>
   <option value="1">1xxx</option>
  <option value="2">2xxx</option>
   <option value="3">3yyy</option>

                    </select>

```

YOu meant something like this? Onclicking the first dropdown option it will open second dropdown and so on?

Body:
I am working on a very old coded project but it is running perfectly  on selected option.The coder populate one hidden drop down which is dynamic like this.

              <select name="agentnamee">
                <option value="">Please AgentName</option>
                  <?php $i = 0; while($i < $buyerCodeNum){ ?>
                <option value="<?php echo
                  mysql_result($buyerCode,$i,"name"); ?>"><?php echo
                  mysql_result($buyerCode,$i,"name"); ?>
                </option>
                  <?php $i++;}?>
              </select>
              remove

now i want to populate two hidden drop down boxes on  selected option from first drop down box

i tried this but it is not working

using two  under one select tag

kindly genius coders help me

Body:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
 $('#agentName').hide();
 $('#agentID').hide();
    $('#purpose').on('change', function() {
      if (this.value > 0)
      {
       $('#agentName').show();
      }
      else
      {
        $("#agentName").hide();
      }
    });
 $("#agentName").on('click', function() {
      if (this.value > 0)
      {
       $('#agentID').show();
      }
     else
      {
        $("#agentID").hide();
      }
   });
});
</script>
</head>
<body>
<select id='purpose'>
<option value="1">Personal use</option>
<option value="2">Business use</option>
<option value="3">Passing on to a client</option>
</select>
<div style='display:none;' id='business'>Business Name</div>

 <select name="agentnamee" id="agentName">
 <option value="0">Please AgentName</option>
  <option value="1">zzz</option>
  <option value="2">xxx</option>
   <option value="3">yyy</option>

                    </select>
                    <a href="#" class="remove" rel="agentname">remove</a>
      <select name="agentID" id="agentID">
 <option value="0">Please AgentID</option>
   <option value="1">1xxx</option>
  <option value="2">2xxx</option>
   <option value="3">3yyy</option>

                    </select>

</body>
</html>

YOu meant something like this? Onclicking the first dropdown option it will open second dropdown and so on?


问:
jQuery or CSS: replacing the ® mark with ®
I have this HTML heading:

```<code><h1>Time Matters®</h1> (equals to: Time Matters®)
</code>```

I need a way to control the '&reg ;' mark either by CSS or jQuery. As far as I know, I don't think it's possible to target '&reg ;' with CSS, is there?

Now, if jQuery is used, I need to enclose '&reg ;' in  tags, like this:

```<code><h1>Time Matters<sup>®</sup></h1>
</code>```

...this way I can target the element via CSS.

I tried adapting this tutorial but the code encapsulates all words in  tags.

Any idea how to accomplish this? Any help would be greatly appreciated.

Thanks.

答:
A normal Javascript String .replace() should do it:

```<code>$(function() {
    $('h1').each(function(i, elem) {
        $(elem).html(function(i, html) {
            return html.replace(/(®)/, "<sup>$1</sup>");
        });
    });
});
</code>```

Example: http://www.jsfiddle.net/4yUqL/24/

```<code>// off-topic
</code>```

I just realized it, wow this looks pretty impressive

```<code>(®)(®)
</code>```

Title: jQuery or CSS: replacing the ® mark with <sup>®</sup>

Body:
I have this HTML heading:

Time Matters®
 (equals to: Time Matters®)

I need a way to control the '&reg ;' mark either by CSS or jQuery. As far as I know, I don't think it's possible to target '&reg ;' with CSS, is there?

Now, if jQuery is used, I need to enclose '&reg ;' in  tags, like this:

Time Matters®

...this way I can target the element via CSS.

I tried adapting this tutorial but the code encapsulates all words in  tags.

Any idea how to accomplish this? Any help would be greatly appreciated.

Thanks.

Body:
A normal Javascript String .replace() should do it:

$(function() {
    $('h1').each(function(i, elem) {
        $(elem).html(function(i, html) {
            return html.replace(/(®)/, "<sup>$1</sup>");
        });
    });
});

Example: http://www.jsfiddle.net/4yUqL/24/

// off-topic

I just realized it, wow this looks pretty impressive

(®)(®)


问:
Memory for a member array in C#
I have been programming for a while today and I think I need a break because I can't seem to figure this very simple thing. A help will be greatly appreciated.

I have a class (actually Form1) and there a member array int[,]f.
Now I don't manage memory for it there and then (maybe I should?).
Instead in another method, I call a function say:

```<code>myFunction(f,.....);
</code>```

this function is like

```<code>void myFunction(int[,] f, ...some other arguments)
{
    //....
    f = new int[NX ,NY];
    //....
}
</code>```

As you can see, I separate memory for the array f inside the function.

Now my question is; is this memory going to be garbage collected when I leave myFunction?

答:
First, you have to understand a few very important things:

Garbage Collection happens randomly.

Secondly,

Only those objects that have no variables referring to them are eligible for GC

Thirdly,

```<code>f= new int[NX,NY];
</code>```

You are making f refer to something else. The original f is still referenced by the Form1.f. But this new int[NX, NY] object is now created and referred to only by the local f in the method.

After the method returns, nothing should be referring to the new f (unless you assigned it to somewhere else), so the new f becomes eligible for GC. Note that I said "becomes eligible for GC" instead of "is garbage collected".

However, since Form1 is still holding a reference to the original f, the original f will not become eligible for GC before the form does (unless you set it to something else).

Title: Memory for a member array in C#

Body:
I have been programming for a while today and I think I need a break because I can't seem to figure this very simple thing. A help will be greatly appreciated.

I have a class (actually Form1) and there a member array int[,]f.
Now I don't manage memory for it there and then (maybe I should?).
Instead in another method, I call a function say:

myFunction(f,.....);

this function is like

void myFunction(int[,] f, ...some other arguments)
{
    //....
    f = new int[NX ,NY];
    //....
}

As you can see, I separate memory for the array f inside the function.

Now my question is; is this memory going to be garbage collected when I leave myFunction?

Body:
First, you have to understand a few very important things:

Garbage Collection happens randomly.

Secondly,

Only those objects that have no variables referring to them are eligible for GC

Thirdly,

f= new int[NX,NY];

You are making f refer to something else. The original f is still referenced by the Form1.f. But this new int[NX, NY] object is now created and referred to only by the local f in the method.

After the method returns, nothing should be referring to the new f (unless you assigned it to somewhere else), so the new f becomes eligible for GC. Note that I said "becomes eligible for GC" instead of "is garbage collected".

However, since Form1 is still holding a reference to the original f, the original f will not become eligible for GC before the form does (unless you set it to something else).


问:
Anagram - Minimum Number of deletion - failing certain test cases
This is a program that to solve the following question "Given two strings,  and , that may or may not be of the same length, determine the minimum number of character deletions required to make  and  anagrams. Any characters can be deleted from either of the strings". In the end, both strings should have the same letters and same frequency of each letter. For e.g., String A = ccda String B = dcac
My logic is to replace the letter that are same in both strings with a dummy string say "0". So when I count the number of letter in each string that is not equal to "0", it gives me the number of deletion.
But I don't know why this fails for certain cases.

```<code>#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int main(){
  int count =0;
  const char dummy= '0';
  int i =0, j=0;
    char* a = (char *)malloc(512000 * sizeof(char));
    scanf("%s",a);
    char* b = (char *)malloc(512000 * sizeof(char));
    scanf("%s",b);
    for (i=0;a[i]!= '\0' ;i++){
      for(j=0; b[j]!= '\0';j++){
        if (a[i]==b[j]){
          a[i]= dummy;
          b[j]= dummy;
        }

      }
    }
    for (i=0;a[i]!= '\0' ;i++){
      if(a[i]!= dummy){
        count = count+1;
      }
    }
    for (i=0;a[i]!= '\0' ;i++){
      if(b[i]!= dummy){
        count = count+1;
      }
    }
    printf("%d",count);
    return 0;
}
</code>```

One of the test case it failed was
String A : fcrxzwscanmligyxyvym
String B : jxwtrhvujlmrpdoqbisbwhmgpmeoke
Result given : 22
Expected result : 30

Can anyone please point me the error here. Please, thanks in advance!

答:
You've an error in your code - invalid condition in second loop.

```<code>for (i=0;a[i]!= '\0' ;i++){
  if(a[i]!= dummy){
    count = count+1;
  }
}
for (i=0;a[i]!= '\0' ;i++){
         ^^^^
  if(b[i]!= dummy){
    count = count+1;
  }
}
</code>```

In marked point should be b[i] rather than a[i].

Minor nitpicking: since you're learning to code, try to get few useful habbits as you go. Code should be pretty (not very pretty, mind you, but ascethic) - it helps to ease reading for both you and everyone else. Consequence matters. If you do spaces around operators, do it everywhere. Layout matters. All of that would help you notice your (common to pros as well, they just find it sooner) mistake.
Also there's a better algorithm in terms of running performance. :)

Body:
This is a program that to solve the following question "Given two strings,  and , that may or may not be of the same length, determine the minimum number of character deletions required to make  and  anagrams. Any characters can be deleted from either of the strings". In the end, both strings should have the same letters and same frequency of each letter. For e.g., String A = ccda String B = dcac
My logic is to replace the letter that are same in both strings with a dummy string say "0". So when I count the number of letter in each string that is not equal to "0", it gives me the number of deletion.
But I don't know why this fails for certain cases.

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int main(){
  int count =0;
  const char dummy= '0';
  int i =0, j=0;
    char* a = (char *)malloc(512000 * sizeof(char));
    scanf("%s",a);
    char* b = (char *)malloc(512000 * sizeof(char));
    scanf("%s",b);
    for (i=0;a[i]!= '\0' ;i++){
      for(j=0; b[j]!= '\0';j++){
        if (a[i]==b[j]){
          a[i]= dummy;
          b[j]= dummy;
        }

      }
    }
    for (i=0;a[i]!= '\0' ;i++){
      if(a[i]!= dummy){
        count = count+1;
      }
    }
    for (i=0;a[i]!= '\0' ;i++){
      if(b[i]!= dummy){
        count = count+1;
      }
    }
    printf("%d",count);
    return 0;
}

One of the test case it failed was
String A : fcrxzwscanmligyxyvym
String B : jxwtrhvujlmrpdoqbisbwhmgpmeoke
Result given : 22
Expected result : 30

Can anyone please point me the error here. Please, thanks in advance!

Body:
You've an error in your code - invalid condition in second loop.

for (i=0;a[i]!= '\0' ;i++){
  if(a[i]!= dummy){
    count = count+1;
  }
}
for (i=0;a[i]!= '\0' ;i++){
         ^^^^
  if(b[i]!= dummy){
    count = count+1;
  }
}

In marked point should be b[i] rather than a[i].

Minor nitpicking: since you're learning to code, try to get few useful habbits as you go. Code should be pretty (not very pretty, mind you, but ascethic) - it helps to ease reading for both you and everyone else. Consequence matters. If you do spaces around operators, do it everywhere. Layout matters. All of that would help you notice your (common to pros as well, they just find it sooner) mistake.
Also there's a better algorithm in terms of running performance. :)


问:
Read a file's data within a specified range using VB script. Is it possible?
This is the middle of the code I'm trying to work with. Is there a way to make the file it's reading open and read from line 2 to line 97? Where I need the correction is starred (****). What I'm trying to do is get the data from lines 2 through 97 to compare to another file I'll have to open from the same lines. The beginning and ends of each file are different but the middle information should match thus I need these specific lines. </p>

```<code>' Build Aliquot file name
strFile = aBarcodeExportDir & "A-" & yearStr & "-" & splitStr2(0) & ".csv"
'msgbox("open file: " & strFile)

If (objFS.FileExists(strFile)) Then
    ' Open A file
    Set objFile = objFS.OpenTextFile(strFile)

    ' Build string with file name minus extension - used later to determine EOF
    strFileNameNoExtension = "A-" & yearStr & "-" & splitStr2(0)

    ' Create dictionary to hold key/value pairs - key = position; value = barcode
    Set dictA = CreateObject("Scripting.Dictionary")

    ' Begin processing A file
    Do Until objFile.AtEndOfStream(*****)

        ' Read a line
        strLine = objFile.ReadLine(*****)

        ' Split on semi-colons
        splitStr = Split(strLine, ";")

        ' If splitStr array contains more than 1 element then continue
        If(UBound(splitStr) > 0) Then

            ' If barcode field is equal to file name then EOF
            If(splitStr(6) = strFileNameNoExtension) Then
                ' End of file - exit loop
                Exit Do
            Else
                ' Add to dictionary
                ' To calculate position
                ' A = element(2) = position in row (1-16)
                compA = splitStr(2)
                ' B = element(4) = row
                compB = splitStr(4)
                ' C = element(5.1) = number of max positions in row
                splitElement5 = Split(splitStr(5), "/")
                compC = splitElement5(0)
                ' position = C * (B - 1) + A
                position = compC * (compB - 1) + compA
                barcode = splitStr(6) & ";" & splitStr(0) & ";" & splitStr(1) & ";" & splitStr(2)

                'msgbox(position & ":" & barcode)

                ' Add to dictionary
                dictA.Add CStr(position), barcode

            End If

        End If
    Loop

    ' Close A file
    objFile.Close
</code>```

答:
To give the exact answer, we may have to look at your text files(I mean with all the split functions you are using). But, If you just want to compare lines 2-97 of two text files, you can get a hint from the following piece of code:</p>

```<code>strPath1 = "C:\Users\gr.singh\Desktop\abc\file1.txt"          'Replace with your File1 Path
strPath2 = "C:\Users\gr.singh\Desktop\abc\file2.txt"          'Replace with your File2 Path
Set objFso = CreateObject("Scripting.FileSystemObject")
Set objFile1 = objFso.OpenTextFile(strPath1,1)
Set objFile2 = objFso.OpenTextFile(strPath2,1)

blnMatchFailed = False
Do Until objFile1.AtEndOfStream
    If objFile1.Line=1 Then
        objFile1.SkipLine()                         'Skips the 1st line of both the files
        objFile2.SkipLine()
    ElseIf objFile1.Line>=2 And objFile1.Line<=97 Then
        strFile1 = objFile1.ReadLine()
        strFile2 = objFile2.ReadLine()
        If StrComp(strFile1,strFile2,1)<>0 Then     'textual comparison. Change 1 to 0, if you want binary comparison of both lines
            blnMatchFailed = True
            intFailedLine = objFile1.Line
            Exit Do                                 'As soon as match fails, exit the Do while Loop
        Else
            blnMatchFailed = False
        End If
    Else
        Exit Do
    End If
Loop

If blnMatchFailed Then
    MsgBox "Comparison Failed at line "&intFailedLine
Else
    MsgBox "Comparison Passed"
End If
objFile1.Close
objFile2.Close
Set objFile1 = Nothing
Set objFile2 = Nothing
Set objFso = Nothing
</code>```

Body:
This is the middle of the code I'm trying to work with. Is there a way to make the file it's reading open and read from line 2 to line 97? Where I need the correction is starred (****). What I'm trying to do is get the data from lines 2 through 97 to compare to another file I'll have to open from the same lines. The beginning and ends of each file are different but the middle information should match thus I need these specific lines.

' Build Aliquot file name
strFile = aBarcodeExportDir & "A-" & yearStr & "-" & splitStr2(0) & ".csv"
'msgbox("open file: " & strFile)

If (objFS.FileExists(strFile)) Then
    ' Open A file
    Set objFile = objFS.OpenTextFile(strFile)

    ' Build string with file name minus extension - used later to determine EOF
    strFileNameNoExtension = "A-" & yearStr & "-" & splitStr2(0)

    ' Create dictionary to hold key/value pairs - key = position; value = barcode
    Set dictA = CreateObject("Scripting.Dictionary")

    ' Begin processing A file
    Do Until objFile.AtEndOfStream(*****)

        ' Read a line
        strLine = objFile.ReadLine(*****)

        ' Split on semi-colons
        splitStr = Split(strLine, ";")

        ' If splitStr array contains more than 1 element then continue
        If(UBound(splitStr) > 0) Then

            ' If barcode field is equal to file name then EOF
            If(splitStr(6) = strFileNameNoExtension) Then
                ' End of file - exit loop
                Exit Do
            Else
                ' Add to dictionary
                ' To calculate position
                ' A = element(2) = position in row (1-16)
                compA = splitStr(2)
                ' B = element(4) = row
                compB = splitStr(4)
                ' C = element(5.1) = number of max positions in row
                splitElement5 = Split(splitStr(5), "/")
                compC = splitElement5(0)
                ' position = C * (B - 1) + A
                position = compC * (compB - 1) + compA
                barcode = splitStr(6) & ";" & splitStr(0) & ";" & splitStr(1) & ";" & splitStr(2)

                'msgbox(position & ":" & barcode)

                ' Add to dictionary
                dictA.Add CStr(position), barcode

            End If

        End If
    Loop

    ' Close A file
    objFile.Close

Body:
To give the exact answer, we may have to look at your text files(I mean with all the split functions you are using). But, If you just want to compare lines 2-97 of two text files, you can get a hint from the following piece of code:

strPath1 = "C:\Users\gr.singh\Desktop\abc\file1.txt"          'Replace with your File1 Path
strPath2 = "C:\Users\gr.singh\Desktop\abc\file2.txt"          'Replace with your File2 Path
Set objFso = CreateObject("Scripting.FileSystemObject")
Set objFile1 = objFso.OpenTextFile(strPath1,1)
Set objFile2 = objFso.OpenTextFile(strPath2,1)

blnMatchFailed = False
Do Until objFile1.AtEndOfStream
    If objFile1.Line=1 Then
        objFile1.SkipLine()                         'Skips the 1st line of both the files
        objFile2.SkipLine()
    ElseIf objFile1.Line>=2 And objFile1.Line<=97 Then
        strFile1 = objFile1.ReadLine()
        strFile2 = objFile2.ReadLine()
        If StrComp(strFile1,strFile2,1)<>0 Then     'textual comparison. Change 1 to 0, if you want binary comparison of both lines
            blnMatchFailed = True
            intFailedLine = objFile1.Line
            Exit Do                                 'As soon as match fails, exit the Do while Loop
        Else
            blnMatchFailed = False
        End If
    Else
        Exit Do
    End If
Loop

If blnMatchFailed Then
    MsgBox "Comparison Failed at line "&intFailedLine
Else
    MsgBox "Comparison Passed"
End If
objFile1.Close
objFile2.Close
Set objFile1 = Nothing
Set objFile2 = Nothing
Set objFso = Nothing


问:
Getting the current logged in user (FullToken Context)
I have a Problem, which is... i start a programm with right click -> run as administrator.
Which means the programm is running in an administrative context.

```<code>WindowsIdentity.GetCurrent().Name;
</code>```

if i try to get the user name that way i will get the user that started the programm as admin.. for example "administrator", but what i need is the name of the current logged in user which is for example: bob

Can anybody help me out? :)

答:
All .NET libraries will give you the user from the current context ('Administrator' in your case).

If you are trying to secure your code, you might consider reading about: Security in the .NET framework

Body:
I have a Problem, which is... i start a programm with right click -> run as administrator.
Which means the programm is running in an administrative context.

WindowsIdentity.GetCurrent().Name;

if i try to get the user name that way i will get the user that started the programm as admin.. for example "administrator", but what i need is the name of the current logged in user which is for example: bob

Can anybody help me out? :)


问:
"Java.lang.UnsatisfiedLinkError: no opencv_java320 in java.library.path"
I have a selenium test that when it finishes makes some operations with OpenCV. With IntelliJ IDEA it works fine, the operations process correctly, but when I try to execute through command line (for Jenkins use in the near future), I get the error mentioned above:

"Java.lang.UnsatisfiedLinkError: no opencv_java320 in java.library.path"

I read the other questions on here and I've set up the java.library.path to the path where the jar and dll files are, but the error still comes up and I'm running out of ideas.

Could you please help me?

Thanks!

答:
Please find below a working snippet. Which you need to adapt to your needs.

assume following file structure

```<code>libs\opencv_java320.dll
pom.xml
src\test\java\sub\optimal\OpenCVTest.java
</code>```

pom.xml - the part for the testing

```<code><build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.20</version>
            <configuration>
                <argLine>-Djava.library.path=${project.basedir}/libs/</argLine>
            </configuration>
        </plugin>
    </plugins>
</build>
</code>```

sub\optimal\OpenCVTest.java

```<code>package sub.optimal;
import org.junit.Test;
public class OpenCVTest {
    @Test
    public void someOpenCVTest() {
        System.out.printf("java.library.path: %s%n",
                System.getProperty("java.library.path"));
        System.loadLibrary("opencv_java320");
    }
}
</code>```

run the test

```<code>mvn compile test
</code>```

output

```<code>...
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running sub.optimal.OpenCVTest
java.library.path: X:\develop\opencv-demo/libs/
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: ...
...
</code>```

Body:
Please find below a working snippet. Which you need to adapt to your needs.

assume following file structure

libs\opencv_java320.dll
pom.xml
src\test\java\sub\optimal\OpenCVTest.java

pom.xml - the part for the testing

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.20</version>
            <configuration>
                <argLine>-Djava.library.path=${project.basedir}/libs/</argLine>
            </configuration>
        </plugin>
    </plugins>
</build>

sub\optimal\OpenCVTest.java

package sub.optimal;
import org.junit.Test;
public class OpenCVTest {
    @Test
    public void someOpenCVTest() {
        System.out.printf("java.library.path: %s%n",
                System.getProperty("java.library.path"));
        System.loadLibrary("opencv_java320");
    }
}

run the test

mvn compile test

output

...
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running sub.optimal.OpenCVTest
java.library.path: X:\develop\opencv-demo/libs/
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: ...
...


问:
how to put a text field on top of google maps iOS
My goal is to put a text field on top of google maps iOS but seems like it doesn't work

When I run the app, the text field doesn't exist on top of Google Maps

The code

```<code>import UIKit
import GoogleMaps

class ViewController: UIViewController {

    @IBOutlet var mapView: GMSMapView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let camera = GMSCameraPosition.camera(withLatitude: -33.86, longitude: 151.20, zoom: 6.0)
        mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)

        let marker = GMSMarker()
        marker.position = CLLocationCoordinate2D(latitude: -33.86, longitude: 151.20)
        marker.title = "Sydney"
        marker.snippet = "Australia"
        marker.map = mapView

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
</code>```

答: Instead of adding UITextField as subView of MapView, add both in a same UIView & just put the UITextfield over MApView. Change it like this

Body:
My goal is to put a text field on top of google maps iOS but seems like it doesn't work

When I run the app, the text field doesn't exist on top of Google Maps

The code

import UIKit
import GoogleMaps

class ViewController: UIViewController {

    @IBOutlet var mapView: GMSMapView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let camera = GMSCameraPosition.camera(withLatitude: -33.86, longitude: 151.20, zoom: 6.0)
        mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)

        let marker = GMSMarker()
        marker.position = CLLocationCoordinate2D(latitude: -33.86, longitude: 151.20)
        marker.title = "Sydney"
        marker.snippet = "Australia"
        marker.map = mapView

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}