问:
Replicate Countifs() in pandas with multiple conditions
I have a DataFrame of the form:

What I would like to achieve is a DataFrame that has unique groups and a count of non-zeros for each column 1-9. It would look like the below.

I'm pretty much at a loss on this. I saw the question here, but this doesn't address the grouping aspect. How can I achieve this using pandas?

答:
Assuming you have the following DF:

```<code>In [82]: df
Out[82]:
    Group  1  2  3  4  5
0  Group1  0  1  4  0  1
1  Group1  3  0  4  1  5
2  Group2  0  1  4  3  6
3  Group2  5  1  4  0  7
4  Group3  0  0  4  7  8
5  Group3  7  1  4  7  9
</code>```

Solution:

```<code>In [83]: df.set_index('Group').ne(0).groupby(level=0).sum().reset_index()
Out[83]:
    Group    1    2    3    4    5
0  Group1  1.0  1.0  2.0  1.0  2.0
1  Group2  1.0  2.0  2.0  1.0  2.0
2  Group3  1.0  1.0  2.0  2.0  2.0
</code>```

as integers:

```<code>In [84]: df.set_index('Group').ne(0).groupby(level=0).sum().astype(int).reset_index()
Out[84]:
    Group  1  2  3  4  5
0  Group1  1  1  2  1  2
1  Group2  1  2  2  1  2
2  Group3  1  1  2  2  2
</code>```

UPDATE:

```<code>In [92]: df
Out[92]:
    Group  1  2  3  4  5
0  Group1  0  1  4  0  0
1  Group1  3  0  4  1  0
2  Group2  0  1  4  3  0
3  Group2  5  1  4  0  0
4  Group3  0  0  4  7  0
5  Group3  7  1  4  7  0

In [93]: df.set_index('Group').ne(0).groupby(level=0).sum().astype(int).reset_index()
Out[93]:
    Group  1  2  3  4  5
0  Group1  1  1  2  1  0
1  Group2  1  2  2  1  0
2  Group3  1  1  2  2  0
</code>```

Timing:

```<code>In [37]: %timeit df.set_index('Group').ne(0).groupby(level=0).sum().astype(int).reset_index()
100 loops, best of 3: 6.24 ms per loop

In [38]: %timeit df.pivot_table(index='Group', aggfunc=np.count_nonzero)
100 loops, best of 3: 19.2 ms per loop
</code>```

let's test it against a bigger (60.000 rows) DF:

```<code>In [39]: df = pd.concat([df] * 10**4, ignore_index=True)

In [40]: df.shape
Out[40]: (60000, 6)

In [42]: %timeit df.set_index('Group').ne(0).groupby(level=0).sum().astype(int).reset_index()
10 loops, best of 3: 22.4 ms per loop

In [43]: %timeit df.pivot_table(index='Group', aggfunc=np.count_nonzero)
10 loops, best of 3: 43 ms per loop
</code>```

Conclusion:

IMO high-level function pivot_table is slower due to additional overhead, but t he difference is not that huge for bigger data sets...

Body:
Assuming you have the following DF:

In [82]: df
Out[82]:
    Group  1  2  3  4  5
0  Group1  0  1  4  0  1
1  Group1  3  0  4  1  5
2  Group2  0  1  4  3  6
3  Group2  5  1  4  0  7
4  Group3  0  0  4  7  8
5  Group3  7  1  4  7  9

Solution:

In [83]: df.set_index('Group').ne(0).groupby(level=0).sum().reset_index()
Out[83]:
    Group    1    2    3    4    5
0  Group1  1.0  1.0  2.0  1.0  2.0
1  Group2  1.0  2.0  2.0  1.0  2.0
2  Group3  1.0  1.0  2.0  2.0  2.0

as integers:

In [84]: df.set_index('Group').ne(0).groupby(level=0).sum().astype(int).reset_index()
Out[84]:
    Group  1  2  3  4  5
0  Group1  1  1  2  1  2
1  Group2  1  2  2  1  2
2  Group3  1  1  2  2  2

UPDATE:

In [92]: df
Out[92]:
    Group  1  2  3  4  5
0  Group1  0  1  4  0  0
1  Group1  3  0  4  1  0
2  Group2  0  1  4  3  0
3  Group2  5  1  4  0  0
4  Group3  0  0  4  7  0
5  Group3  7  1  4  7  0

In [93]: df.set_index('Group').ne(0).groupby(level=0).sum().astype(int).reset_index()
Out[93]:
    Group  1  2  3  4  5
0  Group1  1  1  2  1  0
1  Group2  1  2  2  1  0
2  Group3  1  1  2  2  0

Timing:

In [37]: %timeit df.set_index('Group').ne(0).groupby(level=0).sum().astype(int).reset_index()
100 loops, best of 3: 6.24 ms per loop

In [38]: %timeit df.pivot_table(index='Group', aggfunc=np.count_nonzero)
100 loops, best of 3: 19.2 ms per loop

let's test it against a bigger (60.000 rows) DF:

In [39]: df = pd.concat([df] * 10**4, ignore_index=True)

In [40]: df.shape
Out[40]: (60000, 6)

In [42]: %timeit df.set_index('Group').ne(0).groupby(level=0).sum().astype(int).reset_index()
10 loops, best of 3: 22.4 ms per loop

In [43]: %timeit df.pivot_table(index='Group', aggfunc=np.count_nonzero)
10 loops, best of 3: 43 ms per loop

Conclusion:

IMO high-level function pivot_table is slower due to additional overhead, but t he difference is not that huge for bigger data sets...


来源: stackexchange

问:
require a module from memory instead of from disk - is this possible?
I'd like to require a Node.js module from memory, e.g. because it is generated at runtime or received from a network stream.

Is this possible at all?

How could you resolve this issue (without writing to disk and loading from there, of course)?

Basically, something such as:

```<code>var code = 'module.exports = { foo: "bar" };';
var obj = require(code);
console.log(obj.foo); // => bar
</code>```

The only approach I can currently think of is using the eval function, such as:

```<code>var myModule = {};
eval(
  '(function (module) {' +
  '  var local = 5;' +
  '  module.exports = {' +
  '    foo: \'bar\'' +
  '  };' +
  '  module.exports.baz = \'baz\';' +
  '})(myModule)');
</code>```

After evaluating, myModule.exports contains the exported object:

```<code>{
  foo: 'bar',
  baz: 'baz'
}
</code>```

and anything that should be local inside the module stays local.

Hence, you could create a function require2, such as:

```<code>var require2 = function (code) {
  var temp = {};
  eval('(function (module) {' + code + '})(temp);');
  return temp.exports;
};
</code>```

Anyway, I am interested in better ideas ... :-)

PS: Being able to require from a stream would be awesome :-)

答:
This has already been answered here:

However, you can find a more complete implementation in the require-from-string package in Github.

The TL;DR is that you use the Modules package in node.js to _compile the code from a string.

ContentLicense: CC BY-SA 3.0

Body:
I'd like to require a Node.js module from memory, e.g. because it is generated at runtime or received from a network stream.

Is this possible at all?

How could you resolve this issue (without writing to disk and loading from there, of course)?

Basically, something such as:

var code = 'module.exports = { foo: "bar" };';
var obj = require(code);
console.log(obj.foo); // => bar

The only approach I can currently think of is using the eval function, such as:

var myModule = {};
eval(
  '(function (module) {' +
  '  var local = 5;' +
  '  module.exports = {' +
  '    foo: \'bar\'' +
  '  };' +
  '  module.exports.baz = \'baz\';' +
  '})(myModule)');

After evaluating, myModule.exports contains the exported object:

{
  foo: 'bar',
  baz: 'baz'
}

and anything that should be local inside the module stays local.

Hence, you could create a function require2, such as:

var require2 = function (code) {
  var temp = {};
  eval('(function (module) {' + code + '})(temp);');
  return temp.exports;
};

Anyway, I am interested in better ideas ... :-)

PS: Being able to require from a stream would be awesome :-)


问:
Is Spark only applying my UDF on records being shown?
I have a feeling Spark is being cleverer than me and reordering (or at least in comparison to the written code) what is running on executors etc.

Suppose I have a very simple spark query in scala as follows.

```<code>val sqlContext = new org.apache.spark.sql.hive.HiveContext(sc)
val rawData = sqlContext.sql("FROM mytable SELECT *")
</code>```

I then create a new column using some functionality in a UDF, this function is not lightweight (or at least some of the time) and relies on multiple columns in the data. Roughly speaking my UDF looks similar to this although the processing is only an example.

```<code>def method1(s1:String, s2:String):String = {
  List(s1, s2).mkString(" ")
}

val method1UDF = udf(method1 _)

val dataWithCol = rawData
                  .withColumn("newcol", method1UDF($"c1",$"c2"))

dataWithCol.show(100)
</code>```

My question actually revolves around the last statement, or at least I think it does.

If my dataset has 1 billion records in it, is Spark actually only applying my withColumn to 100 records, or is it applying it to all 1 million records and then just returning the first 100?

In Hive I presume the equivalent would be:

```<code>SELECT t.c1, t.c2, CONCAT_WS(" ",t.c1,t.c2) as newCol from (
    SELECT c1,c2 as newCol FROM mytable limit 100
) t
</code>```

Even though in code it looks like i've written the equivalent of the following query

```<code>SELECT * from (
    SELECT c1,c2, CONCAT_WS(" ",c1,c2) as newCol FROM mytable
) t limit 100
</code>```

I suspect it is doing the former since adding a filter on the new column drastically slows down the operation.  If I change the last line to:

```<code>dataWithCol.filter($"newCol" === "H i").show(100)
</code>```

This is now having to apply the function to a lot more data (presumably the entire dataset) before it does the limit of 100, similar to the following Hive query:

```<code>SELECT * from (
    SELECT c1,c2, CONCAT_WS(" ",c1,c2) as newCol FROM mytable
) t where t.newCol == "H i" limit 100
</code>```

Am I along the right lines with what Spark is doing in the background?  Is it optimising my query by only applying the processing on records which will end up being viewed?

答:
If you are not sure you can alway make an experiment:

```<code>Spark context available as 'sc' (master = local[*], app id = local-1490732267478).
Spark session available as 'spark'.
Welcome to
      ____              __
     / __/__  ___ _____/ /__
    _\ \/ _ \/ _ `/ __/  '_/
   /___/ .__/\_,_/_/ /_/\_\   version 2.1.0
      /_/

Using Scala version 2.11.8 (OpenJDK 64-Bit Server VM, Java 1.8.0_121)
Type in expressions to have them evaluated.
Type :help for more information.

scala> :paste
// Entering paste mode (ctrl-D to finish)

val rawData = spark.range(0, 1000000000, 1, 1000)
  .toDF("id")
  .select(
    $"id".cast("string").alias("s1"),
    $"id".cast("string").alias("s2"))

val counter = sc.longAccumulator("counter")

def f = udf((s1: String, s2: String) => {
  counter.add(1)
  s"$s1 $s2"
})

