答:
You have referred to ALI_LEASE_IN for DEF14 when you've have provided a table alias for it. Change that column to h.DEF14 AS e6.</p>

```<code>SELECT b.equip_name a2,
   b.model b3,
   b.def2 c4,
   b.def3 d5,
   h.DEF14 AS e6,
   '' f7,
   TO_CHAR (b.pre_rent) h9,
   b.start_date k10,
   sup.name j11,
   org.name l12,
   b.memo o13,
   h.bill_date bdate,
   h.pk_group
FROM   ali_lease_in_b b,
   ali_lease_in h,
   bd_supplier sup,
   org_itemorg org
WHERE      b.pk_lease_in = h.pk_lease_in
   AND h.pk_supplier = sup.pk_supplier
   AND b.pk_org = org.pk_itemorg
</code>```

Title: Invalid identifier when I query in my table

Body:
In my table ALI_LEASE_IN, I have a DEF14 field, (sorry about the red frame, choose to DEF16), you can see in my snapshot.

But when I execute the query sql:

select b.equip_name a2,b.model b3,b.def2 c4,b.def3 d5,
  ALI_LEASE_IN.DEF14 as e6,
  '' f7,
  To_char(b.pre_rent) h9,
  b.start_date k10,
  sup.name j11,
  org.name l12,
  b.memo o13,
  h.bill_date bdate,
  h.pk_group
from ali_lease_in_b b,ali_lease_in h,bd_supplier sup,org_itemorg org
where b.pk_lease_in=h.pk_lease_in
  and h.pk_supplier=sup.pk_supplier
  and b.pk_org=org.pk_itemorg

But I got this error below:

[SQL]select b.equip_name a2,b.model b3,b.def2 c4,b.def3 d5,
ALI_LEASE_IN.DEF14 as e6,
'' f7,
To_char(b.pre_rent) h9,b.start_date k10,sup.name j11,org.name l12, b.memo o13,h.bill_date bdate,h.pk_group
from ali_lease_in_b b,ali_lease_in h,bd_supplier sup,org_itemorg org
where b.pk_lease_in=h.pk_lease_in
and h.pk_supplier=sup.pk_supplier
and b.pk_org=org.pk_itemorg
--and h.pk_org in (parameter('param3'))
                   --     and substr(h.bill_date,1,10) >= parameter('param1')
                    --    and substr(h.bill_date,1,10) <= parameter('param2')
[Err] ORA-00904: "ALI_LEASE_IN"."DEF14": invalid identifier

I don't know why, my snapshot shows the DEF14 is exsits in my table.

My environment is :

database is Oracle,
visual software is navicat.

Body:
You have referred to ALI_LEASE_IN for DEF14 when you've have provided a table alias for it. Change that column to h.DEF14 AS e6.

SELECT b.equip_name a2,
   b.model b3,
   b.def2 c4,
   b.def3 d5,
   h.DEF14 AS e6,
   '' f7,
   TO_CHAR (b.pre_rent) h9,
   b.start_date k10,
   sup.name j11,
   org.name l12,
   b.memo o13,
   h.bill_date bdate,
   h.pk_group
FROM   ali_lease_in_b b,
   ali_lease_in h,
   bd_supplier sup,
   org_itemorg org
WHERE      b.pk_lease_in = h.pk_lease_in
   AND h.pk_supplier = sup.pk_supplier
   AND b.pk_org = org.pk_itemorg


来源: stackexchange

问:
Captive Network Assistant in Safari does not support Session Storage
I am building an Angular 2 application. The application is bootstrapped when a user joins the wifi network and they are redirected to the application which is rendered in a Captive Portal. The application works in all the other browsers with the exception of Safari for OS X.

I cannot debug this but from researching the behavior of OS X it seems that the Captive Portal Assistant launches some limited browser which does not support Session Storage.

https://grpugh.wordpress.com/2014/10/29/an-undocumented-change-to-captive-network-assistant-settings-in-os-x-10-10-yosemite/

This is breaking my application because when the appellation is bootstrapped it needs to store flags in Session storage before it redirects the user to the login page. Those flags are what the login page uses to determine if the user entered the application via the wifi redirect or the application url.

How do I get around this problem? I have researched and have not found any solution to my problem. Our application basically works from the point of a user attempting to access the private wifi network and this needs to work on a Mac.

答: Use cookies to store the flags instead? You could even check for window.sessionStorage availability and fall back to cookies if it's unavailable.

ContentLicense: CC BY-SA 3.0


问:
Is html title attribute a toolip?
I have question to know the truth. can some one tell me is HTML title attribute a tool tip.
Someone told me it is not a tooltip.
Can anybody describe what is a tool tip?
and HTML title is it or not?
I need the truth pleas.

答:
https://www.w3schools.com/tags/att_title.asp

"The title attribute is part of the Global Attributes, and can be used on any HTML element."

It is simply an attribute, and the value of this attribute is being shown by most browsers when hovering over the element looking like a tool tip.

In my opinion, it actually is a tooltip, since the value of the attribute is shown when the user hovers his mouse over the element. But the styling and even if the value is being shown is up to the browser, and you have no control over it.

It just depends on what is a tooltip for you personally :)
Usually, "web people" refer to tooltips as popup content when hovering over an element. Usually, these tooltips are being shown using JavaScript or vanilly CSS.
https://www.w3schools.com/howto/howto_css_tooltip.asp

My 2 cents - but I think it's really up to one personally whether you think of it as a tooltip.

Title: Is html title attribute a toolip?


问:
How to pass bitset of any size to a function?
The following program compiles fine.

```<code>#include <iostream>
#include <bitset>

void foo(std::bitset<10> n)
{
    std::cout << n.size() << "\n";
}

int main()
{
    std::bitset<10> n;
    foo(n);
}
</code>```

```<code>$ g++ -std=c++11 -Wall -Wextra -pedantic foo.cpp
$ ./a.out
10
</code>```

How can I modify the foo() function such that it can accept bitset of any size?

答:
The std::bitset<N> are types, so you can create a template function that accept a generic type

```<code>template <typename T>
void foo (T n)
 { std::cout << n.size() << "\n"; }
</code>```

Observe that this function will work with not only with all std::bitset but also with all types with a size() member that return a value that can be send to std::cout, as a lot of STL containers (std::set, std::vector, std::map, etc).

So, by example, you can also call foo() as follows

```<code> std::vector<int> v(20);
 foo(v);
</code>```

This can be good or bad, according to your requirements.

If you want a function that accept only a std::bitset, so you can follows the solution suggested by songyuanyao: you can explicit std::bitset and templatize the dimension.

```<code>template <std::size_t N>
void foo (std::bitset<N> n)
{ std::cout << n.size() << "\n"; }
</code>```

but, in this case, there is no need to use size(); you can use directly N

```<code>template <std::size_t N>
void foo (std::bitset<N>)
{ std::cout << N << "\n"; }
</code>```

