问:
Diffrent way of implementation security ends with the same error
I have implemented an application with combination Spring Boot and Angular 4. I put all Angular files under /resources/static directory:

static directory

Then I added to Spring Security classes:

```<code>@Configuration
@EnableWebMvc
@ComponentScan("com.inventory")
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/static/**")
                .addResourceLocations("classpath:/resources/static/");
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index.html");
    }
}
</code>```

and:

```<code>@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordencoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests()
                .antMatchers("/").permitAll()
                .anyRequest().authenticated();
    }
</code>```

and it seem that everythings should work. Unfortunately whenever I run my app it throws exception:

```<code>There was an unexpected error (type=Internal Server Error, status=500).
Could not resolve view with name 'index.html' in servlet with name 'dispatcherServlet'.
</code>```

Of course I tried diffrent solution like adding this:

```<code>@Controller
public class ViewController {

    @RequestMapping(value = "/#/")
    public String index() {
        return "forward:/index.html";
    }

    @RequestMapping(value = "/")
    public String home() {
        return "forward:/index.html";
    }
}
</code>```

But nothing works. Does anyone has a clue what else can I do?

答:
When using Spring boot normally you don't have to configure resource handler manually, spring boot will automatically load contents from the following loc:

/static

/public

/resources

/META-INF/resources

see spring boot guides on loading static contents

Body:
I have implemented an application with combination Spring Boot and Angular 4. I put all Angular files under /resources/static directory:

static directory

Then I added to Spring Security classes:

@Configuration
@EnableWebMvc
@ComponentScan("com.inventory")
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/static/**")
                .addResourceLocations("classpath:/resources/static/");
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index.html");
    }
}

and:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordencoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests()
                .antMatchers("/").permitAll()
                .anyRequest().authenticated();
    }

and it seem that everythings should work. Unfortunately whenever I run my app it throws exception:

There was an unexpected error (type=Internal Server Error, status=500).
Could not resolve view with name 'index.html' in servlet with name 'dispatcherServlet'.

Of course I tried diffrent solution like adding this:

@Controller
public class ViewController {

    @RequestMapping(value = "/#/")
    public String index() {
        return "forward:/index.html";
    }

    @RequestMapping(value = "/")
    public String home() {
        return "forward:/index.html";
    }
}

But nothing works. Does anyone has a clue what else can I do?


来源: stackexchange

问:
Core Data - Memory Management?
```<code>[myArray addObject:myObject];
[object release];
</code>```

In obvjective c every time you add an object with retain count of 1 to an array, you must release it right after to prevent a leak.

Does this apply to NSManagedObjects ?
Because in the code above if myObject is an instance of NSManagedObject I get "EXC_BAD_ACCESS"

答:
Look at the code:

```<code>[myArray addObject:myObject];
[object release]; //!!!What is object?
</code>```

Did you mean?

```<code>[myArray addObject:myObject];
[myObject release];
</code>```

And Cocoa Memory Management Programming Guide is a must to read.
If you don't want to read the whole thing the Memory Management Rules are the most important part.

In general when using Core Data you'll apply the same Memory Management Rules, but there are some caveats.

ContentLicense: CC BY-SA 2.5

Title: Core Data - Memory Management?

Body:
[myArray addObject:myObject];
[object release];

In obvjective c every time you add an object with retain count of 1 to an array, you must release it right after to prevent a leak.

Does this apply to NSManagedObjects ?
Because in the code above if myObject is an instance of NSManagedObject I get "EXC_BAD_ACCESS"

Body:
Look at the code:

[myArray addObject:myObject];
[object release]; //!!!What is object?

Did you mean?

[myArray addObject:myObject];
[myObject release];

And Cocoa Memory Management Programming Guide is a must to read.
If you don't want to read the whole thing the Memory Management Rules are the most important part.

In general when using Core Data you'll apply the same Memory Management Rules, but there are some caveats.


问:
How to call the jQuery module functions?
In this way, I want to understand JavaScript Module Pattern With jQuery.
I have a simple task for myself, There is one button and three jQuery functions, I want after clicking on the button, one function1 call another function2, and fucnction2 call function3 with an alert message.

My jQuery and html code.

$(document).ready(function() {
  $("#myBtn").click(function() {
    //How to add another two functions?
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script type='text/javascript' src='alertScript.js'></script>
</head>

<body>
  <button type="button" class="btn btn-default btn-lg" id="myBtn">Push</button>
</body>

</html></code>```

Thanks for any advise.

答:
try this method

$(document).ready(function() {
    $("#btnclick").click(function() {
        console.log('function1 called');
       function1();
    });
});
 function function1() {
            alert('1 call funtion2');
              console.log('function2 called');
            function2();
        }
        function function2() {
          alert('2 call funtion3');
            console.log('function3 called');
            function3();
        }
        function function3() {
          console.log('1 2 3 calling');
            alert('function 1 call function 2 and function2 call function 3');
        }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
</head>

<body>
    <button type="button" class="btn btn-default btn-lg" id="btnclick">Push</button>
</body>
</html></code>```

ContentLicense: CC BY-SA 3.0

Body:
In this way, I want to understand JavaScript Module Pattern With jQuery.
I have a simple task for myself, There is one button and three jQuery functions, I want after clicking on the button, one function1 call another function2, and fucnction2 call function3 with an alert message.

My jQuery and html code.

$(document).ready(function() {
  $("#myBtn").click(function() {
    //How to add another two functions?
  });
});

  <button type="button" class="btn btn-default btn-lg" id="myBtn">Push</button>

Thanks for any advise.

Body:
try this method

$(document).ready(function() {
    $("#btnclick").click(function() {
        console.log('function1 called');
       function1();
    });
});
 function function1() {
            alert('1 call funtion2');
              console.log('function2 called');
            function2();
        }
        function function2() {
          alert('2 call funtion3');
            console.log('function3 called');
            function3();
        }
        function function3() {
          console.log('1 2 3 calling');
            alert('function 1 call function 2 and function2 call function 3');
        }

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
</head>

<body>
    <button type="button" class="btn btn-default btn-lg" id="btnclick">Push</button>
</body>
</html>


问:
Methods to insert or replace values in to object
I've got an object like this

```<code>var obj2= {
        'home' : {
            '1' : {
                  'year' : '1999'
                  },
            '2' : {
                  'year' : '2000'
                  'month' : '11'
                  },
        },
        'company' : {
            '1' : {
                  'year' : '2010'
                  'month' : '2'
                  },
        }
    };
</code>```

And I would like to add some more keys inside the object or replace value if this key chain already exists, for ex:

```<code>buss_type = "home",
type_id = "1",
date_type = "month",
value = "9"

var tmp_obj1 = {[buss_type]: {[type_id]: {[date_type]: value}}};
</code>```

and

```<code>buss_type = "company",
type_id = "2",
date_type = "month",
value = "12"

var tmp_obj2 = {[buss_type]: {[type_id]: {[date_type]: value}}};
</code>```

to make object:

```<code>obj = {
    'home' : {
        '1' : {
            'year' : '1999',
            'month' : '9'
        },
        '2' : {
            'year' : '2000',
            'month' : '11'
        },
    },
    'company' : {
        '1' : {
            'year' : '2020',
            'month' : '10'
        },
        '2' : {
            'month' : '12'
        }
    },
};
</code>```

Arrays methods like .push() or .concat() adding new keys on the end only instead of replacing values of existing ones.

Are there any object methods that can make it easy to manage or should I just use loops and check all keys before adding new or changing value of existing one?

Thanks.

答:
You don't need to create a loop instead you can programmatically access the key you're about to add using this syntax:</p>

```<code>buss_type = "home",
type_id = "1",
date_type = "month",
value = "9"

if(obj[buss_type]){
   if(obj[buss_type][type_id]){
      obj[buss_type][type_id][date_type] =  value
   }else{
       obj[buss_type][type_id] = { date_type: value }
   }
}else{
    obj[buss_type] = { type_id: { date_type: value } }
}
</code>```

Body:
I've got an object like this

var obj2= {
        'home' : {
            '1' : {
                  'year' : '1999'
                  },
            '2' : {
                  'year' : '2000'
                  'month' : '11'
                  },
        },
        'company' : {
            '1' : {
                  'year' : '2010'
                  'month' : '2'
                  },
        }
    };

And I would like to add some more keys inside the object or replace value if this key chain already exists, for ex:

buss_type = "home",
type_id = "1",
date_type = "month",
value = "9"

var tmp_obj1 = {[buss_type]: {[type_id]: {[date_type]: value}}};

and

buss_type = "company",
type_id = "2",
date_type = "month",
value = "12"

var tmp_obj2 = {[buss_type]: {[type_id]: {[date_type]: value}}};

to make object:

obj = {
    'home' : {
        '1' : {
            'year' : '1999',
            'month' : '9'
        },
        '2' : {
            'year' : '2000',
            'month' : '11'
        },
    },
    'company' : {
        '1' : {
            'year' : '2020',
            'month' : '10'
        },
        '2' : {
            'month' : '12'
        }
    },
};

Arrays methods like .push() or .concat() adding new keys on the end only instead of replacing values of existing ones.

Are there any object methods that can make it easy to manage or should I just use loops and check all keys before adding new or changing value of existing one?

Thanks.

Body:
You don't need to create a loop instead you can programmatically access the key you're about to add using this syntax:

buss_type = "home",
type_id = "1",
date_type = "month",
value = "9"

if(obj[buss_type]){
   if(obj[buss_type][type_id]){
      obj[buss_type][type_id][date_type] =  value
   }else{
       obj[buss_type][type_id] = { date_type: value }
   }
}else{
    obj[buss_type] = { type_id: { date_type: value } }
}


问:
Firefox iframe scrolling issue
I have a web page that is hosted in an iframe.  I can only modify this page and not the containing page.

By default, my page's scrollbar is disabled, however if my page's size is over a certain threshold, I need to be able to turn on the vertical scrollbar.  The following code seems to work in all browsers but Firefox:

```<code>function getDocHeight() {
    var D = document;
    return Math.max(
        Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
        Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
        Math.max(D.body.clientHeight, D.documentElement.clientHeight)
    );
}

function setScrollbar() {
    if (getDocHeight() > 5000) {
        pageBody.style.overflow = 'scroll';
    }
}
</code>```

here is my HTML:

```<code><html xmlns="http://www.w3.org/1999/xhtml" >
    <head><title>My title</title></head>
    <body id="pageBody" onload="setScrollbar();">
    </body>
</html>
</code>```

Firefox seems to be ignoring the style.overflow = 'scroll'.  I've done a good bit of searching, and I can't seem to find a solution.  Any ideas?

答:
Unfortunately Firefox displays the scrollbars on the body of a frame based on the overflow style on the frame, not on the body. So the easiest way is to insert a 100% size borderless scrollable subframe, and load the real content in there instead.

If you don't want to do that, then you can mess around with nested DIVs like this:

```<code><body style="margin: 0px;"> <!-- override default body margin -->
  <div style="height: 100%; overflow: auto;"> <!-- The actual scrollable area -->
    <div style="margin: 8px;"> <!-- to emulate default body margin -->
      <!-- Content goes here -->
    </div>
  </div>
</body>
</code>```

Title: Firefox iframe scrolling issue

Body:
I have a web page that is hosted in an iframe.  I can only modify this page and not the containing page.

By default, my page's scrollbar is disabled, however if my page's size is over a certain threshold, I need to be able to turn on the vertical scrollbar.  The following code seems to work in all browsers but Firefox:

function getDocHeight() {
    var D = document;
    return Math.max(
        Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
        Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
        Math.max(D.body.clientHeight, D.documentElement.clientHeight)
    );
}

function setScrollbar() {
    if (getDocHeight() > 5000) {
        pageBody.style.overflow = 'scroll';
    }
}

here is my HTML:

    <title>My title</title>

Firefox seems to be ignoring the style.overflow = 'scroll'.  I've done a good bit of searching, and I can't seem to find a solution.  Any ideas?

Body:
Unfortunately Firefox displays the scrollbars on the body of a frame based on the overflow style on the frame, not on the body. So the easiest way is to insert a 100% size borderless scrollable subframe, and load the real content in there instead.

If you don't want to do that, then you can mess around with nested DIVs like this:

<body style="margin: 0px;"> <!-- override default body margin -->
  <div style="height: 100%; overflow: auto;"> <!-- The actual scrollable area -->
    <div style="margin: 8px;"> <!-- to emulate default body margin -->
      <!-- Content goes here -->
    </div>
  </div>
</body>


问:
Algorithm of CSS3 filter blur
Doc on MDN describes that filter blur applies a Gaussian blur to the input image. I have compared it with OpenCV's GaussianBlur, but their effect are not same.

I want to implement the same effect with CSS3 filter blur. Where can I find the algorithm?

答:
There are a lot of parameters that you can tweak on a Gaussian filter. Knowing that is a Gaussian filter is only half the solution..

You will need to know the size of the filter (3x3, 5x5, or any odd number combinations), the Gaussian standard deviation of the Gaussian in each axis(although i think it should be symmetrical)

You need to know and implement those parameters to your Gaussian filter in order to get the same effect.

Title: Algorithm of CSS3 filter blur


问:
My Flask-AppBuilder project only display ID for related table, instead of its name, Why?
I am going to use F.A.B for fast custom IoT APP Web as backend.

By running the sample project of F.A.B tutorial and documents, the http://127.0.0.1:5000/contactmodelview/list/ ContactView list page, the Contact Group is shown as name, in black, instead of id.

I cloned the design, there is a 1:N relationship (one account has many devices, as same as ContactGroup has many contacts), here is the code:

models.py

```<code>class Account(Model):
    id = Column(Integer, primary_key = True)
    username = Column(String(128), unique = True)
    password = Column(String(128))
    email = Column(String(128))
    oauth = Column(String(128))
    cellphone = Column(String(32))

    def __repr__(self):
        return self.username

class Device(Model):
    id = Column(Integer, primary_key = True)
    snr = Column(String(256), unique = True)
    name = Column(String(128))
    addr = Column(String(256))
    latitude = Column(Float)
    longitude = Column(Float)
    status = Column(Integer)
    api_id = Column(String(512))
    api_key = Column(String(256))
    api_dev_id = Column(String(256), unique = True)
    api_dev_key = Column(String(256))
    owner_id = Column(Integer, ForeignKey('account.id'))
    owner = relationship("Account")

    def __repr__(self):
        return self.name
</code>```

views.py

```<code>class DeviceView(ModelView):
    datamodel = SQLAInterface(Device)
    related_views = [ApplicationView, EventView]

    label_columns = {'snr':'SNR', 'api_dev_id':'Device ID', 'owner_id':'Owner'}
    list_columns = ['snr','name','addr','owner_id']

    show_fieldsets = [
    ('Summary',
        {'fields':['snr','name','owner_id']}
    ),
    ('Device Info',
            {'fields':'addr','latitude','longitude','status','api_id','api_key','api_dev_id','api_dev_key'],'expanded':True}
    ),
    ]

class AccountView(ModelView):
    datamodel = SQLAInterface(Account)
    related_views = [DeviceView]
</code>```

However, the list of DeviceView shows related ID in blue, and No Account name is displayed. However in DeviceDetail view, the Account name is displayed.

What's the differences?

答:
I found the reason, and change my view code as following:

```<code>class DeviceView(ModelView):
    datamodel = SQLAInterface(Device)
    related_views = [ApplicationView, EventView]

    label_columns = {'snr':'SNR', 'api_dev_id':'Device ID', 'owner_id':'Owner'}
    list_columns = ['name','snr','addr','owner']

    show_fieldsets = [
    ('Summary',
        {'fields':['snr','name','owner']}
    ),
    ('Device Info',
        {'fields':['addr','latitude','longitude','status','api_id','api_key','api_dev_id','api_dev_key'],'expanded':True}
    ),
    ]
</code>```

The major differences are replacing field 'owner_id' with 'owner'.

Body:
I am going to use F.A.B for fast custom IoT APP Web as backend.

By running the sample project of F.A.B tutorial and documents, the http://127.0.0.1:5000/contactmodelview/list/ ContactView list page, the Contact Group is shown as name, in black, instead of id.

I cloned the design, there is a 1:N relationship (one account has many devices, as same as ContactGroup has many contacts), here is the code:

models.py

class Account(Model):
    id = Column(Integer, primary_key = True)
    username = Column(String(128), unique = True)
    password = Column(String(128))
    email = Column(String(128))
    oauth = Column(String(128))
    cellphone = Column(String(32))

    def __repr__(self):
        return self.username

class Device(Model):
    id = Column(Integer, primary_key = True)
    snr = Column(String(256), unique = True)
    name = Column(String(128))
    addr = Column(String(256))
    latitude = Column(Float)
    longitude = Column(Float)
    status = Column(Integer)
    api_id = Column(String(512))
    api_key = Column(String(256))
    api_dev_id = Column(String(256), unique = True)
    api_dev_key = Column(String(256))
    owner_id = Column(Integer, ForeignKey('account.id'))
    owner = relationship("Account")

    def __repr__(self):
        return self.name

views.py

class DeviceView(ModelView):
    datamodel = SQLAInterface(Device)
    related_views = [ApplicationView, EventView]

    label_columns = {'snr':'SNR', 'api_dev_id':'Device ID', 'owner_id':'Owner'}
    list_columns = ['snr','name','addr','owner_id']

    show_fieldsets = [
    ('Summary',
        {'fields':['snr','name','owner_id']}
    ),
    ('Device Info',
            {'fields':'addr','latitude','longitude','status','api_id','api_key','api_dev_id','api_dev_key'],'expanded':True}
    ),
    ]

class AccountView(ModelView):
    datamodel = SQLAInterface(Account)
    related_views = [DeviceView]

However, the list of DeviceView shows related ID in blue, and No Account name is displayed. However in DeviceDetail view, the Account name is displayed.

What's the differences?

Body:
I found the reason, and change my view code as following:

class DeviceView(ModelView):
    datamodel = SQLAInterface(Device)
    related_views = [ApplicationView, EventView]

    label_columns = {'snr':'SNR', 'api_dev_id':'Device ID', 'owner_id':'Owner'}
    list_columns = ['name','snr','addr','owner']

    show_fieldsets = [
    ('Summary',
        {'fields':['snr','name','owner']}
    ),
    ('Device Info',
        {'fields':['addr','latitude','longitude','status','api_id','api_key','api_dev_id','api_dev_key'],'expanded':True}
    ),
    ]

The major differences are replacing field 'owner_id' with 'owner'.


问:
Need equality of CPBarPlot.barOffset in CPScatterPlot
What is equality of CPBarPlot.barOffset in CPScatterPlot ? So I can change the offset of my scatter plot.

答:
The barOffset is a CGFloat. It is the amount that the bars are offset from their true position given by the location coordinate. The units are a fraction of the barWidth property. For example:

```<code>barOffset = 0.5;   // moves the bars half a barWidth in the positive direction
barOffset = -0.25; // moves the bar a quarter of a barWidth in the negative direction
</code>```

Body:
The barOffset is a CGFloat. It is the amount that the bars are offset from their true position given by the location coordinate. The units are a fraction of the barWidth property. For example:

barOffset = 0.5;   // moves the bars half a barWidth in the positive direction
barOffset = -0.25; // moves the bar a quarter of a barWidth in the negative direction


问:
Why is the click function unable to apply more than one random index to my arrays
I'm stuck on the random quote machine project on Free Code Camp. I can generate random quotes and colors but they are only generated once using the click event. Subsequent clicks of the "New quote" button generate new random indexing for my colors and quotes array.

var quote = ["It is not the size of the dog in the fight, but the size of the fight in the dog.-Archie Griffen", "Nothing lasts forever. Not even your troubles.-Arnold H Glasgow", "There are only two ways to live your life. One is as though nothing is a miracle. The other is as though everything is a miracle-Albert Einstein"];

// problem area
var col = ["red", "blue", "yellow", "pink", "brown"];
var i = Math.floor(Math.random() * col.length);
var j = Math.floor(Math.random() * quote.length);

$(document).ready(function() {
  $("button").click(function() {
    $(".quote-window").html(quote[j]);
    $("body").css("background-color", col[i]);
  });
});
```

答:
You need to calculate variable i and j in the <button> click handler.

var quote = ["It is not the size of the dog in the fight, but the size of the fight in the dog.-Archie Griffen",
  "Nothing lasts forever. Not even your troubles.-Arnold H Glasgow",
  "There are only two ways to live your life. One is as though nothing is a miracle. The other is as though everything is a miracle-Albert Einstein"
];
var col = ["red", "blue", "yellow", "pink", "brown"];

$(document).ready(function() {
  $("button").click(function() {
    var i = Math.floor(Math.random() * col.length);
    var j = Math.floor(Math.random() * quote.length);
    $(".quote-window").html(quote[j]);
    $("body").css("background-color", col[i]);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click Me</button>
<div class='quote-window'></div></code>```

ContentLicense: CC BY-SA 4.0

Body:
You need to calculate variable i and j in the <button> click handler.

var quote = ["It is not the size of the dog in the fight, but the size of the fight in the dog.-Archie Griffen",
  "Nothing lasts forever. Not even your troubles.-Arnold H Glasgow",
  "There are only two ways to live your life. One is as though nothing is a miracle. The other is as though everything is a miracle-Albert Einstein"
];
var col = ["red", "blue", "yellow", "pink", "brown"];

$(document).ready(function() {
  $("button").click(function() {
    var i = Math.floor(Math.random() * col.length);
    var j = Math.floor(Math.random() * quote.length);
    $(".quote-window").html(quote[j]);
    $("body").css("background-color", col[i]);
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click Me</button>
<div class='quote-window'></div>


问:
Add an event listener to the window
I am trying to add an event listener to the window, but I am unsure how to get the window.

I currently have this.

```<code>let onUnhandledRejection = (e) => {
  /* TODO: write this */
}

WindowRe.addEventListener(
  "unhandledrejection",
  onUnhandledRejection,
  WINDOW_GOES_HERE: Dom.window
);
</code>```

答:
The current window object is available as Webapi.Dom.window

```<code>let onUnhandledRejection = (e) => {
  /* TODO: write this */
}

Webapi.Dom.Window.addEventListener(
  "unhandledrejection",
  onUnhandledRejection,
  Webapi.Dom.window
);
</code>```

You also shouldn't use WindowRe as it's a private API.

Title: Add an event listener to the window

Body:
I am trying to add an event listener to the window, but I am unsure how to get the window.

I currently have this.

let onUnhandledRejection = (e) => {
  /* TODO: write this */
}

WindowRe.addEventListener(
  "unhandledrejection",
  onUnhandledRejection,
  WINDOW_GOES_HERE: Dom.window
);

Body:
The current window object is available as Webapi.Dom.window

let onUnhandledRejection = (e) => {
  /* TODO: write this */
}

Webapi.Dom.Window.addEventListener(
  "unhandledrejection",
  onUnhandledRejection,
  Webapi.Dom.window
);

You also shouldn't use WindowRe as it's a private API.


问:
Python: insert value to matrix
I have a Problem with the simple insertion into a matrix in python: (I am not very python experienced)

matrix = numpy.zeros(shape=(len(10), len(10)), dtype=int)

Now I want to insert specific values to the matrix index, e.g. at line 1, column 1.

How do i do that? I already was on https://docs.scipy.org/doc/numpy but with the insert-method it does not work.

I just want a simple style like: matrix[1][1] = 17

It has to be a matrix in that style, because after insertion I have to do a singular value decomposition.

答:
You're syntax is incorrect in the np.zeros constructor.

Here's what it should look like:

```<code>matrix = numpy.zeros(shape=(10, 10), dtype=int)
</code>```

You can then set a value using normal array syntax:

```<code>matrix[1,4] = 10
print matrix

