问:
How to update a table with joining two other tables
We have three tables here, Session table which is connected to Green_fact table with Session_id field. Time_session table is the third table which is made of SessionDate from Session table with a primary key for every single day.

How can I populate the Date_ID field in Green_fact table.
the code below is what I think use, but it doesn't work properly

```<code>update green_fact
   inner join "SESSION" on green_fact."SESSION_ID" = "SESSION"."SessionID"
   inner join "TIME_SESSION" on "TIME_SESSION"."SESSION_DATE" = "SESSION"."SessionDate"
   set green_fact."DATE_ID" = "TIME_SESSION"."ID" where green_fact."SESSION_ID" = "SESSION"."SessionID";
</code>```

答:
Use below query for update from two tables :</p>

```<code>UPDATE green_fact SET green_fact."DATE_ID" = A.Id
FROM
(
    SELECT "TIME_SESSION"."ID" Id ,  "SESSION"."SessionID" SessionID
    FROM "TIME_SESSION"
    JOIN "SESSION" ON  "TIME_SESSION"."SESSION_DATE" =
    "SESSION"."SessionDate"
) A
WHERE green_fact."SESSION_ID" = A.SessionID;
</code>```

Body:
We have three tables here, Session table which is connected to Green_fact table with Session_id field. Time_session table is the third table which is made of SessionDate from Session table with a primary key for every single day.

How can I populate the Date_ID field in Green_fact table.
the code below is what I think use, but it doesn't work properly

update green_fact
   inner join "SESSION" on green_fact."SESSION_ID" = "SESSION"."SessionID"
   inner join "TIME_SESSION" on "TIME_SESSION"."SESSION_DATE" = "SESSION"."SessionDate"
   set green_fact."DATE_ID" = "TIME_SESSION"."ID" where green_fact."SESSION_ID" = "SESSION"."SessionID";

Body:
Use below query for update from two tables :

UPDATE green_fact SET green_fact."DATE_ID" = A.Id
FROM
(
    SELECT "TIME_SESSION"."ID" Id ,  "SESSION"."SessionID" SessionID
    FROM "TIME_SESSION"
    JOIN "SESSION" ON  "TIME_SESSION"."SESSION_DATE" =
    "SESSION"."SessionDate"
) A
WHERE green_fact."SESSION_ID" = A.SessionID;


来源: stackexchange

问:
setNavigationBarHidden doesn't work after setViewControllers
I found that setNavigationBarHidden doesn't work after setViewControllers?

This is my code:

HomeNavController.swift:

```<code>class HomeNavController: UINavigationController {

    weak var tabBar: HomeTabBar!

    var tab: HomeTab = .match {
        didSet {
            switch self.tab {
            case .match:
                self.setViewControllers([MatchViewController()], animated: false)
            case .moments:
                self.setViewControllers([MomentsViewController()], animated: false)
            case .myPosts:
                self.setViewControllers([PostsViewController()], animated: false)
            }
        }
    }
}
</code>```

MatchViewController.swift

```<code>override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    self.navigationController?.setNavigationBarHidden(true, animated: false)
}
</code>```

It works well when I first switch to MatchViewController instance, but it doesn't works after I change the HomeNavController instance's viewControllers with func setViewControllers.

Is it a bug of UINavigationController?

答:
Maybe try setting the properties, this worked in my case: </p>

```<code>    let navigationBarAppearance = UINavigationBar.appearance()
    let transparentColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0);
    // Sets the translucent background color
    navigationBarAppearance.backgroundColor = transparentColor
    navigationBarAppearance.titleTextAttributes = [NSForegroundColorAttributeName:transparentColor]
    // Hides the border
    navigationBarAppearance.shadowImage = UIImage()
    navigationBarAppearance.setBackgroundImage(UIImage(), for: .default)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I found that setNavigationBarHidden doesn't work after setViewControllers?

This is my code:

HomeNavController.swift:

class HomeNavController: UINavigationController {

    weak var tabBar: HomeTabBar!

    var tab: HomeTab = .match {
        didSet {
            switch self.tab {
            case .match:
                self.setViewControllers([MatchViewController()], animated: false)
            case .moments:
                self.setViewControllers([MomentsViewController()], animated: false)
            case .myPosts:
                self.setViewControllers([PostsViewController()], animated: false)
            }
        }
    }
}

MatchViewController.swift

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    self.navigationController?.setNavigationBarHidden(true, animated: false)
}

It works well when I first switch to MatchViewController instance, but it doesn't works after I change the HomeNavController instance's viewControllers with func setViewControllers.

Is it a bug of UINavigationController?

Body:
Maybe try setting the properties, this worked in my case:

    let navigationBarAppearance = UINavigationBar.appearance()
    let transparentColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0);
    // Sets the translucent background color
    navigationBarAppearance.backgroundColor = transparentColor
    navigationBarAppearance.titleTextAttributes = [NSForegroundColorAttributeName:transparentColor]
    // Hides the border
    navigationBarAppearance.shadowImage = UIImage()
    navigationBarAppearance.setBackgroundImage(UIImage(), for: .default)


问:
How can realize border radius like egg
Can I realize this style of image with css3?

I have set this style of border in

```<code>.image img {border-radius: 40% 60% 60% 40%/50%; }
</code>```

, but I think that isn't right one.

答:
```<code><div style="height=;height: 505px;width: 655px;background-color: #ececec;">
    <img src="test_img.png" height="500" width="650" style="border-top-left-radius: 100% 100%;border-top-right-radius: 100% 160%;border-bottom-left-radius: 135% 100%;border-bottom-right-radius: 50% 50%;">
</div>
</code>```

Title: How can realize border radius like egg

Body:
Can I realize this style of image with css3?

I have set this style of border in

.image img {border-radius: 40% 60% 60% 40%/50%; }

, but I think that isn't right one.


问:
is there a way to guarantee that all properties of an interface are addressed
STOP! IMPORTANT! READ FIRST:

i an NOT looking to solve the serialization problem below, i only used it as an example

the REAL QUESTION IS AT THE END, thank you

UPDATE:

i am aware of an option to iterate through all properties using Object.keys(), however this is not what i am looking for, i am looking for a way to address  each property personally

UPDATE:

problem solved, check out my answer below

ORIGINAL QUESTION:

say i have an interface

```<code>interface Data { one: number; another: string; }
</code>```

i have a serialization method

```<code>serialize(data: Data): string {
    return 'one: ' + data.one + ', another: ' + data.another;
}
</code>```

now i am doing refactoring and want to add a new property to the Data interface, so that

```<code>interface Data { one: number; another: string; yetAnother: boolean; }
</code>```

now by requirement the new property yetAnother must be serialized too, yet the compiler won't point out to that because i didn't ask for it, so there is a chance of a bug to slip in

now my question: is there a way to ask the TypeScript compiler if i addressed all properties of an interface?

crossposted to TypeScript: https://github.com/Microsoft/TypeScript/issues/14947

答:
With my knowledge about TypeScript I'd say it's not possible. But what you're doing looks like you want to simply do

interface Data { one: number; another: string; yetAnother: boolean; }

function serialize(data: Data): string {
  let result = '';

  Object.keys(data).forEach(k => {
    if (data.hasOwnProperty(k)) {
      result += `${k}: ${data[k]}`;
    }
  });

  return result;
}```

Since your interface does not mark these properties as optional (one?: number, note the question mark) it won't be possible to call the function if anything is missing (obviously, if not cast to any or something alike).

Body:
STOP! IMPORTANT! READ FIRST:

i an NOT looking to solve the serialization problem below, i only used it as an example

the REAL QUESTION IS AT THE END, thank you

UPDATE:

i am aware of an option to iterate through all properties using Object.keys(), however this is not what i am looking for, i am looking for a way to address  each property personally

UPDATE:

problem solved, check out my answer below

ORIGINAL QUESTION:

say i have an interface

interface Data { one: number; another: string; }

i have a serialization method

serialize(data: Data): string {
    return 'one: ' + data.one + ', another: ' + data.another;
}

now i am doing refactoring and want to add a new property to the Data interface, so that

interface Data { one: number; another: string; yetAnother: boolean; }

now by requirement the new property yetAnother must be serialized too, yet the compiler won't point out to that because i didn't ask for it, so there is a chance of a bug to slip in

now my question: is there a way to ask the TypeScript compiler if i addressed all properties of an interface?

crossposted to TypeScript: https://github.com/Microsoft/TypeScript/issues/14947

Body:
With my knowledge about TypeScript I'd say it's not possible. But what you're doing looks like you want to simply do

interface Data { one: number; another: string; yetAnother: boolean; }

function serialize(data: Data): string {
  let result = '';

  Object.keys(data).forEach(k => {
    if (data.hasOwnProperty(k)) {
      result += `${k}: ${data[k]}`;
    }
  });

  return result;
}

Since your interface does not mark these properties as optional (one?: number, note the question mark) it won't be possible to call the function if anything is missing (obviously, if not cast to any or something alike).


问:
Can Paragraph Tags in a RichTextBox be Saved or Loaded?
Within a RichTextBox, I use the paragraph Tag for information, such as paragraph topic, e.g.,

```<code>string[] np = new string[]
{
    "B-CC:", "B-HPI:", "B-ROS:", "B-PMH:", "B-PSH:"
};

RichTextControl.Document.Blocks.Clear();
foreach (var s in np)
{
    var p = new Paragraph();
    p.Tag = s;
    RichTextControl.Document.Blocks.Add(p);
}
</code>```

Can the information within the Tag be saved and later recalled from a MemoryStream?

TIA

答:
You could use the XamlWrite.Save method to serialize the RichTextBox, including the Paragraphs and the Tag property values:

```<code>//serialize:
string xaml = System.Windows.Markup.XamlWriter.Save(RichTextControl);
//de-serialize:
RichTextBox rtb = System.Windows.Markup.XamlReader.Parse(xaml) as RichTextBox;
foreach(var p in rtb.Document.Blocks.OfType<Paragraph>())
{
    if(p.Tag != null)
    {
        string tag = p.Tag.ToString();
    }
}
</code>```

Body:
Within a RichTextBox, I use the paragraph Tag for information, such as paragraph topic, e.g.,

string[] np = new string[]
{
    "B-CC:", "B-HPI:", "B-ROS:", "B-PMH:", "B-PSH:"
};

RichTextControl.Document.Blocks.Clear();
foreach (var s in np)
{
    var p = new Paragraph();
    p.Tag = s;
    RichTextControl.Document.Blocks.Add(p);
}

Can the information within the Tag be saved and later recalled from a MemoryStream?

TIA

Body:
You could use the XamlWrite.Save method to serialize the RichTextBox, including the Paragraphs and the Tag property values:

//serialize:
string xaml = System.Windows.Markup.XamlWriter.Save(RichTextControl);
//de-serialize:
RichTextBox rtb = System.Windows.Markup.XamlReader.Parse(xaml) as RichTextBox;
foreach(var p in rtb.Document.Blocks.OfType<Paragraph>())
{
    if(p.Tag != null)
    {
        string tag = p.Tag.ToString();
    }
}