rawData.select(f($"s1", $"s2")).show(10)

// Exiting paste mode, now interpreting.
</code>```

```<code>+-----------+
|UDF(s1, s2)|
+-----------+
|        0 0|
|        1 1|
|        2 2|
|        3 3|
|        4 4|
|        5 5|
|        6 6|
|        7 7|
|        8 8|
|        9 9|
+-----------+
only showing top 10 rows

rawData: org.apache.spark.sql.DataFrame = [s1: string, s2: string]
counter: org.apache.spark.util.LongAccumulator = LongAccumulator(id: 0, name: Some(counter), value: 12)
f: org.apache.spark.sql.expressions.UserDefinedFunction

scala> counter.value
res1: Long = 12
</code>```

As you can see Spark limits the number of records to be processed but it is not exactly precise. You should also remember that these results are version and query dependent.

For example earlier Spark version where fairly limited when applying optimizations to UDF calls. Also upstream wide transformation may affect this behavior and result in processing more (or even all) records.

Body:
I have a feeling Spark is being cleverer than me and reordering (or at least in comparison to the written code) what is running on executors etc.

Suppose I have a very simple spark query in scala as follows.

val sqlContext = new org.apache.spark.sql.hive.HiveContext(sc)
val rawData = sqlContext.sql("FROM mytable SELECT *")

I then create a new column using some functionality in a UDF, this function is not lightweight (or at least some of the time) and relies on multiple columns in the data. Roughly speaking my UDF looks similar to this although the processing is only an example.

def method1(s1:String, s2:String):String = {
  List(s1, s2).mkString(" ")
}

val method1UDF = udf(method1 _)

val dataWithCol = rawData
                  .withColumn("newcol", method1UDF($"c1",$"c2"))

dataWithCol.show(100)

My question actually revolves around the last statement, or at least I think it does.

If my dataset has 1 billion records in it, is Spark actually only applying my withColumn to 100 records, or is it applying it to all 1 million records and then just returning the first 100?

In Hive I presume the equivalent would be:

SELECT t.c1, t.c2, CONCAT_WS(" ",t.c1,t.c2) as newCol from (
    SELECT c1,c2 as newCol FROM mytable limit 100
) t

Even though in code it looks like i've written the equivalent of the following query

SELECT * from (
    SELECT c1,c2, CONCAT_WS(" ",c1,c2) as newCol FROM mytable
) t limit 100

I suspect it is doing the former since adding a filter on the new column drastically slows down the operation.  If I change the last line to:

dataWithCol.filter($"newCol" === "H i").show(100)

This is now having to apply the function to a lot more data (presumably the entire dataset) before it does the limit of 100, similar to the following Hive query:

SELECT * from (
    SELECT c1,c2, CONCAT_WS(" ",c1,c2) as newCol FROM mytable
) t where t.newCol == "H i" limit 100

Am I along the right lines with what Spark is doing in the background?  Is it optimising my query by only applying the processing on records which will end up being viewed?

Body:
If you are not sure you can alway make an experiment:

Spark context available as 'sc' (master = local[*], app id = local-1490732267478).
Spark session available as 'spark'.
Welcome to
      ____              __
     / __/__  ___ _____/ /__
    _\ \/ _ \/ _ `/ __/  '_/
   /___/ .__/\_,_/_/ /_/\_\   version 2.1.0
      /_/

Using Scala version 2.11.8 (OpenJDK 64-Bit Server VM, Java 1.8.0_121)
Type in expressions to have them evaluated.
Type :help for more information.

scala> :paste
// Entering paste mode (ctrl-D to finish)

val rawData = spark.range(0, 1000000000, 1, 1000)
  .toDF("id")
  .select(
    $"id".cast("string").alias("s1"),
    $"id".cast("string").alias("s2"))

val counter = sc.longAccumulator("counter")

def f = udf((s1: String, s2: String) => {
  counter.add(1)
  s"$s1 $s2"
})

rawData.select(f($"s1", $"s2")).show(10)

// Exiting paste mode, now interpreting.

+-----------+
|UDF(s1, s2)|
+-----------+
|        0 0|
|        1 1|
|        2 2|
|        3 3|
|        4 4|
|        5 5|
|        6 6|
|        7 7|
|        8 8|
|        9 9|
+-----------+
only showing top 10 rows

rawData: org.apache.spark.sql.DataFrame = [s1: string, s2: string]
counter: org.apache.spark.util.LongAccumulator = LongAccumulator(id: 0, name: Some(counter), value: 12)
f: org.apache.spark.sql.expressions.UserDefinedFunction

scala> counter.value
res1: Long = 12

As you can see Spark limits the number of records to be processed but it is not exactly precise. You should also remember that these results are version and query dependent.

For example earlier Spark version where fairly limited when applying optimizations to UDF calls. Also upstream wide transformation may affect this behavior and result in processing more (or even all) records.


问:
Adding Recursively to Set
I'm trying to wrap my head around recursive functions with this one function def friends(self, name, degree):. The purpose of this one is to return the set of all friends up to a specified degree (for an address book). It's the last part of a larger class called class SocialAddressBook:. The 'degree' in this class allows the user to 'query' friends of friends: degree one is a direct friend, degree 2 is a friend-of-a-friend, and so on.  The code I have is

```<code>def friends(self, name, degree):
    fs = set()
    if degree == 0:
        return set()
    if degree == 1:
</code>```

which is far as my knowledge on this goes....
also some more context:

Transitive friendship:

```<code>Fred → Barb → Jane → Emma → Lisa
Fred → Sue
              Jane → Mary
</code>```

and so my tests are : a.friends('Fred', 1) == {'Barb', 'Sue'}

a.friends('Fred', 2) == {'Barb', 'Jane', 'Sue'}

a.friends('Fred', 3) == {'Mary', 'Barb', 'Jane', 'Sue', 'Emma'}

a.friends('Fred', 4) == {'Barb', 'Emma', 'Mary', 'Lisa', 'Sue', 'Jane'}

it only goes up to degree 4. SO should I even do this recursively or just manually since I know the degree it goes up to?.

If anyone could point me in the right direction on how to complete this recursively, that'd be awesome, thanks!

答:
It is best to do this iteratively.</p>

```<code>def get_friends_iteratively(self, name, degree)
    if degree < 0:
        raise ValueError('degree should be an int >= 0')
    if degree == 0:
        return set() # no friends of degree 0!
    friends = self.friends
    for _ in range(degree):
        new_friends = set()
        # it is important not to change a set while we iterate through it.
        # thus, we change new_friends, then update friends when we are done.
        for other_person in self.friends:
            new_friends |= other_person.friends
        friends |= new_friends
    return friends

    # In python, the |= ('in-place or') operator updates a set with
    # the union of itself and another set.
</code>```

Title: Adding Recursively to Set

Body:
I'm trying to wrap my head around recursive functions with this one function def friends(self, name, degree):. The purpose of this one is to return the set of all friends up to a specified degree (for an address book). It's the last part of a larger class called class SocialAddressBook:. The 'degree' in this class allows the user to 'query' friends of friends: degree one is a direct friend, degree 2 is a friend-of-a-friend, and so on.  The code I have is

def friends(self, name, degree):
    fs = set()
    if degree == 0:
        return set()
    if degree == 1:

which is far as my knowledge on this goes....
also some more context:

Transitive friendship:

Fred → Barb → Jane → Emma → Lisa
Fred → Sue
              Jane → Mary

and so my tests are : a.friends('Fred', 1) == {'Barb', 'Sue'}

a.friends('Fred', 2) == {'Barb', 'Jane', 'Sue'}

a.friends('Fred', 3) == {'Mary', 'Barb', 'Jane', 'Sue', 'Emma'}

a.friends('Fred', 4) == {'Barb', 'Emma', 'Mary', 'Lisa', 'Sue', 'Jane'}

it only goes up to degree 4. SO should I even do this recursively or just manually since I know the degree it goes up to?.

If anyone could point me in the right direction on how to complete this recursively, that'd be awesome, thanks!

Body:
It is best to do this iteratively.

def get_friends_iteratively(self, name, degree)
    if degree < 0:
        raise ValueError('degree should be an int >= 0')
    if degree == 0:
        return set() # no friends of degree 0!
    friends = self.friends
    for _ in range(degree):
        new_friends = set()
        # it is important not to change a set while we iterate through it.
        # thus, we change new_friends, then update friends when we are done.
        for other_person in self.friends:
            new_friends |= other_person.friends
        friends |= new_friends
    return friends

    # In python, the |= ('in-place or') operator updates a set with
    # the union of itself and another set.


问:
Yii2 breadcrumb not showing
Here's the code to show breadcrumb on my view

```<code><div class="container">
    <?= Breadcrumbs::widget([
        'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
    ]) ?>
    <?= $content ?>
</div>
</code>```

But when I change div class to "container-fluid" the breadcrumb not showing anymore and I really don't know why? I'm new to Yii2.

Please help me with this.

Sorry for my bad English. Thank you.

答: The problem is with padding. The .container class (inside .wrap) has padding: 70px 15px 20px; what gives enough padding top for the breadcrumbs to be shown below the top navbar .The container-fluid class has no padding and the breadcrumbs lie behind the top navbar. Add padding-top: 70px to your .container-fluid class and you will see your breadcrumbs again.

Title: Yii2 breadcrumb not showing

Body:
Here's the code to show breadcrumb on my view

    <?= Breadcrumbs::widget([
        'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
    ]) ?>
    <?= $content ?>

But when I change div class to "container-fluid" the breadcrumb not showing anymore and I really don't know why? I'm new to Yii2.

Please help me with this.

Sorry for my bad English. Thank you.


问:
Triggering build with properties via API
I want to trigger a build on my TeamCity 10.0.3 server, using REST API.

The example is listed in XML-format, and is working in a test application:

```<code><build>
    <buildType id="buildConfID"/>
    <properties>
        <property name="env.myEnv" value="bbb"/>
    </properties>
</build>
</code>```

My API is using JSON instead:

```<code>{"buildType": {"id":"buildConfId"},
 "Properties":[
  {"Name":"myParameter","Value":"bbb"}
 ]
}
</code>```

The build is triggered correctly, but the parameter is not set. What I found out the Properties field needs to be uppercase to be accepted by TeamCity.
I have no clue on how to format parameters so that they will be accepted.

答:
After some research I found the source code for Properties-class. Properties need to be written lower-case, looks like I'm receiving OK-Response, because it wasn't parsed.

The correct call will look like:

```<code>{
 "buildType": {"id":"buildConfId"},
 "properties": {
  "property": [
    {"Name":"myParameter","Value":"bbb"}
   ]
  }
}
</code>```

Body:
I want to trigger a build on my TeamCity 10.0.3 server, using REST API.

The example is listed in XML-format, and is working in a test application:

<build>
    <buildType id="buildConfID"/>
    <properties>
        <property name="env.myEnv" value="bbb"/>
    </properties>