[[ 0  0  0  0  0  0  0  0  0  0]
 [ 0  0  0  0 10  0  0  0  0  0]
 [ 0  0  0  0  0  0  0  0  0  0]
 [ 0  0  0  0  0  0  0  0  0  0]
 [ 0  0  0  0  0  0  0  0  0  0]
 [ 0  0  0  0  0  0  0  0  0  0]
 [ 0  0  0  0  0  0  0  0  0  0]
 [ 0  0  0  0  0  0  0  0  0  0]
 [ 0  0  0  0  0  0  0  0  0  0]
 [ 0  0  0  0  0  0  0  0  0  0]]
</code>```

P.S. as others have mentioned, Python references it's indexes from zero, not one. So to set row 4, column 5 the array indices would be matrix[3,4].

Title: Python: insert value to matrix

Body:
You're syntax is incorrect in the np.zeros constructor.

Here's what it should look like:

matrix = numpy.zeros(shape=(10, 10), dtype=int)

You can then set a value using normal array syntax:

matrix[1,4] = 10
print matrix

[[ 0  0  0  0  0  0  0  0  0  0]
 [ 0  0  0  0 10  0  0  0  0  0]
 [ 0  0  0  0  0  0  0  0  0  0]
 [ 0  0  0  0  0  0  0  0  0  0]
 [ 0  0  0  0  0  0  0  0  0  0]
 [ 0  0  0  0  0  0  0  0  0  0]
 [ 0  0  0  0  0  0  0  0  0  0]
 [ 0  0  0  0  0  0  0  0  0  0]
 [ 0  0  0  0  0  0  0  0  0  0]
 [ 0  0  0  0  0  0  0  0  0  0]]

P.S. as others have mentioned, Python references it's indexes from zero, not one. So to set row 4, column 5 the array indices would be matrix[3,4].


答:
You can use reduce() method to add nested properties to object.

var obj2 = {"home":{"1":{"year":"1999"},"2":{"year":"2000","month":"11"}},"company":{"1":{"year":"2010","month":"2"}}}

function add(obj, value, ...keys) {
  keys.reduce(function(r, e, i, arr) {
    return r[e] || (r[e] = arr[i + 1] ? {} : value)
  }, obj)
}

let buss_type = "home", type_id = "1", date_type = "month", value = "9";
add(obj2, value, buss_type, type_id, date_type)

buss_type = "company", type_id = "2", date_type = "month", value = "12"
add(obj2, value, buss_type, type_id, date_type)

console.log(obj2)```

Title: Methods to insert or replace values in to object


问:
T-SQL / SQL Server - How to recursively select all nested children IDs of a given parent?
Consider the following table and hierarchy:

How can I select all children ids (10012, 10013, 10014) if I have id of parent 10011 (elegantly and efficiently)?

Here ParentId self references a parent folder.

答:
Use a recursive cte </p>

```<code>;WITH cte
AS
(   SELECT
        b.FolderId, b.FolderName, b.ParentiD
    FROM
        table b
    WHERE
        FolderId= 10011
    UNION ALL
    SELECT
        e.FolderId, e.FolderName, e.ParentId
    FROM
        table  e
    INNER JOIN
        cte r ON e.ParentId = r.FodlerId
)
SELECT * FROM cte
</code>```

Body:
Use a recursive cte

;WITH cte
AS
(   SELECT
        b.FolderId, b.FolderName, b.ParentiD
    FROM
        table b
    WHERE
        FolderId= 10011
    UNION ALL
    SELECT
        e.FolderId, e.FolderName, e.ParentId
    FROM
        table  e
    INNER JOIN
        cte r ON e.ParentId = r.FodlerId
)
SELECT * FROM cte


问:
How to draw a virtual framebuffer in Swing?
Suppose I have an array fb that is large enough to hold each 32-bit color pixel for a 128x128 display. It's laid out like a framebuffer would be.

How can I efficiently draw this on the display?

My current method loops over every pixel but that seems rather slow and cumbersome. Is there no way to convert this to an Image?

EDIT: I want to do this using the Java Swing APIs. I do not want any platform-specific code. However, if there is a library that uses the Swing APIs, that is fine.

答:
Cairo is a library thats suports 2D graphics rendering and can be used from Java.

SDLJava is a Java port of the popular C SDL game development library. This also should be able to do what you ask for, although it doesn't seem to have been updated since 2005 so if you have any problems with it support may not be forthcoming.

As an alternative, you could always use some fairly simple C code to open and configure the framebuffer, and then use JNI to return the memory-mapped framebuffer as a direct-mode ByteBuffer, so you can draw to it directly.


答:
Try this:

```<code>DECLARE @DataSource TABLE
(
    [FolderID] INT
   ,[FolderName] VARCHAR(12)
   ,[ParentID] INT
);

INSERT INTO @DataSource ([FolderID], [FolderName], [ParentID])
VALUES (10011, 'NEw Folder', NULL)
      ,(10012, 'NEw Folder', 10011)
      ,(10013, 'NEw Folder', 10012)
      ,(10014, 'NEw Folder', 10013)
      ,(10021, 'NEw Folder', NULL)
      ,(10022, 'NEw Folder', 10021)
      ,(10023, 'NEw Folder', 10022);

DECLARE @ParentID INT = 10011;

WITH DataSource AS
(
    SELECT *
    FROM @DataSource
    WHERE [FolderID] = @ParentID
    UNION ALL
    SELECT A.*
    FROM DataSource R
    INNER JOIN @DataSource A
        ON R.[FolderID] = A.[ParentID]
)
SELECT DISTINCT [FolderID]
FROM DataSource
WHERE [FolderID] <> @ParentID;
</code>```

Title: T-SQL / SQL Server - How to recursively select all nested children IDs of a given parent?

Body:
Consider the following table and hierarchy:

How can I select all children ids (10012, 10013, 10014) if I have id of parent 10011 (elegantly and efficiently)?

Here ParentId self references a parent folder.

Body:
Try this:

DECLARE @DataSource TABLE
(
    [FolderID] INT
   ,[FolderName] VARCHAR(12)
   ,[ParentID] INT
);

INSERT INTO @DataSource ([FolderID], [FolderName], [ParentID])
VALUES (10011, 'NEw Folder', NULL)
      ,(10012, 'NEw Folder', 10011)
      ,(10013, 'NEw Folder', 10012)
      ,(10014, 'NEw Folder', 10013)
      ,(10021, 'NEw Folder', NULL)
      ,(10022, 'NEw Folder', 10021)
      ,(10023, 'NEw Folder', 10022);

DECLARE @ParentID INT = 10011;

WITH DataSource AS
(
    SELECT *
    FROM @DataSource
    WHERE [FolderID] = @ParentID
    UNION ALL
    SELECT A.*
    FROM DataSource R
    INNER JOIN @DataSource A
        ON R.[FolderID] = A.[ParentID]
)
SELECT DISTINCT [FolderID]
FROM DataSource
WHERE [FolderID] <> @ParentID;


答:
You get the i and j variables outside the click function and never change them. That's why when you click on the button, j and i already have values and they won't change.

Add those variable declarations inside the click function. See below

There is a possibility that the random generated numbers are the same with the previous generated number, to make sure that doesn't happen there's a little more work to be done. But you have a very good starting point with the below code.

var quote = ["It is not the size of the dog in the fight, but the size of the fight in the dog.-Archie Griffen", "Nothing lasts forever. Not even your troubles.-Arnold H Glasgow", "There are only two ways to live your life. One is as though nothing is a miracle. The other is as though everything is a miracle-Albert Einstein"];

// problem area
var col = ["red", "blue", "yellow", "pink", "brown"];

$(document).ready(function() {
  $("button").click(function() {
    var i = Math.floor(Math.random() * col.length);
    var j = Math.floor(Math.random() * quote.length);
    $(".quote-window").html(quote[j]);
    $("body").css("background-color", col[i]);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>
  Click
</button>
<div class="quote-window">

</div></code>```

Title: Why is the click function unable to apply more than one random index to my arrays

Body:
I'm stuck on the random quote machine project on Free Code Camp. I can generate random quotes and colors but they are only generated once using the click event. Subsequent clicks of the "New quote" button generate new random indexing for my colors and quotes array.

var quote = ["It is not the size of the dog in the fight, but the size of the fight in the dog.-Archie Griffen", "Nothing lasts forever. Not even your troubles.-Arnold H Glasgow", "There are only two ways to live your life. One is as though nothing is a miracle. The other is as though everything is a miracle-Albert Einstein"];

// problem area
var col = ["red", "blue", "yellow", "pink", "brown"];
var i = Math.floor(Math.random() * col.length);
var j = Math.floor(Math.random() * quote.length);

$(document).ready(function() {
  $("button").click(function() {
    $(".quote-window").html(quote[j]);
    $("body").css("background-color", col[i]);
  });
});

Body:
You get the i and j variables outside the click function and never change them. That's why when you click on the button, j and i already have values and they won't change.

Add those variable declarations inside the click function. See below

There is a possibility that the random generated numbers are the same with the previous generated number, to make sure that doesn't happen there's a little more work to be done. But you have a very good starting point with the below code.

var quote = ["It is not the size of the dog in the fight, but the size of the fight in the dog.-Archie Griffen", "Nothing lasts forever. Not even your troubles.-Arnold H Glasgow", "There are only two ways to live your life. One is as though nothing is a miracle. The other is as though everything is a miracle-Albert Einstein"];

// problem area
var col = ["red", "blue", "yellow", "pink", "brown"];

$(document).ready(function() {
  $("button").click(function() {
    var i = Math.floor(Math.random() * col.length);
    var j = Math.floor(Math.random() * quote.length);
    $(".quote-window").html(quote[j]);
    $("body").css("background-color", col[i]);
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>
  Click
</button>
<div class="quote-window">

</div>


问:
Find elements by offset position with jQuery
Is there a simple method to fetch all elements at a specific offset position (by using jQuery)? Or do I have to check the offset of each element in the DOM?</p>

答:
If jQuery has a method, then it'll loop through all elements and check. There isn't another logical way to do it.

As far as I know, jQuery doesn't, so do loop through the Elements; you can use $().each(function());


问:
Change orientation based on Scroll event in RecyclerView
I'm trying to change orientation of recyclerview based on user's scroll up/down or left/right action. Here is my onCreate() method:

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler);
    recyclerView.setAdapter(new MyAdapter(totalItemCount));

    // default orientation is VERTICAL
    gridLayoutManager = new GridLayoutManager(this, spanCount, LinearLayoutManager.VERTICAL, false);
    recyclerView.setLayoutManager(gridLayoutManager);

    RecyclerView.OnScrollListener listener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            Log.i("TAG", "current orientation: " + gridLayoutManager.getOrientation());

            if (dx > 0) {
                Log.i("TAG", "dx = " + dx);
                recyclerView.post(new Runnable() {
                    @Override
                    public void run() {
                        gridLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
                    }
                });

            } else if (dy > 0) {
                Log.i("TAG", "dy = " + dy);
                recyclerView.post(new Runnable() {
                    @Override
                    public void run() {
                        gridLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
                    }
                });
            }
            recyclerView.setLayoutManager(gridLayoutManager);
        }
    };

    recyclerView.addOnScrollListener(listener);
}
</code>```

The issue is that it does not change orientation in recyclerview. Is it right approach to change orientation?

EDIT

There is no exception after suggested code modification (by @RobCo). But I can not change orientation still.

答:
The error message is very clear:

Cannot call this method in a scroll callback. Scroll callbacks might be run during a measure & layout pass where you cannot change theRecyclerView data. Any method call that might change the structure of the RecyclerView or the adapter contents should be postponed to the next frame.

So, setOrientation cannot be called from a layout or measure pass, or during a scroll callback.   You'll have to post a Runnable to the next frame:

```<code>    recyclerView.post(new Runnable() {
        @Override
        public void run() {
            gridLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        }
    });
</code>```

Body:
I'm trying to change orientation of recyclerview based on user's scroll up/down or left/right action. Here is my onCreate() method:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler);
    recyclerView.setAdapter(new MyAdapter(totalItemCount));

    // default orientation is VERTICAL
    gridLayoutManager = new GridLayoutManager(this, spanCount, LinearLayoutManager.VERTICAL, false);
    recyclerView.setLayoutManager(gridLayoutManager);

    RecyclerView.OnScrollListener listener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            Log.i("TAG", "current orientation: " + gridLayoutManager.getOrientation());

            if (dx > 0) {
                Log.i("TAG", "dx = " + dx);
                recyclerView.post(new Runnable() {
                    @Override
                    public void run() {
                        gridLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
                    }
                });

            } else if (dy > 0) {
                Log.i("TAG", "dy = " + dy);
                recyclerView.post(new Runnable() {
                    @Override
                    public void run() {
                        gridLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
                    }
                });
            }
            recyclerView.setLayoutManager(gridLayoutManager);
        }
    };

    recyclerView.addOnScrollListener(listener);
}