问:
Template parameters in Python
I would like to use a Filename class that only allows itself to be constructed with a certain extension. I can't just use the constructor (e.g. FileName(".txt"), because I want my class to be used in function annotations, e.g.

```<code>def my_func( file_name : FileName[".txt"] ): . . .
</code>```

I can see inbuilt types such as the type-hint classes get around this issue using templates:

```<code>List[T]
Union[T, U]
Optional[T]` # inherits Union[T, None`]
</code>```

And I can obtain these parameters via, e.g. my_union.__union_args__.

Is it possible to create my own class that takes template parameters?

答:
Found the answer (eventually). I case anyone else is interested, you just need to define get_item on the metaclass:

```<code>def __getitem__( self, item ):
    return self.__class__( self.__name__,
                           (self,) + self.__bases__,
                           dict( self.__dict__ ),
                           item = item )
</code>```

Then item can be anything you want (an extension, a type, etc.)

Quite nicely, the IDE (I'm using PyCharm) seems to have no problem picking up any extra attributes when it parses the annotations.

Title: Template parameters in Python

Body:
I would like to use a Filename class that only allows itself to be constructed with a certain extension. I can't just use the constructor (e.g. FileName(".txt"), because I want my class to be used in function annotations, e.g.

def my_func( file_name : FileName[".txt"] ): . . .

I can see inbuilt types such as the type-hint classes get around this issue using templates:

List[T]
Union[T, U]
Optional[T]` # inherits Union[T, None`]

And I can obtain these parameters via, e.g. my_union.__union_args__.

Is it possible to create my own class that takes template parameters?

Body:
Found the answer (eventually). I case anyone else is interested, you just need to define get_item on the metaclass:

def __getitem__( self, item ):
    return self.__class__( self.__name__,
                           (self,) + self.__bases__,
                           dict( self.__dict__ ),
                           item = item )

Then item can be anything you want (an extension, a type, etc.)