If, in addiction, you want that foo accept a std::bitset<N> with (by example) N in a range of values (say [10,20[), and you can use C++11, you can use SFINAE and write something as follows

```<code>template <std::size_t N>
typename std::enable_if<(N >= 10U) && (N < 20U)>::type foo (std::bitset<N>)
 { std::cout << N << "\n"; }
</code>```

Now you have

```<code>std::bitset<10> n10;
std::bitset<15> n15;
std::bitset<25> n25;

foo(n10);    // compile
foo(n15);    // compile
// foo(n25); // compilation error
</code>```

Body:
The following program compiles fine.

#include <iostream>
#include <bitset>

void foo(std::bitset<10> n)
{
    std::cout << n.size() << "\n";
}

int main()
{
    std::bitset<10> n;
    foo(n);
}

$ g++ -std=c++11 -Wall -Wextra -pedantic foo.cpp
$ ./a.out
10

How can I modify the foo() function such that it can accept bitset of any size?

Body:
The std::bitset<N> are types, so you can create a template function that accept a generic type

template <typename T>
void foo (T n)
 { std::cout << n.size() << "\n"; }

Observe that this function will work with not only with all std::bitset but also with all types with a size() member that return a value that can be send to std::cout, as a lot of STL containers (std::set, std::vector, std::map, etc).

So, by example, you can also call foo() as follows

 std::vector<int> v(20);
 foo(v);

This can be good or bad, according to your requirements.

If you want a function that accept only a std::bitset, so you can follows the solution suggested by songyuanyao: you can explicit std::bitset and templatize the dimension.

template <std::size_t N>
void foo (std::bitset<N> n)
{ std::cout << n.size() << "\n"; }

but, in this case, there is no need to use size(); you can use directly N

template <std::size_t N>
void foo (std::bitset<N>)
{ std::cout << N << "\n"; }

If, in addiction, you want that foo accept a std::bitset<N> with (by example) N in a range of values (say [10,20[), and you can use C++11, you can use SFINAE and write something as follows

template <std::size_t N>
typename std::enable_if<(N >= 10U) && (N < 20U)>::type foo (std::bitset<N>)
 { std::cout << N << "\n"; }

Now you have

std::bitset<10> n10;
std::bitset<15> n15;
std::bitset<25> n25;

foo(n10);    // compile
foo(n15);    // compile
// foo(n25); // compilation error


问:
Check if only certain values exist in a list (Python)
I have the following list:

```<code>A = [x,y,z]
</code>```

and I need help with writing a code in Python that returns True if any combination of x or y or z is in the list, but returns False if any other variables outside of A is in the list.

Example:

```<code>B = [x]  (return True)
B = [l] (return False)
B = [x,z] (return True)
B = [x,y,z,l] (return False)
</code>```

答:
You can make a set from your list, and check if the elements are its subset</p>

```<code>sA = set(list)
sE = set(elements)
check = sE <= sA
</code>```

Body:
I have the following list:

A = [x,y,z]

and I need help with writing a code in Python that returns True if any combination of x or y or z is in the list, but returns False if any other variables outside of A is in the list.

Example:

B = [x]  (return True)
B = [l] (return False)
B = [x,z] (return True)
B = [x,y,z,l] (return False)

Body:
You can make a set from your list, and check if the elements are its subset

sA = set(list)
sE = set(elements)
check = sE <= sA


问:
Setting an option selected in a combobox as a variable that changes as the option selected in the combobox does
I am trying to set the option selected in the dropdown of a combobox as a variable, however, the label I am using to represent the variable is currently just reading   .!combobox   . For example if I selected 'Customer 2' from the dropdown , the label would change to customer 2. I may need to use a button to do this but I am unsure how to make that work.

```<code>import tkinter as tk
from tkinter import ttk
root = tk.Tk()

ICus = tk.StringVar(root)

ICus.set("Select Customer")

ICustomer = ttk.Combobox( textvariable = ICus, state = 'readonly')
ICustomer['values'] = ("Customer1", "Customer2", "Customer3")
ICustomer.grid(row = 2, column = 2)

label_ICustVar = tk.Label( text= ICustomer)
label_ICustVar.grid(row = 3, column = 3)
</code>```

To put it simply I want the option selected in the dropdown to be set as a variable that I can use later on in my code. I am quite new to coding so I might be missing something really obvious, any help would be appreciated :)

答:
I think for your use, the link provided by a_guest works best, but regarding your example, I think it's best to use the keyword textvariable of the label, i.e.</p>

```<code># note that this is the StringVar ICUS, not the combobox ICUSTOMER.
label_ICustVar = tk.Label( textvariable= ICus)
label_ICustVar.grid(row = 3, column = 3)
</code>```

Body:
I am trying to set the option selected in the dropdown of a combobox as a variable, however, the label I am using to represent the variable is currently just reading   .!combobox   . For example if I selected 'Customer 2' from the dropdown , the label would change to customer 2. I may need to use a button to do this but I am unsure how to make that work.

import tkinter as tk
from tkinter import ttk
root = tk.Tk()

ICus = tk.StringVar(root)

ICus.set("Select Customer")

ICustomer = ttk.Combobox( textvariable = ICus, state = 'readonly')
ICustomer['values'] = ("Customer1", "Customer2", "Customer3")
ICustomer.grid(row = 2, column = 2)

label_ICustVar = tk.Label( text= ICustomer)
label_ICustVar.grid(row = 3, column = 3)

To put it simply I want the option selected in the dropdown to be set as a variable that I can use later on in my code. I am quite new to coding so I might be missing something really obvious, any help would be appreciated :)

Body:
I think for your use, the link provided by a_guest works best, but regarding your example, I think it's best to use the keyword textvariable of the label, i.e.

# note that this is the StringVar ICUS, not the combobox ICUSTOMER.
label_ICustVar = tk.Label( textvariable= ICus)
label_ICustVar.grid(row = 3, column = 3)


问:
Express body-parser req not shown
I am using Express with body-parser as follows:

// Import all required library

var express = require('express')
var app = express()
var bodyParser = require('body-parser')

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true, limit: '500mb'}))

var port = 3000

// Route for the API
var router = new express.Router()

router.get('/videos', (req, res, next) => {
    console.log('GET /' + req)
    return res.json({
      "Your videos"
    })
})

// Using Router
app.use('/', router)

app.listen(port, function(err){
 if (!err) {
  console.log("API started running at port 3000")
 }
})```
</div>
</div>
</p>

<p>Versions of Library used are</p>

```    "dependencies": {
      "body-parser": "1.16.1",
      "express": "4.14.1"
    }
```

<p>This is not showing any query parameters in <code>req</code>. Resulting following </p>

```   GET /[object Object]
```

When I used POSTMAN to GET localhost:3000/videos?type=popularity.
This kind of api setup has been working for me until now. Can anyone explain me what I did wrong?

Thanks

答:
Query parameters are available through req.query:

```<code>console.log('GET /', req.query);
</code>```

FWIW, body-parser is not a requirement to access these.

Title: Express body-parser req not shown

Body:
I am using Express with body-parser as follows:

// Import all required library

var express = require('express')
var app = express()
var bodyParser = require('body-parser')

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true, limit: '500mb'}))

var port = 3000

// Route for the API
var router = new express.Router()

router.get('/videos', (req, res, next) => {
    console.log('GET /' + req)
    return res.json({
      "Your videos"
    })
})

// Using Router
app.use('/', router)

app.listen(port, function(err){
 if (!err) {
  console.log("API started running at port 3000")
 }
})

Versions of Library used are

    "dependencies": {
      "body-parser": "1.16.1",
      "express": "4.14.1"
    }

This is not showing any query parameters in req. Resulting following

   GET /[object Object]

When I used POSTMAN to GET localhost:3000/videos?type=popularity.
This kind of api setup has been working for me until now. Can anyone explain me what I did wrong?

Thanks

Body:
Query parameters are available through req.query:

console.log('GET /', req.query);

FWIW, body-parser is not a requirement to access these.


问:
Merge two list (java 7)
I have two lists of Personne:  listOne and listTwo.

Personne is:

```<code>public class Personne{
    private String name;
    private Favorite favorite;
    private Collection<Number>  numbers;
}

