问:
jQuery to get background image height and change parent based on ratio
I have a background image for each item; in this case the image size is 580x374.

This is being set inline on the li a item for each as a background image but I need to set the elements height so it shows correctly. The image height returned I need to half as it's two images in one that I need to move position on hover but I can do that.

What I am having a problem with is getting the elements width, getting the background size, working out the ratio of the background image size and setting the height of the container to display it.

I need it to be responsive as well, so it sets right on page load whichever viewport size it is and resize.

Here is where I have got to so far, but I'm new to JS.

HTML EXAMPLE:

```<code><ul>
<li class="collection-list-item grid-item first collection-hover">
 <a href="/collections/butterfly-sofa" data-image="//cdn.shopify.com/s/files/1/1839/7697/collections/category-panel-butterfly.jpg?v=1490985733" style="background-image: url("//cdn.shopify.com/s/files/1/1839/7697/collections/category-panel-butterfly.jpg?v=1490985733");">
  <div class="collection-list-hover-desc right">

    <p>Dein eigener Ruhepol in einer hektischen Welt. Der durch eine Struktur im Inneren formstabile Sitzsack vereint Komfort und Ästhetik.</p>
  </div>
  <div class="collection-list-hover-button left">
    <span class="button">Entdecken</span>
  </div>
</a>
</li>
<li class="collection-list-item grid-item first collection-hover">
 <a href="/collections/butterfly-sofa" data-image="//cdn.shopify.com/s/files/1/1839/7697/collections/category-panel-butterfly.jpg?v=1490985733" style="background-image: url("//cdn.shopify.com/s/files/1/1839/7697/collections/category-panel-butterfly.jpg?v=1490985733");">
  <div class="collection-list-hover-desc right">

    <p>Dein eigener Ruhepol in einer hektischen Welt. Der durch eine Struktur im Inneren formstabile Sitzsack vereint Komfort und Ästhetik.</p>
  </div>
  <div class="collection-list-hover-button left">
    <span class="button">Entdecken</span>
  </div>
</a>
</li>
<li class="collection-list-item grid-item first collection-hover">
 <a href="/collections/butterfly-sofa" data-image="//cdn.shopify.com/s/files/1/1839/7697/collections/category-panel-butterfly.jpg?v=1490985733" style="background-image: url("//cdn.shopify.com/s/files/1/1839/7697/collections/category-panel-butterfly.jpg?v=1490985733");">
  <div class="collection-list-hover-desc right">

    <p>Dein eigener Ruhepol in einer hektischen Welt. Der durch eine Struktur im Inneren formstabile Sitzsack vereint Komfort und Ästhetik.</p>
  </div>
  <div class="collection-list-hover-button left">
    <span class="button">Entdecken</span>
  </div>
</a>
</li>
</ul>
</code>```

JS:

```<code>$('.collection-hover a').each(function (index, value){
  var collection_bg_img = new Image;
  collection_bg_img.src = $(this).data('image');
  var bgImgWidth = collection_bg_img.width;
  var bgImgHeight = collection_bg_img.height;
  var divWidth = $(this).width();
  var realImgHeight = ( bgImgHeight / bgImgWidth) * divWidth;
  var halfImage = (realImgHeight / 2);
  $(this).height(halfImage);
  //console.log(halfImage);
});
</code>```

I guess could set a max width and height and change it width whatever width is set by viewport and adjust height based on ratio?

UPDATE

I tried something like this, not got it working yet though... but maybe a good approach as would be a max width:

```<code>$('.collection-hover a').each(function() {
var maxWidth = 580; // Max width for the image
var maxHeight = 374;    // Max height for the image
var ratio = 0;  // Used for aspect ratio
var width = $(this).width();    // Current image width
var height = $(this).height();  // Current image height

// Check if the current width is larger than the max
if(width > maxWidth){
  ratio = maxWidth / width;   // get ratio for scaling image
  $(this).css("width", maxWidth); // Set new width
  $(this).css("height", height * ratio);  // Scale height based on ratio
  height = height * ratio;    // Reset height to match scaled image
}

var width = $(this).width();    // Current image width
var height = $(this).height();  // Current image height

// Check if current height is larger than max
if(height > maxHeight){
  ratio = maxHeight / height; // get ratio for scaling image
  $(this).css("height", maxHeight);   // Set new height
  $(this).css("width", width * ratio);    // Scale width based on ratio
  width = width * ratio;    // Reset width to match scaled image
}

});
</code>```

答:
You can only :

address DOM elements after the document is ready

measure an image's width after it has successfully loaded.

Therefore :

```<code>jQuery(function($) {
    function resizeBgImgContainers() {
        $('.collection-hover a').each(function() {
            var $a = $(this);
            var img = new Image();
            img.onload = function() {
                $a.height(img.height * $a.width() / img.width / 2);
            };
            img.src = $a.data('image');
        });
    }
    $(window).on('resize', resizeBgImgContainers).trigger('resize');
});
</code>```

Body:
I have a background image for each item; in this case the image size is 580x374.

This is being set inline on the li a item for each as a background image but I need to set the elements height so it shows correctly. The image height returned I need to half as it's two images in one that I need to move position on hover but I can do that.

What I am having a problem with is getting the elements width, getting the background size, working out the ratio of the background image size and setting the height of the container to display it.

I need it to be responsive as well, so it sets right on page load whichever viewport size it is and resize.

Here is where I have got to so far, but I'm new to JS.

HTML EXAMPLE:

Dein eigener Ruhepol in einer hektischen Welt. Der durch eine Struktur im Inneren formstabile Sitzsack vereint Komfort und Ästhetik.

    Entdecken

Dein eigener Ruhepol in einer hektischen Welt. Der durch eine Struktur im Inneren formstabile Sitzsack vereint Komfort und Ästhetik.

    Entdecken

Dein eigener Ruhepol in einer hektischen Welt. Der durch eine Struktur im Inneren formstabile Sitzsack vereint Komfort und Ästhetik.

    Entdecken

JS:

$('.collection-hover a').each(function (index, value){
  var collection_bg_img = new Image;
  collection_bg_img.src = $(this).data('image');
  var bgImgWidth = collection_bg_img.width;
  var bgImgHeight = collection_bg_img.height;
  var divWidth = $(this).width();
  var realImgHeight = ( bgImgHeight / bgImgWidth) * divWidth;
  var halfImage = (realImgHeight / 2);
  $(this).height(halfImage);
  //console.log(halfImage);
});

I guess could set a max width and height and change it width whatever width is set by viewport and adjust height based on ratio?

UPDATE

I tried something like this, not got it working yet though... but maybe a good approach as would be a max width:

$('.collection-hover a').each(function() {
var maxWidth = 580; // Max width for the image
var maxHeight = 374;    // Max height for the image
var ratio = 0;  // Used for aspect ratio
var width = $(this).width();    // Current image width
var height = $(this).height();  // Current image height

// Check if the current width is larger than the max
if(width > maxWidth){
  ratio = maxWidth / width;   // get ratio for scaling image
  $(this).css("width", maxWidth); // Set new width
  $(this).css("height", height * ratio);  // Scale height based on ratio
  height = height * ratio;    // Reset height to match scaled image
}

var width = $(this).width();    // Current image width
var height = $(this).height();  // Current image height

// Check if current height is larger than max
if(height > maxHeight){
  ratio = maxHeight / height; // get ratio for scaling image
  $(this).css("height", maxHeight);   // Set new height
  $(this).css("width", width * ratio);    // Scale width based on ratio
  width = width * ratio;    // Reset width to match scaled image
}

});

Body:
You can only :

address DOM elements after the document is ready

measure an image's width after it has successfully loaded.

Therefore :

jQuery(function($) {
    function resizeBgImgContainers() {
        $('.collection-hover a').each(function() {
            var $a = $(this);
            var img = new Image();
            img.onload = function() {
                $a.height(img.height * $a.width() / img.width / 2);
            };
            img.src = $a.data('image');
        });
    }
    $(window).on('resize', resizeBgImgContainers).trigger('resize');
});


来源: stackexchange

问:
How to make a parametrized module
I know its kind of silly to start a question on Racket with "is it possible" (but here I go)

Is it possible to create a paramterized module similar to OCaml's functors?
Let's say I have the following structure

```<code>;;module A
(define x ...)

(provide foo)

(define (foo a) (format "x for foo: ~a ~a" x a))
(define (bar a) (format "x for bar: ~a ~a" x a))
</code>```

then I define 2 other modules that use module As definitions

```<code>;;module B

(require "A.rkt" #| '(value for x is "lala") |# )

(define result1 (foo "lulu"))
(define result1 (bar "lili"))

;;result1 => "x for foo: lala lulu"
;;result2 => "x for bar: lala lili"
</code>```

and

```<code>;;module C

(require "A.rkt" #| '(value for x is "empty") |# )

(define result1 (foo "really"))
(define result1 (bar "nothing"))

;;result1 => "x for foo: empty really"
;;result2 => "x for bar: empty nothing"
</code>```

Obviously I could define foo and bar to have an additional parameter each,
partially apply that additional param and define new funcs

```<code>;;module A2

(provide foo)

(define (foo x a) (format "x for foo: ~a ~a" x a))
(define (bar x a) (format "x for bar: ~a ~a" x a))
</code>```

and then

```<code>;;module B2

(require "A2.rkt")

(define foo1 (partial foo "homemade"))
(define bar1 (partial bar "homemade"))

(define result1 (foo1 "really"))
(define result1 (bar1 "nothing"))

;;result1 => "x for foo: homemade really"
;;result2 => "x for bar: homemade nothing"
</code>```

but that is really not what I want - rather I want to somehow preserve the module/require way and not have to redefine
the (almost same) functions over and over again.

Any ideas how to do that?

答:
As Alexis mentioned, the closest thing in Racket corresponding to ML functors is the unit system. Here's one translation of your example (slightly simplified) into units.

First, define signatures for the interfaces between components:

```<code>(define-signature in^ (x))
(define-signature out^ (foo bar))
</code>```

The A component takes in values for the in^ bindings (just x here) and produces definitions for the out^ bindings (foo and bar):

```<code>(define-unit A@
  (import in^)
  (export out^)
  (define (foo a) (format "x for foo: ~a ~a" x a))
  (define (bar a) (format "x for bar: ~a ~a" x a)))
</code>```

The B component actually needs to be split into two parts: a unit that provides the definition of x and a unit that uses the foo and bar functions. I've simplified the latter part to just print out the results so I don't have to create another signature.

```<code>(define-unit B-in@
  (import)
  (export in^)
  (define x "lala"))

(define-unit B@
  (import out^)
  (export)
  (printf "~a\n" (foo "lulu"))
  (printf "~a\n" (bar "lili")))
</code>```

In this example, the linkage can be inferred automatically from the signatures and unit definitions. To link these components together and run the result, you can just do this:

```<code>(invoke-unit/infer (link A@ B-in@ B@))
</code>```

That's equivalent to invoking the following compound unit (similar to functor application), which can be written more explicitly like this:

```<code>(invoke-unit (compound-unit/infer (import) (export) (link A@ B-in@ B@)))
</code>```

Instead of asking Racket to infer the linkage, you can also write it explicitly as follows:

```<code>(invoke-unit
 (compound-unit
   (import)
   (export)
   (link [((B-in : in^)) B-in@]
         [((A : out^)) A@ B-in]
         [() B@ A])))
</code>```

Instead of creating an explicit unit to satisfy the in^ import, you can also get the bindings from the context when you invoke the compound unit. For example:

```<code>(define-unit C@
  (import out^)
  (export)
  (printf "~a\n" (foo "really"))
  (printf "~a\n" (foo "nothing")))

(let ([x "empty"])   ;; the in^ bindings come from here!
  (invoke-unit
   (compound-unit/infer (import in^) (export) (link A@ C@))
   (import in^)))
</code>```

Another important special form is define-values/invoke-unit, which takes a unit's exports and turns them into normal Racket definitions.