Quite nicely, the IDE (I'm using PyCharm) seems to have no problem picking up any extra attributes when it parses the annotations.


问:
using Highcharters in R with Shiny, control highstock chart height failed
I called highchart with height parameter to make a taller chart successfully in RStudio:

```<code>chart <- highchart(type = "stock", height=800, ...)
</code>```

When in Shiny, the chart shown up but ignore the height parameter. Is there any way to fix it ?

答:
If you are using shiny you can set the dimension in the highchartOutput() function:

```<code># ui.R
...
highchartOutput("my_hc_id", width = 450, height = 300)
...
</code>```

Other way using the hc_size function compared with the @pork-chop answer:

```<code>library(quantmod)
library(highcharter)
x <- getSymbols("GOOG", auto.assign = FALSE)

b <- hchart(x)
b <- hc_size(b, width = 450, height = 300)
b
</code>```

Body:
I called highchart with height parameter to make a taller chart successfully in RStudio:

chart <- highchart(type = "stock", height=800, ...)

When in Shiny, the chart shown up but ignore the height parameter. Is there any way to fix it ?

Body:
If you are using shiny you can set the dimension in the highchartOutput() function:

# ui.R
...
highchartOutput("my_hc_id", width = 450, height = 300)
...

Other way using the hc_size function compared with the @pork-chop answer:

library(quantmod)
library(highcharter)
x <- getSymbols("GOOG", auto.assign = FALSE)

b <- hchart(x)
b <- hc_size(b, width = 450, height = 300)
b


问:
Graphics lags after suspend. Ubuntu 16.04 NVIDIA GeForce GTX 950M
After suspend ubuntu 16.04 this weird stuff on borders of every window.
I have tried four of this drivers but it not helps.
Drivers:

答: I had the same issue this morning after updating to kernel 4.8.0-45 (HWE) on my 16.04 machine w/ an nVidia 650ti. I tried booting with the previous kernel (4.8.0-41), but I had the same issue. I tried the Noveau drivers, but for some reason they would not recognize either monitor properly (stuck at 1024x768 res on single monitor), so that was unusable. I then tried using switching from the 375.39 proprietary drivers to the 340.102 drivers and that worked (on the latest HWE kernel 4.8.0-45). I see that 340.102 is not available to you, but try one of the other driver versions to see if the problem goes away.</p>


问:
iphone twitter and sharing
Has anyone encountered the following error message when sending to Twitter?

"Error: Incorrect signature"

And on the debug console:

<0xf14cf80 SHKTwitter.m:(356)> Twitter Send Status Error: {"request":"\/1\/statuses\/update.json","error":"Incorrect signature"}

So far as I can tell I've followed the install instructions on http://www.getsharekit.com/install/#download and it is working with Facebook, e-mail etc. just not Twitter.

It would be great if someone has seen this error before and goes "aha!".

答:
All I did to enable twitter Sharing is:

Regitered my App as a Twitter APP (Application Type: Browser)

#define SHKTwitterConsumerKey        @"My..."
#define SHKTwitterSecret            @"My..."
#define SHKTwitterCallbackUrl        @"http://www.anything.com/callback" // You need to set this if using OAuth, see note above (xAuth users can skip it)
\#define SHKTwitterUseXAuth            0 // To use xAuth, set to 1
\#define SHKTwitterUsername            @"" // Enter your app's twitter account if you'dlike to ask the user to follow it when logging in. (Only for xAuth)

Note that for the callback function you can enter any URL you want. even www.google.com. Just make sure it is the same URL in your code.

ContentLicense: CC BY-SA 2.5

Title: iphone twitter and sharing


问:
all group members but the current row
I've got a grouped data frame, like so:

```<code>df <- data.frame(group = rep(1:4, each=3),
                 lets = rep(LETTERS[1:4], times=3))
</code>```

For each row I would now like to identify all lets within the same group other than the lets of the row itself. Using dplyr I can get all lets thus:

```<code>df %>%
  group_by(group) %>%
  mutate(all_lets_in_group = paste(lets, collapse=','))
</code>```

But how do I exclude the lets of the current row from what I feed into paste()?

答:
Another base R method that uses ave, sapply, and setdiff

```<code>ave(df$lets, df$group,
    FUN=function(i) sapply(i, function(j) paste(setdiff(i, j), collapse=",")))
 [1] "B,C" "A,C" "A,B" "A,B" "D,B" "D,A" "D,A" "C,A" "C,D" "C,D" "B,D" "B,C"
</code>```

Title: all group members but the current row

Body:
I've got a grouped data frame, like so:

df <- data.frame(group = rep(1:4, each=3),
                 lets = rep(LETTERS[1:4], times=3))

For each row I would now like to identify all lets within the same group other than the lets of the row itself. Using dplyr I can get all lets thus:

df %>%
  group_by(group) %>%
  mutate(all_lets_in_group = paste(lets, collapse=','))

But how do I exclude the lets of the current row from what I feed into paste()?

Body:
Another base R method that uses ave, sapply, and setdiff

ave(df$lets, df$group,
    FUN=function(i) sapply(i, function(j) paste(setdiff(i, j), collapse=",")))
 [1] "B,C" "A,C" "A,B" "A,B" "D,B" "D,A" "D,A" "C,A" "C,D" "C,D" "B,D" "B,C"


问:
Why can we not return a structure to a function?
Why can we not return a structure as a return value? I would also like to print it as well? I want to print the variables of the structure returned.

```<code>#include <stdio.h>

struct distance
{
    int feet;
    float inch;
};

distance add(struct distance d1,struct distance d2);

distance d3;
int main()
{
    struct distance dist1, dist2,dist3;
    printf("first distance\n");
    scanf("%d",&dist1.feet);
    scanf("%f",&dist1.inch);
    printf("second distance\n");
    scanf("%d",&dist2.feet);
    scanf("%f",&dist2.inch);
    dist3 = add(dist1,dist2);
    printf("sum of distances= %d\'-%.1f\"",dist3.feet,dist3.inch);
    return dist3;
}

 distance add(struct distance d1,struct distance d2){
    //Adding distances d1 and d2 and storing it in d3
    d3.feet = d2.feet+d1.feet;
    d3.inch = d2.inch+d1.inch;
    if(d3.inch>12){
        d3.inch-=12;
        ++d3.feet;
    }
}
</code>```

The following error message is displayed
prog.c:7:1: error: unknown type name ‘distance’
 distance add(struct distance d1,struct distance d2);

答:
You need to return it </p>

```<code>distance add(struct distance d1,struct distance d2){
    struct distance d3;

    //Adding distances d1 and d2 and storing it in d3
    d3.feet = d2.feet+d1.feet;
    d3.inch = d2.inch+d1.inch;
    if(d3.inch>12){
        d3.inch-=12;
        ++d3.feet;
    }
    return d3;
}
</code>```

Body:
Why can we not return a structure as a return value? I would also like to print it as well? I want to print the variables of the structure returned.

#include <stdio.h>

struct distance
{
    int feet;
    float inch;
};

distance add(struct distance d1,struct distance d2);

distance d3;
int main()
{
    struct distance dist1, dist2,dist3;
    printf("first distance\n");
    scanf("%d",&dist1.feet);
    scanf("%f",&dist1.inch);
    printf("second distance\n");
    scanf("%d",&dist2.feet);
    scanf("%f",&dist2.inch);
    dist3 = add(dist1,dist2);
    printf("sum of distances= %d\'-%.1f\"",dist3.feet,dist3.inch);
    return dist3;
}

 distance add(struct distance d1,struct distance d2){
    //Adding distances d1 and d2 and storing it in d3
    d3.feet = d2.feet+d1.feet;
    d3.inch = d2.inch+d1.inch;
    if(d3.inch>12){
        d3.inch-=12;
        ++d3.feet;
    }
}

The following error message is displayed
prog.c:7:1: error: unknown type name ‘distance’
 distance add(struct distance d1,struct distance d2);

Body:
You need to return it

distance add(struct distance d1,struct distance d2){
    struct distance d3;

    //Adding distances d1 and d2 and storing it in d3
    d3.feet = d2.feet+d1.feet;
    d3.inch = d2.inch+d1.inch;
    if(d3.inch>12){
        d3.inch-=12;
        ++d3.feet;
    }
    return d3;
}


问:
Splitting Column data into unknown number of columns
I have a very messy name column, names could look like the names below

```<code>names<-c("Mr John Jo Mcbride","Jim Bucket", "Farshad Jimbo Letrick")
</code>```

The output could be any number of columns, separating into columns from spaces. So above the first name would need four columns, second 2 columns, third would be 3 columns.

I don't care about the order, I just want the data broken into how many ever columns each row needs based on the space separator.

答:
This should do the trick:</p>

```<code>names<-c("Mr John Jo Mcbride","Jim Bucket", "Farshad Jimbo Letrick")

strsplit(names,split = '\\s')
</code>```

Body:
I have a very messy name column, names could look like the names below

names<-c("Mr John Jo Mcbride","Jim Bucket", "Farshad Jimbo Letrick")

The output could be any number of columns, separating into columns from spaces. So above the first name would need four columns, second 2 columns, third would be 3 columns.

I don't care about the order, I just want the data broken into how many ever columns each row needs based on the space separator.

Body:
This should do the trick:

names<-c("Mr John Jo Mcbride","Jim Bucket", "Farshad Jimbo Letrick")

strsplit(names,split = '\\s')


问:
Scapy module blocks PyCharm debugger
Im working on a project in PyCharm, and I need to debug certain part of the code.

When I tried to debug, the debugger just "skipped" the breakpoints without stopping at them.
After a lot of non-helpful tries in the web, I found that when I import the Scapy module, the debugger doesn't work, and when Scapy isn't imported, everything works just FINE.

Btw - Im working on Ubuntu OS.

Any ideas??

答:
Came across this problem myself. It is very annoying. After much debugging, got to an answer.

The cause of the problem seems to be the way scapy imports everything into the global namespace and this seems to break PyCharm (name clash, perhaps?).

By the way, this all applies to v2.3.3 of scapy from 18th October, 2016.

As scapy is loading, it eventually hits a line in scapy/all.py:

```<code>from scapy.layers.all import *
</code>```

This loads scapy/layers/all.py which loads scapy/config.py. This last file initialises Conf.load_layers[] to a list of modules (in scapy/layers).

scapy/layers/all.py then loops through this list, calling _import_star() on each module.

After it loads scapy/layers/x509.py, all breakpoints in PyCharm stop working.

I've FOUR solutions for you, pick the one you like best ...

(1) If you don't use anything to do with X509, you could simply remove this module from the list assigned to Conf.load_layers[] in scapy/config.py (line 383 in my copy of config.py). WARNING: THIS IS A REAL HACK - please avoid doing it unless there is no other way forward for you.

If you need to temporally debug, you can also use this code sample:

```<code>from scapy import config
config.Conf.load_layers.remove("x509")
from scapy.all import *
</code>```

(2) The problem is with symbols being imported into the global namespace. This is fine for classes, bad for constants. There is code in _import_star() that checks the name of the symbol and does NOT load it into the global namespace if it begins with a _ (i.e. a "private" name). You could modify this function to treat the x509 module specially by ignoring names that do not begin X509_. Hopefully this will import the classes defined in x509 and not the constants. Here is a sample patch:

```<code>*** layers/all.py   2017-03-31 12:44:00.673248054 +0100
--- layers/all.py   2017-03-31 12:44:00.673248054 +0100
***************
*** 21,26 ****
--- 21,32 ----
          for name in mod.__dict__['__all__']:
              __all__.append(name)
              globals()[name] = mod.__dict__[name]
+     elif m == "x509":
+         # import but rename as we go ...
+         for name, sym in mod.__dict__.iteritems():
+             if name[0] != '_' and name[:5] != "X509_":
+                 __all__.append("_x509_" + name)
+                 globals()["_x509_" + name] = sym
      else:
          # import all the non-private symbols
          for name, sym in mod.__dict__.iteritems():
</code>```

WARNING: THIS IS A REAL HACK - please avoid doing it unless there is no other way forward for you.

(3) This is a variation on solution (2), so also A REAL HACK (etc. etc.). You could edit scapy/layers/x509.py and prepend a _ to all constants. For example, all instances of default_directoryName should be changed to _default_directoryName. I found the following constants that needed changing: default_directoryName, reasons_mapping, cRL_reasons, ext_mapping, default_issuer, default_subject, attrName_mapping and attrName_specials. This is nice as it matches a fix applied to x509.py that I found in the scapy git repo ...

(4) You could just update to the next version of scapy. I don't know if this will be v2.3.4 or v2.4, as there is (at the time of writing) no next version released yet. So, while this (lack of a new release) continues, you could update to the latest development version (where they have already fixed this problem on Feb 8th 2017). I use scapy installed under my home directory (rather than in the system python packages location), so I did the following:

```<code>pip uninstall scapy
git clone https://github.com/secdev/scapy /tmp/scapy
cd /tmp/scapy
python setup.py install --user
cd -
rm -rf /tmp/scapy
</code>```

Good luck !

Title: Scapy module blocks PyCharm debugger

Body:
Came across this problem myself. It is very annoying. After much debugging, got to an answer.

The cause of the problem seems to be the way scapy imports everything into the global namespace and this seems to break PyCharm (name clash, perhaps?).

By the way, this all applies to v2.3.3 of scapy from 18th October, 2016.

As scapy is loading, it eventually hits a line in scapy/all.py:

from scapy.layers.all import *

This loads scapy/layers/all.py which loads scapy/config.py. This last file initialises Conf.load_layers[] to a list of modules (in scapy/layers).

scapy/layers/all.py then loops through this list, calling _import_star() on each module.

After it loads scapy/layers/x509.py, all breakpoints in PyCharm stop working.

I've FOUR solutions for you, pick the one you like best ...

(1) If you don't use anything to do with X509, you could simply remove this module from the list assigned to Conf.load_layers[] in scapy/config.py (line 383 in my copy of config.py). WARNING: THIS IS A REAL HACK - please avoid doing it unless there is no other way forward for you.

If you need to temporally debug, you can also use this code sample:

from scapy import config
config.Conf.load_layers.remove("x509")
from scapy.all import *

(2) The problem is with symbols being imported into the global namespace. This is fine for classes, bad for constants. There is code in _import_star() that checks the name of the symbol and does NOT load it into the global namespace if it begins with a _ (i.e. a "private" name). You could modify this function to treat the x509 module specially by ignoring names that do not begin X509_. Hopefully this will import the classes defined in x509 and not the constants. Here is a sample patch:

*** layers/all.py   2017-03-31 12:44:00.673248054 +0100
--- layers/all.py   2017-03-31 12:44:00.673248054 +0100
***************
*** 21,26 ****
--- 21,32 ----
          for name in mod.__dict__['__all__']:
              __all__.append(name)
              globals()[name] = mod.__dict__[name]
+     elif m == "x509":
+         # import but rename as we go ...
+         for name, sym in mod.__dict__.iteritems():
+             if name[0] != '_' and name[:5] != "X509_":
+                 __all__.append("_x509_" + name)
+                 globals()["_x509_" + name] = sym
      else:
          # import all the non-private symbols
          for name, sym in mod.__dict__.iteritems():

WARNING: THIS IS A REAL HACK - please avoid doing it unless there is no other way forward for you.

(3) This is a variation on solution (2), so also A REAL HACK (etc. etc.). You could edit scapy/layers/x509.py and prepend a _ to all constants. For example, all instances of default_directoryName should be changed to _default_directoryName. I found the following constants that needed changing: default_directoryName, reasons_mapping, cRL_reasons, ext_mapping, default_issuer, default_subject, attrName_mapping and attrName_specials. This is nice as it matches a fix applied to x509.py that I found in the scapy git repo ...

(4) You could just update to the next version of scapy. I don't know if this will be v2.3.4 or v2.4, as there is (at the time of writing) no next version released yet. So, while this (lack of a new release) continues, you could update to the latest development version (where they have already fixed this problem on Feb 8th 2017). I use scapy installed under my home directory (rather than in the system python packages location), so I did the following:

pip uninstall scapy
git clone https://github.com/secdev/scapy /tmp/scapy
cd /tmp/scapy
python setup.py install --user
cd -
rm -rf /tmp/scapy

Good luck !


问:
Recurring variadic template class parameters
I would like a variadic template class (with, say N template parameters) to define N member functions, each one taking a single parameter of type from the parameters list. I tried this :

```<code>template<class Derived, class... DerivedOthers>
class VtfVisitor : public VtfVisitor<DerivedOthers...>
{
public:
    virtual void visit(Derived& derived) = 0;
};

template<class Derived>
class VtfVisitor
{
public:
    virtual void visit(Derived& derived) = 0;
};
</code>```

Which does not work as I cannot redefine a template class. Then I tried solution proposed by Bo :

```<code>template<class Derived, class... DerivedOthers>
class VtfVisitor : public VtfVisitor<DerivedOthers...>
{
public:
    virtual void visit(Derived& derived) VISITOR_CVQ = 0;
};

template<class Derived>
class VtfVisitor<Derived>
{
public:
    virtual void visit(Derived& derived) VISITOR_CVQ = 0;
};
</code>```

Which still does not work: when trying this with VtfVisitor<D1,D2>, member function visit(D2&) is not defined in the instanciated template class (while visit(D1&) is well defined).

How could I get this to work as expected ?

Thanks for help.

答:
The compiler believes that you are redeclaring the same class with different number of parameters.

To create a specialization for the single argument case, you have to specify that after the class name:

```<code>template<class Derived>
class VtfVisitor<Derived>
{
public:
    virtual void visit(Derived& derived) = 0;
};
</code>```

Body:
I would like a variadic template class (with, say N template parameters) to define N member functions, each one taking a single parameter of type from the parameters list. I tried this :

template<class Derived, class... DerivedOthers>
class VtfVisitor : public VtfVisitor<DerivedOthers...>
{
public:
    virtual void visit(Derived& derived) = 0;
};

template<class Derived>
class VtfVisitor
{
public:
    virtual void visit(Derived& derived) = 0;
};

Which does not work as I cannot redefine a template class. Then I tried solution proposed by Bo :

template<class Derived, class... DerivedOthers>
class VtfVisitor : public VtfVisitor<DerivedOthers...>
{
public:
    virtual void visit(Derived& derived) VISITOR_CVQ = 0;
};

template<class Derived>
class VtfVisitor<Derived>
{
public:
    virtual void visit(Derived& derived) VISITOR_CVQ = 0;
};

Which still does not work: when trying this with VtfVisitor<D1,D2>, member function visit(D2&) is not defined in the instanciated template class (while visit(D1&) is well defined).

How could I get this to work as expected ?

Thanks for help.

Body:
The compiler believes that you are redeclaring the same class with different number of parameters.

To create a specialization for the single argument case, you have to specify that after the class name:

template<class Derived>
class VtfVisitor<Derived>
{
public:
    virtual void visit(Derived& derived) = 0;
};


问:
How can I merge AngularJS , React and Redux?
I am building an application using angular and redux (ngRedux). Now i want to use react instead of angular for improvement in performance. It is a huge application so it is not possible to build it from scratch. So i want to use the routing of angularJS (angular-ui-router) and as any "abc" state become active then the react component become load and this react component should use the pure redux against every single event.

How can i maintain my application accordingly that a single module is build in react-redux and connected to angular only through routing state. Keep in mind that the other modules of application should also not be disturbed.

答:
Well to render React components into Angular is quite easy. But I just assume you use directiveor component from angular already.

So in the case of directive you could skip the whole templating "none sense" and let React handle that for you

```<code>module.directive("reactTest",function() {
  return {
    link:function(scope,element,attr) {
      class App extends React.Component {
        constructor(props) { super(props) }

        render <div></div>
      }
      element.replace(App);

    }
  }
});
</code>```

So this how you would get React into Angular. Redux ist basically the same. You simple use the connect function of redux and off you go.

Body:
Well to render React components into Angular is quite easy. But I just assume you use directiveor component from angular already.

So in the case of directive you could skip the whole templating "none sense" and let React handle that for you

module.directive("reactTest",function() {
  return {
    link:function(scope,element,attr) {
      class App extends React.Component {
        constructor(props) { super(props) }

        render <div></div>
      }
      element.replace(App);

    }
  }
});

So this how you would get React into Angular. Redux ist basically the same. You simple use the connect function of redux and off you go.


问:
Bootstrap tooltips and popovers: To Destroy, or NOT To Destroy?
if I create tooltips and popovers via BS' tooltip() and popover() methods, is there a need to do any explicit destroying of said creations if the DOM changes and the affected elements are no longer present? Am I creating JS dust bunnies by NOT explicitly destroying?</p>

答:
I created a simple fiddle:

http://jsfiddle.net/Oski/5gura2oq/

JS:

```<code>$(function () {
  var element = $('#example').popover();
  element.popover('show');
  element.remove();
});
</code>```

Template:

```<code><p>Click on button to see Popover</p>
<a href="#" id="example" class="btn btn-primary" rel="popover"
  data-content="This is the body of Popover"
  data-original-title="Creativity Tuts">pop
</a>
</code>```

You can remove the anchor element and still have the popover visible, so I think you need to destroy your popover.

Body:
I created a simple fiddle:

http://jsfiddle.net/Oski/5gura2oq/

JS:

$(function () {
  var element = $('#example').popover();
  element.popover('show');
  element.remove();
});

Template:

<p>Click on button to see Popover</p>
<a href="#" id="example" class="btn btn-primary" rel="popover"
  data-content="This is the body of Popover"
  data-original-title="Creativity Tuts">pop
</a>

You can remove the anchor element and still have the popover visible, so I think you need to destroy your popover.


问:
How to create a zip archive of a directory?
How can I create a zip archive of a directory structure in Python?</p>

答:
Modern Python (3.6+) using the pathlib module for concise OOP-like handling of paths, and pathlib.Path.rglob() for recursive globbing. As far as I can tell, this is equivalent to George V. Reilly's answer: zips with compression, the topmost element is a directory, keeps empty dirs, uses relative paths.

```<code>from pathlib import Path
from zipfile import ZIP_DEFLATED, ZipFile

from os import PathLike
from typing import Union

def zip_dir(zip_name: str, source_dir: Union[str, PathLike]):
    src_path = Path(source_dir).expanduser().resolve(strict=True)
    with ZipFile(zip_name, 'w', ZIP_DEFLATED) as zf:
        for file in src_path.rglob('*'):
            zf.write(file, file.relative_to(src_path.parent))
</code>```

Note: as optional type hints indicate, zip_name can't be a Path object (would be fixed in 3.6.2+).

ContentLicense: CC BY-SA 4.0

Body:
Modern Python (3.6+) using the pathlib module for concise OOP-like handling of paths, and pathlib.Path.rglob() for recursive globbing. As far as I can tell, this is equivalent to George V. Reilly's answer: zips with compression, the topmost element is a directory, keeps empty dirs, uses relative paths.

from pathlib import Path
from zipfile import ZIP_DEFLATED, ZipFile

from os import PathLike
from typing import Union

def zip_dir(zip_name: str, source_dir: Union[str, PathLike]):
    src_path = Path(source_dir).expanduser().resolve(strict=True)
    with ZipFile(zip_name, 'w', ZIP_DEFLATED) as zf:
        for file in src_path.rglob('*'):
            zf.write(file, file.relative_to(src_path.parent))

Note: as optional type hints indicate, zip_name can't be a Path object (would be fixed in 3.6.2+).


问:
Find unknown vertices from two sides of right angled triangle and one vertex
Consider a right angled triangle. The opposite side and adjacent side lengths are known. Also one vertex coordinate is known and angles are known. How to find other two vertex points?</p>

答:
You can't.

-For a 3d triangle, you need at least a point and 2 vector (with proper lengths).

-For a 2d triangle, you need at least another point or 1 vector.


问:
ImportError: No module named skimage, already have scikit-image installed
I am trying to use skimage on mac, and already install the packages with virtualenv, but when I do "from skimage import io", it gave me this error :"ImportError: No module named skimage".
I am wondering if there is anything wrong installation process, but so far I cannot figure it out.

Below is my installation process:

sudo pip install virtualenv

cd /my/project/folder

virtualenv myproject

source myproject/bin/activate

pip install -U scikit-image
Then the result is:

"Successfully installed PyWavelets-0.5.2 cycler-0.10.0 decorator-4.0.11 functools32-3.2.3.post2 matplotlib-2.0.0 networkx-1.11 numpy-1.12.1 olefile-0.44 pillow-4.0.0 python-dateutil-2.6.0 pytz-2017.2 scikit-image-0.13.0 scipy-0.19.0 subprocess32-3.2.7"

It seems that I already have everything, but why import skimage still failed?

Besides, I also tried to used the installation guidance on http://scikit-image.org/download with "pip install -U scikit-image" and "easy_install -U scikit-image", but also failed.

I am on Mac Sierra, with python 2.7. Any suggestion would highly appreciated. Thanks!

答:
I'm using Linux and I couldn't get it working without doing

```<code>sudo apt-get install python-skimage
</code>```

And I got that from the installation page of the docs:

http://scikit-image.org/docs/stable/install.html

I'm not familiar with osx, but maybe try using a package manager like homebrew to install the package like so.

```<code>sudo homebrew install python-skimage
</code>```

I'm actually quite puzzled as to why theres no OSX section in the install section of the docs, but a tiny bit of information in the downloads section.

Body:
I'm using Linux and I couldn't get it working without doing

sudo apt-get install python-skimage

And I got that from the installation page of the docs:

http://scikit-image.org/docs/stable/install.html

I'm not familiar with osx, but maybe try using a package manager like homebrew to install the package like so.

sudo homebrew install python-skimage

I'm actually quite puzzled as to why theres no OSX section in the install section of the docs, but a tiny bit of information in the downloads section.


问:
How to Insert a PHP Value into an Input Value
I have a form on a page that is generated dynamically.

One of the fields is:

```<code><input type="hidden" name="pageURL" id="pageURL" value="" />
</code>```

I'd like to on page load set that value with the current browsers url using:

```<code>$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
</code>```

I can't simply put that php into value="" because that field is generated dynamically. But is there simply javascript or jQuery to load the current page url in the users browser (parameters and all) into a value of an input on a page?

答:
you can use jquery to add the url to your input field

```<code>$('#pageURL' ).val(window.location.href);
</code>```

https://jsfiddle.net/r1k7eghj/

Body:
I have a form on a page that is generated dynamically.

One of the fields is:

<input type="hidden" name="pageURL" id="pageURL" value="" />

I'd like to on page load set that value with the current browsers url using:

$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];