public class Favorite{
    private String id;
    private String name;
    ...
}
</code>```

For each item, I want to merge the two lists if the favorite name and id of the first list equals the favorite name and id of the second list, and then merge the second list to first.

This is a part of my treatement and what i means by merge (its not create an other list ) :

if my condition is true i want to take item of my first list :

```<code>item.setNumbers(item2.getnumbers);
</code>```

What is the best way to do this with Java 7?

答:
I'd try iterating over listOne, check for each desired item if it's in listTwo and in that case add the entries from listOne and listTwo to a new list.

Something like

https://gist.github.com/a2465b03fb7503f9c8190ab72c328c10

Title: Merge two list (java 7)

Body:
I have two lists of Personne:  listOne and listTwo.

Personne is:

public class Personne{
    private String name;
    private Favorite favorite;
    private Collection<Number>  numbers;
}

public class Favorite{
    private String id;
    private String name;
    ...
}

For each item, I want to merge the two lists if the favorite name and id of the first list equals the favorite name and id of the second list, and then merge the second list to first.

This is a part of my treatement and what i means by merge (its not create an other list ) :

if my condition is true i want to take item of my first list :

item.setNumbers(item2.getnumbers);

What is the best way to do this with Java 7?


问:
Where are Jboss drools projects stored?
I am using kie-drools-wb-6.5.0.Final-eap6_4.war to create a project and generate a DRL file.

But am not able to find the physical location of any file created using the Drools workbench.

Where can I find it?

答: They're in the .niogit directory.

Title: Where are Jboss drools projects stored?

Body: They're in the .niogit directory.


问:
Spring Data JPA repository methods overloading
For example, I have a book JpaRepository. Book has a field called Name, the book repository has a method findOneByName (as the jpa repository method naming convention). But I need two different versions of findOneByName to use in  different use cases. One version is lock annotated, the other is lock-free. Like this:

```<code>public interface BookRepository extends JpaRepository<BookDAO, Long> {

   @Lock(LockModeType.READ)
   BookDAO findOneByName( String name );

   BookDAO findOneByName( String name );
}
</code>```

Is it possible to achieve this in Spring? If so, how to distinguish the two methods when calling them. If not, is there another way to do it while still using the Spring JPA repository interfaces (like findOneBy***).

答:
According to reference we can name query methods with these prefixes: find…By, read…By, query…By, count…By, and get…By.

So methods BookDAO findByName(String name) and BookDAO getByName(String name) will do the same thing.

Body:
For example, I have a book JpaRepository. Book has a field called Name, the book repository has a method findOneByName (as the jpa repository method naming convention). But I need two different versions of findOneByName to use in  different use cases. One version is lock annotated, the other is lock-free. Like this:

public interface BookRepository extends JpaRepository<BookDAO, Long> {

   @Lock(LockModeType.READ)
   BookDAO findOneByName( String name );

   BookDAO findOneByName( String name );
}

Is it possible to achieve this in Spring? If so, how to distinguish the two methods when calling them. If not, is there another way to do it while still using the Spring JPA repository interfaces (like findOneBy***).


问:
Making a simple C# API call
I'm trying to teach myself how to make simple API calls with C#. I'd like to call this "http://hivemc.com/json/userprofile/da10b68dea6a42d58ea8fea66a57b886". This should return some strings in json but I don't know what i'm supposed to do with that.

reference: https://apidoc.hivemc.com/#!/GameData/get_game_game_data_id_UUID

I'm new to programming and I've never done anything with API's. I've tried looking around the internet but I don't understand what I'm supposed to look for. Can someone refer me to an article that can teach me how to do this? I have no idea where to start. An example of the code with explanation would be great but I understand if it's too much to ask.

Thank you!

答:
You should use System.Net.HttpClient from Nuget. Check this link out. It shows you how to get data from the API. The next step is to deserialize it to your model using Newtonsoft.Json.

Hope it helps!

Title: Making a simple C# API call


问:
mongodb distinct sometimes uses index and sometimes doesn't
I have collection A with a non-unique index over "field1".

If I run:

```<code>db.A.explain().distinct("field1")
</code>```

I get:

```<code>"winningPlan" : {
    "stage" : "PROJECTION",
    ...
    "inputStage" : {
        "stage" : "DISTINCT_SCAN",
        "keyPattern" : {
            "field1" : 1.0
        },
    ...
}
</code>```

Which suggests it'll use the index for the distinct call.

However, in collection B with a non-unique index on "type2.key", if I run:

```<code>db.B.explain().distinct("type2.key")
</code>```

I get:

```<code>"winningPlan" : {
    "stage" : "COLLSCAN",
    "filter" : {
        "$and" : []
    },
    ...
}
</code>```

which seems to mean it doesn't use the index.

Why can distinct use the index on collection A but not on collection B, and can I do something to force the use of the index?

Notes:

collection B is a lot bigger then collection A, is there a limit to the size of the index distinct can use?

I've read: Count distinct values in mongoDB and MongoDB - distinct with query doesn't use indexes they don't help to explain the difference in behavior I'm seeing.

Both collections are sharded

mongodb version is 3.2.12

EXAMPLE DOCUMENT

```<code>{
    "_id" : ObjectId("57d6c1cf691fa014e0615aa7"),
    "type1" : [
        {
            "key" : "key1",
            "field" : "value1",
        },
        {
            "key" : "key2",
            "field" : "value2",
        }
    ],
    "type2" : [
        {
            "key" : "key3",
            "field" : "value3",
        },
        {
            "key" : "key4",
            "field" : "value4",
        }
    ]
}
</code>```

The index is on type2.key

答:
The rules when distinct index can be used are there https://github.com/mongodb/mongo/blob/v3.4/src/mongo/db/query/get_executor.cpp#L1104

Most important line for this particular case https://github.com/mongodb/mongo/blob/v3.4/src/mongo/db/query/get_executor.cpp#L1139 says:

Skip multikey indices if we are projecting on a dotted field.

"obj.field2" is a dotted field, so index does not apply.

So basically, distinct() can use indexes only for root fields, not for array nor subdocuments.

Body:
I have collection A with a non-unique index over "field1".

If I run:

db.A.explain().distinct("field1")

I get:

"winningPlan" : {
    "stage" : "PROJECTION",
    ...
    "inputStage" : {
        "stage" : "DISTINCT_SCAN",
        "keyPattern" : {
            "field1" : 1.0
        },
    ...
}

Which suggests it'll use the index for the distinct call.

However, in collection B with a non-unique index on "type2.key", if I run:

db.B.explain().distinct("type2.key")

I get:

"winningPlan" : {
    "stage" : "COLLSCAN",
    "filter" : {
        "$and" : []
    },
    ...
}

which seems to mean it doesn't use the index.

Why can distinct use the index on collection A but not on collection B, and can I do something to force the use of the index?

Notes:

collection B is a lot bigger then collection A, is there a limit to the size of the index distinct can use?

I've read: Count distinct values in mongoDB and MongoDB - distinct with query doesn't use indexes they don't help to explain the difference in behavior I'm seeing.

Both collections are sharded

mongodb version is 3.2.12

EXAMPLE DOCUMENT

{
    "_id" : ObjectId("57d6c1cf691fa014e0615aa7"),
    "type1" : [
        {
            "key" : "key1",
            "field" : "value1",
        },
        {
            "key" : "key2",
            "field" : "value2",
        }
    ],
    "type2" : [
        {
            "key" : "key3",
            "field" : "value3",
        },
        {
            "key" : "key4",
            "field" : "value4",
        }
    ]
}

The index is on type2.key


问:
HMAC-based one time password in C# (RFC 4226 - HOTP)
I am attempting to wrap my brain around generating a 6 digit/character non case sensitive expiring one-time password.

My source is https://www.rfc-editor.org/rfc/rfc4226#section-5

First the definition of the parameters

```<code>C       8-byte counter value, the moving factor.  This counter
       MUST be synchronized between the HOTP generator (client)
       and the HOTP validator (server).

K       shared secret between client and server; each HOTP
       generator has a different and unique secret K.

T       throttling parameter: the server will refuse connections
       from a user after T unsuccessful authentication attempts.
</code>```

Then we have the algorithm to generate the HOTP

```<code>As the output of the HMAC-SHA-1 calculation is 160 bits, we must
   truncate this value to something that can be easily entered by a
   user.

                   HOTP(K,C) = Truncate(HMAC-SHA-1(K,C))
</code>```

Then, we have Truncate defined as

```<code>String = String[0]...String[19]
 Let OffsetBits be the low-order 4 bits of String[19]
 Offset = StToNum(OffsetBits) // 0 <= OffSet <= 15
 Let P = String[OffSet]...String[OffSet+3]
 Return the Last 31 bits of P
</code>```

And then an example is offered for a 6 digit HOTP

```<code>The following code example describes the extraction of a dynamic
binary code given that hmac_result is a byte array with the HMAC-
SHA-1 result:

    int offset   =  hmac_result[19] & 0xf ;
    int bin_code = (hmac_result[offset]  & 0x7f) << 24
       | (hmac_result[offset+1] & 0xff) << 16
       | (hmac_result[offset+2] & 0xff) <<  8
       | (hmac_result[offset+3] & 0xff) ;
</code>```

I am rather at a loss in attempting to convert this into useful C# code for generating one time passwords.  I already have code for creating an expiring HMAC as follows:

```<code>byte[] hashBytes = alg.ComputeHash(Encoding.UTF8.GetBytes(input));
byte[] result = new byte[8 + hashBytes.Length];

hashBytes.CopyTo(result, 8);
BitConverter.GetBytes(expireDate.Ticks).CopyTo(result, 0);
</code>```

I'm just not sure how to go from that, to 6 digits as proposed in the above algorithms.

答:
You have two issues here:

If you are generating alpha-numeric, you are not conforming to the RFC - at this point, you can simply take any N bytes and turn them to a hex string and get alpha-numeric.  Or, convert them to base 36 if you want a-z and 0-9.  Section 5.4 of the RFC is giving you the standard HOTP calc for a set Digit parameter (notice that Digit is a parameter along with C, K, and T).   If you are choosing to ignore this section, then you don't need to convert the code - just use what you want.

Your "result" byte array has the expiration time simply stuffed in the first 8 bytes after hashing.  If your truncation to 6-digit alphanumeric does not collect these along with parts of the hash, it may as well not be calculated at all.  It is also very easy to "fake" or replay - hash the secret once, then put whatever ticks you want in front of it - not really a one time password.  Note that parameter C in the RFC is meant to fulfill the expiring window and should be added to the input prior to computing the hash code.

ContentLicense: CC BY-SA 2.5

Body:
I am attempting to wrap my brain around generating a 6 digit/character non case sensitive expiring one-time password.

My source is https://www.rfc-editor.org/rfc/rfc4226#section-5

First the definition of the parameters

C       8-byte counter value, the moving factor.  This counter
       MUST be synchronized between the HOTP generator (client)
       and the HOTP validator (server).

K       shared secret between client and server; each HOTP
       generator has a different and unique secret K.

T       throttling parameter: the server will refuse connections
       from a user after T unsuccessful authentication attempts.

Then we have the algorithm to generate the HOTP

As the output of the HMAC-SHA-1 calculation is 160 bits, we must
   truncate this value to something that can be easily entered by a
   user.

                   HOTP(K,C) = Truncate(HMAC-SHA-1(K,C))

Then, we have Truncate defined as

String = String[0]...String[19]
 Let OffsetBits be the low-order 4 bits of String[19]
 Offset = StToNum(OffsetBits) // 0 <= OffSet <= 15
 Let P = String[OffSet]...String[OffSet+3]
 Return the Last 31 bits of P

And then an example is offered for a 6 digit HOTP

The following code example describes the extraction of a dynamic
binary code given that hmac_result is a byte array with the HMAC-
SHA-1 result:

    int offset   =  hmac_result[19] & 0xf ;
    int bin_code = (hmac_result[offset]  & 0x7f) << 24
       | (hmac_result[offset+1] & 0xff) << 16
       | (hmac_result[offset+2] & 0xff) <<  8
       | (hmac_result[offset+3] & 0xff) ;

I am rather at a loss in attempting to convert this into useful C# code for generating one time passwords.  I already have code for creating an expiring HMAC as follows:

byte[] hashBytes = alg.ComputeHash(Encoding.UTF8.GetBytes(input));
byte[] result = new byte[8 + hashBytes.Length];

hashBytes.CopyTo(result, 8);
BitConverter.GetBytes(expireDate.Ticks).CopyTo(result, 0);

I'm just not sure how to go from that, to 6 digits as proposed in the above algorithms.


问:
How to auto checked to one of many shipping free choose state when checkout in WooCommerce?
I have a problem making this website.

There are the products to buy: http://tn.freshbrand.vn/danh-muc/than-khu-mui

And the checkout: http://tn.freshbrand.vn/checkout

When user buy more than 2 products and choose "Ngoài HCm" as the state where to ship:

The shipping fee shows 2 possible radio buttons to check.

option1 : 45,000 (for 1 product)

option2 : 65,000 (not for 1 product).

When user choose state (Chọn Quận, huyện) == "Ngoài HCm".

and the cart has 1 product, the shipping fee should be auto checked to 45,000 (default).

and for more than 1 products in cart, it should be auto checked to 65,000.

Before, I had option 65,000 checked when the cart has more than 2 product but this was not ok. I think the jQuery must set when state (delivery destination) is chosen.

Below is my code in form-billing.php

```<code>global $woocommerce;
  $attendee_count = 0;
  if (sizeof($woocommerce->cart->get_cart())>0) :
    foreach ($woocommerce->cart->get_cart() as $item_id => $values) :
      $_product = $values['data'];
      if ($_product->exists() && $values['quantity']>0) :
        if (get_post_meta($_product->id, '_tribe_wooticket_for_event') > 0)
          $attendee_count += $values['quantity'];
      endif;
    endforeach;
  endif;
  echo "<div class='sl_sp'>Number product in cart: <span class='soluong_sp'>" . $attendee_count . "</span></div>";
  if($attendee_count == 1 ){ // so luong la 1 sp
    ?>
    <style>
    .woocommerce ul#shipping_method li:nth-child(2)
    {display: none;}
    </style>
    <?
  }else{ ?>

  <style>
    .woocommerce ul#shipping_method li:nth-child(2){display: block;}
    .woocommerce ul#shipping_method li:nth-child(1){display: none;}
  </style>
  <script>
  jQuery(document).ready(function() {
    jQuery("input#shipping_method_0_oik_weight_zone_shipping_45").prop( "checked", true );
  });
  </script>

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

I was set default state to 'Ngoài HCM', it's show correctly when I add 1 or more products. But when chosen another state, and choose 'Ngoài HCm' again, it's wrong (not checked correctly).

答:
This code is correct:

```<code>jQuery("input#shipping_method_0_oik_weight_zone_shipping_45").prop( "checked", true );
</code>```

I tryed it in the console of your checkout page and it is working.

Now, since this code is injected in the page using Ajax, you don't need the "ready" function wrapper.

The page is already ready.

The load event will not occur.

So in clear, try just this:

```<code><script>
  jQuery("input#shipping_method_0_oik_weight_zone_shipping_45").prop( "checked", true );
</script>
</code>```

Instead of this:

```<code><script>
jQuery(document).ready(function() {
  jQuery("input#shipping_method_0_oik_weight_zone_shipping_45").prop( "checked", true );
});
</script>
</code>```

Body:
I have a problem making this website.

There are the products to buy: http://tn.freshbrand.vn/danh-muc/than-khu-mui

And the checkout: http://tn.freshbrand.vn/checkout

When user buy more than 2 products and choose "Ngoài HCm" as the state where to ship:

The shipping fee shows 2 possible radio buttons to check.

option1 : 45,000 (for 1 product)

option2 : 65,000 (not for 1 product).

When user choose state (Chọn Quận, huyện) == "Ngoài HCm".

and the cart has 1 product, the shipping fee should be auto checked to 45,000 (default).

and for more than 1 products in cart, it should be auto checked to 65,000.

Before, I had option 65,000 checked when the cart has more than 2 product but this was not ok. I think the jQuery must set when state (delivery destination) is chosen.

Below is my code in form-billing.php

global $woocommerce;
  $attendee_count = 0;
  if (sizeof($woocommerce->cart->get_cart())>0) :
    foreach ($woocommerce->cart->get_cart() as $item_id => $values) :
      $_product = $values['data'];
      if ($_product->exists() && $values['quantity']>0) :
        if (get_post_meta($_product->id, '_tribe_wooticket_for_event') > 0)
          $attendee_count += $values['quantity'];
      endif;
    endforeach;
  endif;
  echo "
Number product in cart: " . $attendee_count . "
";
  if($attendee_count == 1 ){ // so luong la 1 sp
    ?>

    <?
  }else{ ?>

<?php }  ?>

I was set default state to 'Ngoài HCM', it's show correctly when I add 1 or more products. But when chosen another state, and choose 'Ngoài HCm' again, it's wrong (not checked correctly).

Body:
This code is correct:

jQuery("input#shipping_method_0_oik_weight_zone_shipping_45").prop( "checked", true );

I tryed it in the console of your checkout page and it is working.

Now, since this code is injected in the page using Ajax, you don't need the "ready" function wrapper.

The page is already ready.

The load event will not occur.

So in clear, try just this:

<script>
  jQuery("input#shipping_method_0_oik_weight_zone_shipping_45").prop( "checked", true );
</script>

Instead of this:

<script>
jQuery(document).ready(function() {
  jQuery("input#shipping_method_0_oik_weight_zone_shipping_45").prop( "checked", true );
});
</script>


问:
add a link on a div displayed on input's focus
I show a tooltip when an input gains focus. This tooltip is a span: hidden, but shown (via CSS) when input has focus.

input + .k-comments {
      display: none;
      max-width: 25em;
      color: #FFF;
      background: #283135;
      padding: 0.3rem;
      margin-top: 0.3rem;
      animation: appearance 2s forwards;
    }

    input:focus + .k-comments {
      display: block;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="myid" type="text"/>
<span class="k-comments">foo a link</span></code>```

If I click on the tooltip (or everywhere else), it disappears: ok.

The problem: my tooltip contains text and a link -> I can't click on the link because the tooltip disappears first.

答:
```
input + .k-comments {
  visibility: hidden;
  opacity: 0;
  max-width: 25em;
  color: #FFF;
  background: #283135;
  padding: 0.3rem;
  margin-top: 0.3rem;
  transition: all 2s linear;
}

input:focus + .k-comments {
  visibility: visible;
  opacity: 1;
  transition: none;
}
```

My solution :add a hidden transition to the comment.

Body:
I show a tooltip when an input gains focus. This tooltip is a span: hidden, but shown (via CSS) when input has focus.

input + .k-comments {
      display: none;
      max-width: 25em;
      color: #FFF;
      background: #283135;
      padding: 0.3rem;
      margin-top: 0.3rem;
      animation: appearance 2s forwards;
    }

    input:focus + .k-comments {
      display: block;
    }

<input id="myid" type="text"/>
foo a link

If I click on the tooltip (or everywhere else), it disappears: ok.

The problem: my tooltip contains text and a link -> I can't click on the link because the tooltip disappears first.

Body:
input + .k-comments {
  visibility: hidden;
  opacity: 0;
  max-width: 25em;
  color: #FFF;
  background: #283135;
  padding: 0.3rem;
  margin-top: 0.3rem;
  transition: all 2s linear;
}

input:focus + .k-comments {
  visibility: visible;
  opacity: 1;
  transition: none;
}

My solution :add a hidden transition to the comment.


问:
redirect after a fetch post call
I am creating an social login page with an Access Management (AM) server.
When user click on the login button then I make a fetch http post call to AM server. AM server generates a HTTP 301 redirect response with auth cookies to the social login page. I need to follow somehow this redirect response and show the new content in the web browser.

UI: ReactJS

Request:

```<code>POST /api/auth/socialauth/initiate HTTP/1.1
Host    example.com
User-Agent  Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:49.0)
Accept  */*
Accept-Language en-US,en;q=0.5
Accept-Encoding gzip, deflate
origin  http://web.example.com:8080
Referer http://web.example.com:8080/myapp/login
Cookie  authId=...; NTID=...
</code>```

Response

```<code>HTTP/1.1 307 Temporary Redirect
https://www.facebook.com/dialog/oauth?client_id=...&scope=public_profile%2Cemail&redirect_uri=http%3A%2F%2Fam.example.com%3A8083%2Fopenam%2Foauth2c%2FOAuthProxy.jsp&response_type=code&state=qtrwtidnwdpbft4ctj2e9mv3mjkifqo
</code>```

React code:

```<code>initiateSocialLogin() {
    var url = "/api/auth/socialauth/initiate";

    fetch(url, { method: 'POST' })
        .then(response => {
            // HTTP 301 response
            // HOW CAN I FOLLOW THE HTTP REDIRECT RESPONSE?
        })
        .catch(function(err) {
            console.info(err + " url: " + url);
        });
}
</code>```

How I can follow the redirect response and show the new content in the web browser?

答:
I have a similar issue and I believe that the answer for fetch inside React is the same as it is for ajax inside JQuery - if you are able to detect that the response is a redirect, then update the window.location.href with the response.url

See for example: How to manage a redirect request after a jQuery Ajax call

Note that 'if you are able to detect that the response is a redirect' might be the tricky part. Fetch responses may contain a 'redirected' flag (see https://developer.mozilla.org/en-US/docs/Web/API/Response) but I've found that is not the case in Chrome. I also find in Chrome I get a 200 status response rather than a redirect status - but that could be something with our SSO implementation. If you are using a fetch polyfill with IE then you'll need to check whether response.url is included or not.

Title: redirect after a fetch post call

Body:
I am creating an social login page with an Access Management (AM) server.
When user click on the login button then I make a fetch http post call to AM server. AM server generates a HTTP 301 redirect response with auth cookies to the social login page. I need to follow somehow this redirect response and show the new content in the web browser.

UI: ReactJS

Request:

POST /api/auth/socialauth/initiate HTTP/1.1
Host    example.com
User-Agent  Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:49.0)
Accept  */*
Accept-Language en-US,en;q=0.5
Accept-Encoding gzip, deflate
origin  http://web.example.com:8080
Referer http://web.example.com:8080/myapp/login
Cookie  authId=...; NTID=...

Response

HTTP/1.1 307 Temporary Redirect
https://www.facebook.com/dialog/oauth?client_id=...&scope=public_profile%2Cemail&redirect_uri=http%3A%2F%2Fam.example.com%3A8083%2Fopenam%2Foauth2c%2FOAuthProxy.jsp&response_type=code&state=qtrwtidnwdpbft4ctj2e9mv3mjkifqo

React code:

initiateSocialLogin() {
    var url = "/api/auth/socialauth/initiate";

    fetch(url, { method: 'POST' })
        .then(response => {
            // HTTP 301 response
            // HOW CAN I FOLLOW THE HTTP REDIRECT RESPONSE?
        })
        .catch(function(err) {
            console.info(err + " url: " + url);
        });
}

How I can follow the redirect response and show the new content in the web browser?


问:
git-svn: re-link git-svn cloned repo to svn
I have on my gitlab a git repo which was originally cloned using git svn clone https://svn.url.com/project/trunk. I used to dcommit to the svn as well as git push to the gitlab from my local copy. But now I have now lost the original local copy where I do the git-svn clone from.. I do git clone from my gitlab but now I lost the capability to fetch from the svn and dcommit again.. Is there any way I can restore it? I've never back up the .git/svn folder under the git directory... :(

答:
It is easy.

Open up your git config (under .git/config)

and add the following to the end

```<code>[svn-remote "svn"]
      url = https://svn.url.com/
      fetch = :refs/remotes/git-svn
</code>```

you can then git-fetch to relink all your git-svn revisions

P.S: if it takes too long and/or your revisions are too many, you can directly move your refs/remotes/git-svn to the last known svn-revision before doing the git-fetch
e.g:

git update-ref refs/remotes/git-svn refs/heads/master

Body:
It is easy.

Open up your git config (under .git/config)

and add the following to the end

[svn-remote "svn"]
      url = https://svn.url.com/
      fetch = :refs/remotes/git-svn

you can then git-fetch to relink all your git-svn revisions

P.S: if it takes too long and/or your revisions are too many, you can directly move your refs/remotes/git-svn to the last known svn-revision before doing the git-fetch
e.g:

git update-ref refs/remotes/git-svn refs/heads/master


问:
Getting errors with trying to create a CRUD Web Service
Hey guys, here are the errors I'm getting:

```<code>Value of type 'Integer' cannot be converted to 'music.MusicDataTable'.
//happens at return deleteSong(...)
Value of type 'Integer' cannot be converted to 'music.MusicDataTable'.
//happens at return insertSong(...)
</code>```

And this is the code, coming from the web service's vb page, where I'm getting the error:

```<code>Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols

<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class getMusicList
     Inherits System.Web.Services.WebService

    <WebMethod()> _
    Public Function GetMusic() As music.MusicDataTable
        Dim music As New musicTableAdapters.MusicTableAdapter
        Return music.GetMusic
    End Function

    Public Function deleteSong(ByVal song_title As String) As music.MusicDataTable
        Dim music As New musicTableAdapters.MusicTableAdapter
        Return music.deleteSong(song_title)
    End Function

    Public Function insertSong(ByVal song_album As String, ByVal song_artist As String, ByVal song_file As String, ByVal song_format As String, ByVal song_size As String, ByVal song_time As String, ByVal song_title As String, ByVal song_track As Integer, ByVal song_year As Integer) As music.MusicDataTable
        Dim music As New musicTableAdapters.MusicTableAdapter
        Return music.insertSong(song_album, song_artist, song_file, song_format, song_size, song_time, song_title, song_track, song_year)
    End Function

End Class
</code>```

MusicDataTable comes from a dataset called music.

The GetMusic() works because I'm not passing it anything. I'm not sure why insertSong and deleteSong aren't working. Any help would be appreciated.

答: apparently music.deleteSong and music.insertSong return integer. you should change the return type of deleteSong and insertSong to integer to match them.

Body:
Hey guys, here are the errors I'm getting:

Value of type 'Integer' cannot be converted to 'music.MusicDataTable'.
//happens at return deleteSong(...)
Value of type 'Integer' cannot be converted to 'music.MusicDataTable'.
//happens at return insertSong(...)

And this is the code, coming from the web service's vb page, where I'm getting the error:

Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols

<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class getMusicList
     Inherits System.Web.Services.WebService

    <WebMethod()> _
    Public Function GetMusic() As music.MusicDataTable
        Dim music As New musicTableAdapters.MusicTableAdapter
        Return music.GetMusic
    End Function

    Public Function deleteSong(ByVal song_title As String) As music.MusicDataTable
        Dim music As New musicTableAdapters.MusicTableAdapter
        Return music.deleteSong(song_title)
    End Function

    Public Function insertSong(ByVal song_album As String, ByVal song_artist As String, ByVal song_file As String, ByVal song_format As String, ByVal song_size As String, ByVal song_time As String, ByVal song_title As String, ByVal song_track As Integer, ByVal song_year As Integer) As music.MusicDataTable
        Dim music As New musicTableAdapters.MusicTableAdapter
        Return music.insertSong(song_album, song_artist, song_file, song_format, song_size, song_time, song_title, song_track, song_year)
    End Function

End Class

MusicDataTable comes from a dataset called music.

The GetMusic() works because I'm not passing it anything. I'm not sure why insertSong and deleteSong aren't working. Any help would be appreciated.


问:
When to return vector iterator instead of vector?
Let's say we have a function 1 :

```<code>vector<T>::iterator GetSomething()
{
 vector<T> vec;

 // Update vec with something...

 return vec.begin();
}
</code>```

And another function 2:

```<code>vector<T> GetSomething()
{
 vector<T> vec;

 // Update vec with something...

 return vec;
}
</code>```

In what situations would we prefer function 1 ?
Also, what would be the lifetime of that vector object ?
How would we know if the iterator is pointing to empty vector ? Probably need to pass pair of iterators to determine begin / end.

答: Apart from the general remark about returning a pointer-like to something disapparead on the stack, option 1 asks for a pair of methods (functions disqualify option 1) : begin & end. Iterators in C++ do not work as in java, python and many others.

Body:
Let's say we have a function 1 :

vector<T>::iterator GetSomething()
{
 vector<T> vec;

 // Update vec with something...

 return vec.begin();
}

And another function 2:

vector<T> GetSomething()
{
 vector<T> vec;

 // Update vec with something...

 return vec;
}

In what situations would we prefer function 1 ?
Also, what would be the lifetime of that vector object ?
How would we know if the iterator is pointing to empty vector ? Probably need to pass pair of iterators to determine begin / end.


问:
How to update value in a List using LINQ
I have a list which I want to update using LINQ.

```<code>class Student
{
    private string name;
    private int marks;
    public string Name { get; set;}
    public int Marks { get; set; }
    public Student(string name, int marks)
    {
        Name = name;
        Marks = marks;
    }
}

List<Student> myList = new List<Student>();
myList.Add(new Student("John", 10));
myList.Add(new Student("Tom", 20));
</code>```

Now I want to update the list using LINQ such that only marks of John gets updated. I am using the following syntax:

```<code>myList.Where(w => w.Name == "Tom").Select(w=> { w.Marks = 35; return w});
</code>```

But this doesnt update data in myList. Can someone tell me where am I going wrong.

答:
Try:</p>

```<code>myList .Where(w=> w.Name  == "dTomi").ToList().ForEach(i => i.Marks  = 35);
</code>```

Body:
I have a list which I want to update using LINQ.

class Student
{
    private string name;
    private int marks;
    public string Name { get; set;}
    public int Marks { get; set; }
    public Student(string name, int marks)
    {
        Name = name;
        Marks = marks;
    }
}

List<Student> myList = new List<Student>();
myList.Add(new Student("John", 10));
myList.Add(new Student("Tom", 20));

Now I want to update the list using LINQ such that only marks of John gets updated. I am using the following syntax:

myList.Where(w => w.Name == "Tom").Select(w=> { w.Marks = 35; return w});

But this doesnt update data in myList. Can someone tell me where am I going wrong.

Body:
Try:

myList .Where(w=> w.Name  == "dTomi").ToList().ForEach(i => i.Marks  = 35);


问:
Timestamp as unique ID
Is there something wrong if i use

```<code>Long uniqueId = System.currentTimeMillis()/1000;

String documentName = ""+ uniqueId;
</code>```

as for example a document name?
Unless the user has a wrong Date it will be always unique right?
Or is there a better way to create always unique number values?
The reason i use Long uniqueId = System.currentTimeMillis()/1000;

is because it has to be unique even if the user generates that document from another device without the same data which means that i cannot create and save unique values and simply add +1 to it.

答:
If you use

System.currentTimeMillis()/1000

then if you save 2 files in the same second you will have 2 identical names for 2 different files.

So i suggest you to use

```<code>UUID.randomUUID().toString()
</code>```

Title: Timestamp as unique ID

Body:
Is there something wrong if i use

Long uniqueId = System.currentTimeMillis()/1000;

String documentName = ""+ uniqueId;

as for example a document name?
Unless the user has a wrong Date it will be always unique right?
Or is there a better way to create always unique number values?
The reason i use Long uniqueId = System.currentTimeMillis()/1000;

is because it has to be unique even if the user generates that document from another device without the same data which means that i cannot create and save unique values and simply add +1 to it.

Body:
If you use

System.currentTimeMillis()/1000

then if you save 2 files in the same second you will have 2 identical names for 2 different files.

So i suggest you to use

UUID.randomUUID().toString()


问:
Running a executable JAR with external dependencies
I'm building a java service which has two distribution. Each distribution must be build different (one has a spring-boot embedded jetty server inside, the other not). In both, I created a distribution with dependencies, except one (already achieved). The jar without jetty is build using maven-assembly-plugin (similarly as here Problems running executable jar with dependencies) the other one uses spring-boot-maven-plugin (see http://docs.spring.io/spring-boot/docs/current/maven-plugin/usage.html). My issue is the external dependencies.

I want add an additional dependency on runtime, but I DON'T WANT TO US OSGi

In both building process the result is a 'executable' jar, which I can run like this:

```<code>java -jar my.jar
</code>```

But I don't know how to address the additional dependencies. If I run the command above without a the external dependency (lets say external.jar) inside my.jar will fail, even if is in the same folder. I can make it work for the distribution without jetty like this:

```<code>java -classpath "./*" my.main.App
</code>```

But this doesn't work for my-with-jetty.jar. I also try to run:

```<code>java -classpath "./*" -jar my-with-jetty.jar
</code>```

This simply doesn't work.

So my question are:

is it possible to pack a jar with almost all the dependencies for both cases?

is it possible to pack the jar as runnable jar such that it not necessary to provide the main class?

of course if yes, how? I would like to run both distribution in the same manner.

I want similar behavior:

```<code>java -cp "./*" java -jar my.jar conf.cfg
</code>```

and

```<code>java -cp "./*" java -jar my-rest.jar conf.cfg
</code>```

Thank you.

答:
You need at least 3 maven projects all under the same parent so they get built together and have the same version.  All your code will be in the shared project, this will be included in both runnable jar projects.  Each runnable jar project will be build differently.

Your parent pom will be something like :

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>foo.bar</groupId>
  <artifactId>parent</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>pom</packaging>

  <modules>
    <module>shared-jar</module>
    <module>spring-boot-jar</module>
    <module>jetty-jar</module>
  </modules>

</project>
</code>```

Your shared-jar project will have all the shared code

Your spring-boot-jar will look like :

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>foo.bar</groupId>
        <artifactId>parent</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <artifactId>spring-boot-jar</artifactId>
    <packaging>jar</packaging>

    <dependencies>
       <dependency>
          <groupId>foo.bar</groupId>
          <artifactId>shared-jar</artifactId>
          <version>${project.version}</version>
       </dependency>
        .... you will need to add all the spring boot dependencies with versions
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <artifactId>maven-failsafe-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

Your jetty-jar will be built using the

```<code>    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>

        <parent>
            <groupId>foo.bar</groupId>
            <artifactId>parent</artifactId>
            <version>1.0-SNAPSHOT</version>
        </parent>
        <artifactId>jetty-jar</artifactId>
        <packaging>jar</packaging>

        <dependencies>
           <dependency>
              <groupId>foo.bar</groupId>
              <artifactId>shared-jar</artifactId>
              <version>${project.version}</version>
           </dependency>
            .... other dependencies
        </dependencies>

 <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.0.0</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer
                                        implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <manifestEntries>
                                        <!-- <Main-Class>foo.bar.Application</Main-Class> -->
                                    </manifestEntries>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

        </plugins>
    </build>

    </project>
</code>```

Body:
I'm building a java service which has two distribution. Each distribution must be build different (one has a spring-boot embedded jetty server inside, the other not). In both, I created a distribution with dependencies, except one (already achieved). The jar without jetty is build using maven-assembly-plugin (similarly as here Problems running executable jar with dependencies) the other one uses spring-boot-maven-plugin (see http://docs.spring.io/spring-boot/docs/current/maven-plugin/usage.html). My issue is the external dependencies.

I want add an additional dependency on runtime, but I DON'T WANT TO US OSGi

In both building process the result is a 'executable' jar, which I can run like this:

java -jar my.jar

But I don't know how to address the additional dependencies. If I run the command above without a the external dependency (lets say external.jar) inside my.jar will fail, even if is in the same folder. I can make it work for the distribution without jetty like this:

java -classpath "./*" my.main.App

But this doesn't work for my-with-jetty.jar. I also try to run:

java -classpath "./*" -jar my-with-jetty.jar

This simply doesn't work.

So my question are:

is it possible to pack a jar with almost all the dependencies for both cases?

is it possible to pack the jar as runnable jar such that it not necessary to provide the main class?

of course if yes, how? I would like to run both distribution in the same manner.

I want similar behavior:

java -cp "./*" java -jar my.jar conf.cfg

and

java -cp "./*" java -jar my-rest.jar conf.cfg

Thank you.

Body:
You need at least 3 maven projects all under the same parent so they get built together and have the same version.  All your code will be in the shared project, this will be included in both runnable jar projects.  Each runnable jar project will be build differently.

Your parent pom will be something like :

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>foo.bar</groupId>
  <artifactId>parent</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>pom</packaging>

  <modules>
    <module>shared-jar</module>
    <module>spring-boot-jar</module>
    <module>jetty-jar</module>
  </modules>

</project>

Your shared-jar project will have all the shared code

Your spring-boot-jar will look like :

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>foo.bar</groupId>
        <artifactId>parent</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <artifactId>spring-boot-jar</artifactId>
    <packaging>jar</packaging>

    <dependencies>
       <dependency>
          <groupId>foo.bar</groupId>
          <artifactId>shared-jar</artifactId>
          <version>${project.version}</version>
       </dependency>
        .... you will need to add all the spring boot dependencies with versions
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <artifactId>maven-failsafe-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

Your jetty-jar will be built using the

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>

        <parent>
            <groupId>foo.bar</groupId>
            <artifactId>parent</artifactId>
            <version>1.0-SNAPSHOT</version>
        </parent>
        <artifactId>jetty-jar</artifactId>
        <packaging>jar</packaging>

        <dependencies>
           <dependency>
              <groupId>foo.bar</groupId>
              <artifactId>shared-jar</artifactId>
              <version>${project.version}</version>
           </dependency>
            .... other dependencies
        </dependencies>

 <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.0.0</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer
                                        implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <manifestEntries>
                                        <!-- <Main-Class>foo.bar.Application</Main-Class> -->
                                    </manifestEntries>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

        </plugins>
    </build>

    </project>


问:
Chrome: Changing Select Value with jQuery is not working correctly
This code worked in IE, FF, and Safari (windows7).

It is not working in Chrome however.

Basically, I am trying to make some changes on page load (Magento product page).  I change the selected option (of a hidden select dropdown), then when they hover over the Add to Cart button, I make sure that an option was selected.

Code below:

```<code>$j('select#attribute76').val( $j('a'+hash).attr('index') ).change();
alert($j('select#attribute76').val()); // shows correctly w/ all browsers
</code>```

... then later on ...

```<code> $j('#addtocartbutton').hover(function(){
      //alert($j('select#attribute76 option:selected').val());// empty in Chrome!
      if ($j('select#attribute76').val()=='')// empty in Chrome!
           $j('.infoOptionsColors a:first').click();
     });
</code>```

What is happening is that Chrome is selecting the option that I am asking it to, but it reverts back somehow...  perhaps there is another call that is overriding it..

答:
I still do not know what the problem was.

I resolved it by moving my code towards the end of the javascript calls more.

The code that I moved it after seems barely related.. assigning the more to the .click function which is just adding/removing classes, and not changing any form values.  + some vide code..

Thanks @clockworkgeek for trying to help.

Body:
This code worked in IE, FF, and Safari (windows7).

It is not working in Chrome however.

Basically, I am trying to make some changes on page load (Magento product page).  I change the selected option (of a hidden select dropdown), then when they hover over the Add to Cart button, I make sure that an option was selected.

Code below:

$j('select#attribute76').val( $j('a'+hash).attr('index') ).change();
alert($j('select#attribute76').val()); // shows correctly w/ all browsers

... then later on ...

 $j('#addtocartbutton').hover(function(){
      //alert($j('select#attribute76 option:selected').val());// empty in Chrome!
      if ($j('select#attribute76').val()=='')// empty in Chrome!
           $j('.infoOptionsColors a:first').click();
     });

What is happening is that Chrome is selecting the option that I am asking it to, but it reverts back somehow...  perhaps there is another call that is overriding it..


问:
Pyvmomi: Permission denied on vcenter
I'm trying to run some sample scripts from the Pyvmomi Community Samples on a vcenter server appliance:
https://github.com/vmware/pyvmomi-community-samples

Caught vmodl fault : Permission to perform this operation was denied.

With another simple script:

```<code>from pyVim.connect import SmartConnect, Disconnect
import ssl

s = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
s.verify_mode = ssl.CERT_NONE

c = SmartConnect(host="IP", user="USER", pwd='PWD', sslContext=s)

datacenter = c.content.rootFolder.childEntity[0]
vms = datacenter.vmFolder.childEntity

for i in vms:
    print(i.name)

Disconnect(c)
</code>```

If I use my domain user account, with which I can login to the vcenter:

Cannot complete login due to an incorrect user name or password.

I used DOMAIN\USERNAME as user.

or as root:

Permission to perform this operation was denied.

I added some permissions in vcenter server, but apparently it is not enough :(.

答:
I was also facing the same issue, I added port it worked.
Need to add port as the parameter,
Change this

```<code>SmartConnect(host="IP", user="USER", pwd='PWD', sslContext=s)
</code>```

to

```<code>import ssl
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
context.verify_mode = ssl.CERT_NONE
SmartConnect(host="IP", user="USER", pwd='PWD', port=443, sslContext=context)
</code>```

Title: Pyvmomi: Permission denied on vcenter

Body:
I'm trying to run some sample scripts from the Pyvmomi Community Samples on a vcenter server appliance:
https://github.com/vmware/pyvmomi-community-samples

Caught vmodl fault : Permission to perform this operation was denied.

With another simple script:

from pyVim.connect import SmartConnect, Disconnect
import ssl

s = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
s.verify_mode = ssl.CERT_NONE

c = SmartConnect(host="IP", user="USER", pwd='PWD', sslContext=s)

datacenter = c.content.rootFolder.childEntity[0]
vms = datacenter.vmFolder.childEntity

for i in vms:
    print(i.name)

Disconnect(c)

If I use my domain user account, with which I can login to the vcenter:

Cannot complete login due to an incorrect user name or password.

I used DOMAIN\USERNAME as user.

or as root:

Permission to perform this operation was denied.

I added some permissions in vcenter server, but apparently it is not enough :(.

Body:
I was also facing the same issue, I added port it worked.
Need to add port as the parameter,
Change this

SmartConnect(host="IP", user="USER", pwd='PWD', sslContext=s)

to

import ssl
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
context.verify_mode = ssl.CERT_NONE
SmartConnect(host="IP", user="USER", pwd='PWD', port=443, sslContext=context)


问:
Upon shuffling I get a None object. What is wrong?
I have shuffled the list and assigned it to another variable and when I am trying to print it, it is giving output as None? What is wrong ?

```<code>list1 = [1,2,3,4,5,6]
list2 = shuffle(list1)
print list2
</code>```

答:
The random.shuffle() function is designed to take a list and shuffle its contents. It does not return the shuffled list. The documentation states:

Shuffle the sequence x in place.

As such, if you try to assign the return to a variable you will get None.

You can do the following instead:

```<code>list1 = [1,2,3,4,5,6]
shuffle(list1)
print list1
</code>```

If you wish to preserve your original list order:

```<code>list1 = [1,2,3,4,5,6]
list2 = list1[::]   # make a copy
shuffle(list2)
print list2
</code>```

Body:
I have shuffled the list and assigned it to another variable and when I am trying to print it, it is giving output as None? What is wrong ?

list1 = [1,2,3,4,5,6]
list2 = shuffle(list1)
print list2

Body:
The random.shuffle() function is designed to take a list and shuffle its contents. It does not return the shuffled list. The documentation states:

Shuffle the sequence x in place.

As such, if you try to assign the return to a variable you will get None.

You can do the following instead:

list1 = [1,2,3,4,5,6]
shuffle(list1)
print list1

If you wish to preserve your original list order:

list1 = [1,2,3,4,5,6]
list2 = list1[::]   # make a copy
shuffle(list2)
print list2


问:
R assign the output from a function to a variable
I want to condunct function which is similar to SAS of which the name of macro variable could be easily added with the other character.

But, I cannot do it in R right now, for example, in the following syntax, I want to create a function which just obtain the mean for some variable and assign a new name for the variable.

```<code>sex=c(1,2,3)

rf<-function(x){
    assign(paste("x", "mean",sep=""),mean(x))
    }
rf(sex)
</code>```

I want to get a new variable "sexmean" whose value is mean(1,2,3).

How could I do ?

答:
The way to do this using functional programming (and R) is to do:

```<code>sexmean <- mean(sex)
</code>```

If you really really want to have a function with the side effect of changing a global variable (this is very bad practice in R and functional programming in general) this will work (but is highly discouraged):

```<code>sex <- c(1,2,3)

rf <-function(x){
  arg_name <- deparse(substitute(x))
  assign(paste(arg_name, "mean",sep=""), mean(x), envir = .GlobalEnv)
}

rf(sex)
</code>```

Body:
I want to condunct function which is similar to SAS of which the name of macro variable could be easily added with the other character.

But, I cannot do it in R right now, for example, in the following syntax, I want to create a function which just obtain the mean for some variable and assign a new name for the variable.

sex=c(1,2,3)

rf<-function(x){
    assign(paste("x", "mean",sep=""),mean(x))
    }
rf(sex)

I want to get a new variable "sexmean" whose value is mean(1,2,3).

How could I do ?

Body:
The way to do this using functional programming (and R) is to do:

sexmean <- mean(sex)

If you really really want to have a function with the side effect of changing a global variable (this is very bad practice in R and functional programming in general) this will work (but is highly discouraged):

sex <- c(1,2,3)

rf <-function(x){
  arg_name <- deparse(substitute(x))
  assign(paste(arg_name, "mean",sep=""), mean(x), envir = .GlobalEnv)
}

rf(sex)


问:
I want to build a custom angularjs Unique Value Directive
I want to build a directive that checks for duplicate username. So I have created an index.html file and an uniqueId directive. Now in the directive I am not able to do ngModel.setValidity(). It is getting undefined.

Also I am fetching data from a local json file username.json.

When I console log console.log(ngModel.$setValidity('unique', unique)) I get undefined.

I have created a plunk for the code::

https://embed.plnkr.co/XTPf9PjiMn9if5Y0DaHt/

答:
You need to iterate through the users present in JSON. And, if your currentValue matches any of those, you need to set it as invalid using $setValidity. Like this:

```<code>dataService.getUsers().then(function(currentusers) {
    console.log(currentusers)
      //Ensure value that being checked hasn't changed
      //since the Ajax call was made
    if (currentValue == element.val()) {
      currentusers.forEach(function(user) {
        if (currentValue === user.property) {
          ngModel.$setValidity('unique', false)
        }
      });
    }
  }, function() {
    //Probably want a more robust way to handle an error
    //For this demo we'll set unique to true though
    ngModel.$setValidity('unique', true);
  });
});
</code>```

Also, your service was getting the JSON every time. Alternatively, you can store your JSON response in a variable inside your angular service (which is a singleton) so it's faster than before. Like this,

```<code>dataFactory.getUsers = function() {
  var deferred = $q.defer()
  if (angular.isDefined(savedResults)) {
    deferred.resolve(savedResults.data);
    return deferred.promise;
  } else {
    return $http.get(serviceBase).then(
      function(results) {
        savedResults = results
        return results.data;
      });
  }
};
</code>```

Here, we return a resolved promise if data is already available. It will get the JSON for the first time and will use from within.

working plunker

Body:
You need to iterate through the users present in JSON. And, if your currentValue matches any of those, you need to set it as invalid using $setValidity. Like this:

dataService.getUsers().then(function(currentusers) {
    console.log(currentusers)
      //Ensure value that being checked hasn't changed
      //since the Ajax call was made
    if (currentValue == element.val()) {
      currentusers.forEach(function(user) {
        if (currentValue === user.property) {
          ngModel.$setValidity('unique', false)
        }
      });
    }
  }, function() {
    //Probably want a more robust way to handle an error
    //For this demo we'll set unique to true though
    ngModel.$setValidity('unique', true);
  });
});

Also, your service was getting the JSON every time. Alternatively, you can store your JSON response in a variable inside your angular service (which is a singleton) so it's faster than before. Like this,

dataFactory.getUsers = function() {
  var deferred = $q.defer()
  if (angular.isDefined(savedResults)) {
    deferred.resolve(savedResults.data);
    return deferred.promise;
  } else {
    return $http.get(serviceBase).then(
      function(results) {
        savedResults = results
        return results.data;
      });
  }
};

Here, we return a resolved promise if data is already available. It will get the JSON for the first time and will use from within.

working plunker


问:
Most efficient way to get the highest number from a collection of integers
Question:Most efficient way to get the highest number from a collection of integers

I was recently discussing this question, I had 2 solutions in mind.
1) Iterating over the collection and find the highest number (code below)
2) Use a sorting algorithm.

The first method will have O(n) efficiency

```<code>int getHighestNumber(ArrayList<Integer> list)
    {
        if(list != null && list.size() > 0)
        {
            if(list.size() == 1)
                return list.get(0);

            int maxNum = list.get(0);
            for(int item:list)
            {
                if(item > maxNum)
                    maxNum = item;
            }
            return maxNum;
        }
        return null;
    }