```<code>(let ([x "apple"])  ;; in in^ bindings come from here!
  (define-values/invoke-unit A@ (import in^) (export out^))
  ;; the out^ exports are available for the rest of the let body
  (foo "orange"))
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to make a parametrized module

Body:
I know its kind of silly to start a question on Racket with "is it possible" (but here I go)

Is it possible to create a paramterized module similar to OCaml's functors?
Let's say I have the following structure

;;module A
(define x ...)

(provide foo)

(define (foo a) (format "x for foo: ~a ~a" x a))
(define (bar a) (format "x for bar: ~a ~a" x a))

then I define 2 other modules that use module As definitions

;;module B

(require "A.rkt" #| '(value for x is "lala") |# )

(define result1 (foo "lulu"))
(define result1 (bar "lili"))

;;result1 => "x for foo: lala lulu"
;;result2 => "x for bar: lala lili"

and

;;module C

(require "A.rkt" #| '(value for x is "empty") |# )

(define result1 (foo "really"))
(define result1 (bar "nothing"))

;;result1 => "x for foo: empty really"
;;result2 => "x for bar: empty nothing"

Obviously I could define foo and bar to have an additional parameter each,
partially apply that additional param and define new funcs

;;module A2

(provide foo)

(define (foo x a) (format "x for foo: ~a ~a" x a))
(define (bar x a) (format "x for bar: ~a ~a" x a))

and then

;;module B2

(require "A2.rkt")

(define foo1 (partial foo "homemade"))
(define bar1 (partial bar "homemade"))

(define result1 (foo1 "really"))
(define result1 (bar1 "nothing"))

;;result1 => "x for foo: homemade really"
;;result2 => "x for bar: homemade nothing"

but that is really not what I want - rather I want to somehow preserve the module/require way and not have to redefine
the (almost same) functions over and over again.

Any ideas how to do that?

Body:
As Alexis mentioned, the closest thing in Racket corresponding to ML functors is the unit system. Here's one translation of your example (slightly simplified) into units.

First, define signatures for the interfaces between components:

(define-signature in^ (x))
(define-signature out^ (foo bar))

The A component takes in values for the in^ bindings (just x here) and produces definitions for the out^ bindings (foo and bar):

(define-unit A@
  (import in^)
  (export out^)
  (define (foo a) (format "x for foo: ~a ~a" x a))
  (define (bar a) (format "x for bar: ~a ~a" x a)))

The B component actually needs to be split into two parts: a unit that provides the definition of x and a unit that uses the foo and bar functions. I've simplified the latter part to just print out the results so I don't have to create another signature.

(define-unit B-in@
  (import)
  (export in^)
  (define x "lala"))

(define-unit B@
  (import out^)
  (export)
  (printf "~a\n" (foo "lulu"))
  (printf "~a\n" (bar "lili")))

In this example, the linkage can be inferred automatically from the signatures and unit definitions. To link these components together and run the result, you can just do this:

(invoke-unit/infer (link A@ B-in@ B@))

That's equivalent to invoking the following compound unit (similar to functor application), which can be written more explicitly like this:

(invoke-unit (compound-unit/infer (import) (export) (link A@ B-in@ B@)))

Instead of asking Racket to infer the linkage, you can also write it explicitly as follows:

(invoke-unit
 (compound-unit
   (import)
   (export)
   (link [((B-in : in^)) B-in@]
         [((A : out^)) A@ B-in]
         [() B@ A])))

Instead of creating an explicit unit to satisfy the in^ import, you can also get the bindings from the context when you invoke the compound unit. For example:

(define-unit C@
  (import out^)
  (export)
  (printf "~a\n" (foo "really"))
  (printf "~a\n" (foo "nothing")))

(let ([x "empty"])   ;; the in^ bindings come from here!
  (invoke-unit
   (compound-unit/infer (import in^) (export) (link A@ C@))
   (import in^)))

Another important special form is define-values/invoke-unit, which takes a unit's exports and turns them into normal Racket definitions.

(let ([x "apple"])  ;; in in^ bindings come from here!
  (define-values/invoke-unit A@ (import in^) (export out^))
  ;; the out^ exports are available for the rest of the let body
  (foo "orange"))


问:
Python analyzing csv file
I'm trying to find the three most populated city parts(BYDEL) in 1992

I have a csv file looking like this: http://data.kk.dk/dataset/9070067f-ab57-41cd-913e-bc37bfaf9acd/resource/9fbab4aa-1ee0-4d25-b2b4-b7b63537d2ec/download/befkbhalderkoencivst.csv>

The csv file can be explained as:

AAR: Which year the observation was made

BYDEL: Which part of the city, described by an integer contained in following dict; 1=Indre By, 2=Østerbro, 3=Nørrebro, 4=Vesterbro/Kgs. Enghave, 5=Valby, 6=Vanløse, 7=Brønshøj-Husum, 8=Bispebjerg, 9=Amager Øst, 10=Amager Vest, 99=Udenfor inddeling

ALDER: The age of the observed people

PERSONER: Number of observations with the given features of the row

I have a solution but it is very repetitive and i think that it could be done smarter but I don't have enough experience with python. Could anyone point me in the right direction?

My code/solution looks like this:

```<code>df = pd.read_csv('befkbh.csv',quotechar='"',skipinitialspace=True, delimiter=',', encoding='latin1').fillna(0)
data = df.as_matrix()
Q31 = collections.defaultdict(list)
Q32 = collections.defaultdict(list)
Q33 = collections.defaultdict(list)
Q34 = collections.defaultdict(list)
Q35 = collections.defaultdict(list)
Q36 = collections.defaultdict(list)
Q37 = collections.defaultdict(list)
Q38 = collections.defaultdict(list)
Q39 = collections.defaultdict(list)
Q310 = collections.defaultdict(list)
Q399 = collections.defaultdict(list)
for row in data:
    key = row[0]
    if key == "" or key == 0: continue
    if key == 1992:
        if row[2] == 1:
            val = 0 if(row[5]) ==""  else float(row[5])
            Q31.setdefault(key,[]).append(val)
        if row[2] == 2:
            val = 0 if(row[5]) ==""  else float(row[5])
            Q32.setdefault(key,[]).append(val)
        if row[2] == 3:
            val = 0 if(row[5]) ==""  else float(row[5])
            Q33.setdefault(key,[]).append(val)
        if row[2] == 4:
            val = 0 if(row[5]) ==""  else float(row[5])
            Q34.setdefault(key,[]).append(val)
        if row[2] == 5:
            val = 0 if(row[5]) ==""  else float(row[5])
            Q35.setdefault(key,[]).append(val)
        if row[2] == 6:
            val = 0 if(row[5]) ==""  else float(row[5])
            Q36.setdefault(key,[]).append(val)
        if row[2] == 7:
            val = 0 if(row[5]) ==""  else float(row[5])
            Q37.setdefault(key,[]).append(val)
        if row[2] == 8:
            val = 0 if(row[5]) ==""  else float(row[5])
            Q38.setdefault(key,[]).append(val)
        if row[2] == 9:
            val = 0 if(row[5]) ==""  else float(row[5])
            Q39.setdefault(key,[]).append(val)
        if row[2] == 10:
            val = 0 if(row[5]) ==""  else float(row[5])
            Q310.setdefault(key,[]).append(val)
        if row[2] == 99:
            val = 0 if(row[5]) ==""  else float(row[5])
            Q399.setdefault(key,[]).append(val)

Q312 = {}
for k, v in Q31.items(): Q312[k] = sum(v)
for k, v in Q312.items(): print ("{}:{}".format(k,v))
Q322 = {}
for k, v in Q32.items(): Q322[k] = sum(v)
for k, v in Q322.items(): print ("{}:{}".format(k,v))
Q332 = {}
for k, v in Q33.items(): Q332[k] = sum(v)
for k, v in Q332.items(): print ("{}:{}".format(k,v))
Q342 = {}
for k, v in Q34.items(): Q342[k] = sum(v)
for k, v in Q342.items(): print ("{}:{}".format(k,v))
Q352 = {}
for k, v in Q35.items(): Q352[k] = sum(v)
for k, v in Q352.items(): print ("{}:{}".format(k,v))
Q362 = {}
for k, v in Q36.items(): Q362[k] = sum(v)
for k, v in Q362.items(): print ("{}:{}".format(k,v))
Q372 = {}
for k, v in Q37.items(): Q372[k] = sum(v)
for k, v in Q372.items(): print ("{}:{}".format(k,v))
Q382 = {}
for k, v in Q38.items(): Q382[k] = sum(v)
for k, v in Q382.items(): print ("{}:{}".format(k,v))
Q392 = {}
for k, v in Q39.items(): Q392[k] = sum(v)
for k, v in Q392.items(): print ("{}:{}".format(k,v))
Q3102 = {}
for k, v in Q310.items(): Q3102[k] = sum(v)
for k, v in Q3102.items(): print ("{}:{}".format(k,v))
Q3992 = {}
for k, v in Q399.items(): Q3992[k] = sum(v)
for k, v in Q3992.items(): print ("{}:{}".format(k,v))
</code>```

答:
It's actually a pretty good sign that you've recognized that there has to be an easier way!  Whenever you find yourself violating the DRY principle (Don't Repeat Yourself) you should ask if you've taken a misstep.

While you could remove a lot of your duplication simply by using a dictionary of dictionaries instead of all those named variables, since you're using pandas, I would take advantage of groupby and nlargest instead, which gives me:

```<code>In [47]: dg = df.groupby(["AAR", "BYDEL"], as_index=False)["PERSONER"].sum()

In [48]: dg[dg.AAR == 1992].nlargest(3, "PERSONER")
Out[48]:
    AAR  BYDEL  PERSONER
2  1992      3     67251
1  1992      2     62221
3  1992      4     47854
</code>```

First, we group on the AAR and BYDEL columns, and in each group, we take the PERSONER values and sum them.  This gives us a frame which begins

```<code>n [51]: dg.head(15)
Out[51]:
     AAR  BYDEL  PERSONER