I can't simply put that php into value="" because that field is generated dynamically. But is there simply javascript or jQuery to load the current page url in the users browser (parameters and all) into a value of an input on a page?

Body:
you can use jquery to add the url to your input field

$('#pageURL' ).val(window.location.href);

https://jsfiddle.net/r1k7eghj/


问:
Rolling back changes with reset and force push
i have seen similar topics here, but i didn't find the clear answer.

i have commited and pushed few changes on a remote branch, but that was a mistake and would like to reset this branch to the state it was couple of days ago. (using source tree btw)

```<code>- bad pushed commit
- bad pushed commit
- bad pushed commit
- place i want to return to
- older commits
</code>```

if i do a hard reset to the place i want to return to and then force push it. Will that do the trick, are there any issues with that ?

答:
Actually, the best way avoid merge conflicts (when other people is working on the same repo) is to git revert <SHA> those commits. It will not travel back in time and rewrite history but will create an "inverse" version of said commits.

git revert will create a new commit that's the opposite (or inverse) of the given SHA. If the old commit is "matter", the new commit is "anti-matter"—anything removed in the old commit will be added in the new commit and anything added in the old commit will be removed in the new commit.

Find more info here

Body:
i have seen similar topics here, but i didn't find the clear answer.

i have commited and pushed few changes on a remote branch, but that was a mistake and would like to reset this branch to the state it was couple of days ago. (using source tree btw)

- bad pushed commit
- bad pushed commit
- bad pushed commit
- place i want to return to
- older commits

if i do a hard reset to the place i want to return to and then force push it. Will that do the trick, are there any issues with that ?


答:
If I understand well, you want to retrieve the URL parameters using JavaScript. If not please tell me I will turn this as a comment.

Here is the function you need:

```<code>function getSearchQuery() {
    // Checking if there is any parameter in the URI.
    if (document.location.search) {
        // Returning the parameters of the URI as an object.
        return document.location.search.substr(1).split("&").reduce((item, part) => {
            part            = part.split("=");
            item[part[0]]   = part[1];
            return item;
        }, {});
    } else {
        // Returning an empty object.
        return {};
    }
}
</code>```

I hope this is what you were looking for. You just need to change the input value with this function.

Title: How to Insert a PHP Value into an Input Value

Body:
If I understand well, you want to retrieve the URL parameters using JavaScript. If not please tell me I will turn this as a comment.

Here is the function you need:

function getSearchQuery() {
    // Checking if there is any parameter in the URI.
    if (document.location.search) {
        // Returning the parameters of the URI as an object.
        return document.location.search.substr(1).split("&").reduce((item, part) => {
            part            = part.split("=");
            item[part[0]]   = part[1];
            return item;
        }, {});
    } else {
        // Returning an empty object.
        return {};
    }
}

I hope this is what you were looking for. You just need to change the input value with this function.


问:
How to reformat the date WITHIN a text file C#
I'm writing a piece of code that takes in an access log and cleans it. Removes all data that i don't need and gives me out a clean version. I've cleaned it from redunadant data but i need to re-format the date which is one of the fields inside of the text file. (Below is the cleaned text file thus far)

I had initially planned on splitting it by '/' and then putting the 3 elements of the date into an array (day, month, year) and re-arranging so that the date was in american format - however this then breaks the file path by '/' and i don't want that.

Below is my code so far, any help or ideas would be much appreciated!

enter code here

```<code>  StreamReader reader = new StreamReader(fileName);
        StreamWriter writer = new StreamWriter(newFileName);
        string line;

        string personalIdentifier = new string(fileName.Take(4).ToArray());
        string gender = fileName.Substring(fileName.Length - 5, 1);
        string classification = fileName.Substring(fileName.Length - 8, 2);
        string text = string.Empty;

        while ((line = reader.ReadLine()) != null)
        {
            string[] cleanArray;
            cleanArray = new string[7];

            var result = line.Split('"')
                 .Select((element, index) => index % 2 == 0
                  ? element.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                  : new string[] { element })
                 .SelectMany(element => element).ToList();

            cleanArray[0] = personalIdentifier;
            cleanArray[1] = gender;
            cleanArray[2] = classification;
            cleanArray[3] = result[0];
            cleanArray[4] = result[3];
            cleanArray[5] = result[5];
            cleanArray[6] = result[6];

            //removing the [ at the start of the date
            cleanArray[4] = cleanArray[4].Substring(1);

            //re-formatting the date so that it can be accepted by machine learning
            var dateString = cleanArray[4];
            var date = DateTime.ParseExact(dateString, "dd/MMM/yyyy:HH:mm:ss", CultureInfo.InvariantCulture);
            var newDateString = date.ToString("yyyy-MM-dd HH:mm:ss");

            //push each clean array onto the file that has been automatically created at the top
            writer.WriteLine(string.Join(", ", cleanArray.Select(v => v.ToString())));
            writer.WriteLine();
        }
        reader.DiscardBufferedData();
        writer.Close();
        reader.Close();
        }
</code>```