</code>```

My question is "Can any sorting algorithm beat it (on time scale) on any given input for eg. if the collection is already sorted or not?"
Is there any other way better than this ?

答:
Your question is,there are two options to find the max value of a unsorted list.

Option 1:
using the method you mentioned in the question getHighestNumber

Option 2:
sort the list using world most efficient sorting algorithm and then take the last value of the list.

So what is best option in terms of efficient.

My answer: Option 1, if the array is not sorted no sorting algorithm can beat option 1.

Body:
Question:Most efficient way to get the highest number from a collection of integers

I was recently discussing this question, I had 2 solutions in mind.
1) Iterating over the collection and find the highest number (code below)
2) Use a sorting algorithm.

The first method will have O(n) efficiency

int getHighestNumber(ArrayList<Integer> list)
    {
        if(list != null && list.size() > 0)
        {
            if(list.size() == 1)
                return list.get(0);

            int maxNum = list.get(0);
            for(int item:list)
            {
                if(item > maxNum)
                    maxNum = item;
            }
            return maxNum;
        }
        return null;
    }

My question is "Can any sorting algorithm beat it (on time scale) on any given input for eg. if the collection is already sorted or not?"
Is there any other way better than this ?


问:
How to import test cases from excel sheet to TFS (team foundation server)
I have tried using Test object tool which is used to get test cases from TFS to Excel sheet.

Now i would like to know how to import test cases to TFS(Team foundation server) again from excel sheet.

答:
The simplest way  to import your test case back to TFS is: Import your test cases from web portal by copy and save.

For more details take a look at this thread.


问:
SQL: How to get the actual shift values
I´ve created a report in SSRS in which I display all Machines volume from
last hour:

```<code>where  IntervalStartDateTime >= dateadd(HOUR, -2, GETDATE())
    And IntervalStartDateTime <= dateadd(HOUR, -1, GETDATE())