</build>

My API is using JSON instead:

{"buildType": {"id":"buildConfId"},
 "Properties":[
  {"Name":"myParameter","Value":"bbb"}
 ]
}

The build is triggered correctly, but the parameter is not set. What I found out the Properties field needs to be uppercase to be accepted by TeamCity.
I have no clue on how to format parameters so that they will be accepted.

Body:
After some research I found the source code for Properties-class. Properties need to be written lower-case, looks like I'm receiving OK-Response, because it wasn't parsed.

The correct call will look like:

{
 "buildType": {"id":"buildConfId"},
 "properties": {
  "property": [
    {"Name":"myParameter","Value":"bbb"}
   ]
  }
}


问:
Why do these sum operations not "add up" as they should?
Note: This is a follow[on,up] to this question and this question and this question.

The responses all moved me forward, but even that last one, although it improved matters, did not completely solve this issue.

This query:

```<code>select monthlysales, MemberNo from ReportingMonthlySales
where unit = 'Abuelos' and CYear = 2017 and cmonth = 3
</code>```

...returns a bunch of rows, where the Monthly Sales total is $364,121.69

However, when I try to compartmentalize these monthly sales into four categories, although the sum of them all should be the same, the sum is actually astronomically "huger" - the following code returns the vastly inflated value of 23,924,211.30

24 millions of dollars is almost 70 times as much as the 364 thousand that is the actual sum total. Why is this "crazy" inflation occurring?

Here is the fancy pants but apparently bamboozled code:

```<code>declare @Unit varchar(30);
declare @Year int = 2017;
declare @Month int = 3;
declare @paramdate datetime;
set @paramdate = convert(datetime,convert(char(4),@Year)
                +right('0'+convert(varchar(2),@month),2)
                +'01')

IF OBJECT_ID('tempdb.dbo.#Units', 'U') IS NOT NULL
DROP TABLE #Units

select distinct unit
into #Units
from ReportingMonthlySales;

select
    u.Unit
  , New      = sum(case when ccl.Subcategory = 'New'      then rms.MonthlySales else 0 end)
  , Assumed  = sum(case when ccl.Subcategory = 'Assumed'  then rms.MonthlySales else 0 end)
  , Existing = sum(case when ccl.Subcategory = 'Existing' then rms.MonthlySales else 0 end)
  , Organic  = sum(case when ccl.Subcategory = 'Organic'  then rms.MonthlySales else 0 end)
from #Units u
  left join CustomerCategoryLog ccl
    on u.Unit = ccl.Unit
   and @paramdate >= ccl.begindate and
   (@paramdate <= ccl.enddate OR ccl.enddate is null)
  left join ReportingMonthlySales rms
    on u.Unit = rms.Unit
   and rms.cyear  = @year
   and rms.cmonth = @month
group by u.unit;

The two tables queried are:

CustomerCategoryLog
-------------------
MemberNo (VarChar)
Unit (VarChar)
Custno (VarChar)
Category (VarChar)
Subcategory (VarChar)
BeginDate (DateTime)
EndDate (DateTime)
ChangedBy (VarChar)
ChangedOn (DateTime)

ReportingMonthlySales
---------------------
AutoID (Int)
Unit (VarChar)
MemberNo (VarChar)
NumUnits (Int)
MonthlySales (Money)
CYear (Int)
Cmonth (Int)
CreateDate (DateTime)
</code>```

Is there something faulty in the fancy-pants sql, or ... ?!?

答:
i think this is causing the duplication

```<code>select distinct unit
into #Units
from ReportingMonthlySales;
</code>```

you basically inserted the same data from the table and used at the left join..

try this updated script

```<code>  SELECT
  rms.Unit,
  New = SUM(CASE
    WHEN ccl.Subcategory = 'New' THEN rms.MonthlySales
    ELSE 0
  END),
  Assumed = SUM(CASE
    WHEN ccl.Subcategory = 'Assumed' THEN rms.MonthlySales
    ELSE 0
  END),
  Existing = SUM(CASE
    WHEN ccl.Subcategory = 'Existing' THEN rms.MonthlySales
    ELSE 0
  END),
  Organic = SUM(CASE
    WHEN ccl.Subcategory = 'Organic' THEN rms.MonthlySales
    ELSE 0
  END)
FROM ReportingMonthlySales rms
inner JOIN CustomerCategoryLog ccl
  ON rms.Unit = ccl.Unit
where
  AND @paramdate >= ccl.begindate
  AND (@paramdate <= isnull(ccl.enddate,getdate())
  )
 AND
   rms.cyear = @year
  AND rms.cmonth = @month
GROUP BY rms.unit;
</code>```

Body:
Note: This is a follow[on,up] to this question and this question and this question.

The responses all moved me forward, but even that last one, although it improved matters, did not completely solve this issue.

This query:

select monthlysales, MemberNo from ReportingMonthlySales
where unit = 'Abuelos' and CYear = 2017 and cmonth = 3

...returns a bunch of rows, where the Monthly Sales total is $364,121.69

However, when I try to compartmentalize these monthly sales into four categories, although the sum of them all should be the same, the sum is actually astronomically "huger" - the following code returns the vastly inflated value of 23,924,211.30

24 millions of dollars is almost 70 times as much as the 364 thousand that is the actual sum total. Why is this "crazy" inflation occurring?

Here is the fancy pants but apparently bamboozled code:

declare @Unit varchar(30);
declare @Year int = 2017;
declare @Month int = 3;
declare @paramdate datetime;
set @paramdate = convert(datetime,convert(char(4),@Year)
                +right('0'+convert(varchar(2),@month),2)
                +'01')

IF OBJECT_ID('tempdb.dbo.#Units', 'U') IS NOT NULL
DROP TABLE #Units

select distinct unit
into #Units
from ReportingMonthlySales;

select
    u.Unit
  , New      = sum(case when ccl.Subcategory = 'New'      then rms.MonthlySales else 0 end)
  , Assumed  = sum(case when ccl.Subcategory = 'Assumed'  then rms.MonthlySales else 0 end)
  , Existing = sum(case when ccl.Subcategory = 'Existing' then rms.MonthlySales else 0 end)
  , Organic  = sum(case when ccl.Subcategory = 'Organic'  then rms.MonthlySales else 0 end)
from #Units u
  left join CustomerCategoryLog ccl
    on u.Unit = ccl.Unit
   and @paramdate >= ccl.begindate and
   (@paramdate <= ccl.enddate OR ccl.enddate is null)
  left join ReportingMonthlySales rms
    on u.Unit = rms.Unit
   and rms.cyear  = @year
   and rms.cmonth = @month
group by u.unit;

The two tables queried are:

CustomerCategoryLog
-------------------
MemberNo (VarChar)
Unit (VarChar)
Custno (VarChar)
Category (VarChar)
Subcategory (VarChar)
BeginDate (DateTime)
EndDate (DateTime)
ChangedBy (VarChar)
ChangedOn (DateTime)

ReportingMonthlySales
---------------------
AutoID (Int)
Unit (VarChar)
MemberNo (VarChar)
NumUnits (Int)
MonthlySales (Money)
CYear (Int)
Cmonth (Int)
CreateDate (DateTime)

Is there something faulty in the fancy-pants sql, or ... ?!?

Body:
i think this is causing the duplication

select distinct unit
into #Units
from ReportingMonthlySales;

you basically inserted the same data from the table and used at the left join..

try this updated script

  SELECT
  rms.Unit,
  New = SUM(CASE
    WHEN ccl.Subcategory = 'New' THEN rms.MonthlySales
    ELSE 0
  END),
  Assumed = SUM(CASE
    WHEN ccl.Subcategory = 'Assumed' THEN rms.MonthlySales
    ELSE 0
  END),
  Existing = SUM(CASE
    WHEN ccl.Subcategory = 'Existing' THEN rms.MonthlySales
    ELSE 0
  END),
  Organic = SUM(CASE
    WHEN ccl.Subcategory = 'Organic' THEN rms.MonthlySales
    ELSE 0
  END)
FROM ReportingMonthlySales rms
inner JOIN CustomerCategoryLog ccl
  ON rms.Unit = ccl.Unit
where
  AND @paramdate >= ccl.begindate
  AND (@paramdate <= isnull(ccl.enddate,getdate())
  )
 AND
   rms.cyear = @year
  AND rms.cmonth = @month
GROUP BY rms.unit;


问:
Pylons: preserve ordering in request.params?
I have a question about Pylons's request.params, which returns a MultiDict object.

Does request.params preserve the ordering of the GET parameters in a reliable way?

For example, if I were to visit http://localhost:5000/hello/index?a=1&a=2 and call request.params, could I guarantee that the MultiDict object returned would be in the following order?

```<code>>>> request.params
MultiDict([('a', '1'), ('a', '2')])
</code>```

I'm guessing not, because Python seems to have a separate OrderedMultiDict object used for, well, ordered MultiDicts.

If not, is there any other way I can obtain the GET parameters and preserve their ordering in Pylons?

答:
As I remember, even if you can get Pylons to preserve the ordering, you're not supposed to rely on that kind of behavior because not all user agents (browsers, bots, etc.) preserve ordering either and that's outside your control.

If it's part of the HTTP spec, it's not reliably followed... I doubt it is.

For example, suppose the user agent is a Python application which handles query parameters using dicts.

ContentLicense: CC BY-SA 2.5

Body:
I have a question about Pylons's request.params, which returns a MultiDict object.

Does request.params preserve the ordering of the GET parameters in a reliable way?

For example, if I were to visit http://localhost:5000/hello/index?a=1&a=2 and call request.params, could I guarantee that the MultiDict object returned would be in the following order?

>>> request.params
MultiDict([('a', '1'), ('a', '2')])

I'm guessing not, because Python seems to have a separate OrderedMultiDict object used for, well, ordered MultiDicts.

If not, is there any other way I can obtain the GET parameters and preserve their ordering in Pylons?


问:
Better way than try-catch to pass failure messages back to Web API caller?
I've got many Web API calls that delegate to methods in data-layer classes that call my ORM (Entity Framework) and look like this:

```<code>public OperationResult DeleteThing(Guid id)
{
    var result = new OperationResult() { Success = true };
    using (var context = this.GetContext())
    {
        try
        {
            context.Things.Where(x => x.Id == id).Delete();
            context.SaveChanges();
        }
        catch (Exception ex)
        {
            Logger.Instance.LogException(ex);
            result.AddError("There was a database error deleting the thing. Check log for details.");
        }

    return result;
}
</code>```

(You may recognize the return value as similar to the Notification pattern.)

So I have many of the same try-catch blocks and it smells bad to me.  I'd like to get rid of them all and use a global exception handler to log errors instead, but in addition to logging, I also need to pass a message back to the consumer, specific to each different service method, so that the consumer can perhaps pass the message as the results of the service call appropriately.  Web service consumers, e.g. our web site, ultimately can display the message generated here to clue the user in to the nature of the error.