答:
You can parse your String as DateTime and then parse the DateTime as String in the format you want. Something like this.

```<code>var dateString = "29/Oct/2014:13:36:07";
var date = DateTime.ParseExact(dateString, "dd/MMM/yyyy:HH:mm:ss", CultureInfo.InvariantCulture);
var newDateString = date.ToString("yyyy-MM-dd");
</code>```

and you'll get

2014-10-29

If you need the time as well change the last command to

```<code>var newDateString = date.ToString("yyyy-MM-dd HH:mm:ss");
</code>```

and you'll get

2014-10-29 13:36:07

For more information have a look at the MSDN

Body:
I'm writing a piece of code that takes in an access log and cleans it. Removes all data that i don't need and gives me out a clean version. I've cleaned it from redunadant data but i need to re-format the date which is one of the fields inside of the text file. (Below is the cleaned text file thus far)

I had initially planned on splitting it by '/' and then putting the 3 elements of the date into an array (day, month, year) and re-arranging so that the date was in american format - however this then breaks the file path by '/' and i don't want that.

Below is my code so far, any help or ideas would be much appreciated!

enter code here

  StreamReader reader = new StreamReader(fileName);
        StreamWriter writer = new StreamWriter(newFileName);
        string line;

        string personalIdentifier = new string(fileName.Take(4).ToArray());
        string gender = fileName.Substring(fileName.Length - 5, 1);
        string classification = fileName.Substring(fileName.Length - 8, 2);
        string text = string.Empty;

        while ((line = reader.ReadLine()) != null)
        {
            string[] cleanArray;
            cleanArray = new string[7];

            var result = line.Split('"')
                 .Select((element, index) => index % 2 == 0
                  ? element.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                  : new string[] { element })
                 .SelectMany(element => element).ToList();

            cleanArray[0] = personalIdentifier;
            cleanArray[1] = gender;
            cleanArray[2] = classification;
            cleanArray[3] = result[0];
            cleanArray[4] = result[3];
            cleanArray[5] = result[5];
            cleanArray[6] = result[6];

            //removing the [ at the start of the date
            cleanArray[4] = cleanArray[4].Substring(1);

            //re-formatting the date so that it can be accepted by machine learning
            var dateString = cleanArray[4];
            var date = DateTime.ParseExact(dateString, "dd/MMM/yyyy:HH:mm:ss", CultureInfo.InvariantCulture);
            var newDateString = date.ToString("yyyy-MM-dd HH:mm:ss");

            //push each clean array onto the file that has been automatically created at the top
            writer.WriteLine(string.Join(", ", cleanArray.Select(v => v.ToString())));
            writer.WriteLine();
        }
        reader.DiscardBufferedData();
        writer.Close();
        reader.Close();
        }

Body:
You can parse your String as DateTime and then parse the DateTime as String in the format you want. Something like this.

var dateString = "29/Oct/2014:13:36:07";
var date = DateTime.ParseExact(dateString, "dd/MMM/yyyy:HH:mm:ss", CultureInfo.InvariantCulture);
var newDateString = date.ToString("yyyy-MM-dd");

and you'll get

2014-10-29

If you need the time as well change the last command to

var newDateString = date.ToString("yyyy-MM-dd HH:mm:ss");

and you'll get

2014-10-29 13:36:07

For more information have a look at the MSDN


问:
How to update a table with joining two other tables
We have three tables here, Session table which is connected to Green_fact table with Session_id field. Time_session table is the third table which is made of SessionDate from Session table with a primary key for every single day.

How can I populate the Date_ID field in Green_fact table.
the code below is what I think use, but it doesn't work properly

```<code>update green_fact
   inner join "SESSION" on green_fact."SESSION_ID" = "SESSION"."SessionID"
   inner join "TIME_SESSION" on "TIME_SESSION"."SESSION_DATE" = "SESSION"."SessionDate"
   set green_fact."DATE_ID" = "TIME_SESSION"."ID" where green_fact."SESSION_ID" = "SESSION"."SessionID";
</code>```

答:
Oracle doesn't allow join in update.  You can use correlated subqueries:

```<code>update green_fact gf
   set DATE_ID = (select ts.ID
                  from SESSION s join
                       TIME_SESSION ts
                       on ts.SESSION_DATE = s.SessionDate
                  where gf.SESSION_ID = s.SESSIONID
                 )
   where exists (select ts.ID
                 from SESSION s join
                      TIME_SESSION ts
                      on ts.SESSION_DATE = s.SessionDate
                 where gf.SESSION_ID = s.SESSIONID
                );
</code>```

The exists may not be necessary, if all the rows match.

Body:
We have three tables here, Session table which is connected to Green_fact table with Session_id field. Time_session table is the third table which is made of SessionDate from Session table with a primary key for every single day.

How can I populate the Date_ID field in Green_fact table.
the code below is what I think use, but it doesn't work properly

update green_fact
   inner join "SESSION" on green_fact."SESSION_ID" = "SESSION"."SessionID"
   inner join "TIME_SESSION" on "TIME_SESSION"."SESSION_DATE" = "SESSION"."SessionDate"
   set green_fact."DATE_ID" = "TIME_SESSION"."ID" where green_fact."SESSION_ID" = "SESSION"."SessionID";

Body:
Oracle doesn't allow join in update.  You can use correlated subqueries:

update green_fact gf
   set DATE_ID = (select ts.ID
                  from SESSION s join
                       TIME_SESSION ts
                       on ts.SESSION_DATE = s.SessionDate
                  where gf.SESSION_ID = s.SESSIONID
                 )
   where exists (select ts.ID
                 from SESSION s join
                      TIME_SESSION ts
                      on ts.SESSION_DATE = s.SessionDate
                 where gf.SESSION_ID = s.SESSIONID
                );

The exists may not be necessary, if all the rows match.


问:
How to get authorized user from active directory in asp.net using c#?
I want to get authorized user from active directory for login page. When user enter wrong details the page need to show "Invalid user", if enter correct correct details lets go the home page.

Here mentioned my code. When i run this code the page shows "invalid user" even i enter the correct login details.

```<code>protected void Button1_Click1(object sender, EventArgs e)
        {

            string dominName = "ldap://domain.com:121";
            string userName = "guest";
            string password = "testlogin";

            if (true == AuthenticateUser(dominName, userName, password))
            {
                Response.Redirect("default.aspx");
            }
            else
            {
                Response.Write("Invalid user name or Password!");
            }

        }

        public bool AuthenticateUser(string domain, string username, string password)
        {
            DirectoryEntry entry = new DirectoryEntry(domain, username, password);
            try
            {
                DirectorySearcher search = new DirectorySearcher(entry);
                search.Filter = "(sAMAccountName=" + username + ")";
                search.PropertiesToLoad.Add("cn");
                Response.Write(domain);
                SearchResult result = search.FindOne();

                if (null == result)
                {
                    return false;
                }

            }
            catch (Exception ex)
            {
                return false;
                throw new Exception("Error authenticating user." + ex.Message);
            }
            return true;
        }
</code>```

Find the above code what i make a mistake. Please provide a best solution to this...

答:
You can get it from PrincipalContext. If you have specific domain, you might want to look at this sample code.

```<code>public bool ValidateCredentials(string userName, string password)
{
    userName = userName.EnsureNotNull();
    userName = userName.Trim();

    password = password.EnsureNotNull();
    password = password.Trim();

    using (var context = new PrincipalContext(ContextType.Domain))
    {
        return context.ValidateCredentials(userName, password);
    }
}

public bool IsUserInAdGroup(string userName, string adGroupName)
{
    bool result = false;
    userName = userName.EnsureNotNull();
    userName = userName.Trim();

    using (var context = new PrincipalContext(ContextType.Domain))
    {
        var user = UserPrincipal.FindByIdentity(context, userName);
        if (user != null)
        {
            var group = GroupPrincipal.FindByIdentity(context, adGroupName);
            if (group != null)
            {
                if (user.IsMemberOf(group))
                {
                    result = true;
                }
            }
        }
    }
    return result;
}
</code>```

Body:
I want to get authorized user from active directory for login page. When user enter wrong details the page need to show "Invalid user", if enter correct correct details lets go the home page.

Here mentioned my code. When i run this code the page shows "invalid user" even i enter the correct login details.

protected void Button1_Click1(object sender, EventArgs e)
        {

            string dominName = "ldap://domain.com:121";
            string userName = "guest";
            string password = "testlogin";

            if (true == AuthenticateUser(dominName, userName, password))
            {
                Response.Redirect("default.aspx");
            }
            else
            {
                Response.Write("Invalid user name or Password!");
            }

        }

        public bool AuthenticateUser(string domain, string username, string password)
        {
            DirectoryEntry entry = new DirectoryEntry(domain, username, password);
            try
            {
                DirectorySearcher search = new DirectorySearcher(entry);
                search.Filter = "(sAMAccountName=" + username + ")";
                search.PropertiesToLoad.Add("cn");
                Response.Write(domain);
                SearchResult result = search.FindOne();

                if (null == result)
                {
                    return false;
                }

            }
            catch (Exception ex)
            {
                return false;
                throw new Exception("Error authenticating user." + ex.Message);
            }
            return true;
        }

Find the above code what i make a mistake. Please provide a best solution to this...

Body:
You can get it from PrincipalContext. If you have specific domain, you might want to look at this sample code.

public bool ValidateCredentials(string userName, string password)
{
    userName = userName.EnsureNotNull();
    userName = userName.Trim();

    password = password.EnsureNotNull();
    password = password.Trim();

    using (var context = new PrincipalContext(ContextType.Domain))
    {
        return context.ValidateCredentials(userName, password);
    }
}

public bool IsUserInAdGroup(string userName, string adGroupName)
{
    bool result = false;
    userName = userName.EnsureNotNull();
    userName = userName.Trim();

    using (var context = new PrincipalContext(ContextType.Domain))
    {
        var user = UserPrincipal.FindByIdentity(context, userName);
        if (user != null)
        {
            var group = GroupPrincipal.FindByIdentity(context, adGroupName);
            if (group != null)
            {
                if (user.IsMemberOf(group))
                {
                    result = true;
                }
            }
        }
    }
    return result;
}


问:
Publish subscribe doesn't seem to work
I'm new to meteor and I saw that it's better to remove autopublish.
So I try to publish and subscribe a collection to get two different values.
In my meteor side I have :