</code>```

from last 4 hours:

```<code>where  IntervalStartDateTime >= dateadd(HOUR, -4, GETDATE())
    And IntervalStartDateTime <= dateadd(HOUR, -3, GETDATE())
</code>```

and from last 8 hours:

```<code>where  IntervalStartDateTime >= dateadd(HOUR, -8, GETDATE())
    And IntervalStartDateTime <= dateadd(HOUR, -7, GETDATE())
</code>```

And additionaly I would like to display a row for the actual shift --> here I have some problems.
There a three shifts.
Night Shift: from: 05:45 - 13:45
early shift: from: 13:45 - 21:45
late shift: from : 21:45 - 05:45

Table:

```<code>IntervalStartDateTime
2017-03-28 15:30:00.000
2017-03-28 15:30:00.000
2017-03-28 15:30:00.000
2017-03-28 15:30:00.000
2017-03-28 15:30:00.000
</code>```

How can I get the actual shift value?
I am using Microsoft SQL Server Management Studio

答:
Please try -

```<code>WHERE ( IntervalStartTime >= CASE
                                 WHEN CONVERT( TIME, GETDATE() ) < '05:45:00' THEN CONVERT( DATE, DATEADD( DAY, -1, GETDATE() ) ) + CAST( '21:45:00' AS DATETIME )
                                 WHEN CONVERT( TIME, GETDATE() ) < '13:45:00' THEN CONVERT( DATE, GETDATE() ) + CAST( '05:45:00' AS DATETIME )
                                 WHEN CONVERT( TIME, GETDATE() ) < '21:45:00' THEN CONVERT( DATE, GETDATE() ) + CAST( '13:45:00' AS DATETIME )
                                 ELSE                                              CONVERT( DATE, GETDATE() ) + CAST( '21:45:00' AS DATETIME )
                             END )