The issue is that it does not change orientation in recyclerview. Is it right approach to change orientation?

EDIT

There is no exception after suggested code modification (by @RobCo). But I can not change orientation still.

Body:
The error message is very clear:

Cannot call this method in a scroll callback. Scroll callbacks might be run during a measure & layout pass where you cannot change theRecyclerView data. Any method call that might change the structure of the RecyclerView or the adapter contents should be postponed to the next frame.

So, setOrientation cannot be called from a layout or measure pass, or during a scroll callback.   You'll have to post a Runnable to the next frame:

    recyclerView.post(new Runnable() {
        @Override
        public void run() {
            gridLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        }
    });


问:
Redux for maintaining only shared data
In our Angular app, we are planning to use Redux but decided that we will use it for managing only the data that are shared by at-least two components. The data that are used by only one component will be directly fetched without using Redux. For e.g. assume that a component has to display a list of values and these values are not shared with any other component then we will fetch this list using service. But while fetching this data it may affect some other state in the store, like it may dispatch some action like NETWORK_REQUEST_SENT, NETWORK_REQUEST_COMPLETED, so that a spinner/overlay component can change its display.

Now the question is which part of the code should be responsible for dispatching these actions.

Scenario 1 : The container component that fetches the data from the service could dispatch these actions, but I don't think it belongs here.

Scenario 2 : The service which makes the HTTP call could dispatch these action, then that means the service has to subscribe to the HTTP observable and return its own observable for the component.

Scenario 3 : Could do it in a Redux middleware, but then we have to dispatch an action for fetching the list of values and that means the list of values has to be stored in the store,  that we don't want.

Scenario 4 : As mentioned here, we could create an abstraction layer but then it feels like there is no need for middleware then.

答:
If you are using HttpClientModule you can register an interceptor, like explained in https://medium.com/@ryanchenkie_40935/angular-authentication-using-the-http-client-and-http-interceptors-2f9d1540eb8

You can invoke NETWORK_REQUEST_SENT when it is invoked and NETWORK_REQUEST_COMPLETED in finally to invoke an action when the request completes.
Then there is no need to have another observable.

Title: Redux for maintaining only shared data


问:
How to overlay HTML text/buttons on three.js?
Ok, very new to three.js here but I am trying to achieve what Google has with https://beinternetawesome.withgoogle.com/interland

See - they have their FULL SCREEN Three.js scene and their text, buttons (which are clearly HTML divs, not generated via JS) overlaid perfectly on top.

I have looked at
https://discourse.threejs.org/t/trying-to-overlay-a-button-and-text-on-top-of-a-three-js-scene/390/2

and similar Questions but can't understand the proper way to do this. I don't want to generate my UI elements in Three.js - I just want to use HTML.

What I have so far is I generate my Three.js canvas and add it to my document so that it gets and STAYS the full width/height of my window:

```<code>var controls, camera, renderer, scene, container, w, h;
renderer    = new THREE.WebGLRenderer()
// container = document.getElementById('canvas');
container = window;
w = container.innerWidth;
h = container.innerHeight;
renderer.setSize(w, h)
renderer.setPixelRatio( window.devicePixelRatio );
document.body.appendChild(renderer.domElement);
</code>```

And then with my existing HTML:

```<code><body>
    <div id="ui">
    <p id="message">Test to change</p>
</div>
</code>```

I get the UI div stuck on top, no matter how I play with the CSS or the z index of the UI div:

How can I achieve the Google effect with HTML overlaid over my three.js scene? What am I doing wrong?

I need my canvas to fill the whole window just as Google's does and can't achieve that it seems making the canvas HTML element beforehand and trying to attach everything in JS.

答:
z-index only works with position property except for the case position: static and position: initial.

This button class worked fine with my threejs scene. You can edit left, top accordingly.

```<code>button {
    position: absolute;
    display: block;
    z-index: 99;
    left: 50%;
    top: 50%;
    }
</code>```

Body:
Ok, very new to three.js here but I am trying to achieve what Google has with https://beinternetawesome.withgoogle.com/interland

See - they have their FULL SCREEN Three.js scene and their text, buttons (which are clearly HTML divs, not generated via JS) overlaid perfectly on top.

I have looked at
https://discourse.threejs.org/t/trying-to-overlay-a-button-and-text-on-top-of-a-three-js-scene/390/2

and similar Questions but can't understand the proper way to do this. I don't want to generate my UI elements in Three.js - I just want to use HTML.

What I have so far is I generate my Three.js canvas and add it to my document so that it gets and STAYS the full width/height of my window:

var controls, camera, renderer, scene, container, w, h;
renderer    = new THREE.WebGLRenderer()
// container = document.getElementById('canvas');
container = window;
w = container.innerWidth;
h = container.innerHeight;
renderer.setSize(w, h)
renderer.setPixelRatio( window.devicePixelRatio );
document.body.appendChild(renderer.domElement);

And then with my existing HTML:

Test to change

I get the UI div stuck on top, no matter how I play with the CSS or the z index of the UI div:

How can I achieve the Google effect with HTML overlaid over my three.js scene? What am I doing wrong?

I need my canvas to fill the whole window just as Google's does and can't achieve that it seems making the canvas HTML element beforehand and trying to attach everything in JS.

Body:
z-index only works with position property except for the case position: static and position: initial.

This button class worked fine with my threejs scene. You can edit left, top accordingly.

button {
    position: absolute;
    display: block;
    z-index: 99;
    left: 50%;
    top: 50%;
    }


问:
join function only echoing 1 product of the database
I made a model function so it will echo the products that belong to the profile user I clicked on, the thing is only the first product of that user gets echoed. For example I have an account that uploaded a total of 7 products and the function only shows the first product on the page..

This are the model functions:

```<code>function getdata_aangeboden($user_id){
  $this->db->select("users.*,products.*");
  $this->db->from('users');
  $this->db->join('products','products.user_id = users.user_id','left');
  $this->db->where('users.user_id', $user_id);
  $query = $this->db->get();
  return $query->result();
 }

    // Gets a list of multiple users.
 function getdata($user_id){
  $this->db->select("*");
  $this->db->from('users');
  $this->db->where('user_id', $user_id);
  $query = $this->db->get();
  return $query->result();
 }
</code>```

Controller function:

```<code><?php foreach($products as $product) { ?>
  <div class="main-gifts">
      <a href="<?php echo base_url() ?>/Product/details/<?php echo $product->product_id; ?>">
        <img id="fotos" src="<?php echo base_url(); ?>upload/<?php echo $product->product_foto_thumb; ?>">
        </a>
        <div class="products_discription">
            <h3><?php echo $product->product_naam; ?></h3>
            <div class="ophaal_plaats">
                <p>Plaats: <?php  echo $product->ophaal_plaats; ?></p>
            </div>
            <div class="aangeboden_door">
            <p> <?php
                    foreach($userdetail_list as $row){ ?>
              <tr>
                  <td><?php echo $row->voornaam;?></td>
               </tr>
                    <?php } ?></p>
          </div>
          <div class="status">
          </div>
      </div>
        <a href="<?php echo base_url() ?>/KdGwController/details_bewerken/<?php echo $product->product_id; ?>"><input type="button" class="btn btn-default cb" value="Cadeau bewerken"></input> </a>
  </div>
 <?php } ?>
</code>```

Can someone explain to me why it only shows 1 product and not all the products that belong to the same user_id?
thanks

When I print $products:

```<code>} ?> Array ( [0] => stdClass Object ( [user_id] => 4 [email] => jeremy@gmail.com [voornaam] => Jeremy [achternaam] => Mathieu [straat] => [huisnummer] => 22 [postcode] => 1223lL [woonplaats] => Rotterdam [wachtwoord] => $2y$10$rO.e4j0dofAUZSWV8sP6yOHYqLzhPkRk9FjBylwbaMMmWRoCBp2oy [beschrijving] => Hallo ik ben Jeremy [geboortedatum] => 2017-06-10 [startdatum] => 2017-06-29 [geslacht] => Man [reset_password_key] => [profiel_foto] => 1498736939jeremy.jpg [product_id] => 85 [product_naam] => HIHIHIHI [product_beschrijving] => [ophaal_plaats] => ALLOVER [product_foto] => new_f5cea9c914751e0ad0048800ffec3d05.jpg [product_foto_thumb] => thumb_f5cea9c914751e0ad0048800ffec3d05.jpg [date_created] => 2017-10-25 [date_updated] => 2017-10-25 [category_id] => 2 ) [1] => stdClass Object ( [user_id] => 4 [email] => jeremy@gmail.com [voornaam] => Jeremy [achternaam] => Mathieu [straat] => [huisnummer] => 22 [postcode] => 1223lL [woonplaats] => Rotterdam [wachtwoord] => $2y$10$rO.e4j0dofAUZSWV8sP6yOHYqLzhPkRk9FjBylwbaMMmWRoCBp2oy [beschrijving] => Hallo ik ben Jeremy [geboortedatum] => 2017-06-10 [startdatum] => 2017-06-29 [geslacht] => Man [reset_password_key] => [profiel_foto] => 1498736939jeremy.jpg [product_id] => 86 [product_naam] => HUHUUHU [product_beschrijving] => [ophaal_plaats] => NOWHERE [product_foto] => new_ba2430d2b531bc421f27b5f14667cffb.jpg [product_foto_thumb] => thumb_ba2430d2b531bc421f27b5f14667cffb.jpg [date_created] => 2017-10-25 [date_updated] => 2017-10-25 [category_id] => 4 ) [2] => stdClass Object ( [user_id] => 4 [email] => jeremy@gmail.com [voornaam] => Jeremy [achternaam] => Mathieu [straat] => [huisnummer] => 22 [postcode] => 1223lL [woonplaats] => Rotterdam [wachtwoord] => $2y$10$rO.e4j0dofAUZSWV8sP6yOHYqLzhPkRk9FjBylwbaMMmWRoCBp2oy [beschrijving] => Hallo ik ben Jeremy [geboortedatum] => 2017-06-10 [startdatum] => 2017-06-29 [geslacht] => Man [reset_password_key] => [profiel_foto] => 1498736939jeremy.jpg [product_id] => 87 [product_naam] => HOHOHO [product_beschrijving] => [ophaal_plaats] => NOIDEA [product_foto] => new_e1dfb9a860859ff882d13435e796578c.jpg [product_foto_thumb] => thumb_e1dfb9a860859ff882d13435e796578c.jpg [date_created] => 2017-10-25 [date_updated] => 2017-10-25 [category_id] => 7 ) [3] => stdClass Object ( [user_id] => 4 [email] => jeremy@gmail.com [voornaam] => Jeremy [achternaam] => Mathieu [straat] => [huisnummer] => 22 [postcode] => 1223lL [woonplaats] => Rotterdam [wachtwoord] => $2y$10$rO.e4j0dofAUZSWV8sP6yOHYqLzhPkRk9FjBylwbaMMmWRoCBp2oy [beschrijving] => Hallo ik ben Jeremy [geboortedatum] => 2017-06-10 [startdatum] => 2017-06-29 [geslacht] => Man [reset_password_key] => [profiel_foto] => 1498736939jeremy.jpg [product_id] => 88 [product_naam] => HEHEHE [product_beschrijving] => [ophaal_plaats] => Korea [product_foto] => new_c080495685ed05ab5d4f8a7dcdb8e668.jpg [product_foto_thumb] => thumb_c080495685ed05ab5d4f8a7dcdb8e668.jpg [date_created] => 2017-10-25 [date_updated] => 2017-10-25 [category_id] => 8 ) [4] => stdClass Object ( [user_id] => 4 [email] => jeremy@gmail.com [voornaam] => Jeremy [achternaam] => Mathieu [straat] => [huisnummer] => 22 [postcode] => 1223lL [woonplaats] => Rotterdam [wachtwoord] => $2y$10$rO.e4j0dofAUZSWV8sP6yOHYqLzhPkRk9FjBylwbaMMmWRoCBp2oy [beschrijving] => Hallo ik ben Jeremy [geboortedatum] => 2017-06-10 [startdatum] => 2017-06-29 [geslacht] => Man [reset_password_key] => [profiel_foto] => 1498736939jeremy.jpg [product_id] => 89 [product_naam] => ugilh [product_beschrijving] => hjgluhsfkh;sidh fihsdiuhfluisdhauighsudiahguivhadsuihudisahluihvsaduihvluidsahuihv [ophaal_plaats] => Amsterdam [product_foto] => new_c6dd9fa0dc0be0830ed43940b5907115.jpg [product_foto_thumb] => thumb_c6dd9fa0dc0be0830ed43940b5907115.jpg [date_created] => 2017-10-26 [date_updated] => 2017-10-26 [category_id] => 1 ) [5] => stdClass Object ( [user_id] => 4 [email] => jeremy@gmail.com [voornaam] => Jeremy [achternaam] => Mathieu [straat] => [huisnummer] => 22 [postcode] => 1223lL [woonplaats] => Rotterdam [wachtwoord] => $2y$10$rO.e4j0dofAUZSWV8sP6yOHYqLzhPkRk9FjBylwbaMMmWRoCBp2oy [beschrijving] => Hallo ik ben Jeremy [geboortedatum] => 2017-06-10 [startdatum] => 2017-06-29 [geslacht] => Man [reset_password_key] => [profiel_foto] => 1498736939jeremy.jpg [product_id] => 93 [product_naam] => 11111 [product_beschrijving] => frfewefwe [ophaal_plaats] => 1111 [product_foto] => new_14de53777d648dcbe31dea26fa031ced.jpg [product_foto_thumb] => thumb_14de53777d648dcbe31dea26fa031ced.jpg [date_created] => 2017-10-26 [date_updated] => 2017-10-26 [category_id] => 2 ) [6] => stdClass Object ( [user_id] => 4 [email] => jeremy@gmail.com [voornaam] => Jeremy [achternaam] => Mathieu [straat] => [huisnummer] => 22 [postcode] => 1223lL [woonplaats] => Rotterdam [wachtwoord] => $2y$10$rO.e4j0dofAUZSWV8sP6yOHYqLzhPkRk9FjBylwbaMMmWRoCBp2oy [beschrijving] => Hallo ik ben Jeremy [geboortedatum] => 2017-06-10 [startdatum] => 2017-06-29 [geslacht] => Man [reset_password_key] => [profiel_foto] => 1498736939jeremy.jpg [product_id] => 94 [product_naam] => hiu;ij [product_beschrijving] => hk;h uihucuhsducuisdhuvsdphvjuisjhuvsudih [ophaal_plaats] => Amsterdam [product_foto] => new_f68becfc0741d3a2300f49ed5bcf58a5.jpg [product_foto_thumb] => thumb_f68becfc0741d3a2300f49ed5bcf58a5.jpg [date_created] => 2017-10-26 [date_updated] => 2017-10-26 [category_id] => 5 ) )
</code>```

答:
You need to change your query as follows </p>

```<code>function getdata($user_id){
  $this->db->select("products.*,users.*");
  $this->db->from('products');
  $this->db->join('users','users.user_id = products.user_id','left');
  $this->db->where('users.user_id', $user_id);
  $query = $this->db->get();
  return $query->result();
 }
</code>```

Body:
I made a model function so it will echo the products that belong to the profile user I clicked on, the thing is only the first product of that user gets echoed. For example I have an account that uploaded a total of 7 products and the function only shows the first product on the page..

This are the model functions:

function getdata_aangeboden($user_id){
  $this->db->select("users.*,products.*");
  $this->db->from('users');
  $this->db->join('products','products.user_id = users.user_id','left');
  $this->db->where('users.user_id', $user_id);
  $query = $this->db->get();
  return $query->result();
 }

    // Gets a list of multiple users.
 function getdata($user_id){
  $this->db->select("*");
  $this->db->from('users');
  $this->db->where('user_id', $user_id);
  $query = $this->db->get();
  return $query->result();
 }

Controller function:

<?php foreach($products as $product) { ?>

      <a href="<?php echo base_url() ?>/Product/details/<?php echo $product->product_id; ?>">
        <img id="fotos" src="<?php echo base_url(); ?>upload/<?php echo $product->product_foto_thumb; ?>">

<?php echo $product->product_naam; ?>

Plaats: <?php  echo $product->ophaal_plaats; ?>

 <?php
                    foreach($userdetail_list as $row){ ?>

                  <?php echo $row->voornaam;?>

                    <?php } ?>

        <a href="<?php echo base_url() ?>/KdGwController/details_bewerken/<?php echo $product->product_id; ?>"><input type="button" class="btn btn-default cb" value="Cadeau bewerken"></input>

 <?php } ?>

Can someone explain to me why it only shows 1 product and not all the products that belong to the same user_id?
thanks

When I print $products:

} ?> Array ( [0] => stdClass Object ( [user_id] => 4 [email] => jeremy@gmail.com [voornaam] => Jeremy [achternaam] => Mathieu [straat] => [huisnummer] => 22 [postcode] => 1223lL [woonplaats] => Rotterdam [wachtwoord] => $2y$10$rO.e4j0dofAUZSWV8sP6yOHYqLzhPkRk9FjBylwbaMMmWRoCBp2oy [beschrijving] => Hallo ik ben Jeremy [geboortedatum] => 2017-06-10 [startdatum] => 2017-06-29 [geslacht] => Man [reset_password_key] => [profiel_foto] => 1498736939jeremy.jpg [product_id] => 85 [product_naam] => HIHIHIHI [product_beschrijving] => [ophaal_plaats] => ALLOVER [product_foto] => new_f5cea9c914751e0ad0048800ffec3d05.jpg [product_foto_thumb] => thumb_f5cea9c914751e0ad0048800ffec3d05.jpg [date_created] => 2017-10-25 [date_updated] => 2017-10-25 [category_id] => 2 ) [1] => stdClass Object ( [user_id] => 4 [email] => jeremy@gmail.com [voornaam] => Jeremy [achternaam] => Mathieu [straat] => [huisnummer] => 22 [postcode] => 1223lL [woonplaats] => Rotterdam [wachtwoord] => $2y$10$rO.e4j0dofAUZSWV8sP6yOHYqLzhPkRk9FjBylwbaMMmWRoCBp2oy [beschrijving] => Hallo ik ben Jeremy [geboortedatum] => 2017-06-10 [startdatum] => 2017-06-29 [geslacht] => Man [reset_password_key] => [profiel_foto] => 1498736939jeremy.jpg [product_id] => 86 [product_naam] => HUHUUHU [product_beschrijving] => [ophaal_plaats] => NOWHERE [product_foto] => new_ba2430d2b531bc421f27b5f14667cffb.jpg [product_foto_thumb] => thumb_ba2430d2b531bc421f27b5f14667cffb.jpg [date_created] => 2017-10-25 [date_updated] => 2017-10-25 [category_id] => 4 ) [2] => stdClass Object ( [user_id] => 4 [email] => jeremy@gmail.com [voornaam] => Jeremy [achternaam] => Mathieu [straat] => [huisnummer] => 22 [postcode] => 1223lL [woonplaats] => Rotterdam [wachtwoord] => $2y$10$rO.e4j0dofAUZSWV8sP6yOHYqLzhPkRk9FjBylwbaMMmWRoCBp2oy [beschrijving] => Hallo ik ben Jeremy [geboortedatum] => 2017-06-10 [startdatum] => 2017-06-29 [geslacht] => Man [reset_password_key] => [profiel_foto] => 1498736939jeremy.jpg [product_id] => 87 [product_naam] => HOHOHO [product_beschrijving] => [ophaal_plaats] => NOIDEA [product_foto] => new_e1dfb9a860859ff882d13435e796578c.jpg [product_foto_thumb] => thumb_e1dfb9a860859ff882d13435e796578c.jpg [date_created] => 2017-10-25 [date_updated] => 2017-10-25 [category_id] => 7 ) [3] => stdClass Object ( [user_id] => 4 [email] => jeremy@gmail.com [voornaam] => Jeremy [achternaam] => Mathieu [straat] => [huisnummer] => 22 [postcode] => 1223lL [woonplaats] => Rotterdam [wachtwoord] => $2y$10$rO.e4j0dofAUZSWV8sP6yOHYqLzhPkRk9FjBylwbaMMmWRoCBp2oy [beschrijving] => Hallo ik ben Jeremy [geboortedatum] => 2017-06-10 [startdatum] => 2017-06-29 [geslacht] => Man [reset_password_key] => [profiel_foto] => 1498736939jeremy.jpg [product_id] => 88 [product_naam] => HEHEHE [product_beschrijving] => [ophaal_plaats] => Korea [product_foto] => new_c080495685ed05ab5d4f8a7dcdb8e668.jpg [product_foto_thumb] => thumb_c080495685ed05ab5d4f8a7dcdb8e668.jpg [date_created] => 2017-10-25 [date_updated] => 2017-10-25 [category_id] => 8 ) [4] => stdClass Object ( [user_id] => 4 [email] => jeremy@gmail.com [voornaam] => Jeremy [achternaam] => Mathieu [straat] => [huisnummer] => 22 [postcode] => 1223lL [woonplaats] => Rotterdam [wachtwoord] => $2y$10$rO.e4j0dofAUZSWV8sP6yOHYqLzhPkRk9FjBylwbaMMmWRoCBp2oy [beschrijving] => Hallo ik ben Jeremy [geboortedatum] => 2017-06-10 [startdatum] => 2017-06-29 [geslacht] => Man [reset_password_key] => [profiel_foto] => 1498736939jeremy.jpg [product_id] => 89 [product_naam] => ugilh [product_beschrijving] => hjgluhsfkh;sidh fihsdiuhfluisdhauighsudiahguivhadsuihudisahluihvsaduihvluidsahuihv [ophaal_plaats] => Amsterdam [product_foto] => new_c6dd9fa0dc0be0830ed43940b5907115.jpg [product_foto_thumb] => thumb_c6dd9fa0dc0be0830ed43940b5907115.jpg [date_created] => 2017-10-26 [date_updated] => 2017-10-26 [category_id] => 1 ) [5] => stdClass Object ( [user_id] => 4 [email] => jeremy@gmail.com [voornaam] => Jeremy [achternaam] => Mathieu [straat] => [huisnummer] => 22 [postcode] => 1223lL [woonplaats] => Rotterdam [wachtwoord] => $2y$10$rO.e4j0dofAUZSWV8sP6yOHYqLzhPkRk9FjBylwbaMMmWRoCBp2oy [beschrijving] => Hallo ik ben Jeremy [geboortedatum] => 2017-06-10 [startdatum] => 2017-06-29 [geslacht] => Man [reset_password_key] => [profiel_foto] => 1498736939jeremy.jpg [product_id] => 93 [product_naam] => 11111 [product_beschrijving] => frfewefwe [ophaal_plaats] => 1111 [product_foto] => new_14de53777d648dcbe31dea26fa031ced.jpg [product_foto_thumb] => thumb_14de53777d648dcbe31dea26fa031ced.jpg [date_created] => 2017-10-26 [date_updated] => 2017-10-26 [category_id] => 2 ) [6] => stdClass Object ( [user_id] => 4 [email] => jeremy@gmail.com [voornaam] => Jeremy [achternaam] => Mathieu [straat] => [huisnummer] => 22 [postcode] => 1223lL [woonplaats] => Rotterdam [wachtwoord] => $2y$10$rO.e4j0dofAUZSWV8sP6yOHYqLzhPkRk9FjBylwbaMMmWRoCBp2oy [beschrijving] => Hallo ik ben Jeremy [geboortedatum] => 2017-06-10 [startdatum] => 2017-06-29 [geslacht] => Man [reset_password_key] => [profiel_foto] => 1498736939jeremy.jpg [product_id] => 94 [product_naam] => hiu;ij [product_beschrijving] => hk;h uihucuhsducuisdhuvsdphvjuisjhuvsudih [ophaal_plaats] => Amsterdam [product_foto] => new_f68becfc0741d3a2300f49ed5bcf58a5.jpg [product_foto_thumb] => thumb_f68becfc0741d3a2300f49ed5bcf58a5.jpg [date_created] => 2017-10-26 [date_updated] => 2017-10-26 [category_id] => 5 ) )