0   1992      1     40595
1   1992      2     62221
2   1992      3     67251
3   1992      4     47854
4   1992      5     43688
5   1992      6     34303
6   1992      7     36746
7   1992      8     41668
8   1992      9     45305
9   1992     10     42748
10  1992     99      2187
11  1993      1     40925
12  1993      2     62583
13  1993      3     67783
14  1993      4     47589
</code>```

then we select the rows where AAR == 1992, and the rows with the 3 largest PERSONER values.

I'd strongly recommend reading through a pandas tutorial if you're going to be doing this type of data processing, otherwise you'll find yourself reinventing wheels.

Title: Python analyzing csv file

Body:
I'm trying to find the three most populated city parts(BYDEL) in 1992

I have a csv file looking like this: http://data.kk.dk/dataset/9070067f-ab57-41cd-913e-bc37bfaf9acd/resource/9fbab4aa-1ee0-4d25-b2b4-b7b63537d2ec/download/befkbhalderkoencivst.csv>

The csv file can be explained as:

AAR: Which year the observation was made

BYDEL: Which part of the city, described by an integer contained in following dict; 1=Indre By, 2=Østerbro, 3=Nørrebro, 4=Vesterbro/Kgs. Enghave, 5=Valby, 6=Vanløse, 7=Brønshøj-Husum, 8=Bispebjerg, 9=Amager Øst, 10=Amager Vest, 99=Udenfor inddeling

ALDER: The age of the observed people

PERSONER: Number of observations with the given features of the row

I have a solution but it is very repetitive and i think that it could be done smarter but I don't have enough experience with python. Could anyone point me in the right direction?

My code/solution looks like this:

df = pd.read_csv('befkbh.csv',quotechar='"',skipinitialspace=True, delimiter=',', encoding='latin1').fillna(0)
data = df.as_matrix()
Q31 = collections.defaultdict(list)
Q32 = collections.defaultdict(list)
Q33 = collections.defaultdict(list)
Q34 = collections.defaultdict(list)
Q35 = collections.defaultdict(list)
Q36 = collections.defaultdict(list)
Q37 = collections.defaultdict(list)
Q38 = collections.defaultdict(list)
Q39 = collections.defaultdict(list)
Q310 = collections.defaultdict(list)
Q399 = collections.defaultdict(list)
for row in data:
    key = row[0]
    if key == "" or key == 0: continue
    if key == 1992:
        if row[2] == 1:
            val = 0 if(row[5]) ==""  else float(row[5])
            Q31.setdefault(key,[]).append(val)
        if row[2] == 2:
            val = 0 if(row[5]) ==""  else float(row[5])
            Q32.setdefault(key,[]).append(val)
        if row[2] == 3:
            val = 0 if(row[5]) ==""  else float(row[5])
            Q33.setdefault(key,[]).append(val)
        if row[2] == 4:
            val = 0 if(row[5]) ==""  else float(row[5])
            Q34.setdefault(key,[]).append(val)
        if row[2] == 5:
            val = 0 if(row[5]) ==""  else float(row[5])
            Q35.setdefault(key,[]).append(val)
        if row[2] == 6:
            val = 0 if(row[5]) ==""  else float(row[5])
            Q36.setdefault(key,[]).append(val)
        if row[2] == 7:
            val = 0 if(row[5]) ==""  else float(row[5])
            Q37.setdefault(key,[]).append(val)
        if row[2] == 8:
            val = 0 if(row[5]) ==""  else float(row[5])
            Q38.setdefault(key,[]).append(val)
        if row[2] == 9:
            val = 0 if(row[5]) ==""  else float(row[5])
            Q39.setdefault(key,[]).append(val)
        if row[2] == 10:
            val = 0 if(row[5]) ==""  else float(row[5])
            Q310.setdefault(key,[]).append(val)
        if row[2] == 99:
            val = 0 if(row[5]) ==""  else float(row[5])
            Q399.setdefault(key,[]).append(val)

Q312 = {}
for k, v in Q31.items(): Q312[k] = sum(v)
for k, v in Q312.items(): print ("{}:{}".format(k,v))
Q322 = {}
for k, v in Q32.items(): Q322[k] = sum(v)
for k, v in Q322.items(): print ("{}:{}".format(k,v))
Q332 = {}
for k, v in Q33.items(): Q332[k] = sum(v)
for k, v in Q332.items(): print ("{}:{}".format(k,v))
Q342 = {}
for k, v in Q34.items(): Q342[k] = sum(v)
for k, v in Q342.items(): print ("{}:{}".format(k,v))
Q352 = {}
for k, v in Q35.items(): Q352[k] = sum(v)
for k, v in Q352.items(): print ("{}:{}".format(k,v))
Q362 = {}
for k, v in Q36.items(): Q362[k] = sum(v)
for k, v in Q362.items(): print ("{}:{}".format(k,v))
Q372 = {}
for k, v in Q37.items(): Q372[k] = sum(v)
for k, v in Q372.items(): print ("{}:{}".format(k,v))
Q382 = {}
for k, v in Q38.items(): Q382[k] = sum(v)
for k, v in Q382.items(): print ("{}:{}".format(k,v))
Q392 = {}
for k, v in Q39.items(): Q392[k] = sum(v)
for k, v in Q392.items(): print ("{}:{}".format(k,v))
Q3102 = {}
for k, v in Q310.items(): Q3102[k] = sum(v)
for k, v in Q3102.items(): print ("{}:{}".format(k,v))
Q3992 = {}
for k, v in Q399.items(): Q3992[k] = sum(v)
for k, v in Q3992.items(): print ("{}:{}".format(k,v))

Body:
It's actually a pretty good sign that you've recognized that there has to be an easier way!  Whenever you find yourself violating the DRY principle (Don't Repeat Yourself) you should ask if you've taken a misstep.

While you could remove a lot of your duplication simply by using a dictionary of dictionaries instead of all those named variables, since you're using pandas, I would take advantage of groupby and nlargest instead, which gives me:

In [47]: dg = df.groupby(["AAR", "BYDEL"], as_index=False)["PERSONER"].sum()

In [48]: dg[dg.AAR == 1992].nlargest(3, "PERSONER")
Out[48]:
    AAR  BYDEL  PERSONER
2  1992      3     67251
1  1992      2     62221
3  1992      4     47854

First, we group on the AAR and BYDEL columns, and in each group, we take the PERSONER values and sum them.  This gives us a frame which begins

n [51]: dg.head(15)
Out[51]:
     AAR  BYDEL  PERSONER
0   1992      1     40595
1   1992      2     62221
2   1992      3     67251
3   1992      4     47854
4   1992      5     43688
5   1992      6     34303
6   1992      7     36746
7   1992      8     41668
8   1992      9     45305
9   1992     10     42748
10  1992     99      2187
11  1993      1     40925
12  1993      2     62583
13  1993      3     67783
14  1993      4     47589

then we select the rows where AAR == 1992, and the rows with the 3 largest PERSONER values.

I'd strongly recommend reading through a pandas tutorial if you're going to be doing this type of data processing, otherwise you'll find yourself reinventing wheels.


问:
How to set multiple site_dir in shiny-server.conf
Currently my shiny-server.conf looks like this:

```<code># Instruct Shiny Server to run applications as the user "shiny"
run_as ubuntu shiny;

# Define a server that listens on port 3838
server {
  listen 3838;

  # Define a location at the base URL
  location / {

    # Host the directory of Shiny Apps stored in this directory
    site_dir /srv/shiny-server;

    # Log all Shiny output to files in this directory
    log_dir /var/log/shiny-server;

    # When a user visits the base URL rather than a particular application,
    # an index of the applications available in this directory will be shown.
    directory_index on;
  }
}
</code>```

Is there a way I can set multiple directories in this line?

site_dir /srv/shiny-server

e.g.  by adding  /my_favorite/app_path1/ on top of it.

答:
AS I understand it, the question is: "how to set multiple directories in shiny-server"?

This is my shiny-server.conf:

```<code># Instruct Shiny Server to run applications as the user "shiny"
run_as shiny;

# Define a server that listens on port 3838
server {
  listen 3838;

  # Define a location at the base URL
  location / {

    # Host the directory of Shiny Apps stored in this directory
    site_dir /srv/shiny-server;

    # Log all Shiny output to files in this directory
    log_dir /var/log/shiny-server;

    # When a user visits the base URL rather than a particular application,
    # an index of the applications available in this directory will be shown.
    directory_index on;
  }
}
</code>```

Taking the above into account, you can create as many directories you want under /srv/shiny-server, e.g.:

```<code>+---/srv/shiny-server
|   +---Test
|       +---server.R
|       +---ui.R
|   +---Foo
|       +---server.R
|       +---ui.R
</code>```

Then you connect to each application with:
http://<ip address>:3838/Test or http://<ip address>:3838/Foo etc.

Of course, if there is no desire to have physical directories under /srv/shiny-server it is possible to symlink them: for example, the directory sample-apps where the standard examples of shiny are stored, is symlinked from /opt/shiny-server/samples/sample-apps.

It is also possible to have per-users directories, but this seems to be out of the question's scope.

Body:
Currently my shiny-server.conf looks like this:

# Instruct Shiny Server to run applications as the user "shiny"
run_as ubuntu shiny;

# Define a server that listens on port 3838
server {
  listen 3838;

  # Define a location at the base URL
  location / {

    # Host the directory of Shiny Apps stored in this directory
    site_dir /srv/shiny-server;

    # Log all Shiny output to files in this directory
    log_dir /var/log/shiny-server;

    # When a user visits the base URL rather than a particular application,
    # an index of the applications available in this directory will be shown.
    directory_index on;
  }
}

Is there a way I can set multiple directories in this line?

site_dir /srv/shiny-server

e.g.  by adding  /my_favorite/app_path1/ on top of it.

Body:
AS I understand it, the question is: "how to set multiple directories in shiny-server"?

This is my shiny-server.conf:

# Instruct Shiny Server to run applications as the user "shiny"
run_as shiny;

# Define a server that listens on port 3838
server {
  listen 3838;

  # Define a location at the base URL
  location / {

    # Host the directory of Shiny Apps stored in this directory
    site_dir /srv/shiny-server;

    # Log all Shiny output to files in this directory
    log_dir /var/log/shiny-server;

    # When a user visits the base URL rather than a particular application,
    # an index of the applications available in this directory will be shown.
    directory_index on;
  }
}

Taking the above into account, you can create as many directories you want under /srv/shiny-server, e.g.:

+---/srv/shiny-server
|   +---Test
|       +---server.R
|       +---ui.R
|   +---Foo
|       +---server.R
|       +---ui.R

Then you connect to each application with:
http://<ip address>:3838/Test or http://<ip address>:3838/Foo etc.

Of course, if there is no desire to have physical directories under /srv/shiny-server it is possible to symlink them: for example, the directory sample-apps where the standard examples of shiny are stored, is symlinked from /opt/shiny-server/samples/sample-apps.

It is also possible to have per-users directories, but this seems to be out of the question's scope.


问:
Content Security Policy Violation on File Preview
This is quite odd, and I've checked around and attempted many things to no avail.

I have a simple file upload, it displays the image prior to uploading it. This works fine in my local development environment, and it also works fine on the staging server.

On the production server, it doesn't work. This is what is showing in my console:

refused to load the image 'blob:https://example.com/a7ced718-483b-4bc2-9db0-f012c8c6af5a' because it violates the following Content Security Policy directive: "img-src 'self' data:

However, I have no CSP defined, and it works fine on an exact replica server utilized for staging to test for bugs.

Furthermore, I've tried to add a CSP in the meta tag at the head of the document, but it does not solve the problem either. This is the CSP I attempted to implement:

```<code><meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src https://*; child-src 'none';">
</code>```

Can anyone shed some light into why this may not be working?

答:
Check the response headers the server sends (using browser devtools or curl or whatever).

The production server must be sending a Content-Security-Policy response header.

If so, the reason your meta element has no effect is, the browser uses the most-restrictive CSP policy, wherever it’s specified—and the Content-Security-Policy header your production server is sending is more restrictive than the one you’re specifying with the meta element.

See the details on multiple polices at https://w3c.github.io/webappsec-csp/#multiple-policies and the details on  the meta element at https://w3c.github.io/webappsec-csp/#meta-element —

A policy specified via a meta element will be enforced along
with any other policies active for the protected resource, regardless
of where they’re specified. The general impact of enforcing multiple
policies is described in §8.1 The effect of multiple policies.

8.1. The effect of multiple policies

The impact is that adding additional policies to the list of policies
to enforce can only further restrict the capabilities of the protected resource.

So it seems that the Content-Security-Policy header your production server is sending has img-src 'self' data: but in order for your image URL to be allowed and to avoid the error you’re seeing, the Content-Security-Policy header your production server is sending needs to at least also include blob: in its source list: img-src 'self' data: blob:.

Body:
This is quite odd, and I've checked around and attempted many things to no avail.

I have a simple file upload, it displays the image prior to uploading it. This works fine in my local development environment, and it also works fine on the staging server.

On the production server, it doesn't work. This is what is showing in my console:

refused to load the image 'blob:https://example.com/a7ced718-483b-4bc2-9db0-f012c8c6af5a' because it violates the following Content Security Policy directive: "img-src 'self' data:

However, I have no CSP defined, and it works fine on an exact replica server utilized for staging to test for bugs.

Furthermore, I've tried to add a CSP in the meta tag at the head of the document, but it does not solve the problem either. This is the CSP I attempted to implement:

<meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src https://*; child-src 'none';">

Can anyone shed some light into why this may not be working?

ContentLicense: CC BY-SA 4.0


问:
My slider refuses to slide, it just vanishes
Here's my problem: I have an image slider that's refusing to actually slide. I've spent the last two hours browsing answers here, and looking at JSFiddles. Nothing seems to be of any help.

This is my problem: I have an HTML table contained within a div, with given properties below. When the button at the top is clicked, the slider (the div with id "slider") is supposed to toggle via a slide animation. But instead, it appears or disappears without an animation!

I've made sure it has a height and width, and everything else that various answers said it needs (though if I didn't have to define a height and width in px, thus letting it expand or contract to however large or small it needs to be, would be great). But yet there's no animation! It just disappears!

Please help!

Also, most of the HTML is the table which you can ignore. Just the beginning and end are important.

```<code><h2><strong>SPRING CONVENTION SCHEDULE OF EVENTS</strong></h2>
<br>
<button id="toggleSwitch" onClick="toggleFlipFlop();">Click here to show table</button>