Can anyone suggest a better way? My instinct is to go through and replace with catches of specific exception types, but that seems like a lot of work for zero practical benefit and a harm to my code maintainability.

答:
Similar to Stuart's answer, you can also use a Filter attribute inherited from ExceptionFilterAttribute to modify the response based on any input you require.

Here's a full working example that accomplishes:

Custom message for exception type

Modifying the operation result

Fall through generic message for all exception types

ValuesController.cs

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Filters;
using Demo.Models;

namespace Demo.Controllers
{
    public class ValuesController : ApiController
    {

        // DELETE api/values/5

        [OperationError("The operation failed to delete the entity")]
        public OperationResult Delete(int id)
        {
            throw new ArgumentException("ID is bad", nameof(id));
        }

        // DELETE api/values/5?specific=[true|false]

        [OperationError("The operation tried to divide by zero", typeof(DivideByZeroException))]
        [OperationError("The operation failed for no specific reason")]
        public OperationResult DeleteSpecific(int id, bool specific)
        {
            if (specific)
            {
                throw new DivideByZeroException("DBZ");
            }
            else
            {
                throw new ArgumentException("ID is bad", nameof(id));
            }
        }
    }

    public class OperationErrorAttribute : ExceptionFilterAttribute
    {
        public Type ExceptionType { get; }
        public string ErrorMessage { get; }

        public OperationErrorAttribute(string errorMessage)
        {
            ErrorMessage = errorMessage;
        }

        public OperationErrorAttribute(string errorMessage, Type exceptionType)
        {
            ErrorMessage = errorMessage;
            ExceptionType = exceptionType;
        }

        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            // Exit early for non OperationResult action results
            if (actionExecutedContext.ActionContext.ActionDescriptor.ReturnType != typeof(OperationResult))
            {
                base.OnException(actionExecutedContext);
                return;
            }

            OperationResult result = new OperationResult() {Success = false};

            // Add error for specific exception types
            Type exceptionType = actionExecutedContext.Exception.GetType();

            if (ExceptionType != null)
            {
                if (exceptionType == ExceptionType)
                {
                    result.AddError(ErrorMessage);
                }
                else
                {
                    // Fall through
                    base.OnException(actionExecutedContext);
                    return;
                }
            }
            else if (ErrorMessage != null)
            {
                result.AddError(ErrorMessage);
            }

            // TODO: Log exception, generate correlation ID, etc.

            // Set new result
            actionExecutedContext.Response =
                actionExecutedContext.Request.CreateResponse(HttpStatusCode.InternalServerError, result);