Body:
You need to change your query as follows

function getdata($user_id){
  $this->db->select("products.*,users.*");
  $this->db->from('products');
  $this->db->join('users','users.user_id = products.user_id','left');
  $this->db->where('users.user_id', $user_id);
  $query = $this->db->get();
  return $query->result();
 }


问:
Jquery resizable does not work
i am trying to use jquery-ui resizable.

here i am creating the resizable:

```<code>jQuery("#id404").resizable();
</code>```

here is the div after i created the resizable.

```<code><div style="right: 7px; top: 120px; left:0%; bottom:340px; position:absolute; overflow:visible; z-index:2; cursor:pointer;">
   <div
      id="id404"
      name="resizable_div"
      class="ui-resizable"
      style="position:relative; width:100%; height:100%; overflow:hidden;">
   <div class="ui-resizable-handle ui-resizable-e"></div>
   <div class="ui-resizable-handle ui-resizable-s"></div>
   <div class="ui-resizable-handle ui-resizable-se ui-icon ui-icon-gripsmall-diagonal-se" style="z-index: 1001; "></div>
</div>
</div>
</code>```

now, this does not work.

although the div becomes resizable (the handles appear, the icon changes etc) when i'm trying to resize the div box, it stays the same size no matter what i'm doing.
The resize process does occur, because while debugging this, the onStop and onStart callbacks did fire.

anyone can tell me what i did wrong?

i assume it is something to do with absolute divs.

thanks,

Tal

答: The targeted ID takes on the parent's width and height, and yet has overflow hidden, so it cannot be resized beyond the parent's dimentsions.</p>

Title: Jquery resizable does not work

Body:
i am trying to use jquery-ui resizable.

here i am creating the resizable:

jQuery("#id404").resizable();

here is the div after i created the resizable.

now, this does not work.

although the div becomes resizable (the handles appear, the icon changes etc) when i'm trying to resize the div box, it stays the same size no matter what i'm doing.
The resize process does occur, because while debugging this, the onStop and onStart callbacks did fire.

anyone can tell me what i did wrong?

i assume it is something to do with absolute divs.

thanks,

Tal


问:
How to finish this simple proof involving booleans
This is my progress on an exercise from here: https://github.com/userhr/MIT-6.826-2017

```<code>(** **** Exercise: 2 stars (andb_true_elim2)  *)
(** Prove the following claim, marking cases (and subcases) with
    bullets when you use [destruct]. *)

Theorem andb_true_elim2 : forall b c : bool,
  andb b c = true -> c = true.
Proof.
  intros c.
  (** Prove anything && false == false. *)
  assert (forall x : bool, andb x false = false) as H.
  destruct x.
   -reflexivity.
   -reflexivity.
   (** Obviously true at this point since we have shown that no
       matter what, andb b c will be false if one of them is
       false. My idea is to use H to show that if it is to be
       true, than both arguments must be true.
   *)
Qed.
</code>```

The reason why I felt it's necessary to show that (forall x : bool, andb x false = false) is because I can't figure out how to do the obvious proof by proving that (forall a b : bool, andb a b = true -> a = true, b = true)

答:
Code snippet for this is</p>

```<code>Theorem andb_true_elim2 : forall b c : bool,
  andb b c = true -> c = true.
Proof.
  intros b c H.
  destruct c.
  Case "c = true".
    reflexivity.
  Case "c = false".
    rewrite <- H.
  destruct b.
  SCase "b = true".
    reflexivity.
  SCase "b = false".
    reflexivity.
Qed.
</code>```

Body:
This is my progress on an exercise from here: https://github.com/userhr/MIT-6.826-2017

(** **** Exercise: 2 stars (andb_true_elim2)  *)
(** Prove the following claim, marking cases (and subcases) with
    bullets when you use [destruct]. *)

Theorem andb_true_elim2 : forall b c : bool,
  andb b c = true -> c = true.
Proof.
  intros c.
  (** Prove anything && false == false. *)
  assert (forall x : bool, andb x false = false) as H.
  destruct x.
   -reflexivity.
   -reflexivity.
   (** Obviously true at this point since we have shown that no
       matter what, andb b c will be false if one of them is
       false. My idea is to use H to show that if it is to be
       true, than both arguments must be true.
   *)
Qed.

The reason why I felt it's necessary to show that (forall x : bool, andb x false = false) is because I can't figure out how to do the obvious proof by proving that (forall a b : bool, andb a b = true -> a = true, b = true)

Body:
Code snippet for this is

Theorem andb_true_elim2 : forall b c : bool,
  andb b c = true -> c = true.
Proof.
  intros b c H.
  destruct c.
  Case "c = true".
    reflexivity.
  Case "c = false".
    rewrite <- H.
  destruct b.
  SCase "b = true".
    reflexivity.
  SCase "b = false".
    reflexivity.
Qed.


问:
File included but class not found
I know there is many people with this kind of problem, but I haven't found any solution that would be helpful in my case.

I have a simple Wordpress plugin which contains of a main plugin file and two additional files.

```<code>/myplugin.php
/framework/template/content.php
/framework/pagination/pagination.php
</code>```

The myplugin.php simply echoes the content.php file. The pagination.php is a class with name 'Pagination' - its a github project, you can see it's content here. Flexible-PHP-Pagination

The problem occurs when I try to work with this class in the content.php file. I can include the class without no problems, but as soon as I want to create object off the Pagination class, it returns fatal error:

```<code>Fatal error: Uncaught Error: Class 'Pagination' not found in /var/www/.../wp-content/plugins/myplugin/framework/template/content.php:382
</code>```

The way I create the object is this:

```<code>$nav = new Pagination($max, $total, $page, $maxNum);
(Note: all variables have proper values)
</code>```

The line 382 is the one where I create $nav variable, not where I include the file (thats on line 3). Any ideas what the problem could be?

UPDATE (WORKS NOW)
This is how I imported the file before:

```<code>include(plugins_url('', __FILE__ ) . '/..../myfile.php');
</code>```

Apperently, it should not be done like that, but this way instead:

```<code>require(plugin_dir_path( __FILE__) . '..../myfile.php'); /* Notice missing slash */
</code>```

Now it works.

答:
You should load the class using:

```<code>add_action( 'plugins_loaded', array( 'someClassy', 'init' ));

class someClassy {

    public static function init() {
        $class = __CLASS__;
        new $class;
    }

    public function __construct() {
           //construct what you see fit here...
    }

    //etc...
}
</code>```

or

```<code>add_shortcode( 'baztag', array( My_Plugin::get_instance(), 'foo' ) );
class My_Plugin {

    private $var = 'foo';

    protected static $instance = NULL;

    public static function get_instance() {

        // create an object
        NULL === self::$instance and self::$instance = new self;

        return self::$instance; // return the object
    }

    public function foo() {

        return $this->var; // never echo or print in a shortcode!
    }
}
</code>```

Title: File included but class not found

Body:
I know there is many people with this kind of problem, but I haven't found any solution that would be helpful in my case.

I have a simple Wordpress plugin which contains of a main plugin file and two additional files.

/myplugin.php
/framework/template/content.php
/framework/pagination/pagination.php

The myplugin.php simply echoes the content.php file. The pagination.php is a class with name 'Pagination' - its a github project, you can see it's content here. Flexible-PHP-Pagination

The problem occurs when I try to work with this class in the content.php file. I can include the class without no problems, but as soon as I want to create object off the Pagination class, it returns fatal error:

Fatal error: Uncaught Error: Class 'Pagination' not found in /var/www/.../wp-content/plugins/myplugin/framework/template/content.php:382

The way I create the object is this:

$nav = new Pagination($max, $total, $page, $maxNum);
(Note: all variables have proper values)

The line 382 is the one where I create $nav variable, not where I include the file (thats on line 3). Any ideas what the problem could be?

UPDATE (WORKS NOW)
This is how I imported the file before:

include(plugins_url('', __FILE__ ) . '/..../myfile.php');

Apperently, it should not be done like that, but this way instead:

require(plugin_dir_path( __FILE__) . '..../myfile.php'); /* Notice missing slash */

Now it works.

Body:
You should load the class using:

add_action( 'plugins_loaded', array( 'someClassy', 'init' ));

class someClassy {

    public static function init() {
        $class = __CLASS__;
        new $class;
    }

    public function __construct() {
           //construct what you see fit here...
    }

    //etc...
}

or

add_shortcode( 'baztag', array( My_Plugin::get_instance(), 'foo' ) );
class My_Plugin {

    private $var = 'foo';

    protected static $instance = NULL;

    public static function get_instance() {

        // create an object
        NULL === self::$instance and self::$instance = new self;

        return self::$instance; // return the object
    }

    public function foo() {

        return $this->var; // never echo or print in a shortcode!
    }
}


问:
pandas sparse dataframe head error
I am trying to get see the head of a sparse dataframe created using get_dummies.