</code>```

Note : This is my first time trying SQL-Server, but I'm going to have start sometime I guess.  :)

If you have any questions or comments, then please feel free to post a Comment accordingly.

Further Reading...

combining Date and Time fields to DateTime, SQL Server 2008

How to return the date part only from a SQL Server datetime datatype

Title: SQL: How to get the actual shift values

Body:
I´ve created a report in SSRS in which I display all Machines volume from
last hour:

where  IntervalStartDateTime >= dateadd(HOUR, -2, GETDATE())
    And IntervalStartDateTime <= dateadd(HOUR, -1, GETDATE())

from last 4 hours:

where  IntervalStartDateTime >= dateadd(HOUR, -4, GETDATE())
    And IntervalStartDateTime <= dateadd(HOUR, -3, GETDATE())

and from last 8 hours:

where  IntervalStartDateTime >= dateadd(HOUR, -8, GETDATE())
    And IntervalStartDateTime <= dateadd(HOUR, -7, GETDATE())

And additionaly I would like to display a row for the actual shift --> here I have some problems.
There a three shifts.
Night Shift: from: 05:45 - 13:45
early shift: from: 13:45 - 21:45
late shift: from : 21:45 - 05:45

Table:

IntervalStartDateTime
2017-03-28 15:30:00.000
2017-03-28 15:30:00.000
2017-03-28 15:30:00.000
2017-03-28 15:30:00.000
2017-03-28 15:30:00.000

How can I get the actual shift value?
I am using Microsoft SQL Server Management Studio

Body:
Please try -

WHERE ( IntervalStartTime >= CASE
                                 WHEN CONVERT( TIME, GETDATE() ) < '05:45:00' THEN CONVERT( DATE, DATEADD( DAY, -1, GETDATE() ) ) + CAST( '21:45:00' AS DATETIME )
                                 WHEN CONVERT( TIME, GETDATE() ) < '13:45:00' THEN CONVERT( DATE, GETDATE() ) + CAST( '05:45:00' AS DATETIME )
                                 WHEN CONVERT( TIME, GETDATE() ) < '21:45:00' THEN CONVERT( DATE, GETDATE() ) + CAST( '13:45:00' AS DATETIME )
                                 ELSE                                              CONVERT( DATE, GETDATE() ) + CAST( '21:45:00' AS DATETIME )
                             END )

Note : This is my first time trying SQL-Server, but I'm going to have start sometime I guess.  :)

If you have any questions or comments, then please feel free to post a Comment accordingly.

Further Reading...

combining Date and Time fields to DateTime, SQL Server 2008

How to return the date part only from a SQL Server datetime datatype


问:
Order by 'rand' not working on Wordpress foreach loop
I am trying to order some data by 'rand' on a foreach loop I have created which is outputting some users which I have created a custom role for. all the other bits are great apart from this.

This is the current state of the loop:

```<code><?php