<!--table for Friday events-->
<div id = "slider" class="hidden">
<table id="friday-table">
<tbody>
<tr>
<th colspan="2"><strong>SCHEDULE OF EVENTS FOR FRIDAY, MARCH 31</strong></th>
</tr>
<tr>
<td>3:45 - 5:00</td>
<td>CONVENTION REGISTRATION</td>
</tr>
<tr>
<td>4:30 - 5:15</td>
<td>GRAPHIC ARTS REGISTRATION</td>
</tr>
<tr>
<td>4:30 - 4:50</td>
<td>CANDIDATES MEETING</td>
</tr>
<tr>
<td>5:15 - 5:25</td>
<td>SPIRIT COMPETITION</td>
</tr>
<tr>
<td>5:25 - 6:00</td>
<td>GENERAL ASSEMBLY</td>
</tr>
<tr>
<td>7:00 - 9:00</td>
<td>COSTUME CONTEST</td>
</tr>
<tr>
<td>7:30 - 9:00</td>
<td>SKIT CONTEST</td>
</tr>
<tr>
<td>7:15 - 8:00</td>
<td>ESSAY CONTEST</td>
</tr>
<tr>
<td>8:00 - 8:30</td>
<td>IMPROMPTU ART</td>
</tr>
<tr>
<td>8:00 - 9:30</td>
<td>SERVICE PROJECT</td>
</tr>
<tr>
<td>8:00 - 9:30</td>
<td>BOARD GAMES</td>
</tr>
</tbody>
</table>
<!--table for Saturday events-->
<table id="saturday-table">
<tbody>
<tr>
<th colspan="2"><strong>SCHEDULE OF EVENTS FOR SATURDAY, APRIL 1</strong></th>
</tr>
<tr>
<td>8:00 - 9:00</td>
<td>SCRAPBOOK CHECK-IN</td>
</tr>
<tr>
<td>8:00 - 9:00</td>
<td>GRAPHIC ARTS</td>
</tr>
<tr>
<td>8:15 - 8:45</td>
<td>CONVENTION REGISTRATION AND SATURDAY CHECK-IN</td>
</tr>
<tr>
<td>9:00 - 10:00</td>
<td>ACADEMIC TESTING (all levels)</td>
</tr>
<tr>
<td>10:15 - 10:45</td>
<td>SEMINAR SESSION I</td>
</tr>
<tr>
<td>10:30 - 12:30</td>
<td>DRAMATIC INTERPRETATION</td>
</tr>
<tr>
<td>10:30 - 11:00</td>
<td>MIDDLE SCHOOL CERTAMEN FINALS</td>
</tr>
<tr>
<td>11:00 - 11:30</td>
<td>SEMINAR SESSION II</td>
</tr>
<tr>
<td>11:00 - 11:30</td>
<td>ADVANCED CERTAMEN FINALS</td>
</tr>
<tr>
<td>11:30 - 12:00</td>
<td>INTERMEDIATE CERTAMEN FINALS</td>
</tr>
<tr>
<td>12:00 - 12:30</td>
<td>NOVICE CERTAMEN FINALS</td>
</tr>
<tr>
<td>12:30 - 3:00</td>
<td>GRAPHIC ARTS VIEWING</td>
</tr>
<tr>
<td>12:45 - 1:30</td>
<td>"MEET THE CANDIDATES" MEETING</td>
</tr>
<tr>
<td>1:00 - 2:30</td>
<td>LATIN SIGHT READING</td>
</tr>
<tr>
<td>1:00 - 2:30</td>
<td>ENGLISH ORATORY</td>
</tr>
<tr>
<td>1:00 - 2:30</td>
<td>OPEN CERTAMEN</td>
</tr>
<tr>
<td>1:30 - 2:30</td>
<td>OLYMPIKA I</td>
</tr>
<tr>
<td>2:00</td>
<td>VOTING BALLOTS DUE</td>
</tr>
<tr>
<td>3:00 - 4:00</td>
<td>OLYMPIKA II</td>
</tr>
<tr>
<td>3:00 - 3:30</td>
<td>CHARIOT RACING AND CATAPULT</td>
</tr>
<tr>
<td>3:00 - 3:30</td>
<td>GRAPHIC ARTS PICKUP</td>
</tr>
<tr>
<td>4:20 - 4:30</td>
<td>SPIRIT COMPETITION</td>
</tr>
<tr>
<td>4:30 - 5:00</td>
<td>CLOSING GENERAL ASSEMBLY</td>
</tr>
</tbody>
</table>
</div>
</code>```

And my CSS:

```<code>#slider{
height: 1530px;
width: 524.317px;
transition: all 2s ease-in-out;
}
.hidden{
    height: 0;
}
</code>```

And the JS:

```<code>//script for slide down reveal for table
//to avoid taking up too much space
function toggleFlipFlop() {
    var toggleSwitch = $("#toggleSwitch");
    var slider = $("#slider");
    console.log("HTML elements translated to objects");
    function slideMe(slider) {
        slider.toggleClass("hidden");
        console.log("hidden class toggled");
    };
    console.log("SlideMe() successfully defined");
    toggleSwitch.onclick = slideMe(slider);
    console.log("onclick attribute of toggleswitch set");
}
</code>```

答:
You're over complicating. You use an inline onClick that calls a function that instantiates a function that calls again a click on the same button... ehh

Also, since you cannot reliably animate/toggle height in CSS3 use jQuery slideToggle()

function toggleFlipFlop() {
  $("#slider").slideToggle(1000);
}

// REMOVE inline JS: onClick="toggleFlipFlop();"
// and use this:
$("#toggleSwitch").on("click", toggleFlipFlop);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#slider {
  height: 1530px;
  width: 524.317px;
  /*transition: all 1s ease-in-out; you cannot use this I'm sorry. */
}

.hidden {
  display: none; /* use this instead */
}</code>```

SPRING CONVENTION SCHEDULE OF EVENTS

<button id="toggleSwitch">Click here to show table</button>

        SCHEDULE OF EVENTS FOR FRIDAY, MARCH 31

        3:45 - 5:00
        CONVENTION REGISTRATION

        4:30 - 5:15
        GRAPHIC ARTS REGISTRATION

        4:30 - 4:50
        CANDIDATES MEETING

        5:15 - 5:25
        SPIRIT COMPETITION

        5:25 - 6:00
        GENERAL ASSEMBLY

        7:00 - 9:00
        COSTUME CONTEST

        7:30 - 9:00
        SKIT CONTEST

        7:15 - 8:00
        ESSAY CONTEST

        8:00 - 8:30
        IMPROMPTU ART

        8:00 - 9:30
        SERVICE PROJECT

        8:00 - 9:30
        BOARD GAMES

        SCHEDULE OF EVENTS FOR SATURDAY, APRIL 1

        8:00 - 9:00
        SCRAPBOOK CHECK-IN

        8:00 - 9:00
        GRAPHIC ARTS

        8:15 - 8:45
        CONVENTION REGISTRATION AND SATURDAY CHECK-IN

        9:00 - 10:00
        ACADEMIC TESTING (all levels)

        10:15 - 10:45
        SEMINAR SESSION I

        10:30 - 12:30
        DRAMATIC INTERPRETATION

        10:30 - 11:00
        MIDDLE SCHOOL CERTAMEN FINALS

        11:00 - 11:30
        SEMINAR SESSION II

        11:00 - 11:30
        ADVANCED CERTAMEN FINALS

        11:30 - 12:00
        INTERMEDIATE CERTAMEN FINALS

        12:00 - 12:30
        NOVICE CERTAMEN FINALS

        12:30 - 3:00
        GRAPHIC ARTS VIEWING

        12:45 - 1:30
        "MEET THE CANDIDATES" MEETING

        1:00 - 2:30
        LATIN SIGHT READING

        1:00 - 2:30
        ENGLISH ORATORY

        1:00 - 2:30
        OPEN CERTAMEN

        1:30 - 2:30
        OLYMPIKA I

        2:00
        VOTING BALLOTS DUE

        3:00 - 4:00
        OLYMPIKA II

        3:00 - 3:30
        CHARIOT RACING AND CATAPULT

        3:00 - 3:30
        GRAPHIC ARTS PICKUP

        4:20 - 4:30
        SPIRIT COMPETITION

        4:30 - 5:00
        CLOSING GENERAL ASSEMBLY