```<code>Meteor.publish('channelUser',
    function(){
    var user = Meteor.users.findOne({
        '_id':this.userId
    });
        console.log(user);
       var test = Channels.find({
            '_id': {$in : user.profile.channelIds}
        });
        return test;
    }
);

Meteor.publish('channelToJoin',
function(){
    var user = Meteor.users.findOne({
        '_id':this.userId
    });
    console.log(user);

    var test = Channels.find({'_id': {$nin: user.profile.channelIds}});
    console.log(test);
    return test;
});
</code>```

And in my client side in a first component I have :

```<code>this.channelSub = MeteorObservable.subscribe('channelUser').subscribe();
   this.channels = Channels.find({});
</code>```

And on a second component :

```<code> Meteor.subscribe("channelToJoin");
this.channels = Channels.find({}).zone();
</code>```

But on my client side on both of the component, I have the same data.
Is there some kind of conflict in the subscribe ?

I hope I was clear to describe my problem !

答:
Pub/Sub just fills your Client collection Channels.
You can see it as a flow filling your local bucket. You may have several subscriptions filling different documents of Channels collection, but all end up in that single collection on the Client.

Then you have to adjust your query on client side to get the documents you need (e.g. Channels.find({'_id': {$nin: user.profile.channelIds}}); on Client as well). Of course you may have different queries in different templates, and different from the server publication as well.

See also How do I control two subscriptions to display within a single template?

Title: Publish subscribe doesn't seem to work

Body:
I'm new to meteor and I saw that it's better to remove autopublish.
So I try to publish and subscribe a collection to get two different values.
In my meteor side I have :

Meteor.publish('channelUser',
    function(){
    var user = Meteor.users.findOne({
        '_id':this.userId
    });
        console.log(user);
       var test = Channels.find({
            '_id': {$in : user.profile.channelIds}
        });
        return test;
    }
);

Meteor.publish('channelToJoin',
function(){
    var user = Meteor.users.findOne({
        '_id':this.userId
    });
    console.log(user);

    var test = Channels.find({'_id': {$nin: user.profile.channelIds}});
    console.log(test);
    return test;
});

And in my client side in a first component I have :

this.channelSub = MeteorObservable.subscribe('channelUser').subscribe();
   this.channels = Channels.find({});

And on a second component :

 Meteor.subscribe("channelToJoin");
this.channels = Channels.find({}).zone();

But on my client side on both of the component, I have the same data.
Is there some kind of conflict in the subscribe ?

I hope I was clear to describe my problem !


问:
Metadata file '.dll' could not be found
I am working on a WPF, C# 3.0 project, and I get this error:

```<code>Error 1 Metadata file
'WORK=- \Tools\VersionManagementSystem\BusinessLogicLayer\bin\Debug
\BusinessLogicLayer.dll' could not be found C:\-=WORK=- \Tools
\VersionManagementSystem\VersionManagementSystem\CSC VersionManagementSystem
</code>```

This is how I reference my usercontrols:

```<code>xmlns:vms="clr-namespace:VersionManagementSystem"
<vms:SignOffProjectListing Margin="5"/>
</code>```

It happens after every failed build. The only way I can get the solution to compile is to comment out all my user controls and re-build the project, and then I uncomment the usercontrols and everything is fine.

I have checked build orders and dependencies configurations.

As you can see, it seems to have truncated the DLL file's absolute path... I have read that there is a bug with the length. Is this a possible problem?

It's very annoying and having to comment, build, and uncomment, the build is becoming extremely tiresome.

答:
For me it occurred when I included a new project to a solution.

Visual Studio automatically selects .NET framework 4.5.

I changed to version .NET 4.5.2 like the other libraries, and it worked.

Title: Metadata file '.dll' could not be found

Body:
I am working on a WPF, C# 3.0 project, and I get this error:

Error 1 Metadata file
'WORK=- \Tools\VersionManagementSystem\BusinessLogicLayer\bin\Debug
\BusinessLogicLayer.dll' could not be found C:\-=WORK=- \Tools
\VersionManagementSystem\VersionManagementSystem\CSC VersionManagementSystem

This is how I reference my usercontrols:

xmlns:vms="clr-namespace:VersionManagementSystem"
<vms:SignOffProjectListing Margin="5"/>

It happens after every failed build. The only way I can get the solution to compile is to comment out all my user controls and re-build the project, and then I uncomment the usercontrols and everything is fine.

I have checked build orders and dependencies configurations.

As you can see, it seems to have truncated the DLL file's absolute path... I have read that there is a bug with the length. Is this a possible problem?

It's very annoying and having to comment, build, and uncomment, the build is becoming extremely tiresome.


问:
How to apply colour changes to all HTML pages
I am trying to change the colour of the background and text on multiple pages rather than on just one.

The code at the bottom can change the colour and text on one page but DOES NOT CARRY OVER TO OTHERS. How would I do it to all my web pages rather than do it on each page individually every time. I am creating this in Notepad++ and running it in Xampp.

```<code>  <!DOCTYPE HTML>
<html lang="en">
  <head>
  <script>
localStorage.setItem('backgroundcolours', 'bgc.options[selectedIndex].value');
localStorage.setItem('myBackgroundColor', '#000088');}
 retrrievecolour() {
var changingText = document.getElementById('changemytext');
var changingbackground = document.getElementById('changemybg');

changingText.style.color = localStorage.backgroundcolours;
changingBackground.style.backgroundColor = localStorage.myBackgroundColor;}</script>
<script language="JavaScript" type="text/javascript">

</script>
  <script src="js/scripts.js"></script>
  <meta charset="utf-8">
  <title>Home page </title>
<div id='changemybg'><div id='changemytext'>
 <script !type="text/javascript" charset="utf-8"></script>

<a class="active" href="Homepage.html">dif</a>
<a class="active" href="newtest.html">Home </a>
<a class="active" href="test.html">test </a>
 </head>

<body>

<script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
 <form name=backgroundcolour>Background<br><select NAME=backgroundcolouring size= 1
onChange="document.getElementById('changemybg').style.background=backgroundcolouring.options[selectedIndex].value">
    <option VALUE="#FFFFFF">White </option>
    <option VALUE="#F0F0FF">Light Blue </option>
    <option VALUE="#FFFFD4">Light Yellow </option>
    <option VALUE="#EEEEEE">Light Gray </option>
</select></form></td>
<td align="center"><form name=textcolours>Text<br><select NAME=textcolour size=1
onChange="document.getElementById('changemytext').style.color=textcolour.options[selectedIndex].value">
    <option VALUE="#000000">Black </option>
    <option VALUE="#444444">Charcoal </option>
    <option VALUE="#000088">Dark Blue </option>
    <option VALUE="#117722">Dark Green </option>
</select></form></td>
</tr></table>
</body>
</html>
</code>```

答:
CSS styles like color: #FFFFFF; and background-color: #000088 are simple name-value pairings, so you can straightforwardly use HTML5 localStorage for this.

To set the values:

```<code>localStorage.setItem('myColor', '#FFFFFF');
localStorage.setItem('myBackgroundColor', '#000088');
</code>```

To retrieve the values:

```<code>var changingText = document.getElementById('changemytext');
var changingbackground = document.getElementById('changemybg');

changingText.style.color = localStorage.myColor;
changingBackground.style.backgroundColor = localStorage.myBackgroundColor;
</code>```

Body:
I am trying to change the colour of the background and text on multiple pages rather than on just one.

The code at the bottom can change the colour and text on one page but DOES NOT CARRY OVER TO OTHERS. How would I do it to all my web pages rather than do it on each page individually every time. I am creating this in Notepad++ and running it in Xampp.

  <!DOCTYPE HTML>

  <meta charset="utf-8">
  <title>Home page </title>

dif
Home
test

 <form name=backgroundcolour>Background
<select NAME=backgroundcolouring size= 1
onChange="document.getElementById('changemybg').style.background=backgroundcolouring.options[selectedIndex].value">
    <option VALUE="#FFFFFF">White </option>
    <option VALUE="#F0F0FF">Light Blue </option>
    <option VALUE="#FFFFD4">Light Yellow </option>
    <option VALUE="#EEEEEE">Light Gray </option>
</select></form>
<form name=textcolours>Text
<select NAME=textcolour size=1
onChange="document.getElementById('changemytext').style.color=textcolour.options[selectedIndex].value">
    <option VALUE="#000000">Black </option>
    <option VALUE="#444444">Charcoal </option>
    <option VALUE="#000088">Dark Blue </option>
    <option VALUE="#117722">Dark Green </option>
</select></form>

Body:
CSS styles like color: #FFFFFF; and background-color: #000088 are simple name-value pairings, so you can straightforwardly use HTML5 localStorage for this.

To set the values:

localStorage.setItem('myColor', '#FFFFFF');
localStorage.setItem('myBackgroundColor', '#000088');

To retrieve the values:

var changingText = document.getElementById('changemytext');
var changingbackground = document.getElementById('changemybg');

changingText.style.color = localStorage.myColor;
changingBackground.style.backgroundColor = localStorage.myBackgroundColor;


问:
render editor in cshtml for a viewmodel
I have the following viewmodel :

```<code>public MyViewModel
{
       prop string p1 {get;set;}
       prop string p2 {get;set;}
}
</code>```

And in my razor view I am trying to implement a form allowing the edition of this model, this is what I've done :

```<code>@model MyViewModel
@using (Html.BeginForm("MyAction", "MyController", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
  @Html.TextBoxFor(model => model.p1)
  @Html.TextBoxFor(model => model.p2)
}
</code>```

This is working, but it's a little heavy as I must update my razor view with a new line each time I add or remove a property to my viewmodel.
Wouldn't be possible to generate in one line a form allowing the edition of all viewmodel properties. I tried these 2 followings lines, but it rendered nothing :

```<code>@model MyViewModel
@Html.EditorForModel() //or @Html.EditorFor(model => model)
</code>```

答:
The whole entire point of using editor templates is to customize how things are presented. If all you want to do is call Html.EditorForModel(), you can do that straight in the view without needing an editor template at all.

The reason this is not working in particular, is because you basically have a infinite recursion. Html.EditorForModel() will utilize the editor template, if there is one, to render the fields for the model. Logically, you can't call that in the actual editor template.

If you want to simplify things, you should work on creating custom editor templates for basic types: String, DateTime, etc. Then you can call something like Html.EditorForModel() and it will render fields for all the properties on that model using the editor templates for those property types. That way, you get your custom fields, while still not having to manually specify each one. The only reason to create editor templates for complex types like your MyViewModel is if you want to do something very specific there. Otherwise, leave it alone.

FWIW, you should never include an actual form in an editor template. That's just wrong on oh so many levels, and will create far more problems than you think you're solving.

Title: render editor in cshtml for a viewmodel

Body:
I have the following viewmodel :

public MyViewModel
{
       prop string p1 {get;set;}
       prop string p2 {get;set;}
}

And in my razor view I am trying to implement a form allowing the edition of this model, this is what I've done :