// Featured Consultants
$consultants = get_users( 'role=consultant&number=2' );
// Array of WP_User objects.
foreach ( $consultants as $consultant ) {

    // Check for 'featured' Consultants
    if($consultant->featured == 'Yes'){

        echo '<div class="columns six consultantCard">';

            echo '<div class="columns four">';
            echo get_avatar( $consultant->id, 150 );
            echo '</div>';

            echo '<div class="columns eight">';
                // Get users details
                echo '<span class="name">' . esc_html( $consultant->first_name ) . ' ' . esc_html( $consultant->last_name ) . '</span>';
                echo '<span class="jobTitle">' . esc_html( $consultant->job_title ) . '</span>';
                echo '<span class="location">Currently based in ' . esc_html( $consultant->current_location ) . '</span>';

                // Check if user is less than 30 days old
                if( strtotime($consultant->user_registered) < strtotime('30 days') ){
                    echo '<span class="newTag">New</span>';
                }

                // Check if user is featured
                if($consultant->featured == 'Yes'){
                    echo '<span class="featuredTag">Featured Candiate</span>';
                }

                // Check if user is accredited
                if($consultant->accredited == 'Yes'){ ?>
                    <span class="icon"><img src="<?php bloginfo('template_url');?>/assets/img/icons/accreditedIcon.png" /></span>
                    <?php echo '<span class="accreditedTag">Bench Accredited</span>';
                }
            echo '</div>';

        echo '</div>';

    } else{
        echo 'No Featured Consultants';
    }
}
?>
</code>```

It just appears to be showing the latest entries and nothing more. I tried to also create an array but still the same result like so:

```<code>$consultant = array(
'role' => 'consultant',
'order'     => 'rand'
);
</code>```

答:
We can use the get_users() to get a list of authors, users with a specific role, a user with specific meta, etc. The function returns users which can be ordered by ID, login, nickname, email, URL, registered, display_name, post_count, or meta_value. But there is no random option such as what get_posts() function provides to shows posts randomly.

Since the get_users() function uses WP_User_Query class, there is an action hook pre_user_query we can use to modify the class variable. The idea is using our own 'rand' order by the parameter. If we put 'rand' to the orderby parameter, user_login will be used instead. In this case, we need to replace it with RAND() to result in users randomly. In this example below, we I ‘rand’ and you can use your own order by name.

```<code>// Add this code in your function.php
add_action( 'pre_user_query', 'my_random_user_query' );