```

Yep. You cannot transition height reliably in CSS3. (min-height eventually, but even than it's not perfect)

Body:
Here's my problem: I have an image slider that's refusing to actually slide. I've spent the last two hours browsing answers here, and looking at JSFiddles. Nothing seems to be of any help.

This is my problem: I have an HTML table contained within a div, with given properties below. When the button at the top is clicked, the slider (the div with id "slider") is supposed to toggle via a slide animation. But instead, it appears or disappears without an animation!

I've made sure it has a height and width, and everything else that various answers said it needs (though if I didn't have to define a height and width in px, thus letting it expand or contract to however large or small it needs to be, would be great). But yet there's no animation! It just disappears!

Please help!

Also, most of the HTML is the table which you can ignore. Just the beginning and end are important.

SPRING CONVENTION SCHEDULE OF EVENTS

<button id="toggleSwitch" onClick="toggleFlipFlop();">Click here to show table</button>

SCHEDULE OF EVENTS FOR FRIDAY, MARCH 31

3:45 - 5:00
CONVENTION REGISTRATION

4:30 - 5:15
GRAPHIC ARTS REGISTRATION

4:30 - 4:50
CANDIDATES MEETING

5:15 - 5:25
SPIRIT COMPETITION

5:25 - 6:00
GENERAL ASSEMBLY

7:00 - 9:00
COSTUME CONTEST

7:30 - 9:00
SKIT CONTEST

7:15 - 8:00
ESSAY CONTEST

8:00 - 8:30
IMPROMPTU ART

8:00 - 9:30
SERVICE PROJECT

8:00 - 9:30
BOARD GAMES

SCHEDULE OF EVENTS FOR SATURDAY, APRIL 1

8:00 - 9:00
SCRAPBOOK CHECK-IN

8:00 - 9:00
GRAPHIC ARTS

8:15 - 8:45
CONVENTION REGISTRATION AND SATURDAY CHECK-IN

9:00 - 10:00
ACADEMIC TESTING (all levels)

10:15 - 10:45
SEMINAR SESSION I

10:30 - 12:30
DRAMATIC INTERPRETATION

10:30 - 11:00
MIDDLE SCHOOL CERTAMEN FINALS

11:00 - 11:30
SEMINAR SESSION II

11:00 - 11:30
ADVANCED CERTAMEN FINALS

11:30 - 12:00
INTERMEDIATE CERTAMEN FINALS

12:00 - 12:30
NOVICE CERTAMEN FINALS

12:30 - 3:00
GRAPHIC ARTS VIEWING

12:45 - 1:30
"MEET THE CANDIDATES" MEETING

1:00 - 2:30
LATIN SIGHT READING

1:00 - 2:30
ENGLISH ORATORY

1:00 - 2:30
OPEN CERTAMEN

1:30 - 2:30
OLYMPIKA I

2:00
VOTING BALLOTS DUE

3:00 - 4:00
OLYMPIKA II

3:00 - 3:30
CHARIOT RACING AND CATAPULT

3:00 - 3:30
GRAPHIC ARTS PICKUP

4:20 - 4:30
SPIRIT COMPETITION

4:30 - 5:00
CLOSING GENERAL ASSEMBLY

And my CSS:

#slider{
height: 1530px;
width: 524.317px;
transition: all 2s ease-in-out;
}
.hidden{
    height: 0;
}

And the JS:

//script for slide down reveal for table
//to avoid taking up too much space
function toggleFlipFlop() {
    var toggleSwitch = $("#toggleSwitch");
    var slider = $("#slider");
    console.log("HTML elements translated to objects");
    function slideMe(slider) {
        slider.toggleClass("hidden");
        console.log("hidden class toggled");
    };
    console.log("SlideMe() successfully defined");
    toggleSwitch.onclick = slideMe(slider);
    console.log("onclick attribute of toggleswitch set");
}

Body:
You're over complicating. You use an inline onClick that calls a function that instantiates a function that calls again a click on the same button... ehh

Also, since you cannot reliably animate/toggle height in CSS3 use jQuery slideToggle()

function toggleFlipFlop() {
  $("#slider").slideToggle(1000);
}

// REMOVE inline JS: onClick="toggleFlipFlop();"
// and use this:
$("#toggleSwitch").on("click", toggleFlipFlop);

#slider {
  height: 1530px;
  width: 524.317px;
  /*transition: all 1s ease-in-out; you cannot use this I'm sorry. */
}

.hidden {
  display: none; /* use this instead */
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2><strong>SPRING CONVENTION SCHEDULE OF EVENTS</strong></h2>
<br>
<button id="toggleSwitch">Click here to show table</button>

<!--table for Friday events-->
<div id="slider" class="hidden">
  <table id="friday-table">
    <tbody>
      <tr>
        <th colspan="2"><strong>SCHEDULE OF EVENTS FOR FRIDAY, MARCH 31</strong></th>
      </tr>
      <tr>
        <td>3:45 - 5:00</td>
        <td>CONVENTION REGISTRATION</td>
      </tr>
      <tr>
        <td>4:30 - 5:15</td>
        <td>GRAPHIC ARTS REGISTRATION</td>
      </tr>
      <tr>
        <td>4:30 - 4:50</td>
        <td>CANDIDATES MEETING</td>
      </tr>
      <tr>
        <td>5:15 - 5:25</td>
        <td>SPIRIT COMPETITION</td>
      </tr>
      <tr>
        <td>5:25 - 6:00</td>
        <td>GENERAL ASSEMBLY</td>
      </tr>
      <tr>
        <td>7:00 - 9:00</td>
        <td>COSTUME CONTEST</td>
      </tr>
      <tr>
        <td>7:30 - 9:00</td>
        <td>SKIT CONTEST</td>
      </tr>
      <tr>
        <td>7:15 - 8:00</td>
        <td>ESSAY CONTEST</td>
      </tr>
      <tr>
        <td>8:00 - 8:30</td>
        <td>IMPROMPTU ART</td>
      </tr>
      <tr>
        <td>8:00 - 9:30</td>
        <td>SERVICE PROJECT</td>
      </tr>
      <tr>
        <td>8:00 - 9:30</td>
        <td>BOARD GAMES</td>
      </tr>
    </tbody>
  </table>
  <!--table for Saturday events-->
  <table id="saturday-table">
    <tbody>
      <tr>
        <th colspan="2"><strong>SCHEDULE OF EVENTS FOR SATURDAY, APRIL 1</strong></th>
      </tr>
      <tr>
        <td>8:00 - 9:00</td>
        <td>SCRAPBOOK CHECK-IN</td>
      </tr>
      <tr>
        <td>8:00 - 9:00</td>
        <td>GRAPHIC ARTS</td>
      </tr>
      <tr>
        <td>8:15 - 8:45</td>
        <td>CONVENTION REGISTRATION AND SATURDAY CHECK-IN</td>
      </tr>
      <tr>
        <td>9:00 - 10:00</td>
        <td>ACADEMIC TESTING (all levels)</td>
      </tr>
      <tr>
        <td>10:15 - 10:45</td>
        <td>SEMINAR SESSION I</td>
      </tr>
      <tr>
        <td>10:30 - 12:30</td>
        <td>DRAMATIC INTERPRETATION</td>
      </tr>
      <tr>
        <td>10:30 - 11:00</td>
        <td>MIDDLE SCHOOL CERTAMEN FINALS</td>
      </tr>
      <tr>
        <td>11:00 - 11:30</td>
        <td>SEMINAR SESSION II</td>
      </tr>
      <tr>
        <td>11:00 - 11:30</td>
        <td>ADVANCED CERTAMEN FINALS</td>
      </tr>
      <tr>
        <td>11:30 - 12:00</td>
        <td>INTERMEDIATE CERTAMEN FINALS</td>
      </tr>
      <tr>
        <td>12:00 - 12:30</td>
        <td>NOVICE CERTAMEN FINALS</td>
      </tr>
      <tr>
        <td>12:30 - 3:00</td>
        <td>GRAPHIC ARTS VIEWING</td>
      </tr>
      <tr>
        <td>12:45 - 1:30</td>
        <td>"MEET THE CANDIDATES" MEETING</td>
      </tr>
      <tr>
        <td>1:00 - 2:30</td>
        <td>LATIN SIGHT READING</td>
      </tr>
      <tr>
        <td>1:00 - 2:30</td>
        <td>ENGLISH ORATORY</td>
      </tr>
      <tr>
        <td>1:00 - 2:30</td>
        <td>OPEN CERTAMEN</td>
      </tr>
      <tr>
        <td>1:30 - 2:30</td>
        <td>OLYMPIKA I</td>
      </tr>
      <tr>
        <td>2:00</td>
        <td>VOTING BALLOTS DUE</td>
      </tr>
      <tr>
        <td>3:00 - 4:00</td>
        <td>OLYMPIKA II</td>
      </tr>
      <tr>
        <td>3:00 - 3:30</td>
        <td>CHARIOT RACING AND CATAPULT</td>
      </tr>
      <tr>
        <td>3:00 - 3:30</td>
        <td>GRAPHIC ARTS PICKUP</td>
      </tr>
      <tr>
        <td>4:20 - 4:30</td>
        <td>SPIRIT COMPETITION</td>
      </tr>
      <tr>
        <td>4:30 - 5:00</td>
        <td>CLOSING GENERAL ASSEMBLY</td>
      </tr>
    </tbody>
  </table>
</div>

Yep. You cannot transition height reliably in CSS3. (min-height eventually, but even than it's not perfect)


问:
AxMSTSCLib Logoff
I'm currently developing a tool that uses remote desktop sessions using the RDP protocol. I'm able to connect and disconnect to a remote desktop but I want to add the logoff functionality to it. I've looked far and wide in the various documentation but have not been successful yet.

I'm currently using AxMsRdpClient6NotSafeForScripting because I'm not yet able to get it working with the regular AxMsRdpClient6 without the NotSafeForScripting (or with any other version for that matter). So the issue is probably that this doesn't support logoff and I have to use the AxMsRdpClient6 version, I suppose ...

Any help or suggestions would be greatly appreciated.

A demo of the code I'm currently using can be found below

```<code>        AxMsRdpClient6NotSafeForScripting rdp = new AxMsRdpClient6NotSafeForScripting();
        host.Child = rdp;
        rdp.CreateControl();
        rdp.Server = serverName;
        rdp.UserName = username;
        IMsTscNonScriptable secured = (IMsTscNonScriptable)rdp.GetOcx();
        IMsRdpClient10 client = (IMsRdpClient10)rdp.GetOcx();
        client.DesktopHeight = 750;
        client.DesktopWidth = 750;
        secured.ClearTextPassword = pwd;

        rdp.Connect();