            base.OnException(actionExecutedContext);
        }
    }
}
</code>```

Specific exception:

Generic exception:

Body:
I've got many Web API calls that delegate to methods in data-layer classes that call my ORM (Entity Framework) and look like this:

public OperationResult DeleteThing(Guid id)
{
    var result = new OperationResult() { Success = true };
    using (var context = this.GetContext())
    {
        try
        {
            context.Things.Where(x => x.Id == id).Delete();
            context.SaveChanges();
        }
        catch (Exception ex)
        {
            Logger.Instance.LogException(ex);
            result.AddError("There was a database error deleting the thing. Check log for details.");
        }

    return result;
}

(You may recognize the return value as similar to the Notification pattern.)

So I have many of the same try-catch blocks and it smells bad to me.  I'd like to get rid of them all and use a global exception handler to log errors instead, but in addition to logging, I also need to pass a message back to the consumer, specific to each different service method, so that the consumer can perhaps pass the message as the results of the service call appropriately.  Web service consumers, e.g. our web site, ultimately can display the message generated here to clue the user in to the nature of the error.

Can anyone suggest a better way? My instinct is to go through and replace with catches of specific exception types, but that seems like a lot of work for zero practical benefit and a harm to my code maintainability.

Body:
Similar to Stuart's answer, you can also use a Filter attribute inherited from ExceptionFilterAttribute to modify the response based on any input you require.

Here's a full working example that accomplishes:

Custom message for exception type

Modifying the operation result

Fall through generic message for all exception types

ValuesController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Filters;
using Demo.Models;

namespace Demo.Controllers
{
    public class ValuesController : ApiController
    {

        // DELETE api/values/5

        [OperationError("The operation failed to delete the entity")]
        public OperationResult Delete(int id)
        {
            throw new ArgumentException("ID is bad", nameof(id));
        }

        // DELETE api/values/5?specific=[true|false]

        [OperationError("The operation tried to divide by zero", typeof(DivideByZeroException))]
        [OperationError("The operation failed for no specific reason")]
        public OperationResult DeleteSpecific(int id, bool specific)
        {
            if (specific)
            {
                throw new DivideByZeroException("DBZ");
            }
            else
            {
                throw new ArgumentException("ID is bad", nameof(id));
            }
        }
    }

    public class OperationErrorAttribute : ExceptionFilterAttribute
    {
        public Type ExceptionType { get; }
        public string ErrorMessage { get; }

        public OperationErrorAttribute(string errorMessage)
        {
            ErrorMessage = errorMessage;
        }

        public OperationErrorAttribute(string errorMessage, Type exceptionType)
        {
            ErrorMessage = errorMessage;
            ExceptionType = exceptionType;
        }

        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            // Exit early for non OperationResult action results
            if (actionExecutedContext.ActionContext.ActionDescriptor.ReturnType != typeof(OperationResult))
            {
                base.OnException(actionExecutedContext);
                return;
            }

            OperationResult result = new OperationResult() {Success = false};

            // Add error for specific exception types
            Type exceptionType = actionExecutedContext.Exception.GetType();

            if (ExceptionType != null)
            {
                if (exceptionType == ExceptionType)
                {
                    result.AddError(ErrorMessage);
                }
                else
                {
                    // Fall through
                    base.OnException(actionExecutedContext);
                    return;
                }
            }
            else if (ErrorMessage != null)
            {
                result.AddError(ErrorMessage);
            }

            // TODO: Log exception, generate correlation ID, etc.

            // Set new result
            actionExecutedContext.Response =
                actionExecutedContext.Request.CreateResponse(HttpStatusCode.InternalServerError, result);

            base.OnException(actionExecutedContext);
        }
    }
}

Specific exception:

Generic exception:


问:
Parse Cloud JS Script - Error Code: 141
I've written up a Parse Cloud script in JS which gets called in my Objective-C app. When the script gets called I get an error with the code: 141.
Here is the code, it gets called when a user accepts a friend request from another user (I'm also not entirely familiar with JS either):

```<code>Parse.Cloud.define("addFriendToFriendsRelation", function(request, response) {

Parse.Cloud.useMasterKey();

var friendRequestId = request.params.friendRequest;
var query = new Parse.Query("FriendRequest");

//get the friend request object
query.get(friendRequestId, {

    success: function(friendRequest) {

        //get the user the request was from
        var fromUser = friendRequest.get("from");
        //get the user the request is to
        var toUser = friendRequest.get("to");

        var relation = fromUser.relation("friends");
        //add the user the request was to (the accepting user) to the fromUsers friends
        relation.add(toUser);

        //save the fromUser
        fromUser.save(null, {

            success: function() {

                //saved the user, now edit the request status and save it
                friendRequest.set("status", "accepted");
                friendRequest.save(null, {

                    success: function() {

                        response.success("saved relation and updated friendRequest");
                    },

                    error: function(error) {

                        response.error(error);
                    }

                });

            },

            error: function(error) {

             response.error(error);

            }

        });

    },

    error: function(error) {

        response.error(error);

    }

});

});
</code>```

All help and suggestions are greatly appreciated. Thank you.

EDIT: In my code I am calling:

```<code>[PFCloud callFunctionInBackground:@"addFriendToFriendsRelation" withParameters:@{@"friendRequest" : friendRequest.objectId} block:^(id object, NSError *error) {
</code>```

EDIT2: The error I am getting in the JS script is the last

```<code>        error: function(error) {

        response.error(error);

    }
</code>```

to be called.

答:
This will solve your problem , all you have to do is

add

```<code>useMasterKey: true
</code>```

in the find method.
change your code to this

```<code>Parse.Cloud.define("addFriendToFriendsRelation", function(request, response) {

Parse.Cloud.useMasterKey();

var friendRequestId = request.params.friendRequest;
var query = new Parse.Query("FriendRequest");

//get the friend request object
query.get(friendRequestId, {

   useMasterKey: true, success: function(friendRequest) {

        //get the user the request was from
        var fromUser = friendRequest.get("from");
        //get the user the request is to
        var toUser = friendRequest.get("to");

        var relation = fromUser.relation("friends");
        //add the user the request was to (the accepting user) to the fromUsers friends
        relation.add(toUser);

        //save the fromUser
        fromUser.save(null, {

            success: function() {

                //saved the user, now edit the request status and save it
                friendRequest.set("status", "accepted");
                friendRequest.save(null, {

                    success: function() {

                        response.success("saved relation and updated friendRequest");
                    },

                    error: function(error) {

                        response.error(error);
                    }

                });

            },

            error: function(error) {

             response.error(error);

            }

        });

    },

    error: function(error) {

        response.error(error);

    }

});

});
</code>```

Title: Parse Cloud JS Script - Error Code: 141

Body:
I've written up a Parse Cloud script in JS which gets called in my Objective-C app. When the script gets called I get an error with the code: 141.
Here is the code, it gets called when a user accepts a friend request from another user (I'm also not entirely familiar with JS either):

Parse.Cloud.define("addFriendToFriendsRelation", function(request, response) {

Parse.Cloud.useMasterKey();

var friendRequestId = request.params.friendRequest;
var query = new Parse.Query("FriendRequest");

//get the friend request object
query.get(friendRequestId, {

    success: function(friendRequest) {

        //get the user the request was from
        var fromUser = friendRequest.get("from");
        //get the user the request is to
        var toUser = friendRequest.get("to");

        var relation = fromUser.relation("friends");
        //add the user the request was to (the accepting user) to the fromUsers friends
        relation.add(toUser);

        //save the fromUser
        fromUser.save(null, {

            success: function() {

                //saved the user, now edit the request status and save it
                friendRequest.set("status", "accepted");
                friendRequest.save(null, {

                    success: function() {

                        response.success("saved relation and updated friendRequest");
                    },

                    error: function(error) {

                        response.error(error);
                    }

                });

            },

            error: function(error) {

             response.error(error);

            }

        });

    },

    error: function(error) {

        response.error(error);

    }

});

});

All help and suggestions are greatly appreciated. Thank you.

EDIT: In my code I am calling:

[PFCloud callFunctionInBackground:@"addFriendToFriendsRelation" withParameters:@{@"friendRequest" : friendRequest.objectId} block:^(id object, NSError *error) {

EDIT2: The error I am getting in the JS script is the last

        error: function(error) {

        response.error(error);

    }

to be called.

Body:
This will solve your problem , all you have to do is

add

useMasterKey: true

in the find method.
change your code to this

Parse.Cloud.define("addFriendToFriendsRelation", function(request, response) {

Parse.Cloud.useMasterKey();

var friendRequestId = request.params.friendRequest;
var query = new Parse.Query("FriendRequest");

//get the friend request object
query.get(friendRequestId, {

   useMasterKey: true, success: function(friendRequest) {

        //get the user the request was from
        var fromUser = friendRequest.get("from");
        //get the user the request is to
        var toUser = friendRequest.get("to");

        var relation = fromUser.relation("friends");
        //add the user the request was to (the accepting user) to the fromUsers friends
        relation.add(toUser);

        //save the fromUser
        fromUser.save(null, {

            success: function() {

                //saved the user, now edit the request status and save it
                friendRequest.set("status", "accepted");
                friendRequest.save(null, {

                    success: function() {

                        response.success("saved relation and updated friendRequest");
                    },

                    error: function(error) {

                        response.error(error);
                    }

                });

            },

            error: function(error) {

             response.error(error);

            }

        });

    },

    error: function(error) {

        response.error(error);

    }

});

});


问:
Creating a simple menu using while loop in c++
I'm trying to create a simple program in c++ to calculate the mean, sum, max and min value out of 10 numbers. I want to allow the user to click 4 to stop the program. This is the part of my code I need help with:</p>

```<code>void printOut(int max, int min, int avr)
{
    int run = true;
    short choice;

    while(run == true)
        {
    cout<<endl<<"1 = mean "<<endl;
    cout<<"2 = max/min "<<endl;
    cout<<"3 = sum "<<endl;
    cout<<"4 = quit "<<endl;
    cin >> choice;

    if (choice == 1)
    {
        cout<<endl<<"Mean = "<<avr<<endl;

    }
    else if (choice == 2)
    {
        cout<<endl<<"Max = "<<max<<endl<<"Min = "<<min<<endl;
    }
     else if (choice == 3)
    {
        cout<<endl<<"Sum = "<<sum<<endl;
    }
    else if (choice == 4)
    {
        run == false;
    }
    else
    {
        cout << "Error";
    }
        }
}
</code>```

答:
There is a pretty simple and clear way to cope with your problem. Just
set infinite while loop and make exit condition, or set this condition directly in the while statement. I used the last approach in this code snippet.

Also, I highly recommend you use a switch-case system to control your input. It would make your code more readable.

Finally, your code should look like this:

```<code>short choice;

while(choice != 4)
{
    ...
    cin >> choice;
    ...
    switch(choice)
    {
        ...
        case 4:
            cout << "Exit";
        ...
    }
}
</code>```

Body:
I'm trying to create a simple program in c++ to calculate the mean, sum, max and min value out of 10 numbers. I want to allow the user to click 4 to stop the program. This is the part of my code I need help with:

void printOut(int max, int min, int avr)
{
    int run = true;
    short choice;

    while(run == true)
        {
    cout<<endl<<"1 = mean "<<endl;
    cout<<"2 = max/min "<<endl;
    cout<<"3 = sum "<<endl;
    cout<<"4 = quit "<<endl;
    cin >> choice;

    if (choice == 1)
    {
        cout<<endl<<"Mean = "<<avr<<endl;

    }
    else if (choice == 2)
    {
        cout<<endl<<"Max = "<<max<<endl<<"Min = "<<min<<endl;
    }
     else if (choice == 3)
    {
        cout<<endl<<"Sum = "<<sum<<endl;
    }
    else if (choice == 4)
    {
        run == false;
    }
    else
    {
        cout << "Error";
    }
        }
}

Body:
There is a pretty simple and clear way to cope with your problem. Just
set infinite while loop and make exit condition, or set this condition directly in the while statement. I used the last approach in this code snippet.

Also, I highly recommend you use a switch-case system to control your input. It would make your code more readable.

Finally, your code should look like this:

short choice;

while(choice != 4)
{
    ...
    cin >> choice;
    ...
    switch(choice)
    {
        ...
        case 4:
            cout << "Exit";
        ...
    }
}


问:
SQL Server: Apply different multipliers by date
I have a table that records sales and I want a report on how much tax was paid on each item. The basic rule is all sales before April 1st had a .52% tax, all sales after that date will have a 0.5% tax.

I'm trying to get this using the following query

```<code>select ItemCode,
    sum(Quantity) QuantitySold,
    WhsCode as Store,
    case when (docdate < '20170401') then sum(Quantity * .0052) else sum(Quantity * .005) end as Tax
from SalesTable
group by whscode,
    itemcode
</code>```

However I get a

DocDate' is invalid in the select list because it is not contained in
  either an aggregate function or the GROUP BY clause.

error if I run it as is. Adding DocDate to the group by clause creates a mess of duplicates (On one example I went from 185 rows to 1508 rows).

Does SQL simply not allow you to use WHEN statements whose conditional is not included in the Group clause or should I be using something else?

答:
Error is because you are using docdate directly without adding it to the group by clause.

I think this is what you want:

```<code>select ItemCode,
    sum(Quantity) QuantitySold,
    WhsCode as Store,
    sum(price * case when docdate < '20170401' then 0.0052 else 0.005 end) as Tax
from SalesTable
group by whscode,
    itemcode
</code>```

Body:
I have a table that records sales and I want a report on how much tax was paid on each item. The basic rule is all sales before April 1st had a .52% tax, all sales after that date will have a 0.5% tax.

I'm trying to get this using the following query

select ItemCode,
    sum(Quantity) QuantitySold,
    WhsCode as Store,
    case when (docdate < '20170401') then sum(Quantity * .0052) else sum(Quantity * .005) end as Tax
from SalesTable
group by whscode,
    itemcode

However I get a

DocDate' is invalid in the select list because it is not contained in
  either an aggregate function or the GROUP BY clause.

error if I run it as is. Adding DocDate to the group by clause creates a mess of duplicates (On one example I went from 185 rows to 1508 rows).

Does SQL simply not allow you to use WHEN statements whose conditional is not included in the Group clause or should I be using something else?

Body:
Error is because you are using docdate directly without adding it to the group by clause.

I think this is what you want:

select ItemCode,
    sum(Quantity) QuantitySold,
    WhsCode as Store,
    sum(price * case when docdate < '20170401' then 0.0052 else 0.005 end) as Tax
from SalesTable
group by whscode,
    itemcode


问:
Best practice for Invoice Prefix in MySQL?
I'm designing a schema for invoicing and I'm trying to decide on the best practice for carrying out the following requirements. There are multiple companies which have multiple branches. Each branch will want its own auto-increment number independent of the other branches (and companies). On top of that, there are different classes of invoices. I have set up the following table structure

tbl_invoices

|company_id|branch_id|class_id|invoice_id|...other invoice data columns...|

tbl_branches

|branch_id|branch_prefix|

tbl_classes

|class_id|class_prefix|

I am strongly favouring INNODB because of FKs and transactions. However, I have a problem with auto-increment (MyISAM would auto-increment multiple column primary keys easily). Another issue I have is having to join multiple tables all the time when I pull the invoice data because I need the full invoice_id that concats the different prefixes. I've also ran into the issue of what happens when the prefix strings change in the future. It's probably unwarranted for the past issued invoices to also have their prefixes change. I'm thinking I should add an additional prefix column for tbl_invoices which will store the full concat prefix on insert. I'm not too sure if this is the right practice? I've considered storing the entire invoice_id in full concat form in the column but I wouldn't be able to enforce uniqueness for INV-0001 from INV-00001.

This would still mean I have difficulty with the auto-increment.

答:
If you have low insertion volume and are willing to tolerate a little friction you can set a UNIQUE index on your invoice numbers. If they're formatted properly, that is they will sort correctly because they're of form INV-00001 instead of INV-1, INV-2, etc. then you can do this:

```<code>SELECT MAX(ident) FROM invoices WHERE ident LIKE 'INV-%'
</code>```

Then try and insert with that incremented by one. This is an optimistic approach, that is you're expecting it will probably work, and if not, you'll get an error about an index conflict and you can increment and try again until it succeeds.

A pessimistic approach, where you're expecting it to fail, involves transactions and an increment table where you track the increments for each prefix. You'll need to do some quick locking here to avoid creating a lot of contention. This system is a lot more complicated to get working flawlessly, and if done incorrectly can lead to ugly lock problems.

I'd go with the optimistic approach until you have a specific reason why it won't work.

Body:
If you have low insertion volume and are willing to tolerate a little friction you can set a UNIQUE index on your invoice numbers. If they're formatted properly, that is they will sort correctly because they're of form INV-00001 instead of INV-1, INV-2, etc. then you can do this:

SELECT MAX(ident) FROM invoices WHERE ident LIKE 'INV-%'

Then try and insert with that incremented by one. This is an optimistic approach, that is you're expecting it will probably work, and if not, you'll get an error about an index conflict and you can increment and try again until it succeeds.

A pessimistic approach, where you're expecting it to fail, involves transactions and an increment table where you track the increments for each prefix. You'll need to do some quick locking here to avoid creating a lot of contention. This system is a lot more complicated to get working flawlessly, and if done incorrectly can lead to ugly lock problems.

I'd go with the optimistic approach until you have a specific reason why it won't work.


问:
Pinterest : data-pinmedia does not override source
I'm using Pinterest for my web site here : http://www.encadrement-art.com/galerie.htm

My source image is a thumb image, so the "pin it" button does not show any image in this page.

But when I use the data-pin-media attribute (for the first image in this page), the "pin it" button does not show the image yet.

What is the problem ?

答:
Thank you for your help .... but it does not works ... :(

The minimum size of my src image must be 200X200px ... al my thunmbnail are in 150x150px :(


问:
Profile model for Devise users?
I want to extend the sign up form of my devise installation. I created a Profile model and am asking myself now, how can I add specific data of the form to this model. Where is the UserController of devise located?

Thanks in advance!

答:
It's not very clear from your question, but I'm assuming your Devise model is User and you created another model Profile that belongs to user.

You'll need to create a controller for your User model with rails g controller users.

You'll also need to generate the views for your users with rails generate devise:views
 so that the user can add profile info when he's creating his account.

From there, it's just like any other model: create a user and profile instance and link the two. Then, in controllers, use current_user.profile to access the current user's profile.

Note that if you're going to manage users this way, you'll need to remove the :registerable module from the User model (also read https://github.com/plataformatec/devise/wiki/How-To:-Manage-users-through-a-CRUD-interface)

ContentLicense: CC BY-SA 4.0

Title: Profile model for Devise users?


问:
How to connect mySQL database using C++
I'm trying to connect the database from my website and display some rows using C++.
So bascily I'm trying to make an application that does a select query from a table from my site database. Now, this must be possible because I've seen tons of applications doing it.

How do I do this? Can some one make an example and tell me what libraries I should be using?

答: I had to include -lmysqlcppconn to my build in order to get it to work.</p>

Title: How to connect mySQL database using C++


问:
Azure AD application adding a key via Powershell
I'm trying to add a key in my Azure AD application using PowerShell.  Unfortunately i was try first with Azure CLI, but after some research and some stackoverflow answers I figure out, that this cannot be done.

I'm trying to automate the task from the link below via Powershell: http://blog.davidebbo.com/2014/12/azure-service-principal.html

I'm also following these steps:
https://blogs.technet.microsoft.com/kv/2015/06/02/azure-key-vault-step-by-step/

Is there any way to create/retrieve the following things in Powershell:

VaultUrl,
AuthClientId,
AuthClientSecret.

答:
This can be done using either the method New-AzureRmADApplication (to include it when you create the application), but apparently not with Set-AzureRmADApplication (i.e. to set it after creating the app; I'm not sure there is a way to do that via powershell).  But it's not clear how to set this just from knowing the methods.  This site led me to the answer: https://sabin.io/blog/adding-an-azure-active-directory-application-and-key-using-powershell/.

The gist is that you have to provide what those methods refer to as PasswordCredentials, though the Azure portal seems to call them keys, and some powershell commands, like SqlAzureAuthenticationContext call the value you are setting the Secret (all of which are confusing terms).  Here's how I did it to create with the credential:

```<code># Be sure to note $KeyValue! It can't be retrieved.
# It's the "Secret" you can pass to methods like Add-SqlAzureAuthenticationContext in order to authenticate.
$KeyValue = [guid]::NewGuid()
Write-Output "The password you've set is $KeyValue"

$psadCredential = New-Object Microsoft.Azure.Commands.Resources.Models.ActiveDirectory.PSADPasswordCredential
$startDate = Get-Date
$psadCredential.StartDate = $startDate
$psadCredential.EndDate = $startDate.AddYears(1)
$psadCredential.KeyId = [guid]::NewGuid()
$psadCredential.Password = $KeyValue

$adApplication = New-AzureRmADApplication –DisplayName “MyNewApp”`
-HomePage "http://MyNewApp"`
-IdentifierUris "http://MyNewApp"`
-PasswordCredentials $psadCredential
</code>```

Body:
This can be done using either the method New-AzureRmADApplication (to include it when you create the application), but apparently not with Set-AzureRmADApplication (i.e. to set it after creating the app; I'm not sure there is a way to do that via powershell).  But it's not clear how to set this just from knowing the methods.  This site led me to the answer: https://sabin.io/blog/adding-an-azure-active-directory-application-and-key-using-powershell/.

The gist is that you have to provide what those methods refer to as PasswordCredentials, though the Azure portal seems to call them keys, and some powershell commands, like SqlAzureAuthenticationContext call the value you are setting the Secret (all of which are confusing terms).  Here's how I did it to create with the credential:

# Be sure to note $KeyValue! It can't be retrieved.
# It's the "Secret" you can pass to methods like Add-SqlAzureAuthenticationContext in order to authenticate.
$KeyValue = [guid]::NewGuid()
Write-Output "The password you've set is $KeyValue"

$psadCredential = New-Object Microsoft.Azure.Commands.Resources.Models.ActiveDirectory.PSADPasswordCredential
$startDate = Get-Date
$psadCredential.StartDate = $startDate
$psadCredential.EndDate = $startDate.AddYears(1)
$psadCredential.KeyId = [guid]::NewGuid()
$psadCredential.Password = $KeyValue

$adApplication = New-AzureRmADApplication –DisplayName “MyNewApp”`
-HomePage "http://MyNewApp"`
-IdentifierUris "http://MyNewApp"`
-PasswordCredentials $psadCredential


问:
splitting bash string by delimiter (last line with delimiter) into array
I'm having a hard time splitting a string like this:

```<code>444,555,text with, separator
</code>```

into this:

```<code>444
555
text with, separator
</code>```

i.e. into a 3-element array (last element may contain comma)

I tried sed but I end up having 4 elements due to the last comma.

Any ideas?

Thanks,

Body:
I'm having a hard time splitting a string like this:

444,555,text with, separator

into this:

444
555
text with, separator

i.e. into a 3-element array (last element may contain comma)

I tried sed but I end up having 4 elements due to the last comma.

Any ideas?

Thanks,

Body:
echo "444,555,text with, separator" | sed  "s/\([0-9]*\),\([0-9]*\),\(.*\)/\1\n\2\n\3/"

Output:

444
555
text with, separator


问:
Why won't IntelliJ use tabs?
As per How can I use tabs for indentation in IntelliJ IDEA?, I have gone through and set each extension to "Use tab character" as seen below.

It doesn't work though - IntelliJ is still inserting spaces when I hit the tab button.  Did I miss something?  Where is intelliJ's [Please use tabs like I ef'ing told you to do] button?

(FYI, I'm using IntelliJ Ultimate 2016.2)

This looks promising...

... but apparently it's all lies :(

答:
If you open up the .editorconfig file, you will see something akin to the following

```<code># editorconfig.org
root = true

[*]
indent_style = spaces
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
</code>```

I changed it to tab and 4, closed the project and reopened it.

I know this is an absurd step to have to take, and have an open bug report with them about it.

Title: Why won't IntelliJ use tabs?

Body:
If you open up the .editorconfig file, you will see something akin to the following

# editorconfig.org
root = true

[*]
indent_style = spaces
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

I changed it to tab and 4, closed the project and reopened it.

I know this is an absurd step to have to take, and have an open bug report with them about it.


问:
Docker communication between two containers with Java
There are two java files, Server.java and Client.java.
Both are in separate containers.

DOCKER FILES:
The dockerfile(in the folder named 'Server') that i use for server is:

```<code>FROM java:8
COPY Server.java /
RUN javac Server.java
EXPOSE 25000
ENTRYPOINT ["java"]
CMD ["Server"]
</code>```

The dockerfile(in the folder named 'Client') for client is:

```<code>FROM java:8
COPY Client.java /
RUN javac Client.java
EXPOSE 25000
ENTRYPOINT ["java"]
CMD ["Client"]
</code>```

BUILDING THE CONTAINERS:
Building the containers using sudo docker build -t serverimage .

RUNNING THE CONTAINERS:
I run the images using the command sudo docker run <IMAGE_NAME>.And I am running the serverimage first.

The error i am getting(When i run clientimage) is:

```<code>java.net.ConnectException: Connection refused: connect
</code>```

Server.java File:

```<code>import java.io.*;
import java.net.*;
public class MyServer {
   public static void main(String[] args){
       try{
           ServerSocket ss=new ServerSocket(25000);
           Socket s=ss.accept();//establishes connection
           DataInputStream dis=new DataInputStream(s.getInputStream());
           String  str=(String)dis.readUTF();
           System.out.println("message= "+str);
           ss.close();
       }catch(Exception e){System.out.println(e);}
   }
}
</code>```

Client.java File:

```<code>import java.io.*;
import java.net.*;
public class MyClient {
   public static void main(String[] args) {
      try{
         Socket s=new Socket("localhost",25000);
         DataOutputStream dout=new DataOutputStream(s.getOutputStream());
         dout.writeUTF("Hello Server");
         dout.flush();
         dout.close();
         s.close();
      }catch(Exception e){System.out.println(e);}
   }
}
</code>```

What am I possibly doing wrong?
Thank you!

答:
For modern docker versions (1.13+)

To understand where this approach goes wrong, the docker networking guide has all of the intricate details, but it largely boils down to the fact that you can't simply reference localhost in one container and expect it to route to another container running on your host.

By default each container runs on a bridge network, and each container effectively appears as a separate host on that bridge network, in the same subnet. The containers can reference other containers via their assigned IP address on the bridge network, but localhost simply refers to the container itself, rather than the underlying host that's running the container.

To achieve predictable routing similar to what you're after, you can define your own bridge network and run the client and server containers on that user-defined network. This does require one small code change in your Client.java. Instead of localhost, you have to address the server with a chosen alias, say server. Once you've edited the client code and rebuilt clientimage, try the following:

Create the network - sudo docker network create client_server_network

Run the server - sudo docker run --network-alias server --network client_server_network -it serverimage

Run the client - sudo docker run --network client_server_network -it clientimage

You should see message= Hello Server print in the server terminal

Note that I provided an additional --network-alias server to the server's docker run, to add a network alias where the client can predictably reach the server container. You have multiple ways of achieving that aliasing, including using the --name option, but check out the docker embedded dns docs for more details.

For older docker versions (1.12-)

Docker provides a container linking functionality, exposed via the --link option supplied to docker run. You'll need some of the same updates as above, notably using something like server in place of localhost, and running the server container with --name server. The docker run would look like:

Run the server - sudo docker run --name server -it serverimage

Run the client - sudo docker run --link server -it clientimage

You should see message= Hello Server print in the server terminal

Body:
There are two java files, Server.java and Client.java.
Both are in separate containers.

DOCKER FILES:
The dockerfile(in the folder named 'Server') that i use for server is:

FROM java:8
COPY Server.java /
RUN javac Server.java
EXPOSE 25000
ENTRYPOINT ["java"]
CMD ["Server"]

The dockerfile(in the folder named 'Client') for client is:

FROM java:8
COPY Client.java /
RUN javac Client.java
EXPOSE 25000
ENTRYPOINT ["java"]
CMD ["Client"]

BUILDING THE CONTAINERS:
Building the containers using sudo docker build -t serverimage .

RUNNING THE CONTAINERS:
I run the images using the command sudo docker run <IMAGE_NAME>.And I am running the serverimage first.

The error i am getting(When i run clientimage) is:

java.net.ConnectException: Connection refused: connect

Server.java File:

import java.io.*;
import java.net.*;
public class MyServer {
   public static void main(String[] args){
       try{
           ServerSocket ss=new ServerSocket(25000);
           Socket s=ss.accept();//establishes connection
           DataInputStream dis=new DataInputStream(s.getInputStream());
           String  str=(String)dis.readUTF();
           System.out.println("message= "+str);
           ss.close();
       }catch(Exception e){System.out.println(e);}
   }
}

Client.java File:

import java.io.*;
import java.net.*;
public class MyClient {
   public static void main(String[] args) {
      try{
         Socket s=new Socket("localhost",25000);
         DataOutputStream dout=new DataOutputStream(s.getOutputStream());
         dout.writeUTF("Hello Server");
         dout.flush();
         dout.close();
         s.close();
      }catch(Exception e){System.out.println(e);}
   }
}

What am I possibly doing wrong?
Thank you!


问:
No space between elements in a Thymeleaf each loop
With Thymeleaf when I do :

1

I get :

```<code><span>1</span>
<span>1</span>
<span>1</span>
...
</code>```

How can I have this :

111...

?

答:
It is processed with a new line due the next issue, to improve readability:

https://github.com/thymeleaf/thymeleaf/issues/113

At the moment, I don't think you could avoid the break line without patching it. So, if you want to have this behavior you could patch the class AbstractIterationAttrProcessor. How? Just create a class with the same name and package in your project, and copy the content of the original one:

Package: org.thymeleaf.processor.attr

Class Name = AbstractIterationAttrProcessor

Then change the conditional in line 133 to avoid the new line if it is an span element. It would be like next:

```<code>if (preserveWhitespace && index > 0 && !element.getOriginalName().equals("span")) {
      parentNode.insertBefore(element, new Text(whitespace));
}
</code>```

I've just added !element.getOriginalName().equals("span") to the condition.  With this patch your span will be processed as:

```<code> <span>1</span><span>1</span>
</code>```

I've opened an issue due your question:

https://github.com/thymeleaf/thymeleaf/issues/586

Body:
With Thymeleaf when I do :

1

I get :

1
1
1
...

How can I have this :

111...

?

Body:
It is processed with a new line due the next issue, to improve readability:

https://github.com/thymeleaf/thymeleaf/issues/113

At the moment, I don't think you could avoid the break line without patching it. So, if you want to have this behavior you could patch the class AbstractIterationAttrProcessor. How? Just create a class with the same name and package in your project, and copy the content of the original one:

Package: org.thymeleaf.processor.attr

Class Name = AbstractIterationAttrProcessor

Then change the conditional in line 133 to avoid the new line if it is an span element. It would be like next:

if (preserveWhitespace && index > 0 && !element.getOriginalName().equals("span")) {
      parentNode.insertBefore(element, new Text(whitespace));
}

I've just added !element.getOriginalName().equals("span") to the condition.  With this patch your span will be processed as:

 <span>1</span><span>1</span>

I've opened an issue due your question:

https://github.com/thymeleaf/thymeleaf/issues/586


问:
Android Studio - Failed to complete Gradle execution - getPid()
I just installed Android Studio, I installed the recommended packages from the SDK Manager, now I am trying to build a sample app. I got this error message:

```<code>Failed to complete Gradle execution:
Cause:
net.rubygrapefruit.platform.internal.jni.PosixProcessFunctions.getPid()
</code>```

Any ideas how to solve this?

答:
Personally, I have updated the version of the Gradle Wrapper to the latest.

Open the file gradle-wrapper.properties.

Change the url of distributionUrl.

Example:

```<code>distributionUrl=https\://services.gradle.org/distributions/gradle-3.2.1-bin.zip
</code>```

Refresh the Gragle project and you should be good to go.

Body:
I just installed Android Studio, I installed the recommended packages from the SDK Manager, now I am trying to build a sample app. I got this error message:

Failed to complete Gradle execution:
Cause:
net.rubygrapefruit.platform.internal.jni.PosixProcessFunctions.getPid()

Any ideas how to solve this?

Body:
Personally, I have updated the version of the Gradle Wrapper to the latest.

Open the file gradle-wrapper.properties.

Change the url of distributionUrl.

Example:

distributionUrl=https\://services.gradle.org/distributions/gradle-3.2.1-bin.zip

Refresh the Gragle project and you should be good to go.


问:
How to extract the numbers into a separate array from a string
Given this string

```<code>"In 2015, I want to know how much does iPhone 6+ cost?"
</code>```

how can I return [2015, 6]?

My first attempt at this was

```<code>numbers = str.tr("^0-9", '')
</code>```

but that produces 20156.

答:
You can use scan:

```<code>numbers = str.scan(/\d+/)
# => ["2015", "6"]
</code>```

Body:
Given this string

"In 2015, I want to know how much does iPhone 6+ cost?"

how can I return [2015, 6]?

My first attempt at this was

numbers = str.tr("^0-9", '')

but that produces 20156.

Body:
You can use scan:

numbers = str.scan(/\d+/)
# => ["2015", "6"]


问:
Following and unfollowing events
I've done Michael Hartl Ruby on Rails 5 tutorial and am now trying to apply the code to my own app.

What I'm trying to do is:

Follow/Unfollow an event

Display total count of users following this event

Users can see all the events that they are following

The current error appears when I try to render the conferences that current user is following.

The error that I get is:

```<code>ActionController::UrlGenerationError in Users#show
No route matches {:action=>"followers", :controller=>"conferences", :id=>nil} missing required keys: [:id]
</code>```

The line that causes the problem is:

```<code>  <a href="<%= followers_conference_path(@conference) %>">
</code>```

Now obviously their is something wrong in my routing and I assume the following problem states that conferences is missing a required id?

Does anyone know the solution to my problem? Which is getting allowing users to follow events and see what events they are following

USER CONTROLLER SHOW

```<code>  def show
    @user = User.find(params[:id])
    @microposts = @user.microposts.paginate(page: params[:page])
    @managments = @user.managments.paginate(page: params[:page])
    @conference = Conference.find(params[:id])
  end
</code>```

ROUTES.RB

```<code>Rails.application.routes.draw do

  root   'static_pages#home'

  get    '/help',    to: 'static_pages#help'
  get    '/about',   to: 'static_pages#about'
  get    '/contact', to: 'static_pages#contact'

  get    '/my_conference', to: 'my_conference#show'
  get    '/conferences', to: 'conferences#index'
  get    '/conferences_list', to: 'conferences#index_admin'

  get    '/my_employees', to: 'employees#index'

  get    '/signup',  to: 'users#new'

  get    '/login',   to: 'sessions#new'
  post   '/login',   to: 'sessions#create'
  delete '/logout',  to: 'sessions#destroy'

  get    '/login',   to: 'sessions#new'

  put 'activate/:id(.:format)', :to => 'users#activate', :as => :activate_user
  put 'deactivate/:id(.:format)', :to => 'users#deactivate', :as => :deactivate_user

  put 'activate_employee/:id(.:format)', :to => 'employees#activate', :as => :activate_employee
  put 'deactivate_employee/:id(.:format)', :to => 'employees#deactivate', :as => :deactivate_employee

  resources :users do
    member do
      get :following
    end
  end
  resources :conferences do
    member do
      get :followers
    end
  end
  resources :articles
  resources :users
  resources :employees
  resources :account_activations, only: [:edit]
  resources :activations, only: [:edit]
  resources :password_resets,     only: [:new, :create, :edit, :update]
  resources :microposts,          only: [:create, :destroy]
  resources :managments
  resources :conferences
  resources :relationships,       only: [:create, :destroy]

end
</code>```

CONFERENCES_CONTROLLER.RB

```<code>class ConferencesController < ApplicationController
  before_action :logged_in_user, only: [:create, :destroy]
  before_action :correct_user,   only: :destroy
  before_action :admin_user,     only: :destroy

    def index

      @conferences = Conference.paginate(page: params[:page])

      if params[:search]
        @conferences = Conference.search(params[:search]).order("created_at DESC").paginate(page: params[:page])
      else
        @conferences = Conference.all.order('created_at DESC').paginate(page: params[:page])
      end
    end

  def new
    @user = User.new
    @conference = Conference.new
  end

  def create

    @conference = current_user.conferences.build(conference_params)
    if @conference.save
      flash[:success] = "conference created!"
      redirect_to conferences_path
    else
      @feed_items = current_user.feed.paginate(page: params[:page])
      render 'new'
    end
  end

  def destroy
    @conference.destroy
    flash[:success] = "conference deleted"
    redirect_to request.referrer || root_url
  end

  def following
    @title = "Following"
    @conference  = Conference.find(params[:id])
    @conferences = @conference.following.paginate(page: params[:page])
    render 'show_follow'
  end

  def followers
    @title = "Followers"
    @user  = User.find(params[:id])
    @users = @user.followers.paginate(page: params[:page])
    render 'show_follow'
  end

  private

    def conference_params
      params.require(:conference).permit(:conference,:country , :month, :presence, :audience, :cost ,:picture)
    end

    # Confirms an admin user.
    def admin_user
      redirect_to(root_url) unless current_user.admin?
    end

    def correct_user
      @conference = current_user.conferences.find_by(id: params[:id])
      redirect_to root_url if @conference.nil?
    end

end
</code>```

答:
You don't want to use the user id to get the @conference object, I'm sure. Instead, you are probably generating a list of conferences the user is following. In that case, you'd use something like this

```<code><% @user.conferences.each do |conference| %>
  <a href="<%= followers_conference_path(conference) %>"><%= conference.name %></a>
<% end %>
</code>```

And, in Rails, you would usually use the link_to helper, and maybe include a count to show how many followers the conference has.

```<code><% @user.conferences.each do |conference| %>
  <%= link_to conference.name, followers_conference_path(conference) %>
  (<%= pluralize conference.users.count, 'follower' %>)
<% end %>
</code>```

Title: Following and unfollowing events

Body:
I've done Michael Hartl Ruby on Rails 5 tutorial and am now trying to apply the code to my own app.

What I'm trying to do is:

Follow/Unfollow an event

Display total count of users following this event

Users can see all the events that they are following

The current error appears when I try to render the conferences that current user is following.

The error that I get is:

ActionController::UrlGenerationError in Users#show
No route matches {:action=>"followers", :controller=>"conferences", :id=>nil} missing required keys: [:id]

The line that causes the problem is:

  <a href="<%= followers_conference_path(@conference) %>">

Now obviously their is something wrong in my routing and I assume the following problem states that conferences is missing a required id?

Does anyone know the solution to my problem? Which is getting allowing users to follow events and see what events they are following

USER CONTROLLER SHOW

  def show
    @user = User.find(params[:id])
    @microposts = @user.microposts.paginate(page: params[:page])
    @managments = @user.managments.paginate(page: params[:page])
    @conference = Conference.find(params[:id])
  end

ROUTES.RB

Rails.application.routes.draw do

  root   'static_pages#home'

  get    '/help',    to: 'static_pages#help'
  get    '/about',   to: 'static_pages#about'
  get    '/contact', to: 'static_pages#contact'

  get    '/my_conference', to: 'my_conference#show'
  get    '/conferences', to: 'conferences#index'
  get    '/conferences_list', to: 'conferences#index_admin'

  get    '/my_employees', to: 'employees#index'

  get    '/signup',  to: 'users#new'

  get    '/login',   to: 'sessions#new'
  post   '/login',   to: 'sessions#create'
  delete '/logout',  to: 'sessions#destroy'

  get    '/login',   to: 'sessions#new'

  put 'activate/:id(.:format)', :to => 'users#activate', :as => :activate_user
  put 'deactivate/:id(.:format)', :to => 'users#deactivate', :as => :deactivate_user

  put 'activate_employee/:id(.:format)', :to => 'employees#activate', :as => :activate_employee
  put 'deactivate_employee/:id(.:format)', :to => 'employees#deactivate', :as => :deactivate_employee

  resources :users do
    member do
      get :following
    end
  end
  resources :conferences do
    member do
      get :followers
    end
  end
  resources :articles
  resources :users
  resources :employees
  resources :account_activations, only: [:edit]
  resources :activations, only: [:edit]
  resources :password_resets,     only: [:new, :create, :edit, :update]
  resources :microposts,          only: [:create, :destroy]
  resources :managments
  resources :conferences
  resources :relationships,       only: [:create, :destroy]

end

CONFERENCES_CONTROLLER.RB

class ConferencesController < ApplicationController
  before_action :logged_in_user, only: [:create, :destroy]
  before_action :correct_user,   only: :destroy
  before_action :admin_user,     only: :destroy

    def index

      @conferences = Conference.paginate(page: params[:page])

      if params[:search]
        @conferences = Conference.search(params[:search]).order("created_at DESC").paginate(page: params[:page])
      else
        @conferences = Conference.all.order('created_at DESC').paginate(page: params[:page])
      end
    end

  def new
    @user = User.new
    @conference = Conference.new
  end

  def create

    @conference = current_user.conferences.build(conference_params)
    if @conference.save
      flash[:success] = "conference created!"
      redirect_to conferences_path
    else
      @feed_items = current_user.feed.paginate(page: params[:page])
      render 'new'
    end
  end

  def destroy
    @conference.destroy
    flash[:success] = "conference deleted"
    redirect_to request.referrer || root_url
  end

  def following
    @title = "Following"
    @conference  = Conference.find(params[:id])
    @conferences = @conference.following.paginate(page: params[:page])
    render 'show_follow'
  end

  def followers
    @title = "Followers"
    @user  = User.find(params[:id])
    @users = @user.followers.paginate(page: params[:page])
    render 'show_follow'
  end

  private

    def conference_params
      params.require(:conference).permit(:conference,:country , :month, :presence, :audience, :cost ,:picture)
    end

    # Confirms an admin user.
    def admin_user
      redirect_to(root_url) unless current_user.admin?
    end

    def correct_user
      @conference = current_user.conferences.find_by(id: params[:id])
      redirect_to root_url if @conference.nil?
    end

end

Body:
You don't want to use the user id to get the @conference object, I'm sure. Instead, you are probably generating a list of conferences the user is following. In that case, you'd use something like this

<% @user.conferences.each do |conference| %>
  <a href="<%= followers_conference_path(conference) %>"><%= conference.name %></a>
<% end %>

And, in Rails, you would usually use the link_to helper, and maybe include a count to show how many followers the conference has.

<% @user.conferences.each do |conference| %>
  <%= link_to conference.name, followers_conference_path(conference) %>
  (<%= pluralize conference.users.count, 'follower' %>)
<% end %>


问:
how to tell if oracle database is installed on pc
i work for a company as java developer, they gave me laptop that was previously used by another person, to test my java application i need to have oracle on laptop and create some sample database with sample data. when I got the laptop i found that there is oracle installed on it, but i don't know if this is only oracle client or full oracle installation (server + client)
please can you tell me how to figure out if there is only oracle client on laptop or full database installation, plus i need to know if there is some default username and password so that i can access the database and create schema and tables in it, so that i can test my java application.
i thinking to see DBA but i thought of dropping a question here first, maybe i can solve the problem by myself</p>

答:
You can check simply using command prompt. Open command prompt and type connect. Provide the username and password and press Enter. It will show "connected" if the database is in your system.

Username: system (default)

Password: (what you provided while installing)


问:
Entity Framework inheritance creating coresponding entity
I have an EF model where I logically have a "template" type and an "instance of the template type"

Basically my templates are like a work flow and the instances are those templates applied to an object. The association is that a template has zero to many instances, an instance is always based on a template. For example the template may be “send letter”   which gets applied to a customer to create an instance of the letter sent, which includes the date sent, the pdf of the letter etc.

The templates have a few subclasses/types which will always match an instance which also has a corresponding subclass.

The issue is how can I ensure that when I create an instance (which will have a reference to the template) that the instance is of the correct inherited type.

For example if the template is of type TemplateType2 (inherits from template)  and I add an instance to loan1 .. loan1.TemplateInstances.add(foo) … I want to ensure that foo is of type InstanceType2.

The way I am doing it now seems like such a hack.  I am storing the instance entity name as a scalar value in the template entity, and using reflection to create the correct type of the instance.

It works, but it is basically using the value of a property to do mapping, exposing the possibility of all sorts of errors if they do not match the name of the instance name, or worse if they enter the wrong entity name.

Any ideas or thoughts how to tackle this issue?

答:
I ended up solving this through a bit of a hack.
I used naming conventions and adding my own handler to the context savingchanges method
and then a bit of reflection.  Not the best solution but it works.

the main part...

```<code>   For Each entry As ObjectStateEntry In DirectCast(sender, ObjectContext).ObjectStateManager.GetObjectStateEntries(EntityState.Added)
            If Not entry.IsRelationship Then

[blah blah...snip]

ObjectName = Me.GetType.ToString
                    If ObjectName = "QSEntityFrameWork.TaskTemplate" Then
                        ObjectName = "QSEntityFrameWork.TaskInstance"
                    Else
                        ObjectName = ObjectName.Replace("Task", "Instance")
                    End If
                    oh = Activator.CreateInstance("QSEntityFrameWork", ObjectName)
                    Dim obj As Object = oh.Unwrap
                    obj.TaskTemplateID = Me.TaskTemplateID
                    obj.TaskStartDate = DateTime.Now
                    obj.ProcessInstanceID = ProcessIntanceID
                    Return obj
</code>```

Body:
I ended up solving this through a bit of a hack.
I used naming conventions and adding my own handler to the context savingchanges method
and then a bit of reflection.  Not the best solution but it works.

the main part...

   For Each entry As ObjectStateEntry In DirectCast(sender, ObjectContext).ObjectStateManager.GetObjectStateEntries(EntityState.Added)
            If Not entry.IsRelationship Then

[blah blah...snip]

ObjectName = Me.GetType.ToString
                    If ObjectName = "QSEntityFrameWork.TaskTemplate" Then
                        ObjectName = "QSEntityFrameWork.TaskInstance"
                    Else
                        ObjectName = ObjectName.Replace("Task", "Instance")
                    End If
                    oh = Activator.CreateInstance("QSEntityFrameWork", ObjectName)
                    Dim obj As Object = oh.Unwrap
                    obj.TaskTemplateID = Me.TaskTemplateID
                    obj.TaskStartDate = DateTime.Now
                    obj.ProcessInstanceID = ProcessIntanceID
                    Return obj


问:
error in webpack compiling
I've got an error while I'm trying to run my angular2 project. It occured after switching from PC with ubuntu to MacOS X. Node version: 7.7.4, npm version: 4.1.2. I'm running npm webpack-dev-server --inline --progress --watch --port 8180 and then I'm getting this information:

```<code>WARNING in ./~/@angular/core/src/linker/system_js_ng_module_factory_loader.js
69:15-36 Critical dependency: the request of a dependency is an expression

WARNING in ./~/@angular/core/src/linker/system_js_ng_module_factory_loader.js
85:15-102 Critical dependency: the request of a dependency is an expression

WARNING in ./~/angular2-focus/~/@angular/core/@angular/core.es5.js
5889:15-36 Critical dependency: the request of a dependency is an expression

WARNING in ./~/angular2-focus/~/@angular/core/@angular/core.es5.js
5905:15-102 Critical dependency: the request of a dependency is an expression

ERROR in [default] /Users/user/Documents/Java/WORK/mediahelper/media-helper/src/main/web/node_modules/angular2-focus/node_modules/@angular/core/src/animation/animation_metadata_wrapped.d.ts:12:32
Initializers are not allowed in ambient contexts.

[...]

ERROR in [default] /Users/user/node_modules/@types/core-js/index.d.ts:651:4
All declarations of 'prototype' must have identical modifiers.

ERROR in [default] /Users/user/node_modules/@types/core-js/index.d.ts:666:4
All declarations of 'prototype' must have identical modifiers.

ERROR in [default] /Users/user/node_modules/@types/core-js/index.d.ts:680:4
All declarations of 'prototype' must have identical modifiers.

ERROR in [default] /Users/user/node_modules/@types/core-js/index.d.ts:692:4
All declarations of 'value' must have identical modifiers.

ERROR in [default] /Users/user/node_modules/@types/core-js/index.d.ts:804:4
All declarations of 'prototype' must have identical modifiers.
</code>```

答:
Just updated my pet project to @angular4 and got similar warnings

```<code>angular/core.es5.js 5889:15-36 Critical dependency:
the request of a dependency is an expression
</code>```

Change your webpack.conf.js

```<code>from: /angular(\|/)core(\|/)(esm(\|/)src|src)(\|/)linker/
to:   /angular(\|/)core(\|/)@angular/
</code>```

Link to reddit thread: https://www.reddit.com/r/Angular2/comments/6160c2/angular_400_now_available/dfci3gm/

Title: error in webpack compiling

Body:
I've got an error while I'm trying to run my angular2 project. It occured after switching from PC with ubuntu to MacOS X. Node version: 7.7.4, npm version: 4.1.2. I'm running npm webpack-dev-server --inline --progress --watch --port 8180 and then I'm getting this information:

WARNING in ./~/@angular/core/src/linker/system_js_ng_module_factory_loader.js
69:15-36 Critical dependency: the request of a dependency is an expression

WARNING in ./~/@angular/core/src/linker/system_js_ng_module_factory_loader.js
85:15-102 Critical dependency: the request of a dependency is an expression

WARNING in ./~/angular2-focus/~/@angular/core/@angular/core.es5.js
5889:15-36 Critical dependency: the request of a dependency is an expression

WARNING in ./~/angular2-focus/~/@angular/core/@angular/core.es5.js
5905:15-102 Critical dependency: the request of a dependency is an expression

ERROR in [default] /Users/user/Documents/Java/WORK/mediahelper/media-helper/src/main/web/node_modules/angular2-focus/node_modules/@angular/core/src/animation/animation_metadata_wrapped.d.ts:12:32
Initializers are not allowed in ambient contexts.

[...]

ERROR in [default] /Users/user/node_modules/@types/core-js/index.d.ts:651:4
All declarations of 'prototype' must have identical modifiers.

ERROR in [default] /Users/user/node_modules/@types/core-js/index.d.ts:666:4
All declarations of 'prototype' must have identical modifiers.

ERROR in [default] /Users/user/node_modules/@types/core-js/index.d.ts:680:4
All declarations of 'prototype' must have identical modifiers.

ERROR in [default] /Users/user/node_modules/@types/core-js/index.d.ts:692:4
All declarations of 'value' must have identical modifiers.

ERROR in [default] /Users/user/node_modules/@types/core-js/index.d.ts:804:4
All declarations of 'prototype' must have identical modifiers.

Body:
Just updated my pet project to @angular4 and got similar warnings

angular/core.es5.js 5889:15-36 Critical dependency:
the request of a dependency is an expression

Change your webpack.conf.js

from: /angular(\|/)core(\|/)(esm(\|/)src|src)(\|/)linker/
to:   /angular(\|/)core(\|/)@angular/

Link to reddit thread: https://www.reddit.com/r/Angular2/comments/6160c2/angular_400_now_available/dfci3gm/