@model MyViewModel
@using (Html.BeginForm("MyAction", "MyController", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
  @Html.TextBoxFor(model => model.p1)
  @Html.TextBoxFor(model => model.p2)
}

This is working, but it's a little heavy as I must update my razor view with a new line each time I add or remove a property to my viewmodel.
Wouldn't be possible to generate in one line a form allowing the edition of all viewmodel properties. I tried these 2 followings lines, but it rendered nothing :

@model MyViewModel
@Html.EditorForModel() //or @Html.EditorFor(model => model)


问:
print IP Address and Username(operating System or Software) in oracle report
is there any possibility that print the IP address and Operating System or Software schema on the report of that client where from the report is printed</p>

答:
Google for sys_context.

```<code>SELECT SYS_CONTEXT ('USERENV', 'SESSION_USER') ,  SYS_CONTEXT ('USERENV', 'IP_ADDRESS') ,  SYS_CONTEXT ('USERENV', 'OS_USER')  FROM DUAL;
</code>```

Result of this select will relevant if user is connected directly to oracle not by web application

Body:
Google for sys_context.

SELECT SYS_CONTEXT ('USERENV', 'SESSION_USER') ,  SYS_CONTEXT ('USERENV', 'IP_ADDRESS') ,  SYS_CONTEXT ('USERENV', 'OS_USER')  FROM DUAL;

Result of this select will relevant if user is connected directly to oracle not by web application


问:
CarrierWave not uploading (after upgrade)
A month back I upgraded my Ruby version on RoR-app from 1.9.3 to 2.3.3. I have been successfully using fog & carrierwave to upload images to Amazon S3 before that but after the upgrade it stopped working. It does not upload my images to S3 any longer, the folders and files are not created there. What makes this so problematic is that I cannot troubleshoot it at all, I get no error messages or anything.

Versions:

fog 1.38.0

carrierwave 1.0.0

ruby 2.3.3

rails 4.1.13

Useful information:

I have tried fog/aws and carrierwave-aws with the same (failing) result

If I change the AWS credentials to something obviously false, the same problem occurs. I.e., it seems like there could be something wrong with the CarrierWave config file, or that it is not loaded or something

The objects (Gift) are being saved properly

I have not done any changes on Amazon, as far as I know.

I have tried to swith to another set of AWS Access key and id but with the same problem.

I am using AssetSync on the same app (with the same credentials) to upload to AWS and this works! I.e. there shouldn't be something wrong with AWS/S3.

initializers/carrierwave.rb

```<code>CarrierWave.configure do |config|
  config.storage = 'fog'
  config.fog_credentials = {
    :provider               => 'AWS',
    :aws_access_key_id      => 'ABC123CODE',
    :aws_secret_access_key  => '+ABC123CODEKEY',
    :region                 => 'eu-central-1'
  }
  config.fog_directory  = 'myapp-se'
  config.cache_dir = "#{Rails.root}/tmp"

  config.fog_attributes = {
    expires: 1.year.from_now.httpdate,
    cache_control: "max-age=#{1.year.to_i}"
  }

  config.ignore_integrity_errors = false
  config.ignore_processing_errors = false
  config.ignore_download_errors = false

end
</code>```

Gift-model (gift.rb) - (related part)

```<code>  mount_uploader :cached_image, GiftImageUploader
  #validates_integrity_of :cached_image
  #validates_processing_of :cached_image
  validates_integrity_of :cached_image
  validates_processing_of :cached_image
  validates_download_of :cached_image

    file = Tempfile.new(["image", ".jpg"])
    file.binmode

    begin
      open(URI.parse(external_image_url), :allow_redirections => :safe) do |data|
        file.write data.read
      end
    rescue Exception => e
      logger.info "Error fetching image for product #{id}: " + e.message
      return false
    end

    file.rewind

    self.cached_image = file
    begin
      self.skip_callbacks = true
      if self.save!
        logger.info "Successfully cached image for product #{id}"
        return true
      else
        logger.info "Soft Error saving product #{id}"
        return false
      end
      self.skip_callbacks = false
    rescue Exception => e
      logger.info "Rescue Error saving product #{id}" + e.message
    end
</code>```

Uploader file

```<code>class GiftImageUploader < CarrierWave::Uploader::Base
  include CarrierWave::RMagick

  storage :fog

  def store_dir
    "cached/gifts/#{model.id}"
  end

  def extension_white_list
    %w(jpg jpeg gif png)
  end

  version :s300 do
    process resize_to_fit: [300, 300]
  end

  version :s200, :from_version => :s300 do
    process resize_to_fit: [200, 200]
  end

  version :s150, :from_version => :s200 do
    process resize_to_fit: [150, 150]
  end

  version :sq150 do
    process resize_to_fill: [150, 150]
  end

  version :s75, :from_version => :s150 do
    process resize_to_fit: [75, 75]
  end

  version :sq75 do
    process resize_to_fill: [75, 75]
  end

end
</code>```

What I need help with:

Since my major issue is that this all fails silently, I cannot even begin to troubleshoot the function. Any suggestion on how I could trial-and-error troubleshoot this app until I can get some information on the error would be highly appreciated.

If you can see anything in the code that would solve the problem would of course be really useful as well!

答: I solved this using carrierwave-aws gem. The solution is too complex and too specific for my particular application to be of interest for future readers. Frankly, I am not really sure why this solved this issue.</p>

Body:
A month back I upgraded my Ruby version on RoR-app from 1.9.3 to 2.3.3. I have been successfully using fog & carrierwave to upload images to Amazon S3 before that but after the upgrade it stopped working. It does not upload my images to S3 any longer, the folders and files are not created there. What makes this so problematic is that I cannot troubleshoot it at all, I get no error messages or anything.

Versions:

fog 1.38.0

carrierwave 1.0.0

ruby 2.3.3

rails 4.1.13

Useful information:

I have tried fog/aws and carrierwave-aws with the same (failing) result

If I change the AWS credentials to something obviously false, the same problem occurs. I.e., it seems like there could be something wrong with the CarrierWave config file, or that it is not loaded or something

The objects (Gift) are being saved properly

I have not done any changes on Amazon, as far as I know.

I have tried to swith to another set of AWS Access key and id but with the same problem.

I am using AssetSync on the same app (with the same credentials) to upload to AWS and this works! I.e. there shouldn't be something wrong with AWS/S3.

initializers/carrierwave.rb

CarrierWave.configure do |config|
  config.storage = 'fog'
  config.fog_credentials = {
    :provider               => 'AWS',
    :aws_access_key_id      => 'ABC123CODE',
    :aws_secret_access_key  => '+ABC123CODEKEY',
    :region                 => 'eu-central-1'
  }
  config.fog_directory  = 'myapp-se'
  config.cache_dir = "#{Rails.root}/tmp"

  config.fog_attributes = {
    expires: 1.year.from_now.httpdate,
    cache_control: "max-age=#{1.year.to_i}"
  }

  config.ignore_integrity_errors = false
  config.ignore_processing_errors = false
  config.ignore_download_errors = false

end

Gift-model (gift.rb) - (related part)

  mount_uploader :cached_image, GiftImageUploader
  #validates_integrity_of :cached_image
  #validates_processing_of :cached_image
  validates_integrity_of :cached_image
  validates_processing_of :cached_image
  validates_download_of :cached_image

    file = Tempfile.new(["image", ".jpg"])
    file.binmode

    begin
      open(URI.parse(external_image_url), :allow_redirections => :safe) do |data|
        file.write data.read
      end
    rescue Exception => e
      logger.info "Error fetching image for product #{id}: " + e.message
      return false
    end

    file.rewind

    self.cached_image = file
    begin
      self.skip_callbacks = true
      if self.save!
        logger.info "Successfully cached image for product #{id}"
        return true
      else
        logger.info "Soft Error saving product #{id}"
        return false
      end
      self.skip_callbacks = false
    rescue Exception => e
      logger.info "Rescue Error saving product #{id}" + e.message
    end

Uploader file

class GiftImageUploader < CarrierWave::Uploader::Base
  include CarrierWave::RMagick

  storage :fog

  def store_dir
    "cached/gifts/#{model.id}"
  end

  def extension_white_list
    %w(jpg jpeg gif png)
  end

  version :s300 do
    process resize_to_fit: [300, 300]
  end

  version :s200, :from_version => :s300 do
    process resize_to_fit: [200, 200]
  end

  version :s150, :from_version => :s200 do
    process resize_to_fit: [150, 150]
  end

  version :sq150 do
    process resize_to_fill: [150, 150]
  end

  version :s75, :from_version => :s150 do
    process resize_to_fit: [75, 75]
  end

  version :sq75 do
    process resize_to_fill: [75, 75]
  end

end

What I need help with:

Since my major issue is that this all fails silently, I cannot even begin to troubleshoot the function. Any suggestion on how I could trial-and-error troubleshoot this app until I can get some information on the error would be highly appreciated.

If you can see anything in the code that would solve the problem would of course be really useful as well!


问:
Finding all paths between two nodes on a DAG
I have a DAG that has the following adjacency list

```<code>L | G, B, P
G | P, I
B | I
P | I
I | R
R | \
</code>```

I want to find all paths from L to R. I know that I have to do some kind of DFS, and this is what I have so far. (Excuse the Javascript)

```<code>function dfs(G, start_vertex) {

    const fringe = []
    const visited = new Set()
    const output = []
    fringe.push(start_vertex)

    while (fringe.length != 0) {
        const vertex = fringe.pop()
        if (!visited.has(vertex)) {
            output.push(vertex)
            for (neighbor in G[vertex].neighbors) {
                fringe.push(neighbor)
            }
            visited.add(vertex)
        }
    }

    return output
}
</code>```

The output of dfs(G, "L") is [ 'L', 'P', 'I', 'R', 'B', 'G' ] which is indeed a depth first traversal of this graph, but not the result I'm looking for. After doing some searching, I realize there may be a recursive solution, but there were some comments about this problem being "NP-hard" and something about "exponential paths" which I don't understand.

答: The problem is indeed np-hard because the number of possible paths between two nodes is exponential to the number of nodes. so no way around having a worst-case  exponential runtime.</p>

Body:
I have a DAG that has the following adjacency list

L | G, B, P
G | P, I
B | I
P | I
I | R
R | \

I want to find all paths from L to R. I know that I have to do some kind of DFS, and this is what I have so far. (Excuse the Javascript)

function dfs(G, start_vertex) {

    const fringe = []
    const visited = new Set()
    const output = []
    fringe.push(start_vertex)

    while (fringe.length != 0) {
        const vertex = fringe.pop()
        if (!visited.has(vertex)) {
            output.push(vertex)
            for (neighbor in G[vertex].neighbors) {
                fringe.push(neighbor)
            }
            visited.add(vertex)
        }
    }

    return output
}

The output of dfs(G, "L") is [ 'L', 'P', 'I', 'R', 'B', 'G' ] which is indeed a depth first traversal of this graph, but not the result I'm looking for. After doing some searching, I realize there may be a recursive solution, but there were some comments about this problem being "NP-hard" and something about "exponential paths" which I don't understand.


问:
Writing an SQL query to return all fields from 2 sqlite tables (Android app)
Hi I'm creating a fitness app where workout info can be saved to 2 tables (TABLE_CARDIO for cardio activity and TABLE_WEIGHTS for weight training activity). Below is the structure of the 2 tables:

```<code>public static final String DATABASE_NAME = "FitnessTracker.db";
public static final String TABLE_WEIGHTS = "saved_workout_weights";
public static final String COL_1 = "ID";
public static final String COL_2 = "DATE";
public static final String COL_3 = "EXERCISE";
public static final String COL_4 = "WEIGHT";
public static final String COL_5 = "REPS";
public static final String COL_6 = "SETS";

public static final String TABLE_CARDIO = "saved_workout_cardio";
public static final String COL_1a = "ID";
public static final String COL_2a = "DATE";
public static final String COL_3a = "TIME";
</code>```

I then have the following method with a query for selecting all data from both tables (which is what I need):

```<code>public Cursor getWorkoutData() {
    SQLiteDatabase db = this.getWritableDatabase();
    String query = "SELECT * FROM " + TABLE_CARDIO + "FULL OUTER JOIN " + TABLE_WEIGHTS + "ON" + TABLE_CARDIO.DATE = TABLE_WEIGHTS.DATE; ;
    Cursor result = db.rawQuery(query,null);
    return result;
}
</code>```

As you can see, within the query, I'm trying to join the 2 tables using the 'DATE' field as a foreign key. However, android studio is highlighting 'DATE' in red and throwing the error 'Cannot resolve symbol'.

I know there are some similar questions to this up here but I've been unable to implement any of the solutions in to my scenario. Any help with this would be appreciated!

答:
Forgot to place "=". Your query should be like following

```<code>String query = "SELECT * FROM " + TABLE_CARDIO + " FULL OUTER JOIN " + TABLE_WEIGHTS + " ON " + TABLE_CARDIO.DATE + " = " + TABLE_WEIGHTS.DATE;
</code>```

Dont forget to place whitespaces around of sql keywords.

Added

Another thing is ambigous field names. So you need to place table names before fields.

```<code>String query = "SELECT * FROM " + TABLE_CARDIO + " FULL OUTER JOIN " + TABLE_WEIGHTS + " ON " + TABLE_CARDIO + ".DATE = " + TABLE_WEIGHTS + ".DATE";
</code>```

And please don't use select * from ... queries. :-)

Body:
Hi I'm creating a fitness app where workout info can be saved to 2 tables (TABLE_CARDIO for cardio activity and TABLE_WEIGHTS for weight training activity). Below is the structure of the 2 tables:

public static final String DATABASE_NAME = "FitnessTracker.db";
public static final String TABLE_WEIGHTS = "saved_workout_weights";
public static final String COL_1 = "ID";
public static final String COL_2 = "DATE";
public static final String COL_3 = "EXERCISE";
public static final String COL_4 = "WEIGHT";
public static final String COL_5 = "REPS";
public static final String COL_6 = "SETS";

public static final String TABLE_CARDIO = "saved_workout_cardio";
public static final String COL_1a = "ID";
public static final String COL_2a = "DATE";
public static final String COL_3a = "TIME";

I then have the following method with a query for selecting all data from both tables (which is what I need):

public Cursor getWorkoutData() {
    SQLiteDatabase db = this.getWritableDatabase();
    String query = "SELECT * FROM " + TABLE_CARDIO + "FULL OUTER JOIN " + TABLE_WEIGHTS + "ON" + TABLE_CARDIO.DATE = TABLE_WEIGHTS.DATE; ;
    Cursor result = db.rawQuery(query,null);
    return result;
}

As you can see, within the query, I'm trying to join the 2 tables using the 'DATE' field as a foreign key. However, android studio is highlighting 'DATE' in red and throwing the error 'Cannot resolve symbol'.

I know there are some similar questions to this up here but I've been unable to implement any of the solutions in to my scenario. Any help with this would be appreciated!

Body:
Forgot to place "=". Your query should be like following

String query = "SELECT * FROM " + TABLE_CARDIO + " FULL OUTER JOIN " + TABLE_WEIGHTS + " ON " + TABLE_CARDIO.DATE + " = " + TABLE_WEIGHTS.DATE;

Dont forget to place whitespaces around of sql keywords.

Added

Another thing is ambigous field names. So you need to place table names before fields.

String query = "SELECT * FROM " + TABLE_CARDIO + " FULL OUTER JOIN " + TABLE_WEIGHTS + " ON " + TABLE_CARDIO + ".DATE = " + TABLE_WEIGHTS + ".DATE";

And please don't use select * from ... queries. :-)


问:
Sass color transform calculation
I have two shades of the color blue (#1E95EF -> #1988DD), and need to figure out the color transformation that has happened in order to replicate it across other colors in my palette (red, green etc).

I've used combinations of darken()/lighten() & saturate()/desaturate() to eyeball the transformation, and have gotten it pretty close:

desaturate(darken(#1E95EF, 4.5%), 8%); === #1A88DC

But I need to get it exactly right, so that the small errors that I make with the percentage decimal points are not replicated across all of the colors. How can I figure out exactly what transformation has occurred?

Here is what I've tried:

sassmeister gist

In this snippet, the relevant classes to my example are .ga-primary and .ga-primary-hover

答:
You can measure the differences between colors in different ways, depending on the color model/space you're using. Hex colors use RGB, but the HSL model will be more useful here. It records a color as 3 values: Hue, Saturation and Lightness.

We can use SASS's HSL functions to work out how each value of the color differs, and then selectively apply that difference to other colors:

```<code>$start-color: #1E95EF
$end-color: #1988DD

//We won't need the hue-difference in practice
$hue-difference: hue($start-color) - hue($end-color)

//These express the difference as a percentage
$saturation-difference: saturation($start-color) - saturation($end-color)
$lightness-difference: lightness($start-color) - lightness($end-color)

@function color-adjust($base-color)
  //Apply the lightness and saturation changes but keep the original Hue
  @return hsl(hue($base-color), saturation($base-color) + $saturation-difference, lightness($base-color) + $lightness-difference)

//To find the adjusted color, just pass whatever base color you like to the color-adjust function:
background: color-adjust(red)
</code>```

Here's a demo with a few colors: http://codepen.io/anon/pen/bqOaZZ

Obviously that code can be compacted a lot - I'm thinking that what you really want is to define your variants as a set of Saturation/Lightness changes, and then apply them to your whole palette (rather than trying to 'reverse-engineer' it from one example pair). If you want help with something to do that, let me know!

Title: Sass color transform calculation

Body:
You can measure the differences between colors in different ways, depending on the color model/space you're using. Hex colors use RGB, but the HSL model will be more useful here. It records a color as 3 values: Hue, Saturation and Lightness.

We can use SASS's HSL functions to work out how each value of the color differs, and then selectively apply that difference to other colors:

$start-color: #1E95EF
$end-color: #1988DD

//We won't need the hue-difference in practice
$hue-difference: hue($start-color) - hue($end-color)

//These express the difference as a percentage
$saturation-difference: saturation($start-color) - saturation($end-color)
$lightness-difference: lightness($start-color) - lightness($end-color)

@function color-adjust($base-color)
  //Apply the lightness and saturation changes but keep the original Hue
  @return hsl(hue($base-color), saturation($base-color) + $saturation-difference, lightness($base-color) + $lightness-difference)

//To find the adjusted color, just pass whatever base color you like to the color-adjust function:
background: color-adjust(red)

Here's a demo with a few colors: http://codepen.io/anon/pen/bqOaZZ

Obviously that code can be compacted a lot - I'm thinking that what you really want is to define your variants as a set of Saturation/Lightness changes, and then apply them to your whole palette (rather than trying to 'reverse-engineer' it from one example pair). If you want help with something to do that, let me know!


问:
Adding a custom JSONB text_field tag with simple_form
I have a JSONB type options column on a model in my Rails application and I am in a situation where I need to provide JSONB nested parameters manually for every single form. That's why the official solution proposed here is not an option.

So I might want to have something like:

```<code>options[first_name], options[last_name]
</code>```

for one instance, and a totally different set for another:

```<code>options[pet_dog], options[frank_sinatra]
</code>```

I assume it can well be implemented using something like

```<code>= f.text_field :options[pet_dog]
</code>```

But it's not working.

答:
How did you implement the jsonb column? Have you added this to the model?

```<code>serialize :options, HashSerializer
store_accessor :options, :pet_dog, :pet_cat, :pet_cow
</code>```

*Note that HashSerializer is a class acting as a serializer, which looks like this:

```<code>class HashSerializer
  def self.dump(hash)
    hash.to_json
  end

  def self.load(hash)
    (hash || {}).with_indifferent_access
  end
end
</code>```

What those 2 lines on the model do is allowing you using accessor (getter and setter) for the json/jsonb keys. So you can do this:

```<code>object = Model.new
object.pet_dog = 'Dog1'
object.pet_cat = 'Cat1'
object.options = {"pet_dog"=>"Dog1", "pet_cat"=>"Cat1"}
</code>```

Which in turn, allows you to use it as form fields:

```<code>f.text_field :pet_dog
f.text_field :pet_cat
</code>```

Do not forget to whitelist the attributes in the strong_params method

You can read more on this comprehensive post by Nando Vieira:
http://nandovieira.com/using-postgresql-and-jsonb-with-ruby-on-rails

Also, if you want a shortcut, there is a gem for this:
https://github.com/devmynd/jsonb_accessor

Body:
I have a JSONB type options column on a model in my Rails application and I am in a situation where I need to provide JSONB nested parameters manually for every single form. That's why the official solution proposed here is not an option.

So I might want to have something like:

options[first_name], options[last_name]

for one instance, and a totally different set for another:

options[pet_dog], options[frank_sinatra]

I assume it can well be implemented using something like

= f.text_field :options[pet_dog]

But it's not working.

Body:
How did you implement the jsonb column? Have you added this to the model?

serialize :options, HashSerializer
store_accessor :options, :pet_dog, :pet_cat, :pet_cow

*Note that HashSerializer is a class acting as a serializer, which looks like this:

class HashSerializer
  def self.dump(hash)
    hash.to_json
  end

  def self.load(hash)
    (hash || {}).with_indifferent_access
  end
end

What those 2 lines on the model do is allowing you using accessor (getter and setter) for the json/jsonb keys. So you can do this:

object = Model.new
object.pet_dog = 'Dog1'
object.pet_cat = 'Cat1'
object.options = {"pet_dog"=>"Dog1", "pet_cat"=>"Cat1"}

Which in turn, allows you to use it as form fields:

f.text_field :pet_dog
f.text_field :pet_cat

Do not forget to whitelist the attributes in the strong_params method

You can read more on this comprehensive post by Nando Vieira:
http://nandovieira.com/using-postgresql-and-jsonb-with-ruby-on-rails

Also, if you want a shortcut, there is a gem for this:
https://github.com/devmynd/jsonb_accessor