</code>```

答:
This is independent of the ActiveX control version you use actually - the control doesn't have a logoff method, because it isn't an action exposed by the RDP protocol (at least as far as I remember).

It is possible to remotely log off your RDP session, but you have to use the Win32 WTSLogoffSession function (https://msdn.microsoft.com/en-us/library/aa383836(v=vs.85).aspx) to do it. Unfortunately that's a little painful to do from C# since you'd need to deal with PInvoke and marshalling structures in order to find the right session, but it should at least be possible.

Title: AxMSTSCLib Logoff

Body:
I'm currently developing a tool that uses remote desktop sessions using the RDP protocol. I'm able to connect and disconnect to a remote desktop but I want to add the logoff functionality to it. I've looked far and wide in the various documentation but have not been successful yet.

I'm currently using AxMsRdpClient6NotSafeForScripting because I'm not yet able to get it working with the regular AxMsRdpClient6 without the NotSafeForScripting (or with any other version for that matter). So the issue is probably that this doesn't support logoff and I have to use the AxMsRdpClient6 version, I suppose ...

Any help or suggestions would be greatly appreciated.

A demo of the code I'm currently using can be found below

        AxMsRdpClient6NotSafeForScripting rdp = new AxMsRdpClient6NotSafeForScripting();
        host.Child = rdp;
        rdp.CreateControl();
        rdp.Server = serverName;
        rdp.UserName = username;
        IMsTscNonScriptable secured = (IMsTscNonScriptable)rdp.GetOcx();
        IMsRdpClient10 client = (IMsRdpClient10)rdp.GetOcx();
        client.DesktopHeight = 750;
        client.DesktopWidth = 750;
        secured.ClearTextPassword = pwd;

        rdp.Connect();


问:
How to pass parent object's id along with my serialised sortable items?
I've got an Ajax call from the stop event of my jQuery UI sortable that currently looks like this:

```<code>...
stop:function(event, ui) {
    $.ajax({
        type: "POST",
        url: "<?php echo site_url('messages/reorder'); ?>",
        data: $("#messagelist").sortable("serialize")
    });
...
</code>```

Now, that's fine, and it's working (messages/reorder is a server-side Ajax function that updates the database based on the serialised IDs.)

However, I have multiple lists I could be editing from this page, and I need to pass along the ID of the "parent" object of the list, too.

Is there a standard way of doing this? I know the ID server-side when generating the page. Is there a best-practice way of adding the ID to the "data" that's passed along in my Ajax call?

Sorry if I'm missing something obvious; I'm fairly new to jQuery and Javascript and entirely new to "sortable"...

答:
I ended up doing this by the simple expedient of:</p>

```<code>data: "parent_id=" + p_id + "&" + $("#messagelist tbody").sortable("serialize")
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I've got an Ajax call from the stop event of my jQuery UI sortable that currently looks like this:

...
stop:function(event, ui) {
    $.ajax({
        type: "POST",
        url: "<?php echo site_url('messages/reorder'); ?>",
        data: $("#messagelist").sortable("serialize")
    });
...

Now, that's fine, and it's working (messages/reorder is a server-side Ajax function that updates the database based on the serialised IDs.)

However, I have multiple lists I could be editing from this page, and I need to pass along the ID of the "parent" object of the list, too.

Is there a standard way of doing this? I know the ID server-side when generating the page. Is there a best-practice way of adding the ID to the "data" that's passed along in my Ajax call?

Sorry if I'm missing something obvious; I'm fairly new to jQuery and Javascript and entirely new to "sortable"...

Body:
I ended up doing this by the simple expedient of:

data: "parent_id=" + p_id + "&" + $("#messagelist tbody").sortable("serialize")


问:
How can I check if there is a value for a key in local storage?
The user should only be able to store information if there is not a preexisting value stored to the key. How can i check if there is already a value, and alert the user that there is already a value? I know i have to use an if statement. If there is a value alert the user. Else set item...(save the object). But how do i check for the value?</p>

```<code>function addEvent() {
    var announcement = {
        title: document.getElementById('title').value,
        group: document.getElementById('group').value,
        author: document.getElementById('author').value,
        type: document.getElementById('type').value,
        date: document.getElementById('date').value,
        time: document.getElementById('time').value,
        gender: document.getElementById('gender').value,
        grade: document.getElementById('grade').value,
        message: document.getElementById('message').value
    };
    var objS = JSON.stringify(announcement);

    localStorage.setItem('announcement', objS);

    alert('Announcement successfully stored!');
}

function showA() {
    var getObj = localStorage.getItem('announcement');
    var objP = JSON.parse(getObj);

    document.getElementById('showAnnouncement').innerHTML = "Announcement"+"<br/>Title:"+objP.title+"<br/>Group:"+objP.group+"<br />Author:"+objP.author+"<br />Type:"+objP.type+"<br/>Date:"+objP.date+"<br />Time:"+objP.time+"<br/>Gender:"+objP.gender+"<br/>Grades:"+objP.grade+"<br />Message:"+objP.message;
}
</code>```

答:
I think the following code snippet can help you!</p>

```<code>var getObj = localStorage.getItem('announcement');
var obj = JSON.parse(getObj);
for (key in obj) {
  if(obj[key] !== ''){
   alert(key + 'is existed');
  }else{
   var newValue = document.getElementById(key).value;
   obj[key] = newValue == '' ? '' : newValue;
  }
}
var newObjS = JSON.stringify(obj);

localStorage.setItem('announcement', newObjS);
</code>```

Body:
The user should only be able to store information if there is not a preexisting value stored to the key. How can i check if there is already a value, and alert the user that there is already a value? I know i have to use an if statement. If there is a value alert the user. Else set item...(save the object). But how do i check for the value?

function addEvent() {
    var announcement = {
        title: document.getElementById('title').value,
        group: document.getElementById('group').value,
        author: document.getElementById('author').value,
        type: document.getElementById('type').value,
        date: document.getElementById('date').value,
        time: document.getElementById('time').value,
        gender: document.getElementById('gender').value,
        grade: document.getElementById('grade').value,
        message: document.getElementById('message').value
    };
    var objS = JSON.stringify(announcement);

    localStorage.setItem('announcement', objS);

    alert('Announcement successfully stored!');
}

function showA() {
    var getObj = localStorage.getItem('announcement');
    var objP = JSON.parse(getObj);

    document.getElementById('showAnnouncement').innerHTML = "Announcement"+"
Title:"+objP.title+"
Group:"+objP.group+"
Author:"+objP.author+"
Type:"+objP.type+"
Date:"+objP.date+"
Time:"+objP.time+"
Gender:"+objP.gender+"
Grades:"+objP.grade+"
Message:"+objP.message;
}

Body:
I think the following code snippet can help you!

var getObj = localStorage.getItem('announcement');
var obj = JSON.parse(getObj);
for (key in obj) {
  if(obj[key] !== ''){
   alert(key + 'is existed');
  }else{
   var newValue = document.getElementById(key).value;
   obj[key] = newValue == '' ? '' : newValue;
  }
}
var newObjS = JSON.stringify(obj);

localStorage.setItem('announcement', newObjS);


问:
MSBuild and IgnoreStandardErrorWarningFormat
I'm trying to write a MSBuild project that will generate html documentation using doxygen. I couldn't find anything about that on the net except for one example, which seems incomplete; it doesn't parse doxygen warnings.

I found that MSBuild's Exec task has parameters like IgnoreStandardErrorWarningFormat and CustomWarningRegularExpression. What is the "Standard Error/Warning Format" and what kind of REs are allowed in these properties?

Edit: ah, "Inside the Microsoft Build Engine" wrongly describes it as property in .NET 3.5, where it is actually from 4. No use for me...

答: The format is fully documented in the MSBuild source code here.</p>


问:
Modify CSS to hide
I need to hide the "Actions" menu from a document library's toolbar. I know in CSS I can use this "{display: none}" syntax to hide.

Can someone please help find me the right place where I need to put this? I found this .ms-actionbar but dont know if this guy belong to list toolbar or site toolbar.

For example:  http://www.xsolive.com/Shared%20Documents/Forms/AllItems.aspx

答: use fire bug in FF to get the CSS class name by doing inspect element</p>

Title: Modify CSS to hide


问:
Insert read only strings into jTextArea
I am working in a translator that receive relational algebra expressions and translates them into SQL queries, I've already made the translator code, but I'm having some trouble validating the user's inputs.

The translator works with buttons that insert a default expression in the text area and gives the user a blank space to enter some parameters, here's an example:

```<code> Seleccionar(-the user enters parameters here-)( -the user enters parameters here- )
</code>```

Is there a way to make the word "Seleccionar" and the brackets read-only? So the user can't edit the default expressions?

答:
Is there a way to make the word "Seleccionar" and the brackets read-only? So the user can't edit the default expressions?

Check out the Protected Text Component. It allows you to prevent multiple areas of text from being changed.

The implementation uses a custom DocumentFilter and NavigationFilter to implement the custom functionality.

Title: Insert read only strings into jTextArea

Body:
I am working in a translator that receive relational algebra expressions and translates them into SQL queries, I've already made the translator code, but I'm having some trouble validating the user's inputs.

The translator works with buttons that insert a default expression in the text area and gives the user a blank space to enter some parameters, here's an example:

 Seleccionar(-the user enters parameters here-)( -the user enters parameters here- )

Is there a way to make the word "Seleccionar" and the brackets read-only? So the user can't edit the default expressions?


问:
Can I connect to socket.io server using generic method?
I have a node.js server and I attached socket.io listener to it. The code is like this.

```<code>const server = new Hapi.Server();
    server.connection({
        "port": config.port
    });

let io = socketio(server.listener);
io.on("connection", function(socket) {
        console.log("A user connected");

        socket.on("disconnect", function(){
            console.log("A user disconnected");
        });

        // receive message from client
        socket.on("client-server", function(msg) {
            console.log(msg);
        });
    });

// somewhere to emit message
io.emit("server-client", "server to client message");
</code>```

Normally I use the standard way to connect to the websocket server. An example is like this:

```<code><!DOCTYPE html>
<html>
  <head><title>Hello world</title></head>
  <script src="http://localhost:3000/socket.io/socket.io.js"></script>
  <script>
    var socket = io();
    socket.on('server-client', function(data) {document.write(data)});
    socket.emit('client-server', 'test message');
  </script>
  <body>Hello world</body>
</html>
</code>```

It works without issue. Now, my colleague wants to connect to the websocket server from his FME server. Based on his research, the only way he can use to connect to a websocket server is using a url like this:

```<code>ws://localhost:3000/websocket
</code>```

My question is: is there a way to connect to socket.io server listener using this type of string?

If not, is there a way to create a websocket server with ws://host:port url and also attach it to my node.js server?

Or, is there a way to connect to socket.io listener in FME server?

答:
To tell Socket.IO to use WebSocket only, add this on the server:

```<code>io.set('transports', ['websocket']);
</code>```

And on the client add this:

```<code>var socket = io({transports: ['websocket']});
</code>```

Now you can only connect to the WebSocket server using ws protocol.

Body:
I have a node.js server and I attached socket.io listener to it. The code is like this.

const server = new Hapi.Server();
    server.connection({
        "port": config.port
    });

let io = socketio(server.listener);
io.on("connection", function(socket) {
        console.log("A user connected");

        socket.on("disconnect", function(){
            console.log("A user disconnected");
        });

        // receive message from client
        socket.on("client-server", function(msg) {
            console.log(msg);
        });
    });

// somewhere to emit message
io.emit("server-client", "server to client message");

Normally I use the standard way to connect to the websocket server. An example is like this:

<!DOCTYPE html>

  <title>Hello world</title>

  Hello world

It works without issue. Now, my colleague wants to connect to the websocket server from his FME server. Based on his research, the only way he can use to connect to a websocket server is using a url like this:

ws://localhost:3000/websocket

My question is: is there a way to connect to socket.io server listener using this type of string?

If not, is there a way to create a websocket server with ws://host:port url and also attach it to my node.js server?

Or, is there a way to connect to socket.io listener in FME server?

Body:
To tell Socket.IO to use WebSocket only, add this on the server:

io.set('transports', ['websocket']);

And on the client add this:

var socket = io({transports: ['websocket']});

Now you can only connect to the WebSocket server using ws protocol.


问:
How to add an active class to only one parent element with Jquery?
I have the following html code for the quiz with 3 options. I would like to add the class .active to the .questionItem class.

```<code><ul class="questionList">
<li class="questionItem" data-pos="0"><span class="question">Question Text</span></li>
<li class="questionItem" data-pos="1"><span class="question">Question Text</span></li>
<li class="questionItem" data-pos="2"><span class="question">Question Text</span></li>
</ul>
</code>```

Currently I have the following code:

```<code>$(this).parent().find('.questionItem').addClass('active');
</code>```

However, this is adding active to ALL questionItems. Instead I want to add this class to exactly the questionItem class that was clicked on.

答:
It looks like this is referring to the clicked element, so simply use the $(this).  I added some click events to demonstrate how this works.

$(".questionItem").click(function () {
  $(this).addClass('active');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.active {
  background:red;
}</code>```

Question Text

Question Text

Question Text

```
</div>
</div>
</p>

<p>However, if you're instead trying to select the parent, you have no need for a <code>.find</code>:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(".questionItem").click(function () {
  $(this).parent().addClass('active');
});</code>```

.active {
  background:red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="questionList">
<li class="questionItem" data-pos="0"><span class="question">Question Text</span></li>
<li class="questionItem" data-pos="1"><span class="question">Question Text</span></li>
<li class="questionItem" data-pos="2"><span class="question">Question Text</span></li>
</ul></code>```

Body:
I have the following html code for the quiz with 3 options. I would like to add the class .active to the .questionItem class.

Question Text

Question Text

Question Text

Currently I have the following code:

$(this).parent().find('.questionItem').addClass('active');

However, this is adding active to ALL questionItems. Instead I want to add this class to exactly the questionItem class that was clicked on.

Body:
It looks like this is referring to the clicked element, so simply use the $(this).  I added some click events to demonstrate how this works.

$(".questionItem").click(function () {
  $(this).addClass('active');
});

.active {
  background:red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="questionList">
<li class="questionItem" data-pos="0"><span class="question">Question Text</span></li>
<li class="questionItem" data-pos="1"><span class="question">Question Text</span></li>
<li class="questionItem" data-pos="2"><span class="question">Question Text</span></li>
</ul>

However, if you're instead trying to select the parent, you have no need for a .find:

$(".questionItem").click(function () {
  $(this).parent().addClass('active');
});

.active {
  background:red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="questionList">
<li class="questionItem" data-pos="0"><span class="question">Question Text</span></li>
<li class="questionItem" data-pos="1"><span class="question">Question Text</span></li>
<li class="questionItem" data-pos="2"><span class="question">Question Text</span></li>
</ul>


问:
Opencart 2.3.0.2 How to display products of a particular category in front page with a flag
I created a category called "coming soon" and I want products of that category to display in front page and in all products page with a flag "Coming soon." How do I proceed. Your Help will be appreciated.</p>

答:
You can download this module
Show products of Category OpenCart 2.3.0.2 module for free

Installation:

Unzip the downloaded folder.

Upload the files in root folder to your server, no file is overwritten.

Then activate the “Category Products” module.


问:
Do you need to unbind/remove event listeners when navigating away from a React page?
I am making a web app in React. I currently have page A and page B. Page A has a few event listeners bound to various elements on the page. However, when I navigate from page A to page B, I get the following error show up repeatedly in my console (like dozens of errors in the span of a few seconds):

Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the LandingPageHeader component.

Do I need to unbind these listeners in my componentWillUnmount() function (of page A)? Or is something else going on? Also, does it matter that some of these event listeners are bound to the html tag?

It should also be noted that some of the event handlers for the above event listeners do perform functions that involve updating/setting the React state.

答:
Yes, you can unbind event listener in componentWillUnmount, or set a flag in page A component, check this flag every time before setState.

```<code>componentDidMount() {
    var _this = this;
    this._mounted = true;

    // in listenner function
    window.addEventListener('resize', funciton () {
        if (_this._mounted) {
            _this.setState({});
        }
    });
}

componentWillUnmount() {
    this._mounted = false;
}
</code>```

Body:
Yes, you can unbind event listener in componentWillUnmount, or set a flag in page A component, check this flag every time before setState.

componentDidMount() {
    var _this = this;
    this._mounted = true;

    // in listenner function
    window.addEventListener('resize', funciton () {
        if (_this._mounted) {
            _this.setState({});
        }
    });
}

componentWillUnmount() {
    this._mounted = false;
}


问:
SQL ecommerce database - getting count of products purchased by only one user
In my rails app I have a typical ecommerce schema inside a Postgres 9.6 database. Here's a simplified version of it:

```<code>users table
  :name

products table
  :name

shopping_carts table
 :user_id

line_items table
  :price
  :qty
  :product_id
  :shopping_cart_id
</code>```

I've got a working query to return the number of distinct products bought by each user:

```<code>SELECT COUNT(distinct p.*), u.name FROM products p
INNER JOIN line_items l ON p.id = l.product_id
INNER JOIN shopping_carts sc ON l.shopping_cart_id = sc.id
INNER JOIN users u ON sc.user_id = u.id
GROUP BY u.name
</code>```

But I also want a count of products for each user that only that particular user has purchased. A possible method for this in Ruby (once everything was set up with ActiveRecord) might look something like:

```<code>def unique_prod(user)
  user.products.select { |p| p.users.length == 1 }.count
end
</code>```

But how to do it in SQL? I think I need to do it using two counts - one for the number of different user_ids in a given product's shopping_carts (let's call this count user_count), and then a count of products for which user_count = 1. I'm having trouble incorporating the multiple COUNT and GROUP BY statements in working fashion. Any suggestions?

答:
To do it all in one query:

```<code>SELECT scl.user_id, u.name, ct_dist_prod, ct_dist_prod_exclusive
FROM  (
   SELECT sc.user_id
        , count(DISTINCT l.product_id) AS ct_dist_prod
        , count(DISTINCT l.product_id)
                FILTER (WHERE NOT EXISTS (
                           SELECT 1
                           FROM   shopping_carts sc1
                           JOIN   line_items     l1 ON l1.shopping_cart_id = sc1.id
                           WHERE  l1.product_id = l.product_id
                           AND    sc1.user_id  <> sc.user_id)) AS ct_dist_prod_exclusive
   FROM   shopping_carts sc
   JOIN   line_items     l ON l.shopping_cart_id = sc.id
   GROUP  BY 1
   ) scl
JOIN   users u ON u.id = scl.user_id;
</code>```

I added the user_id to the result, because I cannot assume that name is defined unique (which would make your original query slightly incorrect).

The aggregate FILTER clause requires Postgres 9.4 or later:

How can I simplify this game statistics query?

How?

Assuming referential integrity enforced by a FK constraint, you do not need to join to the table products at all for this query.

Neither, at first, to the users table. The basic query boils down to:

```<code>SELECT sc.user_id, count(DISTINCT l.product_id)
FROM   shopping_carts sc
JOIN   line_items     l ON l.shopping_cart_id = sc.id
GROUP  BY 1;
</code>```

Add the 2nd count to this cheaper query, where all rows with products are excluded for which another row with the same product and a different user exists (i.e. bought by a different user, too).

Then join to users to add the name. Cheaper.

Computing only the exclusive count is simpler. Example:

```<code>SELECT sc.user_id, count(DISTINCT l.product_id) AS ct_dist_prod_exclusive
FROM   shopping_carts  sc
JOIN   line_items      l ON l.shopping_cart_id = sc.id
LEFT   JOIN (
             shopping_carts sc1
       JOIN  line_items     l1 ON l1.shopping_cart_id = sc1.id
       ) ON l1.product_id = l.product_id
    AND sc1.user_id <> sc.user_id
WHERE  l1.product_id IS NULL
GROUP  BY 1;
</code>```

Note the essential parentheses.

Related:

Select rows which are not present in other table

Or (in response to your comment):

```<code>SELECT user_id, count(*) AS ct_dist_prod_exclusive
FROM  (
   SELECT max(user_id) AS user_id, l1.product_id
   FROM   line_items l1
   INNER  JOIN shopping_carts sc1 ON l.shopping_cart_id = sc1.id
   GROUP  BY l1.product_id
   HAVING COUNT(DISTINCT sc1.user_id) = 1  -- DISTINCT!
   ) p1
GROUP  BY user_id;
</code>```

HAVING COUNT(DISTINCT sc1.user_id) = 1 because

products purchased by only one user

allows the product to be bought by the same user multiple times.

Body:
In my rails app I have a typical ecommerce schema inside a Postgres 9.6 database. Here's a simplified version of it:

users table
  :name

products table
  :name

shopping_carts table
 :user_id

line_items table
  :price
  :qty
  :product_id
  :shopping_cart_id

I've got a working query to return the number of distinct products bought by each user:

SELECT COUNT(distinct p.*), u.name FROM products p
INNER JOIN line_items l ON p.id = l.product_id
INNER JOIN shopping_carts sc ON l.shopping_cart_id = sc.id
INNER JOIN users u ON sc.user_id = u.id
GROUP BY u.name

But I also want a count of products for each user that only that particular user has purchased. A possible method for this in Ruby (once everything was set up with ActiveRecord) might look something like:

def unique_prod(user)
  user.products.select { |p| p.users.length == 1 }.count
end

But how to do it in SQL? I think I need to do it using two counts - one for the number of different user_ids in a given product's shopping_carts (let's call this count user_count), and then a count of products for which user_count = 1. I'm having trouble incorporating the multiple COUNT and GROUP BY statements in working fashion. Any suggestions?

Body:
To do it all in one query:

SELECT scl.user_id, u.name, ct_dist_prod, ct_dist_prod_exclusive
FROM  (
   SELECT sc.user_id
        , count(DISTINCT l.product_id) AS ct_dist_prod
        , count(DISTINCT l.product_id)
                FILTER (WHERE NOT EXISTS (
                           SELECT 1
                           FROM   shopping_carts sc1
                           JOIN   line_items     l1 ON l1.shopping_cart_id = sc1.id
                           WHERE  l1.product_id = l.product_id
                           AND    sc1.user_id  <> sc.user_id)) AS ct_dist_prod_exclusive
   FROM   shopping_carts sc
   JOIN   line_items     l ON l.shopping_cart_id = sc.id
   GROUP  BY 1
   ) scl
JOIN   users u ON u.id = scl.user_id;

I added the user_id to the result, because I cannot assume that name is defined unique (which would make your original query slightly incorrect).

The aggregate FILTER clause requires Postgres 9.4 or later:

How can I simplify this game statistics query?

How?

Assuming referential integrity enforced by a FK constraint, you do not need to join to the table products at all for this query.

Neither, at first, to the users table. The basic query boils down to:

SELECT sc.user_id, count(DISTINCT l.product_id)
FROM   shopping_carts sc
JOIN   line_items     l ON l.shopping_cart_id = sc.id
GROUP  BY 1;

Add the 2nd count to this cheaper query, where all rows with products are excluded for which another row with the same product and a different user exists (i.e. bought by a different user, too).

Then join to users to add the name. Cheaper.

Computing only the exclusive count is simpler. Example:

SELECT sc.user_id, count(DISTINCT l.product_id) AS ct_dist_prod_exclusive
FROM   shopping_carts  sc
JOIN   line_items      l ON l.shopping_cart_id = sc.id
LEFT   JOIN (
             shopping_carts sc1
       JOIN  line_items     l1 ON l1.shopping_cart_id = sc1.id
       ) ON l1.product_id = l.product_id
    AND sc1.user_id <> sc.user_id
WHERE  l1.product_id IS NULL
GROUP  BY 1;

Note the essential parentheses.

Related:

Select rows which are not present in other table

Or (in response to your comment):

SELECT user_id, count(*) AS ct_dist_prod_exclusive
FROM  (
   SELECT max(user_id) AS user_id, l1.product_id
   FROM   line_items l1
   INNER  JOIN shopping_carts sc1 ON l.shopping_cart_id = sc1.id
   GROUP  BY l1.product_id
   HAVING COUNT(DISTINCT sc1.user_id) = 1  -- DISTINCT!
   ) p1
GROUP  BY user_id;

HAVING COUNT(DISTINCT sc1.user_id) = 1 because

products purchased by only one user

allows the product to be bought by the same user multiple times.


问:
Bind9 and MySQL DLZ Buffer Error
I compiled Bind 9 from source (see below) and set up Bind9 with MySQL DLZ.
I keep getting an error when I attempt to fetch anything from the server about buffer overflow. I've googled many times but can not find anything on how to fix this error.

Configure options:

root@anacrusis:/opt/bind9/bind-9.9.1-P3# named -V BIND 9.9.1-P3 built
  with '--prefix=/opt/bind9' '--mandir=/opt/bind9/man'
  '--infodir=/opt/bind9/info' '--sysconfdir=/opt/bind9/config'
  '--localstatedir=/opt/bind9/var' '--enable-threads'
  '--enable-largefile' '--with-libtool' '--enable-shared'
  '--enable-static' '--with-openssl=/usr' '--with-gssapi=/usr'
  '--with-gnu-ld' '--with-dlz-postgres=no' '--with-dlz-mysql=yes'
  '--with-dlz-bdb=no' '--with-dlz-filesystem=yes' '--with-dlz-stub=yes'
  '--with-dlz-ldap=yes' '--enable-ipv6' 'CFLAGS=-fno-strict-aliasing
  -DDIG_SIGCHASE -O2' 'LDFLAGS=-Wl,-Bsymbolic-functions' 'CPPFLAGS=' using OpenSSL version: OpenSSL 1.0.1 14 Mar 2012 using libxml2
  version: 2.7.8

This is the error I get when I dig example.com (with debug):

Query String: select ttl, type, mx_priority, case when
  lower(type)='txt' then concat('"', data, '"')
          else data end from dns_records where zone = 'example.com' and host = '@'

17-Sep-2012 01:09:33.610 dns_rdata_fromtext: buffer-0x7f5bfca73360:1:
  unexpected end of input 17-Sep-2012 01:09:33.610 dns_sdlz_putrr
  returned error. Error code was: unexpected end of input 17-Sep-2012
  01:09:33.610 Query String: select ttl, type, mx_priority, case when
  lower(type)='txt' then concat('"', data, '"')
          else data end from dns_records where zone = 'example.com' and host = '*'

17-Sep-2012 01:09:33.610 query.c:2579: fatal error: 17-Sep-2012
  01:09:33.610 RUNTIME_CHECK(result == 0) failed 17-Sep-2012
  01:09:33.610 exiting (due to fatal error in library)

Named.conf

```<code>options {
    directory "/opt/bind9/";
    allow-query-cache { none; };
    allow-query { any; };
    recursion no;
};

dlz "Mysql zone" {
    database "mysql
    {host=localhost dbname=system ssl=false user=root pass=*password*}
    {select zone from dns_records where zone = '$zone$'}
    {select ttl, type, mx_priority, case when lower(type)='txt' then concat('\"', data, '\"')
        else data end from dns_records where zone = '$zone$' and host = '$record$'}
    {}
    {}
    {}
    {}";
};
</code>```

答:
I have gotten Bind with DLZ working on CentOS 7. I do not get the error that is effecting you.

I realize this is an older post but I thought I would share my conf files , and configure options.

I am using Bind 9.11.0

configure

```<code> ./configure --prefix=/usr --sysconfdir=/etc/bind --localstatedir=/var --mandir=/usr/share/man --infodir=/usr/share/info --enable-threads --enable-largefile --with-libtool --enable-shared --enable-static --with-openssl=/usr --with-gssapi=/usr --with-gnu-ld --with-dlz-postgres=no --with-dlz-mysql=yes --with-dlz-bdb=no --with-dlz-filesystem=yes --with-dlz-stub=yes --enable-ipv6
</code>```

named.conf

```<code>// This is the primary configuration file for the BIND DNS server named.
//
// Please read /usr/share/doc/bind9/README.Debian.gz for information on the
// structure of BIND configuration files in Debian, *BEFORE* you customize
// this configuration file.
//
// If you are just adding zones, please do that in /etc/bind/named.conf.local
#auskommentiert !!!
#include "/etc/bind/named.conf.options";
#include "/etc/bind/named.conf.local";
#include "/etc/bind/named.conf.default-zones";

key "rndc-key" {
            // how was key encoded
            algorithm hmac-md5;
            // what is the pass-phrase for the key
                secret "noway";
             };

#options {
#default-key "rndc-key";
#default-server 127.0.0.1;
#default-port 953;
#};

controls {
inet * port 953 allow { any; } keys { "rndc-key"; };
#inet * port 53 allow { any; } keys { "rndc-key"; };
};

logging {
    channel query.log {
        file "/var/log/query.log";
        // Set the severity to dynamic to see all the debug messages.
        severity dynamic;
    };

    category queries { query.log; };
};

dlz "Mysql zone" {
   database "mysql
   {host=172.16.254.100 port=3306 dbname=dyn_server_db user=db_user pass=db_password}
   {SELECT zone FROM dyn_dns_records WHERE zone = '$zone$'}
   {SELECT ttl, type, mx_priority, IF(type = 'TXT', CONCAT('\"',data,'\"'), data) AS data
    FROM dyn_dns_records
    WHERE zone = '$zone$' AND host = '$record$' AND type <> 'SOA' AND type <> 'NS'}
   {SELECT ttl, type, data, primary_ns, resp_person, serial, refresh, retry, expire, minimum
    FROM dyn_dns_records
    WHERE zone = '$zone$' AND (type = 'SOA' OR type='NS')}
   {SELECT ttl, type, host, mx_priority, IF(type = 'TXT', CONCAT('\"',data,'\"'), data) AS data, resp_person, serial, refresh, retry, expire, minimum
    FROM dyn_dns_records
    WHERE zone = '$zone$' AND type <> 'SOA' AND type <> 'NS'}
   {SELECT zone FROM xfr_table where zone='$zone$' AND client = '$client$'}";
};
</code>```

Title: Bind9 and MySQL DLZ Buffer Error

Body:
I compiled Bind 9 from source (see below) and set up Bind9 with MySQL DLZ.
I keep getting an error when I attempt to fetch anything from the server about buffer overflow. I've googled many times but can not find anything on how to fix this error.

Configure options:

root@anacrusis:/opt/bind9/bind-9.9.1-P3# named -V BIND 9.9.1-P3 built
  with '--prefix=/opt/bind9' '--mandir=/opt/bind9/man'
  '--infodir=/opt/bind9/info' '--sysconfdir=/opt/bind9/config'
  '--localstatedir=/opt/bind9/var' '--enable-threads'
  '--enable-largefile' '--with-libtool' '--enable-shared'
  '--enable-static' '--with-openssl=/usr' '--with-gssapi=/usr'
  '--with-gnu-ld' '--with-dlz-postgres=no' '--with-dlz-mysql=yes'
  '--with-dlz-bdb=no' '--with-dlz-filesystem=yes' '--with-dlz-stub=yes'
  '--with-dlz-ldap=yes' '--enable-ipv6' 'CFLAGS=-fno-strict-aliasing
  -DDIG_SIGCHASE -O2' 'LDFLAGS=-Wl,-Bsymbolic-functions' 'CPPFLAGS=' using OpenSSL version: OpenSSL 1.0.1 14 Mar 2012 using libxml2
  version: 2.7.8

This is the error I get when I dig example.com (with debug):

Query String: select ttl, type, mx_priority, case when
  lower(type)='txt' then concat('"', data, '"')
          else data end from dns_records where zone = 'example.com' and host = '@'

17-Sep-2012 01:09:33.610 dns_rdata_fromtext: buffer-0x7f5bfca73360:1:
  unexpected end of input 17-Sep-2012 01:09:33.610 dns_sdlz_putrr
  returned error. Error code was: unexpected end of input 17-Sep-2012
  01:09:33.610 Query String: select ttl, type, mx_priority, case when
  lower(type)='txt' then concat('"', data, '"')
          else data end from dns_records where zone = 'example.com' and host = '*'

17-Sep-2012 01:09:33.610 query.c:2579: fatal error: 17-Sep-2012
  01:09:33.610 RUNTIME_CHECK(result == 0) failed 17-Sep-2012
  01:09:33.610 exiting (due to fatal error in library)

Named.conf

options {
    directory "/opt/bind9/";
    allow-query-cache { none; };
    allow-query { any; };
    recursion no;
};

dlz "Mysql zone" {
    database "mysql
    {host=localhost dbname=system ssl=false user=root pass=*password*}
    {select zone from dns_records where zone = '$zone$'}
    {select ttl, type, mx_priority, case when lower(type)='txt' then concat('\"', data, '\"')
        else data end from dns_records where zone = '$zone$' and host = '$record$'}
    {}
    {}
    {}
    {}";
};

Body:
I have gotten Bind with DLZ working on CentOS 7. I do not get the error that is effecting you.

I realize this is an older post but I thought I would share my conf files , and configure options.

I am using Bind 9.11.0

configure

 ./configure --prefix=/usr --sysconfdir=/etc/bind --localstatedir=/var --mandir=/usr/share/man --infodir=/usr/share/info --enable-threads --enable-largefile --with-libtool --enable-shared --enable-static --with-openssl=/usr --with-gssapi=/usr --with-gnu-ld --with-dlz-postgres=no --with-dlz-mysql=yes --with-dlz-bdb=no --with-dlz-filesystem=yes --with-dlz-stub=yes --enable-ipv6

named.conf

// This is the primary configuration file for the BIND DNS server named.
//
// Please read /usr/share/doc/bind9/README.Debian.gz for information on the
// structure of BIND configuration files in Debian, *BEFORE* you customize
// this configuration file.
//
// If you are just adding zones, please do that in /etc/bind/named.conf.local
#auskommentiert !!!
#include "/etc/bind/named.conf.options";
#include "/etc/bind/named.conf.local";
#include "/etc/bind/named.conf.default-zones";

key "rndc-key" {
            // how was key encoded
            algorithm hmac-md5;
            // what is the pass-phrase for the key
                secret "noway";
             };

#options {
#default-key "rndc-key";
#default-server 127.0.0.1;
#default-port 953;
#};

controls {
inet * port 953 allow { any; } keys { "rndc-key"; };
#inet * port 53 allow { any; } keys { "rndc-key"; };
};

logging {
    channel query.log {
        file "/var/log/query.log";
        // Set the severity to dynamic to see all the debug messages.
        severity dynamic;
    };

    category queries { query.log; };
};

dlz "Mysql zone" {
   database "mysql
   {host=172.16.254.100 port=3306 dbname=dyn_server_db user=db_user pass=db_password}
   {SELECT zone FROM dyn_dns_records WHERE zone = '$zone$'}
   {SELECT ttl, type, mx_priority, IF(type = 'TXT', CONCAT('\"',data,'\"'), data) AS data
    FROM dyn_dns_records
    WHERE zone = '$zone$' AND host = '$record$' AND type <> 'SOA' AND type <> 'NS'}
   {SELECT ttl, type, data, primary_ns, resp_person, serial, refresh, retry, expire, minimum
    FROM dyn_dns_records
    WHERE zone = '$zone$' AND (type = 'SOA' OR type='NS')}
   {SELECT ttl, type, host, mx_priority, IF(type = 'TXT', CONCAT('\"',data,'\"'), data) AS data, resp_person, serial, refresh, retry, expire, minimum
    FROM dyn_dns_records
    WHERE zone = '$zone$' AND type <> 'SOA' AND type <> 'NS'}
   {SELECT zone FROM xfr_table where zone='$zone$' AND client = '$client$'}";
};


问:
Good panel interface component for C#?
Any nice Paneled user interface component COM/ActiveX/Source-code for C#/VB?

Like what VS has internally:

Dock to screen edges

Slide open/close (unpinned)

Pin open

Group in tabs

And if possible, open-source/free.

Well, because otherwise I'd have to develop an interface system myself.

答: We use the DevExpress (devexpress.com) Component Suite, which has a Docking Manager that does that sort of thing.</p>

OwnerDisplayName: Jeremy Rudd

Title: Good panel interface component for C#?

OwnerDisplayName: Wade Hatler


问:
Python + MongoDB: How to connect to MongoDB from Python and write data?
I would like to connect to MongoDB from a Python script and write data directly onto it. Would like the DB to be filled like so:

```<code>John
Titles    Values
color     black
age       15

Laly
Titles    Values
color     pink
age       20
</code>```

Currently, it’s written to a .csv file like following, but would like to write it like so to MongoDB:

```<code>import csv

students_file = open(‘./students_file.csv’, ‘w’)
file_writer = csv.writer(students_file)

…

file_writer.writerow([name_title]) #John
file_writer.writerow([‘Titles’, ’Values’])
file_writer.writerow([color_title, color_val]) #In first column: color, in second column: black
file_writer.writerow([age_title, age_val]) #In first column: age, in second column: 15
</code>```

What would be the right approach to connecting to MongoDB using Python, and write strings directly to MongoDB?

Thank you in advance, and will be sure to upvote/accept answer

答:
```<code>#Try this:
from pymongo import MongoClient

# connect to the MongoDB
connection = MongoClient('mongodb://127.0.0.1:<port>')

# connect to test collection
db = connection.test

# create dictionary
student_record = {}

# save rec to dict
student_record = {'name': 'John Doe','grade': 'A+'}

#insert the record
db.test.insert(student_record)

# find all documents
results = db.test.find()

# display documents from collection
for record in results:
    out_name = str(record['name'])
    out_grade = str(record['grade'])
    print(out_name + ',' + out_grade)

# close the connection to MongoDB
connection.close()
</code>```

Body:
I would like to connect to MongoDB from a Python script and write data directly onto it. Would like the DB to be filled like so:

John
Titles    Values
color     black
age       15

Laly
Titles    Values
color     pink
age       20

Currently, it’s written to a .csv file like following, but would like to write it like so to MongoDB:

import csv

students_file = open(‘./students_file.csv’, ‘w’)
file_writer = csv.writer(students_file)

…

file_writer.writerow([name_title]) #John
file_writer.writerow([‘Titles’, ’Values’])
file_writer.writerow([color_title, color_val]) #In first column: color, in second column: black
file_writer.writerow([age_title, age_val]) #In first column: age, in second column: 15

What would be the right approach to connecting to MongoDB using Python, and write strings directly to MongoDB?

Thank you in advance, and will be sure to upvote/accept answer


答:
I think the following code will help you!</p>

```<code>$('.questionItem').click(function(){
  $(this).addClass('active').siblings().removeClass('active');
});
</code>```

Title: How to add an active class to only one parent element with Jquery?

Body:
I think the following code will help you!

$('.questionItem').click(function(){
  $(this).addClass('active').siblings().removeClass('active');
});


问:
Objective-C Block Literal Syntax Principle
i'm a iOS programer from china, I'm so sorry that i can't make an exact title for this question, but i'll try to describe it detailed. If there are any one can help me to change the title, i'm very thankful about that. Sorry for my bad English.

When i using clang -rewrite-objc to see the source code about the Block Syntax, i found there is something that i can't understand. Here is my code:

```<code>int main(int argc, char *argv[]) {
    void (^blk)() = ^ {
    };
    blk();
}
</code>```

And the core source code is

```<code>struct __block_impl {
  void *isa;
  int Flags;
  int Reserved;
  void *FuncPtr;
};

struct __main_block_impl_0 {
  struct __block_impl impl;
  struct __main_block_desc_0* Desc;
  __main_block_impl_0(void *fp, struct __main_block_desc_0 *desc, int flags=0) {
    impl.isa = &_NSConcreteStackBlock;
    impl.Flags = flags;
    impl.FuncPtr = fp;
    Desc = desc;
  }
};

static void __main_block_func_0(struct __main_block_impl_0 *__cself) {

 }

static struct __main_block_desc_0 {
  size_t reserved;
  size_t Block_size;
} __main_block_desc_0_DATA = { 0, sizeof(struct __main_block_impl_0)};

int main(int argc, char *argv[]) {
 void (*blk)() = ((void (*)())&__main_block_impl_0((void *)__main_block_func_0, &__main_block_desc_0_DATA));
 ((void (*)(__block_impl *))((__block_impl *)blk)->FuncPtr)((__block_impl *)blk);
}
</code>```

In the main function, when i call the blk(), the source code cast blk and take the FuncPtr by this code

```<code>((__block_impl *)blk)->FuncPtr)
</code>```

I can't really understand that, is it supposed to do? In my opinion, i prefer to use

```<code>(((__main_block_impl_0 *)blk ->impl).FuncPtr)
</code>```

I don't really know more about C++, if there is anyone who can help me to understand the principle of this code, i'll be very thankful. Thanks for you guys.

答: Well, struct __main_block_impl_0's first member (impl) is a struct __block_impl. So the location of the struct __main_block_impl_0 is the same as the location of the struct __block_impl that is its first member. If you have the pointer to one you can just treat it as a pointer to the other.

Body:
i'm a iOS programer from china, I'm so sorry that i can't make an exact title for this question, but i'll try to describe it detailed. If there are any one can help me to change the title, i'm very thankful about that. Sorry for my bad English.

When i using clang -rewrite-objc to see the source code about the Block Syntax, i found there is something that i can't understand. Here is my code:

int main(int argc, char *argv[]) {
    void (^blk)() = ^ {
    };
    blk();
}

And the core source code is

struct __block_impl {
  void *isa;
  int Flags;
  int Reserved;
  void *FuncPtr;
};

struct __main_block_impl_0 {
  struct __block_impl impl;
  struct __main_block_desc_0* Desc;
  __main_block_impl_0(void *fp, struct __main_block_desc_0 *desc, int flags=0) {
    impl.isa = &_NSConcreteStackBlock;
    impl.Flags = flags;
    impl.FuncPtr = fp;
    Desc = desc;
  }
};

static void __main_block_func_0(struct __main_block_impl_0 *__cself) {

 }

static struct __main_block_desc_0 {
  size_t reserved;
  size_t Block_size;
} __main_block_desc_0_DATA = { 0, sizeof(struct __main_block_impl_0)};

int main(int argc, char *argv[]) {
 void (*blk)() = ((void (*)())&__main_block_impl_0((void *)__main_block_func_0, &__main_block_desc_0_DATA));
 ((void (*)(__block_impl *))((__block_impl *)blk)->FuncPtr)((__block_impl *)blk);
}

In the main function, when i call the blk(), the source code cast blk and take the FuncPtr by this code

((__block_impl *)blk)->FuncPtr)

I can't really understand that, is it supposed to do? In my opinion, i prefer to use

(((__main_block_impl_0 *)blk ->impl).FuncPtr)

I don't really know more about C++, if there is anyone who can help me to understand the principle of this code, i'll be very thankful. Thanks for you guys.


问:
How best store year, month, and day in a MySQL database?
How best store year, month, and day in a MySQL database so that it would be easily retrieved by year, by year-month, by year-month-day combinations?</p>

答:
This may be related to the problem that archivists have with common date datatypes. Often, you want to be able to encode just the year, or just the year and the month, depending on what information is available, but you want to be able to encode this information in just one datatype. This is a problem which doesn't apply in very many other situations. (In answer to this question in the past, I've had techie types dismiss it as a problem with the data: your data is faulty!)

e.g., in a composer catalogue you are recording the fact that the composer dated a manuscript "January 1951". What can you put in a MySQL DATE field to represent this? "1951-01"? "1951-01-00"? Neither is really valid. Normally you end up encoding years, months and days in separate fields and then having to implement the semantics at application level. This is far from ideal.