```<code>import numpy as np
import pandas as pd

df = pd.read_csv(f_loc, sep = " ")
print df.head()
data = pd.get_dummies(df,sparse=True)
print data.head()
</code>```

It gives me the error

```<code>File "/usr/local/lib/python2.7/dist-packages/pandas/core/internals.py", line 1703, in __init__
    raise TypeError("values must be {0}".format(self._holder.__name__))
</code>```

答:
In last version of pandas (0.21.0) it working nice, but some alternatives should works:

```<code>np.random.seed(1997)

df = pd.DataFrame(np.random.randn(100, 4))
df.iloc[:-97] = np.nan
data = df.to_sparse()

print (type(data))
<class 'pandas.core.sparse.frame.SparseDataFrame'>

print (data.head())
          0        1         2         3
0       NaN      NaN       NaN       NaN
1       NaN      NaN       NaN       NaN
2       NaN      NaN       NaN       NaN
3  1.938422  1.78731 -0.619745 -2.560187
4 -0.986231 -1.94293  2.677379 -1.813071

print (data.iloc[:5])
          0        1         2         3
0       NaN      NaN       NaN       NaN
1       NaN      NaN       NaN       NaN
2       NaN      NaN       NaN       NaN
3  1.938422  1.78731 -0.619745 -2.560187
4 -0.986231 -1.94293  2.677379 -1.813071

print (data[:5])
          0        1         2         3
0       NaN      NaN       NaN       NaN
1       NaN      NaN       NaN       NaN
2       NaN      NaN       NaN       NaN
3  1.938422  1.78731 -0.619745 -2.560187
4 -0.986231 -1.94293  2.677379 -1.813071
</code>```

Title: pandas sparse dataframe head error

Body:
I am trying to get see the head of a sparse dataframe created using get_dummies.

import numpy as np
import pandas as pd

df = pd.read_csv(f_loc, sep = " ")
print df.head()
data = pd.get_dummies(df,sparse=True)
print data.head()

It gives me the error

File "/usr/local/lib/python2.7/dist-packages/pandas/core/internals.py", line 1703, in __init__
    raise TypeError("values must be {0}".format(self._holder.__name__))

Body:
In last version of pandas (0.21.0) it working nice, but some alternatives should works:

np.random.seed(1997)

df = pd.DataFrame(np.random.randn(100, 4))
df.iloc[:-97] = np.nan
data = df.to_sparse()

print (type(data))
<class 'pandas.core.sparse.frame.SparseDataFrame'>

print (data.head())
          0        1         2         3
0       NaN      NaN       NaN       NaN
1       NaN      NaN       NaN       NaN
2       NaN      NaN       NaN       NaN
3  1.938422  1.78731 -0.619745 -2.560187
4 -0.986231 -1.94293  2.677379 -1.813071

print (data.iloc[:5])
          0        1         2         3
0       NaN      NaN       NaN       NaN
1       NaN      NaN       NaN       NaN
2       NaN      NaN       NaN       NaN
3  1.938422  1.78731 -0.619745 -2.560187
4 -0.986231 -1.94293  2.677379 -1.813071

print (data[:5])
          0        1         2         3
0       NaN      NaN       NaN       NaN
1       NaN      NaN       NaN       NaN
2       NaN      NaN       NaN       NaN
3  1.938422  1.78731 -0.619745 -2.560187
4 -0.986231 -1.94293  2.677379 -1.813071


问:
sonar issue: remove use of String(byte[])
I have got a recurring sonar issue to "Remove this use of constructor "String(byte[])".
One of the example is of the code below:

```<code> byte[] d = c.doFinal(e);
 return new String(d);
</code>```

I do not know why this is popping up. Any help is welcome. Thanks.

答:
Sonar says:

Using classes and methods that rely on the default system encoding can
  result in code that works fine in its "home" environment. But that
  code may break for customers who use different encodings in ways that
  are extremely difficult to diagnose and nearly, if not completely,
  impossible to reproduce when it's time to fix them.

you should use the String(byte bytes[], Charset charset) constructor instead

you can read more about it here: https://gazelle.ihe.net/sonar/coding_rules#rule_key=squid%3AS1943

Body:
I have got a recurring sonar issue to "Remove this use of constructor "String(byte[])".
One of the example is of the code below:

 byte[] d = c.doFinal(e);
 return new String(d);

I do not know why this is popping up. Any help is welcome. Thanks.


答:
simple self-join will help you

```<code>select e.folderid from table1 e inner join table1 t on e.parentid = t.folderid where t.parentid = 10011
</code>```

try the above query :)

Body:
Consider the following table and hierarchy:

How can I select all children ids (10012, 10013, 10014) if I have id of parent 10011 (elegantly and efficiently)?

Here ParentId self references a parent folder.

Body:
simple self-join will help you

select e.folderid from table1 e inner join table1 t on e.parentid = t.folderid where t.parentid = 10011

try the above query :)


问:
Actionscript 3 'this' question
Could someone point out why does the following code fail in the first case:

CASE 1

```<code>// In a constructor
this.gallery = new Gallery();
addChild(this.gallery);

this.gallery.addEventListener(GalleryEvent.WHATEVER, function(event:*) {
    // When this callback fires, there is a fail:
    // because there is no 'this.gallery'.
    this.gallery.someAction();
});
</code>```

CASE 2

```<code>this.gallery.addEventListener(GalleryEvent.WHATEVER, function(event:*) {
    // This works fine
    gallery.someAction();
})
</code>```

Are there any rules regarding this usage in such cases?

答:
because you're passing this function function(event:*) which means it is executed in that scope.

so when it tries to look for this it is looking for event.gallery.someAction();

when you use gallery, it tries to find it within the list of global variables.

One way to verify this is to add a trace(this) and see what happens.

Title: Actionscript 3 'this' question

Body:
Could someone point out why does the following code fail in the first case:

CASE 1

// In a constructor
this.gallery = new Gallery();
addChild(this.gallery);

this.gallery.addEventListener(GalleryEvent.WHATEVER, function(event:*) {
    // When this callback fires, there is a fail:
    // because there is no 'this.gallery'.
    this.gallery.someAction();
});

CASE 2

this.gallery.addEventListener(GalleryEvent.WHATEVER, function(event:*) {
    // This works fine
    gallery.someAction();
})

Are there any rules regarding this usage in such cases?


问:
How to call one module to another module in yii2
I have two modules user and studio But both module having same inquiries form. So I don't want to re-write code in studio module.
I already done my inquiries form with email functionality in the user module. So I just want to call all the user module inquiries model, controller and view in my studio module.

Is it possible?

答:
It is possible.

If you have already developed the inquiry form in user module, you can develop the inquiry form view in the studio module.

Then, change the form action to use the user module inquiry form URL in studio.


问:
send current date to Api using typescript in format (DateTime)
how can I send current date to API using typescript in a specific format (DateTime)
when I send date to API, it's sent in this format so I got the error.

my ts code:

```<code>date: Date;
constructor( private dataStorageService: DataStorageService) {
    this.date = new Date();
}
onSubmit(Message , form : FormGroup){
    let newMsg = {
        username: Message.username,
        header: Message.header,
        content: Message.content,
        file: Message.file
    }
  this.dataStorageService.postMessage(newMsg, this.Id , this.date).subscribe(data => {
      console.log('done');
      console.log(this.date);
      }, error => {
          console.error("Error saving jobs!");
      })
}
</code>```

http://api.azharcouncil.com/api/notification/PostNotification?user_id=15&Header=hj&Content=hjh&File_Path=null&date=Wed%20Nov%2015%202017%2010:44:56%20GMT+0200%20(Egypt%20Standard%20Time)

So my request is invalid because of the date format...

答:
Here is the complete answer to your question.

Import the DatePipe from in the main module and provide that to your main module in main.module.ts in your provider array like given below:

```<code>import {DatePipe} from '@angular/common';
providers: [DatePipe]
</code>```

Use it in your ts file with these methods, also import DatePipe from @angular/common in your ts file as well.

```<code>import {DatePipe} from '@angular/common';
</code>```

Then in your constructor initialize this:

```<code>constructor(private _http: HttpClient, public datepipe: DatePipe) { }
</code>```

Now use these methods to get the correct date format:

```<code>let myDate = new Date();
console.log(this.datepipe.transform(myDate, 'yyyy-mm-dd'));
someDateVar = this.datepipe.transform(myDate, 'yyyy-mm-dd');
</code>```

Now someDateVar can be used to send it to server which has the date format you need. Also note that you can use multiple other date formats as well which are given in the Angular date pipe documentation.

Body:
how can I send current date to API using typescript in a specific format (DateTime)
when I send date to API, it's sent in this format so I got the error.

my ts code:

date: Date;
constructor( private dataStorageService: DataStorageService) {
    this.date = new Date();
}
onSubmit(Message , form : FormGroup){
    let newMsg = {
        username: Message.username,
        header: Message.header,
        content: Message.content,
        file: Message.file
    }
  this.dataStorageService.postMessage(newMsg, this.Id , this.date).subscribe(data => {
      console.log('done');
      console.log(this.date);
      }, error => {
          console.error("Error saving jobs!");
      })
}

http://api.azharcouncil.com/api/notification/PostNotification?user_id=15&Header=hj&Content=hjh&File_Path=null&date=Wed%20Nov%2015%202017%2010:44:56%20GMT+0200%20(Egypt%20Standard%20Time)

So my request is invalid because of the date format...

Body:
Here is the complete answer to your question.

Import the DatePipe from in the main module and provide that to your main module in main.module.ts in your provider array like given below:

import {DatePipe} from '@angular/common';
providers: [DatePipe]

Use it in your ts file with these methods, also import DatePipe from @angular/common in your ts file as well.

import {DatePipe} from '@angular/common';

Then in your constructor initialize this:

constructor(private _http: HttpClient, public datepipe: DatePipe) { }

Now use these methods to get the correct date format:

let myDate = new Date();
console.log(this.datepipe.transform(myDate, 'yyyy-mm-dd'));
someDateVar = this.datepipe.transform(myDate, 'yyyy-mm-dd');

Now someDateVar can be used to send it to server which has the date format you need. Also note that you can use multiple other date formats as well which are given in the Angular date pipe documentation.


问:
tooltip not coming at correct position in firefox in chartlist.js
I am using chatlist.js to show charts and using its one of the method to show tooltip on chart.

Tooltip on chart is coming fine on all other browsers except firefox I cant find any solution over google and there is no support page on chartlist website.

I am using following default code for tooltip x and y positions

```<code>$toolTip.css({
      left: (event.originalEvent.layerX || event.offsetX) - $toolTip.width() / 2 - 10,
      top: (event.originalEvent.layerY || event.offsetY) - $toolTip.height() - 40
    });
</code>```

答: I had this problem; put position: relative in your chart wrapper div.

Body:
I am using chatlist.js to show charts and using its one of the method to show tooltip on chart.

Tooltip on chart is coming fine on all other browsers except firefox I cant find any solution over google and there is no support page on chartlist website.

I am using following default code for tooltip x and y positions

$toolTip.css({
      left: (event.originalEvent.layerX || event.offsetX) - $toolTip.width() / 2 - 10,
      top: (event.originalEvent.layerY || event.offsetY) - $toolTip.height() - 40
    });


问:
Chrome not caching <object> requests
I am creating HTML object with onload event, that creates another copy of it with the same svg image path.

```<code><object data="/image.svg" type="image/svg+xml"></object>
</code>```

I have set Expires and Cache-Control headers, to prevent double loading. However, chrome ignores them and doesn't use cached image from previous request, like other browsers do. Directly requests to this image are cached, so I guess there is a problem only with  requests caching.

Response Headers of the second request:

```<code>Accept-Ranges:bytes
Age:59
Cache-Control:max-age=1200
Content-Length:267155
Content-Type:image/svg+xml
Date:Tue, 14 Nov 2017 08:16:05 GMT
ETag:"842401d-41393-5598c11d4b740"
Expires:Tue, 14 Nov 2017 08:36:05 GMT
Last-Modified:Tue, 19 Sep 2017 14:56:53 GMT
Server:Apache/2.2.17 (Fedora)
</code>```

答: The real problem was, that if you are using proxy, chrome does not show you "from disk cache" message in developer tools. But it actually does. I had to use low internet speed connection settings to find out the real result.</p>

Title: Chrome not caching <object> requests

Body:
I am creating HTML object with onload event, that creates another copy of it with the same svg image path.

<object data="/image.svg" type="image/svg+xml"></object>

I have set Expires and Cache-Control headers, to prevent double loading. However, chrome ignores them and doesn't use cached image from previous request, like other browsers do. Directly requests to this image are cached, so I guess there is a problem only with  requests caching.

Response Headers of the second request:

Accept-Ranges:bytes
Age:59
Cache-Control:max-age=1200
Content-Length:267155
Content-Type:image/svg+xml
Date:Tue, 14 Nov 2017 08:16:05 GMT
ETag:"842401d-41393-5598c11d4b740"
Expires:Tue, 14 Nov 2017 08:36:05 GMT
Last-Modified:Tue, 19 Sep 2017 14:56:53 GMT
Server:Apache/2.2.17 (Fedora)


问:
Good ways to convert 2d array to object
With <s>ES7</s> ES2017 (ES8) I can convert an object to an array of arrays like this:

```<code>let obj = { a: '1', b: '2', c: '3' }
let arr = Object.entries(obj)
// [ [ 'a', '1' ], [ 'b', '2' ], [ 'c', '3' ] ]
</code>```

But what if I want to go the other way around? I could use a for-loop, or the reduce-method of the Array like below, but is there a more direct approach?

```<code>let arr =[ [ 'a', '1' ], [ 'b', '2' ], [ 'c', '3' ] ]
let obj = arr.reduce((o, x)=>{o[x[0]]=x[1];return o}, {})
// { a: '1', b: '2', c: '3' }
</code>```

A use case: I wanted to convert a string like "a=1;b=2;c=3" to an object like { a: '1', b: '2', c: '3' } and ended up with something like

```<code>"a=1;b=2;c=3"
  .split(";")
  .reduce((o, x)=>{
    let parts=x.split("=")
    o[parts[0]]=parts[1]
    return o
  }, {});
</code>```

Edit: As pointed out in comments, the reduce syntax could be simplified (or shortened, at least) to:

```<code>arr.reduce((o, [k, v])=>(o[k]=v, o), {})
</code>```

...or written with Object.assign like this:

```<code>arr.reduce((o, [k, v])=>Object.assign(o, {[k]: v}), {})
</code>```

Either way, the answer to the question, according to the comments, is no. This is the best approach we've got.

Edit, Jan 2023: .fromEntries() is in stage 4 since 2019, and now supported in all modern browsers.

答:
Do you want some one-line unentries function?

const detries = entries => entries.reduce((result, [key, value]) => Object.assign(result, {[key]: value}), {});

const entries = Object.entries({a: 1, b: 2, c: 3});
const detried = detries(entries);

console.info("ENTRIES", entries);
console.info("DETRIED", detried);```
</div>
</div>
</p>

<hr>

<h1>Edit: <code>Object.fromEntries</code> proposal.</h1>

<p>You will probably be able to use this one instead.</p>

<blockquote>
  <p><code>Object.fromEntries</code> is proposed to perform the reverse of <code>Object.entries</code>: it accepts an iterable of key-value pairs and returns a new object whose own keys and corresponding values are given by those pairs.</p>
</blockquote>

```Object.fromEntries([["apple", 0], ["banana", 1]]) // {apple: 0, banana: 1}
```

Title: Good ways to convert 2d array to object

Body:
With <s>ES7</s> ES2017 (ES8) I can convert an object to an array of arrays like this:

let obj = { a: '1', b: '2', c: '3' }
let arr = Object.entries(obj)
// [ [ 'a', '1' ], [ 'b', '2' ], [ 'c', '3' ] ]

But what if I want to go the other way around? I could use a for-loop, or the reduce-method of the Array like below, but is there a more direct approach?

let arr =[ [ 'a', '1' ], [ 'b', '2' ], [ 'c', '3' ] ]
let obj = arr.reduce((o, x)=>{o[x[0]]=x[1];return o}, {})
// { a: '1', b: '2', c: '3' }

A use case: I wanted to convert a string like "a=1;b=2;c=3" to an object like { a: '1', b: '2', c: '3' } and ended up with something like

"a=1;b=2;c=3"
  .split(";")
  .reduce((o, x)=>{
    let parts=x.split("=")
    o[parts[0]]=parts[1]
    return o
  }, {});

Edit: As pointed out in comments, the reduce syntax could be simplified (or shortened, at least) to:

arr.reduce((o, [k, v])=>(o[k]=v, o), {})

...or written with Object.assign like this:

arr.reduce((o, [k, v])=>Object.assign(o, {[k]: v}), {})

Either way, the answer to the question, according to the comments, is no. This is the best approach we've got.

Edit, Jan 2023: .fromEntries() is in stage 4 since 2019, and now supported in all modern browsers.

Body:
Do you want some one-line unentries function?

const detries = entries => entries.reduce((result, [key, value]) => Object.assign(result, {[key]: value}), {});

const entries = Object.entries({a: 1, b: 2, c: 3});
const detried = detries(entries);

console.info("ENTRIES", entries);
console.info("DETRIED", detried);

Edit: Object.fromEntries proposal.

You will probably be able to use this one instead.

Object.fromEntries is proposed to perform the reverse of Object.entries: it accepts an iterable of key-value pairs and returns a new object whose own keys and corresponding values are given by those pairs.

Object.fromEntries([["apple", 0], ["banana", 1]]) // {apple: 0, banana: 1}


问:
Convert a 64 bits floating point number into two integer numbers < 2^32 and back in Lua 5.1
I want to convert a number (64 bit double precision) into two integer numbers (unsigned 32 bits) and back. Is that possible to do without precision loss? The 64 bit number should fit into two 32 bit numbers, I just can't figure out how to do it in Lua.

My experiments with the bitop library in LuaJIT did not result in anything useful. Is it possible to cast the number to unsigned long long and split that one up, in pure Lua code using the ffi API?

Maybe it's not possible without precision loss. What is a reasonable way to do it, even if I lose precision?

答:
You can extract the bytes of the IEEE 754 representation of a double using math.frexp and rebuild the number from the bytes using math.ldexp.

See packers.double
and
unpack_double.

Try also the simpler code at http://lua-users.org/lists/lua-l/2015-03/msg00159.html.


问:
Methods to insert or replace values in to object
I've got an object like this

```<code>var obj2= {
        'home' : {
            '1' : {
                  'year' : '1999'
                  },
            '2' : {
                  'year' : '2000'
                  'month' : '11'
                  },
        },
        'company' : {
            '1' : {
                  'year' : '2010'
                  'month' : '2'
                  },
        }
    };
</code>```

And I would like to add some more keys inside the object or replace value if this key chain already exists, for ex:

```<code>buss_type = "home",
type_id = "1",
date_type = "month",
value = "9"

var tmp_obj1 = {[buss_type]: {[type_id]: {[date_type]: value}}};
</code>```

and

```<code>buss_type = "company",
type_id = "2",
date_type = "month",
value = "12"

var tmp_obj2 = {[buss_type]: {[type_id]: {[date_type]: value}}};
</code>```

to make object:

```<code>obj = {
    'home' : {
        '1' : {
            'year' : '1999',
            'month' : '9'
        },
        '2' : {
            'year' : '2000',
            'month' : '11'
        },
    },
    'company' : {
        '1' : {
            'year' : '2020',
            'month' : '10'
        },
        '2' : {
            'month' : '12'
        }
    },
};
</code>```

Arrays methods like .push() or .concat() adding new keys on the end only instead of replacing values of existing ones.

Are there any object methods that can make it easy to manage or should I just use loops and check all keys before adding new or changing value of existing one?

Thanks.

答:
You could take an array for the keys and save the last key for direct assignment.

function setValue(object, path, value) {
    var last = path.pop();
    path.reduce(function (o, k) {
        return o[k] = o[k] || {};
    }, object)[last] = value;
}

var object = { home: { 1: { year: '1999' }, 2: { year: '2000', month: '11' } }, company: { 1: { year: '2010', month: '2' } } };

setValue(object, ["home", "1", "month"], "9");
setValue(object, ["company", "2", "month"], "12");

console.log(object);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I've got an object like this

var obj2= {
        'home' : {
            '1' : {
                  'year' : '1999'
                  },
            '2' : {
                  'year' : '2000'
                  'month' : '11'
                  },
        },
        'company' : {
            '1' : {
                  'year' : '2010'
                  'month' : '2'
                  },
        }
    };

And I would like to add some more keys inside the object or replace value if this key chain already exists, for ex:

buss_type = "home",
type_id = "1",
date_type = "month",
value = "9"

var tmp_obj1 = {[buss_type]: {[type_id]: {[date_type]: value}}};

and

buss_type = "company",
type_id = "2",
date_type = "month",
value = "12"

var tmp_obj2 = {[buss_type]: {[type_id]: {[date_type]: value}}};

to make object:

obj = {
    'home' : {
        '1' : {
            'year' : '1999',
            'month' : '9'
        },
        '2' : {
            'year' : '2000',
            'month' : '11'
        },
    },
    'company' : {
        '1' : {
            'year' : '2020',
            'month' : '10'
        },
        '2' : {
            'month' : '12'
        }
    },
};

Arrays methods like .push() or .concat() adding new keys on the end only instead of replacing values of existing ones.

Are there any object methods that can make it easy to manage or should I just use loops and check all keys before adding new or changing value of existing one?

Thanks.

Body:
You could take an array for the keys and save the last key for direct assignment.

function setValue(object, path, value) {
    var last = path.pop();
    path.reduce(function (o, k) {
        return o[k] = o[k] || {};
    }, object)[last] = value;
}

var object = { home: { 1: { year: '1999' }, 2: { year: '2000', month: '11' } }, company: { 1: { year: '2010', month: '2' } } };

setValue(object, ["home", "1", "month"], "9");
setValue(object, ["company", "2", "month"], "12");

console.log(object);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
CQL solr-query getting error - cannot pass json query
I'm new to DSE. Working on DSE based queries to get date range

1) select count(1) from tbl where solr_query='code:maf';
It gives the result.

But When I'am trying to use range query is gives error :-

select count(1) from tbl where solr_query='{q:dt:[ 2017-11-15T10:12:10 TO 2017-11-15T12:10:10Z] }';

Error :- Invalid Request: Error from Server: Code:2200 [Invalid Query] message="Cannot pass JSON query" '{q:dt:[ 2017-11-15T10:12:10 TO 2017-11-15T12:10:10Z] }'

Where I'am going wrong? Please help

Thanks,

答:
you need correctly format your query - it should be JSON inside, like this:

```<code>select count(1) from tbl where
  solr_query='{"q":"dt:[ 2017-11-15T10:12:10 TO 2017-11-15T12:10:10Z]"}';
</code>```

See official documentation for detailed description.

Body:
you need correctly format your query - it should be JSON inside, like this:

select count(1) from tbl where
  solr_query='{"q":"dt:[ 2017-11-15T10:12:10 TO 2017-11-15T12:10:10Z]"}';

See official documentation for detailed description.