function my_random_user_query( $class ) {
    if( 'rand' == $class->query_vars['orderby'] )
        $class->query_orderby = str_replace( 'user_login', 'RAND()', $class->query_orderby );

    return $class;
}
</code>```

The WP_User_Query contains order by query and the our arguments. Now, we have a new order by parameter to WordPress.

```<code>$users = get_users( array(
    'orderby' => 'rand',
    'number'  => 5
));
print_r( $users );
</code>```

Body:
I am trying to order some data by 'rand' on a foreach loop I have created which is outputting some users which I have created a custom role for. all the other bits are great apart from this.

This is the current state of the loop:

<?php

// Featured Consultants
$consultants = get_users( 'role=consultant&number=2' );
// Array of WP_User objects.
foreach ( $consultants as $consultant ) {

    // Check for 'featured' Consultants
    if($consultant->featured == 'Yes'){

        echo '
';

            echo '
';
            echo get_avatar( $consultant->id, 150 );
            echo '
';

            echo '
';
                // Get users details
                echo '' . esc_html( $consultant->first_name ) . ' ' . esc_html( $consultant->last_name ) . '';
                echo '' . esc_html( $consultant->job_title ) . '';
                echo 'Currently based in ' . esc_html( $consultant->current_location ) . '';

                // Check if user is less than 30 days old
                if( strtotime($consultant->user_registered) < strtotime('30 days') ){
                    echo 'New';
                }

                // Check if user is featured
                if($consultant->featured == 'Yes'){
                    echo 'Featured Candiate';
                }

                // Check if user is accredited
                if($consultant->accredited == 'Yes'){ ?>
                    <img src="<?php bloginfo('template_url');?>/assets/img/icons/accreditedIcon.png" />
                    <?php echo 'Bench Accredited';
                }
            echo '
';

        echo '
';

    } else{
        echo 'No Featured Consultants';
    }
}
?>

It just appears to be showing the latest entries and nothing more. I tried to also create an array but still the same result like so:

$consultant = array(
'role' => 'consultant',
'order'     => 'rand'
);

Body:
We can use the get_users() to get a list of authors, users with a specific role, a user with specific meta, etc. The function returns users which can be ordered by ID, login, nickname, email, URL, registered, display_name, post_count, or meta_value. But there is no random option such as what get_posts() function provides to shows posts randomly.

Since the get_users() function uses WP_User_Query class, there is an action hook pre_user_query we can use to modify the class variable. The idea is using our own 'rand' order by the parameter. If we put 'rand' to the orderby parameter, user_login will be used instead. In this case, we need to replace it with RAND() to result in users randomly. In this example below, we I ‘rand’ and you can use your own order by name.

// Add this code in your function.php
add_action( 'pre_user_query', 'my_random_user_query' );

function my_random_user_query( $class ) {
    if( 'rand' == $class->query_vars['orderby'] )
        $class->query_orderby = str_replace( 'user_login', 'RAND()', $class->query_orderby );

    return $class;
}

The WP_User_Query contains order by query and the our arguments. Now, we have a new order by parameter to WordPress.

$users = get_users( array(
    'orderby' => 'rand',
    'number'  => 5
));
print_r( $users );


问:
adding the new row in the bottom of the uitableview after loading the web service value in the tableview in objective c
i am very new to the objective c in my app the tableview is dynamically updated by the web service after loading the web service i have to create one new row and i have to add one new label in it how to do that.can anyone pls suggest me how to do that in my app..

This is my sample code

```<code>-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIdentifier = @"Cell";

    customcell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[customcell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.finacialyear.text=[self->entries1 objectAtIndex:indexPath.row];
    cell.term.text=[self->entries2 objectAtIndex:indexPath.row];
    cell.balance.text=[self->entries3 objectAtIndex:indexPath.row];
    cell.tintColor = [UIColor blueColor];
    return cell;
}
</code>```

Here entries 1,entries 2,entries 3 are nsmutablearray that having the json values.

答:
```<code>// build the index paths for insertion
// since you're adding to the end of datasource, the new rows will start at count
NSMutableArray *indexPaths = [NSMutableArray array];
NSInteger currentCount = self.datasource.count;
for (int i = 0; i < dataToAdd.count; i++) {
    [indexPaths addObject:[NSIndexPath indexPathForRow:currentCount+i inSection:0]];
}

// do the insertion
[self.dataSource addObjects:dataToAdd];

// tell the table view to update (at all of the inserted index paths)
[self.tableView beginUpdates];
[self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationTop];
[self.tableView endUpdates];
</code>```

Body:
i am very new to the objective c in my app the tableview is dynamically updated by the web service after loading the web service i have to create one new row and i have to add one new label in it how to do that.can anyone pls suggest me how to do that in my app..

This is my sample code

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIdentifier = @"Cell";

    customcell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[customcell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.finacialyear.text=[self->entries1 objectAtIndex:indexPath.row];
    cell.term.text=[self->entries2 objectAtIndex:indexPath.row];
    cell.balance.text=[self->entries3 objectAtIndex:indexPath.row];
    cell.tintColor = [UIColor blueColor];
    return cell;
}

Here entries 1,entries 2,entries 3 are nsmutablearray that having the json values.