问:
Bootstrap cells with equal height
I have the following

```<code><div class="row">
  <div class="col-md-6">
    <div class = "box-cell">
      <p>
        Slightly short text
      </p>
    </div>
  </div>
  <div class="col-md-6">
    <div class = "box-cell">
      <p>
        Text that<br>literally<br>spans<br>4 lines
      </p>
    </div>
  </div>
</div>
</code>```

and css

```<code>.box-cell
{
    position:        relative;
    margin:          3px;
    border-style:    groove ridge ridge groove;
    border-width:    3px;
    background-size: cover;
}
</code>```

So the problem that I am facing is that one of the cells is usually taller than the other.IS there any way for me to equalize how much height each cell takes up?
Searching didn't yield me which property I can manipulate to get same height :(

Here is jsfiddle
However in this fiddle I can not get them to be side by side to prove my point

EDIT: I guess I didn't specify it properly. I would like to have the borders be as tall as the tallest cell. So all the examples provided here actually take out the borders and instead color the background. If I do that then yes it gives illusion of every cell being the same, but I would like there to be a border of same height.

答:
Some options to solve it:
Different Tricks on How to Make Bootstrap Columns All the Same Height</p>

Title: Bootstrap cells with equal height

Body:
I have the following

        Slightly short text

        Text that
literally
spans
4 lines

and css

.box-cell
{
    position:        relative;
    margin:          3px;
    border-style:    groove ridge ridge groove;
    border-width:    3px;
    background-size: cover;
}

So the problem that I am facing is that one of the cells is usually taller than the other.IS there any way for me to equalize how much height each cell takes up?
Searching didn't yield me which property I can manipulate to get same height :(

Here is jsfiddle
However in this fiddle I can not get them to be side by side to prove my point

EDIT: I guess I didn't specify it properly. I would like to have the borders be as tall as the tallest cell. So all the examples provided here actually take out the borders and instead color the background. If I do that then yes it gives illusion of every cell being the same, but I would like there to be a border of same height.


来源: stackexchange

问:
how to use sed, awk to print only the path with specific word?
I have a text file looking like this:

```<code>ErrorLog "|/usr/local/apache2/bin/rotatelogs /var/log/apache/error_log.%Y-%m 200M"

ErrorLog "/var/log/apache2/error_log"
</code>```

I need filter only the path with the word error_log.
I need the output as:

```<code>/var/log/apache2/error_log.%Y-%m
</code>```

Or

```<code>/var/log/apache2/error_log
</code>```

答:
With grep:

```<code>grep -o '[^[:space:]]*\<error_log\>[^[:space:]]*' file
</code>```

[^[:space:]]* - match non-whitespace character(s)

\< and \> - are word boundaries

Example output:

```<code>/var/log/apache/error_log.%Y-%m
"/var/log/apache2/error_log"
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a text file looking like this:

ErrorLog "|/usr/local/apache2/bin/rotatelogs /var/log/apache/error_log.%Y-%m 200M"

ErrorLog "/var/log/apache2/error_log"

I need filter only the path with the word error_log.
I need the output as:

/var/log/apache2/error_log.%Y-%m

Or

/var/log/apache2/error_log

Body:
With grep:

grep -o '[^[:space:]]*\<error_log\>[^[:space:]]*' file

[^[:space:]]* - match non-whitespace character(s)

\< and \> - are word boundaries

Example output:

/var/log/apache/error_log.%Y-%m
"/var/log/apache2/error_log"


问:
Running a cmd .bat file with loops and conditions
Hi I am trying to run a scrapy spider using start command from a cmd batch file. I want to run the spider parallely for 10 names from a csv file which contains more than 500 names. So my thought is to basically add some conditions in the loop from 1 to 500 that checks if the 10 command windows have closed, if not then wait for them to close (they auto close after spider is finished). Once the 10 windows which had opened, are closed, open the next 10 and so on. Following is the code I have, i am pretty sure it has big syntax errors. Could you help me debug? Thanks

```<code>cd /d "C:\Users\xyz"
for /f "tokens=1,*" %%m in ('tasklist ^| find /I /C "conhost.exe"') do (set var1=%%m)
set counter=1
for /f "usebackq tokens=1 delims=," %%n in ("test.csv") do (
    (START /MIN "" scrapy crawl xyz_scraper -a query="%%n" -a pages=20)
    set /a counter=counter+1
    for /f "tokens=1,*" %%p in ('tasklist ^| find /I /C "conhost.exe"') do (set var2=%%p)
    SET /A _result=counter%%10
    echo %_result%
    IF _result EQU 0 (
        :abcd
        timeout /t 10
        if var2 EQU var1 (
            goto bcde
            )
            ELSE (
            goto abcd)
        )
    :bcde
    )
pause
</code>```

EDIT: deleted the for loop one. Edited the above code based on some suggestions. I don't understand where would i use quotes for variables and where not and how to print a variables value to cmd.

The updated code below:

```<code>    cd /d "C:\Users\sodhian\sodhi-scraper"
    for /f "tokens=1,*" %%m in ('tasklist ^| find /I /C "conhost.exe"') do (set var1=%%m)
    echo %var1%
    set counter=1
    for /f "usebackq tokens=1 delims=," %%n in ("test comp.csv") do (
        (START /MIN "" scrapy crawl ind_scraper -a query="%%n" -a pages=20)
        set /a "counter=counter+1"
        echo %counter%
        SET /A _result="counter%%2"
        echo %_result%
        IF "%_result%" EQU "0" (
            :abcd
            timeout /t 10
            for /f "tokens=1,*" %%p in ('tasklist ^| find /I /C "conhost.exe"') do (set var2=%%p)
            echo %var2%
            if var2==var1 (
                goto bcde
                )
                ELSE (
                goto abcd)
            )
        :bcde
        )
    pause
</code>```

Edit 2:
Based on Stephan's answer. Tried to accomplish what i mentioned in comment of the answer:

```<code>    setlocal enabledelayedexpansion

    set counter=0
    for /f "usebackq tokens=1 delims=," %%n in ("test comp.csv") do (
      set /a counter+=1
      start /MIN "MySpider!counter!" scrapy crawl ind_scraper -a query="%%n" -a pages=20
      for /f "tokens=1,*" %%b in ('tasklist /v ^| find /I /C "MySpider"') do (set var1=%%b)
      if !var1! geq 5 call :wait
    )
    :wait
    timeout /t 5
    for /f "tokens=1,*" %%p in ('tasklist /v ^| find /I /C "MySpider"') do (set var2=%%p)
    if !var2! geq 5 call :wait
    goto :eof
</code>```

Changed it to the following: (the /v (verbose option in tasklist was making the above slow)

```<code>setlocal enabledelayedexpansion
set counter=0
set max_scrappers=7
for /f "tokens=1,*" %%a in ('tasklist ^| find /C "conhost"') do (set var1=%%a)
for /f "usebackq tokens=1 delims=," %%n in ("test comp.csv") do (
    set /a counter+=1
    start /min "MySpider!counter!" scrapy crawl ind_scraper -a query="%%n" -a pages=20
    for /f "tokens=1,*" %%b in ('tasklist ^| find /C "conhost"') do (set var2=%%b)
    set /a var3=!var2!-!var1!
    if !var3! geq !max_scrappers! call :wait
)
:wait
for /f "tokens=1,*" %%p in ('tasklist ^| find /C "conhost"') do (set var4=%%p)
set /a var5=!var4!-!var1!
if !var5! geq !max_scrappers! call :wait
goto :eof
</code>```

答:
As already noted in the comments, labels inside a code block don't work. But you can call a "function", where goto and labels are no problem:

I choosed other numbers and another command to make it work on every system (and faster). Replacing the timeout command with your spider and adapting the numbers should be no problem.

```<code>@echo off
setlocal enabledelayedexpansion

REM next line just for generating a testfile:
>"test comp.csv" (for /l %%i in (1,1,10) do echo !random:~-1!)

set counter=0
for /f "usebackq tokens=1 delims=," %%n in ("test comp.csv") do (
  set /a counter+=1
  start "MySpider!counter!" timeout %%n
  if !counter! geq 3 call :wait
)
:wait
tasklist /v|find "MySpider">nul && goto :wait
set counter=0
goto :eof
</code>```

Searching for conhost is not a good idea, because there could be other processes. Choose an unique window title instead (MySpider in my example) and look for that title (tasklist /v)

Body:
Hi I am trying to run a scrapy spider using start command from a cmd batch file. I want to run the spider parallely for 10 names from a csv file which contains more than 500 names. So my thought is to basically add some conditions in the loop from 1 to 500 that checks if the 10 command windows have closed, if not then wait for them to close (they auto close after spider is finished). Once the 10 windows which had opened, are closed, open the next 10 and so on. Following is the code I have, i am pretty sure it has big syntax errors. Could you help me debug? Thanks

cd /d "C:\Users\xyz"
for /f "tokens=1,*" %%m in ('tasklist ^| find /I /C "conhost.exe"') do (set var1=%%m)
set counter=1
for /f "usebackq tokens=1 delims=," %%n in ("test.csv") do (
    (START /MIN "" scrapy crawl xyz_scraper -a query="%%n" -a pages=20)
    set /a counter=counter+1
    for /f "tokens=1,*" %%p in ('tasklist ^| find /I /C "conhost.exe"') do (set var2=%%p)
    SET /A _result=counter%%10
    echo %_result%
    IF _result EQU 0 (
        :abcd
        timeout /t 10
        if var2 EQU var1 (
            goto bcde
            )
            ELSE (
            goto abcd)
        )
    :bcde
    )
pause

EDIT: deleted the for loop one. Edited the above code based on some suggestions. I don't understand where would i use quotes for variables and where not and how to print a variables value to cmd.

The updated code below:

    cd /d "C:\Users\sodhian\sodhi-scraper"
    for /f "tokens=1,*" %%m in ('tasklist ^| find /I /C "conhost.exe"') do (set var1=%%m)
    echo %var1%
    set counter=1
    for /f "usebackq tokens=1 delims=," %%n in ("test comp.csv") do (
        (START /MIN "" scrapy crawl ind_scraper -a query="%%n" -a pages=20)
        set /a "counter=counter+1"
        echo %counter%
        SET /A _result="counter%%2"
        echo %_result%
        IF "%_result%" EQU "0" (
            :abcd
            timeout /t 10
            for /f "tokens=1,*" %%p in ('tasklist ^| find /I /C "conhost.exe"') do (set var2=%%p)
            echo %var2%
            if var2==var1 (
                goto bcde
                )
                ELSE (
                goto abcd)
            )
        :bcde
        )
    pause

Edit 2:
Based on Stephan's answer. Tried to accomplish what i mentioned in comment of the answer:

    setlocal enabledelayedexpansion

    set counter=0
    for /f "usebackq tokens=1 delims=," %%n in ("test comp.csv") do (
      set /a counter+=1
      start /MIN "MySpider!counter!" scrapy crawl ind_scraper -a query="%%n" -a pages=20
      for /f "tokens=1,*" %%b in ('tasklist /v ^| find /I /C "MySpider"') do (set var1=%%b)
      if !var1! geq 5 call :wait
    )
    :wait
    timeout /t 5
    for /f "tokens=1,*" %%p in ('tasklist /v ^| find /I /C "MySpider"') do (set var2=%%p)
    if !var2! geq 5 call :wait
    goto :eof

Changed it to the following: (the /v (verbose option in tasklist was making the above slow)

setlocal enabledelayedexpansion
set counter=0
set max_scrappers=7
for /f "tokens=1,*" %%a in ('tasklist ^| find /C "conhost"') do (set var1=%%a)
for /f "usebackq tokens=1 delims=," %%n in ("test comp.csv") do (
    set /a counter+=1
    start /min "MySpider!counter!" scrapy crawl ind_scraper -a query="%%n" -a pages=20
    for /f "tokens=1,*" %%b in ('tasklist ^| find /C "conhost"') do (set var2=%%b)
    set /a var3=!var2!-!var1!
    if !var3! geq !max_scrappers! call :wait
)
:wait
for /f "tokens=1,*" %%p in ('tasklist ^| find /C "conhost"') do (set var4=%%p)
set /a var5=!var4!-!var1!
if !var5! geq !max_scrappers! call :wait
goto :eof

Body:
As already noted in the comments, labels inside a code block don't work. But you can call a "function", where goto and labels are no problem:

I choosed other numbers and another command to make it work on every system (and faster). Replacing the timeout command with your spider and adapting the numbers should be no problem.

@echo off
setlocal enabledelayedexpansion

REM next line just for generating a testfile:
>"test comp.csv" (for /l %%i in (1,1,10) do echo !random:~-1!)

set counter=0
for /f "usebackq tokens=1 delims=," %%n in ("test comp.csv") do (
  set /a counter+=1
  start "MySpider!counter!" timeout %%n
  if !counter! geq 3 call :wait
)
:wait
tasklist /v|find "MySpider">nul && goto :wait
set counter=0
goto :eof

Searching for conhost is not a good idea, because there could be other processes. Choose an unique window title instead (MySpider in my example) and look for that title (tasklist /v)


问:
How to compare two objects in Java 8
Lets take an example you have two employee object having same values as follows.

```<code>Employee employee1 = new Employee(1001, "Sam", 20000);
Employee employee2 = new Employee(1001, "Sam", 20000);
if(doCompareEmployees(employee1, employee2)){
    System.out.println("Both employee objects are same.");
}else{
    System.out.println("Both employee objects are not same.");
}

//Here is compare method using java 8.

private boolean doCompareEmployees(Employee employee1, Employee employee2) {
int returnValue = Comparator.comparing(Employee::getID)
    .thenComparing(Employee::getName)
    .thenComparing(Employee::getSalary)
    .compare(employee1, employee2);
    if (returnValue != 0){
        return false;
    }
    return true;
}
</code>```

I would like know about, is there any other better approach to compare objects in Java 8 ?

答:
If you do not want to define an ordering on your objects, normally you would not write a Comparator.

The typical way to define equality for a class, is to define both an equals() and a hashCode() method. To implement hashCode(), Objects.hash() can help (present since Java 7).

```<code>public int hashCode() {
    return Objects.hash(id, name, salary);
}

public boolean equals(Object o) {
    if (o == this) return true;
    if (o == null || o.getClass() != getClass()) return false;
    Employee e = (Employee) o;
    return id == e.id && salary == e.salary && Objects.equals(name, e.name);
}
</code>```

Although lambda expressions allow to write very elegant code in some cases, they are not the best solution for each problem.

Title: How to compare two objects in Java 8

Body:
Lets take an example you have two employee object having same values as follows.

Employee employee1 = new Employee(1001, "Sam", 20000);
Employee employee2 = new Employee(1001, "Sam", 20000);
if(doCompareEmployees(employee1, employee2)){
    System.out.println("Both employee objects are same.");
}else{
    System.out.println("Both employee objects are not same.");
}

//Here is compare method using java 8.

private boolean doCompareEmployees(Employee employee1, Employee employee2) {
int returnValue = Comparator.comparing(Employee::getID)
    .thenComparing(Employee::getName)
    .thenComparing(Employee::getSalary)
    .compare(employee1, employee2);
    if (returnValue != 0){
        return false;
    }
    return true;
}

I would like know about, is there any other better approach to compare objects in Java 8 ?

Body:
If you do not want to define an ordering on your objects, normally you would not write a Comparator.

The typical way to define equality for a class, is to define both an equals() and a hashCode() method. To implement hashCode(), Objects.hash() can help (present since Java 7).

public int hashCode() {
    return Objects.hash(id, name, salary);
}

public boolean equals(Object o) {
    if (o == this) return true;
    if (o == null || o.getClass() != getClass()) return false;
    Employee e = (Employee) o;
    return id == e.id && salary == e.salary && Objects.equals(name, e.name);
}

Although lambda expressions allow to write very elegant code in some cases, they are not the best solution for each problem.


问:
How do I fade a container to the left when I click on an item in the container
I try to make an effect that is executed by clicking on an item within the container, container slide to right/left and fade, after the content is faded it needs do be display hide to make place for new content.

The future header will be placed outside the container thus the header do not fade. Nothing i tried seem to work. Anybody any suggestions for this problem?

I will be implementing the effect on my website www.bartmulder.nl/beta1.0 so when you click on a photo the container whit all the photos will fade and slide before display none

// change .box1 to .container and you will see the effect that i am looking for
$('.box1').on('click', function() {
  $(this).toggleClass('clicked');

  setTimeout(function() {
    document.getElementById("containerWerk").style.display = "none";
  }, 500);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  -webkit-transition: 0.5s;
  -webkit-transition-timing-function: ease;
  transition-timing-function: ease;
}

.box img {
  margin: 0px auto;
  cursor: pointer;
}

.container.clicked {
  margin-left: -100px;
  opacity: 0;
}</code>```

```

答:
You must apply the class 'clicked' in the parent element '.container', not in the 'this', so use jQuery parent to access the parent element '.container' to add the clicked class in the correct element.

// change .box1 to .container and you will see the effect that i am looking for
$('.box1').on('click', function() {
  $(this).parent('.container').toggleClass('clicked');

  setTimeout(function() {
    document.getElementById("containerWerk").style.display = "none";
  }, 500);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  -webkit-transition: all ease .5s;
  transition: all ease .5s;
  opacity: 1;
  margin-left:0;
  position: relative;
}

.box img {
  margin: 0px auto;
  cursor: pointer;
}

.container.clicked {
  margin-left: -100px;
  opacity: 0;
  transition: all ease .5s;
}</code>```

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

<p>If you want just the image go to other side</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// change .box1 to .container and you will see the effect that i am looking for
$('.box').on('click', function() {
  $(this).toggleClass('clicked');

  setTimeout(function() {
    $(this).css('display','none');
  }, 500);
});</code>```

.container {
  -webkit-transition: all ease .5s;
  transition: all ease .5s;
  opacity: 1;
  margin-left:0;
  position: relative;
}

.box img {
  margin: 0px auto;
  cursor: pointer;
  transition: all ease .5s;
  opacity: 1;
  margin-left:0;
  position: relative;
}

.box.clicked {
  margin-left: -100px;
  opacity: 0;
  transition: all ease .5s;
}```
<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>
<div id="containerWerk" class="container">
  <div class="box box1">
    <img src="https://www.google.com/images/srpr/logo11w.png" width="100" />
  </div>
  <div class="box box2">
    <img src="https://www.google.com/images/srpr/logo11w.png" width="100" />
  </div></code>```

Body:
I try to make an effect that is executed by clicking on an item within the container, container slide to right/left and fade, after the content is faded it needs do be display hide to make place for new content.

The future header will be placed outside the container thus the header do not fade. Nothing i tried seem to work. Anybody any suggestions for this problem?

I will be implementing the effect on my website www.bartmulder.nl/beta1.0 so when you click on a photo the container whit all the photos will fade and slide before display none

// change .box1 to .container and you will see the effect that i am looking for
$('.box1').on('click', function() {
  $(this).toggleClass('clicked');

  setTimeout(function() {
    document.getElementById("containerWerk").style.display = "none";
  }, 500);
});

.container {
  -webkit-transition: 0.5s;
  -webkit-transition-timing-function: ease;
  transition-timing-function: ease;
}

.box img {
  margin: 0px auto;
  cursor: pointer;
}

.container.clicked {
  margin-left: -100px;
  opacity: 0;
}

Body:
You must apply the class 'clicked' in the parent element '.container', not in the 'this', so use jQuery parent to access the parent element '.container' to add the clicked class in the correct element.

// change .box1 to .container and you will see the effect that i am looking for
$('.box1').on('click', function() {
  $(this).parent('.container').toggleClass('clicked');

  setTimeout(function() {
    document.getElementById("containerWerk").style.display = "none";
  }, 500);
});

.container {
  -webkit-transition: all ease .5s;
  transition: all ease .5s;
  opacity: 1;
  margin-left:0;
  position: relative;
}

.box img {
  margin: 0px auto;
  cursor: pointer;
}

.container.clicked {
  margin-left: -100px;
  opacity: 0;
  transition: all ease .5s;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="containerWerk" class="container">
  <div class="box1">
    <img src="https://www.google.com/images/srpr/logo11w.png" width="100" />
  </div>
  <div class="box2">
    <img src="https://www.google.com/images/srpr/logo11w.png" width="100" />
  </div>

If you want just the image go to other side

// change .box1 to .container and you will see the effect that i am looking for
$('.box').on('click', function() {
  $(this).toggleClass('clicked');

  setTimeout(function() {
    $(this).css('display','none');
  }, 500);
});

.container {
  -webkit-transition: all ease .5s;
  transition: all ease .5s;
  opacity: 1;
  margin-left:0;
  position: relative;
}

.box img {
  margin: 0px auto;
  cursor: pointer;
  transition: all ease .5s;
  opacity: 1;
  margin-left:0;
  position: relative;
}

.box.clicked {
  margin-left: -100px;
  opacity: 0;
  transition: all ease .5s;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="containerWerk" class="container">
  <div class="box box1">
    <img src="https://www.google.com/images/srpr/logo11w.png" width="100" />
  </div>
  <div class="box box2">
    <img src="https://www.google.com/images/srpr/logo11w.png" width="100" />
  </div>


问:
Unit testing image tag with image object
i have following reactjs code snippet:

```<code>import lionIcon from 'assets/images/lion.svg';
import dogIcon from 'assets/images/dog.svg';

<img
    className="animal-btn-img"
    src={isLion ? lionIcon : dogIcon}
  />
</code>```

how do i unit test that based on 'isLion' prop, appropriate animal object is set on the img tag.?

```<code>let img = wrapper.find('.animal-btn-img');
console.log(img.prop('src'));
</code>```

the above console.log returns only empty object as {}

答:
try shallow from enzyme, it worked well for me

```<code>import React from 'react'
import {shallow} from 'enzyme'
import Testor from '../components/Testor'

import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

configure({ adapter: new Adapter() });

it('should see image source', () => {
    const container = shallow(<Testor/>)
    expect(container.find('img').props().src).toEqual('http://google.com/')
})
</code>```

Body:
i have following reactjs code snippet:

import lionIcon from 'assets/images/lion.svg';
import dogIcon from 'assets/images/dog.svg';

how do i unit test that based on 'isLion' prop, appropriate animal object is set on the img tag.?

let img = wrapper.find('.animal-btn-img');
console.log(img.prop('src'));

the above console.log returns only empty object as {}

Body:
try shallow from enzyme, it worked well for me

import React from 'react'
import {shallow} from 'enzyme'
import Testor from '../components/Testor'

import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

configure({ adapter: new Adapter() });

it('should see image source', () => {
    const container = shallow(<Testor/>)
    expect(container.find('img').props().src).toEqual('http://google.com/')
})


问:
How to print one val to PartitionBy
I have one problem in Apache Spark GraphX, i tried to partition one graph with this method in the main:

```<code>graph.partitionBy(HDRF, 128)
</code>```

HDRF is a method to do partitioning, I would like to print a val that is inside it, I tried to print but it does not print anything

/EDIT/

```<code>package app

import org.apache.spark.graphx._
import org.apache.spark._
import org.apache.spark.rdd.RDD

/**
  * Main del sistema
  */

object Main{

  def main(args: Array[String]) {

    val sc = new SparkContext(new SparkConf().setMaster("local").setAppName("HDRF"))

    // mostra solo i log in caso di errore
    sc.setLogLevel("ERROR")

    //modifico il file di testo preso in ingresso
    val edges:RDD[Edge[String]]=
      sc.textFile("data/u1.base").map{ line =>
        val fields= line.split("\t")
        Edge(fields(0).toLong,fields(1).toLong,fields(2))
      }

    val graph: Graph[Any,String] =Graph.fromEdges(edges,"defaultProperty")

    graph.partitionBy(HDRF,128)

  }
}
</code>```

.

```<code>package app

import org.apache.spark.graphx._
import scala.collection.concurrent.TrieMap

object HDRF extends PartitionStrategy{
  private var init=0; //lo puoi usare per controllare una fase di inizializzazione che viene eseguita solo la prima volta

  private var partitionsLoad:Array[Long] = Array.empty[Long] //carico (numero di archi) di ogni partizione
  private val vertexIdListPartitions: TrieMap[Long, List[Long]] = TrieMap() //lista di partizioni associate a ogni vertice
  private val vertexIdEdges: TrieMap[Long, Long] = TrieMap() //grado di ogni vertice

  private var edges = 0

  private var sum :Long= 0

  override def getPartition(src:VertexId,dst:VertexId,numParts:Int): PartitionID ={
    var valoreMax:Long =Int.MaxValue
    var partScarica:Int = -1
    var c:Int = 0
    if(init==0){
      init=1
      partitionsLoad=Array.fill[Long](numParts)(0)
    }

    //AGGIORNA IL GRADO CONOSCIUTO DEI VERTICI src E dst NELLA VARIABILE vertexIdEdges
    vertexIdEdges(src)=vertexIdEdges(src)+1
    vertexIdEdges(dst)=vertexIdEdges(dst)+1
    sum=vertexIdEdges(src) + vertexIdEdges(dst)

    //PARTIZIONA IL GRAFO
    if((!vertexIdListPartitions.contains(src))&&(!vertexIdListPartitions.contains(dst))){
      //NESSUNO DEI DUE VERTICI E' STATO MAI INSERITO IN QUALCHE PARTIZIONE
      //SCELGO LA PARTZIIONE PIU' SCARICA E LI ASSEGNO A QUELLA
      while(c==numParts){
        if(partitionsLoad(c)<valoreMax){
          valoreMax=partitionsLoad(c)
          partScarica=c
        }
        c=c+1
      }
      if(partScarica != -1) {
        partitionsLoad(partScarica) = partitionsLoad(partScarica) + 1
        vertexIdListPartitions(partScarica).union(List(src, dst))
      }
      return partScarica

    }else if(((vertexIdListPartitions.contains(src))&&(!vertexIdListPartitions.contains(dst)))||((!vertexIdListPartitions.contains(src))&&(vertexIdListPartitions.contains(dst)))){
      //UNO SOLO DEI DUE VERTICI E' GIA' PRESENTE IN ALMENO UNA PARTIZIONE
      if((vertexIdListPartitions.contains(src))&&(!vertexIdListPartitions.contains(dst))){
        //SI TRATTA DI src
        //SCELGO LA PARTIZIONE PIU' SCARICA TRA QUELLE IN CUI E' PRESENTE src E CI REPLICO dst
        while(c==numParts){
          if(partitionsLoad(c)<valoreMax){
            if(vertexIdListPartitions(c).contains(src)) {
              valoreMax = partitionsLoad(c)
              partScarica = c
            }
          }
          c=c+1
        }
        if(partScarica != -1) {
          partitionsLoad(partScarica) = partitionsLoad(partScarica) + 1
          vertexIdListPartitions(partScarica).union(List(dst))
        }

      }else{
        //SI TRATTA DI dst
        //SCELGO LA PARTZIIONE PIU' SCARICA TRA QUELLE IN CUI E' PRESENTE dst E CI REPLICO src

        while(c==numParts){
          if(partitionsLoad(c)<valoreMax){
            if(vertexIdListPartitions(c).contains(src)) {
              valoreMax = partitionsLoad(c)
              partScarica = c
            }
          }
          c=c+1
        }
        if(partScarica != -1) {
          partitionsLoad(partScarica) = partitionsLoad(partScarica) + 1
          vertexIdListPartitions(partScarica).union(List(src))
        }

      }
    }else if(!vertexIdListPartitions(src).intersect(vertexIdListPartitions(dst)).isEmpty){
      //ENTRAMBI I VERTICI SONO PRESENTI IN DIVERSE PARTIZIONI ED ESISTE UNA INTERSEZIONE DEI SET NON NULLA (CIOE' ESISTE ALMENO UNA PARTIZIONE CHE LI CONTIENE ENTRAMBI)
      //SCELGO NELL'INTERSEZIONE DEI SET LA PARTIZIONE PIU' SCARICA

      while(c==numParts) {
        if (partitionsLoad(c) < valoreMax) {
          if (vertexIdListPartitions(c).contains(src) && vertexIdListPartitions(c).contains(dst)) {
            valoreMax = partitionsLoad(c)
            partScarica = c
          }
        }
        c = c + 1
      }
      if(partScarica != -1) {
        partitionsLoad(partScarica) = partitionsLoad(partScarica) + 1
        vertexIdListPartitions(partScarica).union(List(src))
      }

    }else {
      //ENTRAMBI I VERTICI SONO PRESENTI IN DIVERSE PARTIZIONI MA L'INTERSEZIONE DEI SET E' NULLA (CIOE' NON ESISTE ALCUNA PARTIZIONE CHE LI CONTIENE ENTRAMBI)
      if((vertexIdEdges(src))>=(vertexIdEdges(dst))){
        //SCELGO TRA LE PARTIZIONI A CUI E' ASSEGNATO dst QUELLA PIU' SCARICA E CI COPIO src

        while(c==numParts){
          if(partitionsLoad(c)<valoreMax){
            if(vertexIdListPartitions(c).contains(dst)) {
              valoreMax = partitionsLoad(c)
              partScarica = c
            }
          }
          c=c+1
        }
        if(partScarica != -1) {
          partitionsLoad(partScarica) = partitionsLoad(partScarica) + 1
          vertexIdListPartitions(partScarica).union(List(src))
        }

      }else{
        //SCELGO TRA LE PARTIZIONI A CUI E' ASSEGNATO src QUELLA PIU' SCARICA E CI COPIO dst

        while(c==numParts){
          if(partitionsLoad(c)<valoreMax){
            if(vertexIdListPartitions(c).contains(src)) {
              valoreMax = partitionsLoad(c)
              partScarica = c
            }
          }
          c=c+1
        }
        if(partScarica != -1) {
          partitionsLoad(partScarica) = partitionsLoad(partScarica) + 1
          vertexIdListPartitions(partScarica).union(List(dst))
        }
      }

    }
    edges=edges+1
    if(edges==80000) {
      print(sum)
    }
    return partScarica
  }
}
</code>```

I need to print sum, but I don't understand why it does not appear.

答:
partitionBy, like many Graph functions, is a lazily-evaluated operation that generates a new Graph object, but doesn't actually compute that Graph until it's necessary - i.e. until some action is performed on the result (e.g. counting, persisting, or collecting it).

Using a simpler example we can see that if we act on the result, these prints will be visible:

```<code>object SimpleExample extends PartitionStrategy {
  override def getPartition(src: VertexId, dst: VertexId, numParts: PartitionID): PartitionID = {
    println("partitioning!")
    numParts
  }
}

val result = graph.partitionBy(SimpleExample, 128) // nothing printed so far...

result.edges.count() // now that we act on the result,
// we see "paritioning!" printed (several times).
</code>```

NOTE that printing from a PartitionStrategy (or any transformation function passed to Spark to be performed on an RDD, a Graph, or a Dataset) is not too helpful: these functions are executed on the worker nodes, hence these prints will be "scattered" in outputs of different processes on different machines, and would probably NOT be visible in the output of the driver application (your main function).

Title: How to print one val to PartitionBy

Body:
I have one problem in Apache Spark GraphX, i tried to partition one graph with this method in the main:

graph.partitionBy(HDRF, 128)

HDRF is a method to do partitioning, I would like to print a val that is inside it, I tried to print but it does not print anything

/EDIT/

package app

import org.apache.spark.graphx._
import org.apache.spark._
import org.apache.spark.rdd.RDD

/**
  * Main del sistema
  */

object Main{

  def main(args: Array[String]) {

    val sc = new SparkContext(new SparkConf().setMaster("local").setAppName("HDRF"))

    // mostra solo i log in caso di errore
    sc.setLogLevel("ERROR")

    //modifico il file di testo preso in ingresso
    val edges:RDD[Edge[String]]=
      sc.textFile("data/u1.base").map{ line =>
        val fields= line.split("\t")
        Edge(fields(0).toLong,fields(1).toLong,fields(2))
      }

    val graph: Graph[Any,String] =Graph.fromEdges(edges,"defaultProperty")

    graph.partitionBy(HDRF,128)

  }
}

.

package app

import org.apache.spark.graphx._
import scala.collection.concurrent.TrieMap

object HDRF extends PartitionStrategy{
  private var init=0; //lo puoi usare per controllare una fase di inizializzazione che viene eseguita solo la prima volta

  private var partitionsLoad:Array[Long] = Array.empty[Long] //carico (numero di archi) di ogni partizione
  private val vertexIdListPartitions: TrieMap[Long, List[Long]] = TrieMap() //lista di partizioni associate a ogni vertice
  private val vertexIdEdges: TrieMap[Long, Long] = TrieMap() //grado di ogni vertice

  private var edges = 0

  private var sum :Long= 0

  override def getPartition(src:VertexId,dst:VertexId,numParts:Int): PartitionID ={
    var valoreMax:Long =Int.MaxValue
    var partScarica:Int = -1
    var c:Int = 0
    if(init==0){
      init=1
      partitionsLoad=Array.fill[Long](numParts)(0)
    }

    //AGGIORNA IL GRADO CONOSCIUTO DEI VERTICI src E dst NELLA VARIABILE vertexIdEdges
    vertexIdEdges(src)=vertexIdEdges(src)+1
    vertexIdEdges(dst)=vertexIdEdges(dst)+1
    sum=vertexIdEdges(src) + vertexIdEdges(dst)

    //PARTIZIONA IL GRAFO
    if((!vertexIdListPartitions.contains(src))&&(!vertexIdListPartitions.contains(dst))){
      //NESSUNO DEI DUE VERTICI E' STATO MAI INSERITO IN QUALCHE PARTIZIONE
      //SCELGO LA PARTZIIONE PIU' SCARICA E LI ASSEGNO A QUELLA
      while(c==numParts){
        if(partitionsLoad(c)<valoreMax){
          valoreMax=partitionsLoad(c)
          partScarica=c
        }
        c=c+1
      }
      if(partScarica != -1) {
        partitionsLoad(partScarica) = partitionsLoad(partScarica) + 1
        vertexIdListPartitions(partScarica).union(List(src, dst))
      }
      return partScarica

    }else if(((vertexIdListPartitions.contains(src))&&(!vertexIdListPartitions.contains(dst)))||((!vertexIdListPartitions.contains(src))&&(vertexIdListPartitions.contains(dst)))){
      //UNO SOLO DEI DUE VERTICI E' GIA' PRESENTE IN ALMENO UNA PARTIZIONE
      if((vertexIdListPartitions.contains(src))&&(!vertexIdListPartitions.contains(dst))){
        //SI TRATTA DI src
        //SCELGO LA PARTIZIONE PIU' SCARICA TRA QUELLE IN CUI E' PRESENTE src E CI REPLICO dst
        while(c==numParts){
          if(partitionsLoad(c)<valoreMax){
            if(vertexIdListPartitions(c).contains(src)) {
              valoreMax = partitionsLoad(c)
              partScarica = c
            }
          }
          c=c+1
        }
        if(partScarica != -1) {
          partitionsLoad(partScarica) = partitionsLoad(partScarica) + 1
          vertexIdListPartitions(partScarica).union(List(dst))
        }

      }else{
        //SI TRATTA DI dst
        //SCELGO LA PARTZIIONE PIU' SCARICA TRA QUELLE IN CUI E' PRESENTE dst E CI REPLICO src

        while(c==numParts){
          if(partitionsLoad(c)<valoreMax){
            if(vertexIdListPartitions(c).contains(src)) {
              valoreMax = partitionsLoad(c)
              partScarica = c
            }
          }
          c=c+1
        }
        if(partScarica != -1) {
          partitionsLoad(partScarica) = partitionsLoad(partScarica) + 1
          vertexIdListPartitions(partScarica).union(List(src))
        }

      }
    }else if(!vertexIdListPartitions(src).intersect(vertexIdListPartitions(dst)).isEmpty){
      //ENTRAMBI I VERTICI SONO PRESENTI IN DIVERSE PARTIZIONI ED ESISTE UNA INTERSEZIONE DEI SET NON NULLA (CIOE' ESISTE ALMENO UNA PARTIZIONE CHE LI CONTIENE ENTRAMBI)
      //SCELGO NELL'INTERSEZIONE DEI SET LA PARTIZIONE PIU' SCARICA

      while(c==numParts) {
        if (partitionsLoad(c) < valoreMax) {
          if (vertexIdListPartitions(c).contains(src) && vertexIdListPartitions(c).contains(dst)) {
            valoreMax = partitionsLoad(c)
            partScarica = c
          }
        }
        c = c + 1
      }
      if(partScarica != -1) {
        partitionsLoad(partScarica) = partitionsLoad(partScarica) + 1
        vertexIdListPartitions(partScarica).union(List(src))
      }

    }else {
      //ENTRAMBI I VERTICI SONO PRESENTI IN DIVERSE PARTIZIONI MA L'INTERSEZIONE DEI SET E' NULLA (CIOE' NON ESISTE ALCUNA PARTIZIONE CHE LI CONTIENE ENTRAMBI)
      if((vertexIdEdges(src))>=(vertexIdEdges(dst))){
        //SCELGO TRA LE PARTIZIONI A CUI E' ASSEGNATO dst QUELLA PIU' SCARICA E CI COPIO src

        while(c==numParts){
          if(partitionsLoad(c)<valoreMax){
            if(vertexIdListPartitions(c).contains(dst)) {
              valoreMax = partitionsLoad(c)
              partScarica = c
            }
          }
          c=c+1
        }
        if(partScarica != -1) {
          partitionsLoad(partScarica) = partitionsLoad(partScarica) + 1
          vertexIdListPartitions(partScarica).union(List(src))
        }

      }else{
        //SCELGO TRA LE PARTIZIONI A CUI E' ASSEGNATO src QUELLA PIU' SCARICA E CI COPIO dst

        while(c==numParts){
          if(partitionsLoad(c)<valoreMax){
            if(vertexIdListPartitions(c).contains(src)) {
              valoreMax = partitionsLoad(c)
              partScarica = c
            }
          }
          c=c+1
        }
        if(partScarica != -1) {
          partitionsLoad(partScarica) = partitionsLoad(partScarica) + 1
          vertexIdListPartitions(partScarica).union(List(dst))
        }
      }

    }
    edges=edges+1
    if(edges==80000) {
      print(sum)
    }
    return partScarica
  }
}

I need to print sum, but I don't understand why it does not appear.

Body:
partitionBy, like many Graph functions, is a lazily-evaluated operation that generates a new Graph object, but doesn't actually compute that Graph until it's necessary - i.e. until some action is performed on the result (e.g. counting, persisting, or collecting it).

Using a simpler example we can see that if we act on the result, these prints will be visible:

object SimpleExample extends PartitionStrategy {
  override def getPartition(src: VertexId, dst: VertexId, numParts: PartitionID): PartitionID = {
    println("partitioning!")
    numParts
  }
}

val result = graph.partitionBy(SimpleExample, 128) // nothing printed so far...

result.edges.count() // now that we act on the result,
// we see "paritioning!" printed (several times).

NOTE that printing from a PartitionStrategy (or any transformation function passed to Spark to be performed on an RDD, a Graph, or a Dataset) is not too helpful: these functions are executed on the worker nodes, hence these prints will be "scattered" in outputs of different processes on different machines, and would probably NOT be visible in the output of the driver application (your main function).


问:
Dealing with line Breaks on contentEditable DIV
I have a problem with contenteditable line breaks on SAFARI/CHROME. When I press "return" on a contentEditable
, instead of creating a
 (like Firefox), they create a new
:

```<code><div>Something</div>
<div>Something</div>
</code>```

That looks like (on the contentEditable DIV):

```<code>Something
Something
</code>```

But after sanitization (removing
), I get this:

```<code>SomethingSomething
</code>```

In Firefox, the contenteditable is:

```<code>Something
<br>
Something
</code>```

And that after sanitization looks the same:

```<code>Something
Something
</code>```

Is there any solution to "normalize" this across browsers?

I've found this code on Make a
 instead of

 by pressing Enter on a contenteditable

```<code>$(function(){

  $("#editable")

  // make sure br is always the lastChild of contenteditable
  .live("keyup mouseup", function(){
    if (!this.lastChild || this.lastChild.nodeName.toLowerCase() != "br") {
      this.appendChild(document.createChild("br"));
     }
  })

  // use br instead of div div
  .live("keypress", function(e){
    if (e.which == 13) {
      if (window.getSelection) {
        var selection = window.getSelection(),
          range = selection.getRangeAt(0),
          br = document.createElement("br");
        range.deleteContents();
        range.insertNode(br);
        range.setStartAfter(br);
        range.setEndAfter(br);
        range.collapse(false);
        selection.removeAllRanges();
        selection.addRange(range);
        return false;
      }
    }
  });
});
</code>```

This works, but (in SAFARI and CHROME) I have to press two times the "return" key to get a new line...

Any idea?

Edit: With the code I found ( at the bottom of this question) is working fine except the function that "makes sure a
 element is always the lastChild... Any idea on how to fix this?

Edit 2: I'm getting this error on the console: Uncaught TypeError: Object #<HTMLDocument> has no method 'createChild'

Edit 3: Ok, I changed the document.createChild("br"); to document.createElement("br"); and I think I got it working in FF/Safari/Chrome... All return
 for new lines...

The problem is now that when I'm inside an Ordered or Unordered List, I need to get a new line without
...

Edit 4: If anyone interested in the solution of the last edit: Avoid createElement function if it's inside a
 element (contentEditable)

答:
You can simply use following command
document.execCommand('insertHTML',false,'
');

This command will prevent default behavior and add a tag you wish.
That's all, 1 line of code

And even easier approach.

CSS ONLY.

To you contenteditable element apply display:inline-block rule
and this will add brs only

Body:
I have a problem with contenteditable line breaks on SAFARI/CHROME. When I press "return" on a contentEditable
, instead of creating a
 (like Firefox), they create a new
:

Something

Something

That looks like (on the contentEditable DIV):

Something
Something

But after sanitization (removing
), I get this:

SomethingSomething

In Firefox, the contenteditable is:

Something

Something

And that after sanitization looks the same:

Something
Something

Is there any solution to "normalize" this across browsers?

I've found this code on Make a
 instead of

 by pressing Enter on a contenteditable

$(function(){

  $("#editable")

  // make sure br is always the lastChild of contenteditable
  .live("keyup mouseup", function(){
    if (!this.lastChild || this.lastChild.nodeName.toLowerCase() != "br") {
      this.appendChild(document.createChild("br"));
     }
  })

  // use br instead of div div
  .live("keypress", function(e){
    if (e.which == 13) {
      if (window.getSelection) {
        var selection = window.getSelection(),
          range = selection.getRangeAt(0),
          br = document.createElement("br");
        range.deleteContents();
        range.insertNode(br);
        range.setStartAfter(br);
        range.setEndAfter(br);
        range.collapse(false);
        selection.removeAllRanges();
        selection.addRange(range);
        return false;
      }
    }
  });
});

This works, but (in SAFARI and CHROME) I have to press two times the "return" key to get a new line...

Any idea?

Edit: With the code I found ( at the bottom of this question) is working fine except the function that "makes sure a
 element is always the lastChild... Any idea on how to fix this?

Edit 2: I'm getting this error on the console: Uncaught TypeError: Object #<HTMLDocument> has no method 'createChild'

Edit 3: Ok, I changed the document.createChild("br"); to document.createElement("br"); and I think I got it working in FF/Safari/Chrome... All return
 for new lines...

The problem is now that when I'm inside an Ordered or Unordered List, I need to get a new line without
...

Edit 4: If anyone interested in the solution of the last edit: Avoid createElement function if it's inside a
 element (contentEditable)

Body:
You can simply use following command
document.execCommand('insertHTML',false,'<br>');

This command will prevent default behavior and add a tag you wish.
That's all, 1 line of code

And even easier approach.

CSS ONLY.

To you contenteditable element apply display:inline-block rule
and this will add brs only


问:
Adding ng-boostrap to Angular app makes no effect on HTML controls
I have recently tried adding ng-bootstrap to my asp.net mvc with Angular app.
I followed the steps at ng-bootstrap and I can't get it to work. The controls look like plain html (like I didn't use ng-boostrap at all)
I would appreciate any help.

main.ts

```<code>import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';

platformBrowserDynamic().bootstrapModule(AppModule);
</code>```

systemjs.config.js

```<code>/**
 * System configuration for Angular samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
    System.config({
        paths: {
            // paths serve as alias
            'npm:': '/node_modules/'
        },
        // map tells the System loader where to look for things
        map: {
            // our app is within the app folder
            'app': '/src/app',

            // angular bundles
            '@angular/animations': 'npm:@angular/animations/bundles/animations.umd.js',
            '@angular/animations/browser': 'npm:@angular/animations/bundles/animations-browser.umd.js',
            '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
            '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
            '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
            '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
            '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
            '@angular/platform-browser/animations': 'npm:@angular/platform-browser/bundles/platform-browser-animations.umd.js',
            '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
            '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
            '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
            '@ng-bootstrap/ng-bootstrap': 'npm:@ng-bootstrap/ng-bootstrap/bundles/ng-bootstrap.js',
            // other libraries
            'rxjs': 'npm:rxjs',
            'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js',
            'tslib': 'npm:tslib/tslib.js',
            'bootstrap':                  'node_modules/bootstrap/dist/js/bootstrap.min.js',
            'jquery':                     'node_modules/jquery/dist/jquery.js',

            '@progress': 'npm:@progress',
            '@telerik': 'npm:@telerik'
        },
        // packages tells the System loader how to load when no filename and/or no extension
        packages: {
            app: {
                defaultExtension: 'js',
                meta: {
                    './*.js': {
                        loader: '/src/systemjs-angular-loader.js'
                    }
                }
            },
            rxjs: {
                defaultExtension: 'js'
            }
        }
    });
})(this);
</code>```

app.module.ts

```<code>import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AppComponent }  from './app.component';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';

@NgModule({
    imports: [BrowserModule, BrowserAnimationsModule, NgbModule.forRoot()],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }
</code>```

app.component.ts

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
    templateUrl: './app.component.html'
})
export class AppComponent {}
</code>```

app.component.html

```<code><div class="row">
    <div class="col">
        <h1>Angular</h1>
        <div ngbDropdown class="d-inline-block">
            <button class="btn btn-outline-primary" id="dropdownBasic1" ngbDropdownToggle>Toggle dropdown</button>
            <div ngbDropdownMenu aria-labelledby="dropdownBasic1">
                <button class="dropdown-item">Action - 1</button>
                <button class="dropdown-item">Another Action</button>
                <button class="dropdown-item">Something else is here</button>
            </div>
        </div>
    </div>
</div>
</code>```

答:
According to the ng-bootstrap documentation, you should not include bootstrap.min.js and jQuery in your project because

It is not necessary and might interfere with ng-bootstrap code.

But the main issue is that you didn't include NgbdDropdownBasic into your App module declarations:

```<code>import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AppComponent }  from './app.component';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { NgbdDropdownBasic } from './dropdown-basic'; // this

@NgModule({
  imports: [BrowserModule, BrowserAnimationsModule, NgbModule.forRoot()],
  declarations: [ AppComponent, NgbdDropdownBasic ], // and this
  bootstrap:    [ AppComponent ]
})
export class AppModule { }
</code>```

Each ng-bootstrap entity should be included separately. Want to use Datepicker? include NgbdDatepickerBasic, and so on...

Body:
I have recently tried adding ng-bootstrap to my asp.net mvc with Angular app.
I followed the steps at ng-bootstrap and I can't get it to work. The controls look like plain html (like I didn't use ng-boostrap at all)
I would appreciate any help.

main.ts

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';

platformBrowserDynamic().bootstrapModule(AppModule);

systemjs.config.js

/**
 * System configuration for Angular samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
    System.config({
        paths: {
            // paths serve as alias
            'npm:': '/node_modules/'
        },
        // map tells the System loader where to look for things
        map: {
            // our app is within the app folder
            'app': '/src/app',

            // angular bundles
            '@angular/animations': 'npm:@angular/animations/bundles/animations.umd.js',
            '@angular/animations/browser': 'npm:@angular/animations/bundles/animations-browser.umd.js',
            '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
            '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
            '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
            '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
            '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
            '@angular/platform-browser/animations': 'npm:@angular/platform-browser/bundles/platform-browser-animations.umd.js',
            '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
            '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
            '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
            '@ng-bootstrap/ng-bootstrap': 'npm:@ng-bootstrap/ng-bootstrap/bundles/ng-bootstrap.js',
            // other libraries
            'rxjs': 'npm:rxjs',
            'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js',
            'tslib': 'npm:tslib/tslib.js',
            'bootstrap':                  'node_modules/bootstrap/dist/js/bootstrap.min.js',
            'jquery':                     'node_modules/jquery/dist/jquery.js',

            '@progress': 'npm:@progress',
            '@telerik': 'npm:@telerik'
        },
        // packages tells the System loader how to load when no filename and/or no extension
        packages: {
            app: {
                defaultExtension: 'js',
                meta: {
                    './*.js': {
                        loader: '/src/systemjs-angular-loader.js'
                    }
                }
            },
            rxjs: {
                defaultExtension: 'js'
            }
        }
    });
})(this);

app.module.ts

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AppComponent }  from './app.component';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';

@NgModule({
    imports: [BrowserModule, BrowserAnimationsModule, NgbModule.forRoot()],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
    templateUrl: './app.component.html'
})
export class AppComponent {}

app.component.html

Angular

            <button class="btn btn-outline-primary" id="dropdownBasic1" ngbDropdownToggle>Toggle dropdown</button>

                <button class="dropdown-item">Action - 1</button>
                <button class="dropdown-item">Another Action</button>
                <button class="dropdown-item">Something else is here</button>

Body:
According to the ng-bootstrap documentation, you should not include bootstrap.min.js and jQuery in your project because

It is not necessary and might interfere with ng-bootstrap code.

But the main issue is that you didn't include NgbdDropdownBasic into your App module declarations:

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AppComponent }  from './app.component';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { NgbdDropdownBasic } from './dropdown-basic'; // this

@NgModule({
  imports: [BrowserModule, BrowserAnimationsModule, NgbModule.forRoot()],
  declarations: [ AppComponent, NgbdDropdownBasic ], // and this
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

Each ng-bootstrap entity should be included separately. Want to use Datepicker? include NgbdDatepickerBasic, and so on...


问:
Update Ember model attribute in component
I have the following bit of code in an Ember component:

```<code>markResolved() {
  let reportingFailure = this.get('reportingFailure');
  reportingFailure.resolvedAt = '2017-01-01';
  reportingFailure.save();
}
</code>```

The HTTP request is firing as expected but the resolved_at attribute is not getting set.

What do I have to do differently to get the attribute to set?

答:
How is reportingFailuredefined? Due to the savemethod call, I assume it's an ember-data model.
Try to use .set() to change the resolvedAt attribute?:

```<code>markResolved() {
  let reportingFailure = this.get('reportingFailure');
  reportingFailure.set('resolvedAt', '2017-01-01');
  reportingFailure.save();
}
</code>```

Body:
I have the following bit of code in an Ember component:

markResolved() {
  let reportingFailure = this.get('reportingFailure');
  reportingFailure.resolvedAt = '2017-01-01';
  reportingFailure.save();
}

The HTTP request is firing as expected but the resolved_at attribute is not getting set.

What do I have to do differently to get the attribute to set?

Body:
How is reportingFailuredefined? Due to the savemethod call, I assume it's an ember-data model.
Try to use .set() to change the resolvedAt attribute?:

markResolved() {
  let reportingFailure = this.get('reportingFailure');
  reportingFailure.set('resolvedAt', '2017-01-01');
  reportingFailure.save();
}


问:
ListFragment does not accept my layout
According to this link: ListFragment android developers

I want to set my custom layout for list, but it makes exceptions.

Here is the code:

```<code>public class ListFragmentActivity extends FragmentActivity {

@Override
public void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    FragmentManager fm = getSupportFragmentManager();
    if(fm.findFragmentById(android.R.id.content) == null)
    {
        myListFragments list = new myListFragments();
        fm.beginTransaction().add(android.R.id.content, list).commit();
    }
}

public static class myListFragments extends ListFragment
{
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        return inflater.inflate(R.layout.topoffers, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
        List<OfferModel> offers = Global.getInstance().getOffers();
        List<OfferModel> topOffers = new ArrayList<OfferModel>(4);
        for (int i = 0; i < 4; i++) {
            if (offers.get(i).getOfferImage() == null)
                offers.get(i).setOfferImage(
                        downloadFile(offers.get(i).getOfferImageUrl()));
            topOffers.add(offers.get(i));
        }
        LazyAdapter adapter = new LazyAdapter(getActivity());
        adapter.setData(topOffers);
        setListAdapter(adapter);
        setListShown(true);
    }

    public Bitmap downloadFile(String fileUrl) {
        URL myFileUrl = null;
        try {
            myFileUrl = new URL(fileUrl);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        }
        try {
            HttpURLConnection conn = (HttpURLConnection) myFileUrl
                    .openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            return BitmapFactory.decodeStream(is);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}}
</code>```

and my custom layout is R.layout.topoffers

Logcat:

```<code> 05-15 21:43:56.975: W/dalvikvm(218): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
 05-15 21:43:56.975: E/AndroidRuntime(218): Uncaught handler: thread main exiting due to uncaught exception
 05-15 21:43:56.995: E/AndroidRuntime(218): java.lang.RuntimeException: Unable to start activity ComponentInfo{org.anddev.android.ikiwi/org.anddev.android.ikiwi.ListFragmentActivity}:
    java.lang.IllegalStateException: Can't be used with a custom content view
 05-15 21:43:56.995: E/AndroidRuntime(218):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496)
 05-15 21:43:56.995: E/AndroidRuntime(218):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
 05-15 21:43:56.995: E/AndroidRuntime(218):     at android.app.ActivityThread.access$2200(ActivityThread.java:119)
 05-15 21:43:56.995: E/AndroidRuntime(218):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
 05-15 21:43:56.995: E/AndroidRuntime(218):     at android.os.Handler.dispatchMessage(Handler.java:99)
 05-15 21:43:56.995: E/AndroidRuntime(218):     at android.os.Looper.loop(Looper.java:123)
 05-15 21:43:56.995: E/AndroidRuntime(218):     at android.app.ActivityThread.main(ActivityThread.java:4363)
 05-15 21:43:56.995: E/AndroidRuntime(218):     at java.lang.reflect.Method.invokeNative(Native Method)
 05-15 21:43:56.995: E/AndroidRuntime(218):     at java.lang.reflect.Method.invoke(Method.java:521)
 05-15 21:43:56.995: E/AndroidRuntime(218):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
 05-15 21:43:56.995: E/AndroidRuntime(218):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
 05-15 21:43:56.995: E/AndroidRuntime(218):     at dalvik.system.NativeStart.main(Native Method)
 05-15 21:43:56.995: E/AndroidRuntime(218): Caused by: java.lang.IllegalStateException:
    Can't be used with a custom content view
 05-15 21:43:56.995: E/AndroidRuntime(218):     at android.support.v4.app.ListFragment.setListShown(ListFragment.java:282)
 05-15 21:43:56.995: E/AndroidRuntime(218):     at android.support.v4.app.ListFragment.setListShown(ListFragment.java:258)
 05-15 21:43:56.995: E/AndroidRuntime(218):     at org.anddev.android.ikiwi.ListFragmentActivity$myListFragments.onActivityCreated(ListFragmentActivity.java:57)
 05-15 21:43:56.995: E/AndroidRuntime(218):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:891)
 05-15 21:43:56.995: E/AndroidRuntime(218):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1080)
 05-15 21:43:56.995: E/AndroidRuntime(218):     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:622)
 05-15 21:43:56.995: E/AndroidRuntime(218):     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1416)
 05-15 21:43:56.995: E/AndroidRuntime(218):     at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:505)
 05-15 21:43:56.995: E/AndroidRuntime(218):     at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1129)
 05-15 21:43:56.995: E/AndroidRuntime(218):     at android.app.Activity.performStart(Activity.java:3723)
 05-15 21:43:56.995: E/AndroidRuntime(218):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2468)
 05-15 21:43:56.995: E/AndroidRuntime(218):     ... 11 more
 05-15 21:43:57.025: I/dalvikvm(218): threadid=7: reacting to signal 3
 05-15 21:43:57.025: E/dalvikvm(218): Unable to open stack trace file '/data/anr/traces.txt': Permission denied
</code>```

答:
A little bit late, but did not see this answer.

Inside Fragment:

```<code>    @Override
    public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
            final Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_list_activity,
                container, false);

        ListFragmentHelper.adaptView(view);

        return view;
    }
</code>```

but bear in mind that in fragment_list_activity.xml you need to set  the IDs android:id="@id/loading",  android:id="@id/content" and android:id="@id/empty" for your views!

Title: ListFragment does not accept my layout

Body:
According to this link: ListFragment android developers

I want to set my custom layout for list, but it makes exceptions.

Here is the code:

public class ListFragmentActivity extends FragmentActivity {

@Override
public void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    FragmentManager fm = getSupportFragmentManager();
    if(fm.findFragmentById(android.R.id.content) == null)
    {
        myListFragments list = new myListFragments();
        fm.beginTransaction().add(android.R.id.content, list).commit();
    }
}

public static class myListFragments extends ListFragment
{
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        return inflater.inflate(R.layout.topoffers, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
        List<OfferModel> offers = Global.getInstance().getOffers();
        List<OfferModel> topOffers = new ArrayList<OfferModel>(4);
        for (int i = 0; i < 4; i++) {
            if (offers.get(i).getOfferImage() == null)
                offers.get(i).setOfferImage(
                        downloadFile(offers.get(i).getOfferImageUrl()));
            topOffers.add(offers.get(i));
        }
        LazyAdapter adapter = new LazyAdapter(getActivity());
        adapter.setData(topOffers);
        setListAdapter(adapter);
        setListShown(true);
    }

    public Bitmap downloadFile(String fileUrl) {
        URL myFileUrl = null;
        try {
            myFileUrl = new URL(fileUrl);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        }
        try {
            HttpURLConnection conn = (HttpURLConnection) myFileUrl
                    .openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            return BitmapFactory.decodeStream(is);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}}

and my custom layout is R.layout.topoffers

Logcat:

 05-15 21:43:56.975: W/dalvikvm(218): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
 05-15 21:43:56.975: E/AndroidRuntime(218): Uncaught handler: thread main exiting due to uncaught exception
 05-15 21:43:56.995: E/AndroidRuntime(218): java.lang.RuntimeException: Unable to start activity ComponentInfo{org.anddev.android.ikiwi/org.anddev.android.ikiwi.ListFragmentActivity}:
    java.lang.IllegalStateException: Can't be used with a custom content view
 05-15 21:43:56.995: E/AndroidRuntime(218):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496)
 05-15 21:43:56.995: E/AndroidRuntime(218):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
 05-15 21:43:56.995: E/AndroidRuntime(218):     at android.app.ActivityThread.access$2200(ActivityThread.java:119)
 05-15 21:43:56.995: E/AndroidRuntime(218):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
 05-15 21:43:56.995: E/AndroidRuntime(218):     at android.os.Handler.dispatchMessage(Handler.java:99)
 05-15 21:43:56.995: E/AndroidRuntime(218):     at android.os.Looper.loop(Looper.java:123)
 05-15 21:43:56.995: E/AndroidRuntime(218):     at android.app.ActivityThread.main(ActivityThread.java:4363)
 05-15 21:43:56.995: E/AndroidRuntime(218):     at java.lang.reflect.Method.invokeNative(Native Method)
 05-15 21:43:56.995: E/AndroidRuntime(218):     at java.lang.reflect.Method.invoke(Method.java:521)
 05-15 21:43:56.995: E/AndroidRuntime(218):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
 05-15 21:43:56.995: E/AndroidRuntime(218):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
 05-15 21:43:56.995: E/AndroidRuntime(218):     at dalvik.system.NativeStart.main(Native Method)
 05-15 21:43:56.995: E/AndroidRuntime(218): Caused by: java.lang.IllegalStateException:
    Can't be used with a custom content view
 05-15 21:43:56.995: E/AndroidRuntime(218):     at android.support.v4.app.ListFragment.setListShown(ListFragment.java:282)
 05-15 21:43:56.995: E/AndroidRuntime(218):     at android.support.v4.app.ListFragment.setListShown(ListFragment.java:258)
 05-15 21:43:56.995: E/AndroidRuntime(218):     at org.anddev.android.ikiwi.ListFragmentActivity$myListFragments.onActivityCreated(ListFragmentActivity.java:57)
 05-15 21:43:56.995: E/AndroidRuntime(218):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:891)
 05-15 21:43:56.995: E/AndroidRuntime(218):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1080)
 05-15 21:43:56.995: E/AndroidRuntime(218):     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:622)
 05-15 21:43:56.995: E/AndroidRuntime(218):     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1416)
 05-15 21:43:56.995: E/AndroidRuntime(218):     at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:505)
 05-15 21:43:56.995: E/AndroidRuntime(218):     at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1129)
 05-15 21:43:56.995: E/AndroidRuntime(218):     at android.app.Activity.performStart(Activity.java:3723)
 05-15 21:43:56.995: E/AndroidRuntime(218):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2468)
 05-15 21:43:56.995: E/AndroidRuntime(218):     ... 11 more
 05-15 21:43:57.025: I/dalvikvm(218): threadid=7: reacting to signal 3
 05-15 21:43:57.025: E/dalvikvm(218): Unable to open stack trace file '/data/anr/traces.txt': Permission denied

Body:
A little bit late, but did not see this answer.

Inside Fragment:

    @Override
    public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
            final Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_list_activity,
                container, false);

        ListFragmentHelper.adaptView(view);

        return view;
    }

but bear in mind that in fragment_list_activity.xml you need to set  the IDs android:id="@id/loading",  android:id="@id/content" and android:id="@id/empty" for your views!


问:
Test if a class is serializable
What I need to do is having a unit test that checks whether a given class MyClass is serializable. But I can't only check that the class implements Serializable: all the attributes of the class (and the attributes of the attributes etc.) have to implement Serializable.

Also, a solution like creating an instance of MyClass and try to serialize and deserialize it is not satisfactory: if someone adds an attribute and does not update the unit test, the unit test won't test the new attribute.

One solution would probably be to use reflection recursively to test whether the classes of all the attributes implement Serializable, but that seems really heavy.

Isn't there a better solution?

Thanks.

答:
As a general check, you can use SerializationUtils from Apache Commons, as follows:

```<code>byte [] data = SerializationUtils.serialize(obj);
Object objNew = SerializationUtils.deserialize(data);
</code>```

but it does not guarantee that other instances of that class will serialize properly; for complex objects there is a risk that particular members will not be serializable depending on their members.

Title: Test if a class is serializable

Body:
As a general check, you can use SerializationUtils from Apache Commons, as follows:

byte [] data = SerializationUtils.serialize(obj);
Object objNew = SerializationUtils.deserialize(data);

but it does not guarantee that other instances of that class will serialize properly; for complex objects there is a risk that particular members will not be serializable depending on their members.


答:
grep will do

```<code>$ grep -o '\S*error_log\S*' file

/var/log/apache/error_log.%Y-%m
"/var/log/apache2/error_log"
</code>```

if you want to pull them up to the same line and get rid of the quotes pipe to

... | tr -d '"' | xargs

Title: how to use sed, awk to print only the path with specific word?

Body:
I have a text file looking like this:

ErrorLog "|/usr/local/apache2/bin/rotatelogs /var/log/apache/error_log.%Y-%m 200M"

ErrorLog "/var/log/apache2/error_log"

I need filter only the path with the word error_log.
I need the output as:

/var/log/apache2/error_log.%Y-%m

Or

/var/log/apache2/error_log

Body:
grep will do

$ grep -o '\S*error_log\S*' file

/var/log/apache/error_log.%Y-%m
"/var/log/apache2/error_log"

if you want to pull them up to the same line and get rid of the quotes pipe to

... | tr -d '"' | xargs


问:
How to convert Pandas DataFrame column from Pandas datetime64[ns] to Pyodbc SQL_Timestamp
I am trying to populate Pandas Dataframe into empty MS Access 2016 table via pyodbc. I get the following error message when I try to insert Dataframes into Access: pyodbc.dataerror: ('22008', [ODBC Microsoft Access Driver]Datetime field overflow.

Research showed that MS Access Date/Time datatypes correspond to ODBC SQL_TIMESTAMP datatypes.

I tried the following to convert datetime64[ns] to SQL_TIMESTAMP:

```<code>import datetime
cursor.execute("INSERT sql statement...VALUES(?)", datetime.datetime(order_date))
</code>```

However, I get this error: TypeError: an integer is required (got type Timestamp).

What do I need to do in order to successfully populate Pandas/Numpy's datetime64[ns] values into Access tables? Do I need to convert them into SQL_TIMESTAMP and how?

EDIT:
I tried running Gord Thompson's solution below and I am running into this error:

```<code>import datetime
</code>```

dt = dt64_to_datetime(dt_ns)

>> AttributeError:'datetime' has no attribute 'utcfromtimestamp'

What is the reason behind this error?  (Tested on pyodbc 4.0.17, Python 3.6.2, MS Access 2016)

答:
What do I need to do in order to successfully populate Pandas/Numpy's datetime64[ns] values into Access tables? Do I need to convert them into SQL_TIMESTAMP and how?

As illustrated in this excellent answer, you'll probably need to convert the numpy.datetime64 values to Python datetime values, perhaps like this:

def dt64_to_datetime(dt64):
    if np.isnat(dt64):
        return None
    else:
        unix_epoch = np.datetime64(0, 's')
        one_second = np.timedelta64(1, 's')
        seconds_since_epoch = (dt64 - unix_epoch) / one_second
        return datetime.utcfromtimestamp(seconds_since_epoch)
```

<p>Example usage:</p>

<pre class="lang-python prettyprint-override"><code>dt_ns = np.datetime64('2017-10-24 05:34:20.123456').astype('datetime64[ns]')
print(repr(dt_ns))  # numpy.datetime64('2017-10-24T05:34:20.123456000')
print(f'dt_ns.dtype: {dt_ns.dtype}')  # dt_ns.dtype: datetime64[ns]
dt = dt64_to_datetime(dt_ns)
print(repr(dt))  # datetime.datetime(2017, 10, 24, 5, 34, 20, 123456)

sql = "UPDATE tablename SET datetimefield = ? WHERE id=1"
params = (dt,)
crsr.execute(sql, params)
</code>```

(Tested with pyodbc 4.0.21 and Access 2010.)

Body:
I am trying to populate Pandas Dataframe into empty MS Access 2016 table via pyodbc. I get the following error message when I try to insert Dataframes into Access: pyodbc.dataerror: ('22008', [ODBC Microsoft Access Driver]Datetime field overflow.

Research showed that MS Access Date/Time datatypes correspond to ODBC SQL_TIMESTAMP datatypes.

I tried the following to convert datetime64[ns] to SQL_TIMESTAMP:

import datetime
cursor.execute("INSERT sql statement...VALUES(?)", datetime.datetime(order_date))

However, I get this error: TypeError: an integer is required (got type Timestamp).

What do I need to do in order to successfully populate Pandas/Numpy's datetime64[ns] values into Access tables? Do I need to convert them into SQL_TIMESTAMP and how?

EDIT:
I tried running Gord Thompson's solution below and I am running into this error:

import datetime

dt = dt64_to_datetime(dt_ns)

>> AttributeError:'datetime' has no attribute 'utcfromtimestamp'

What is the reason behind this error?  (Tested on pyodbc 4.0.17, Python 3.6.2, MS Access 2016)

Body:
What do I need to do in order to successfully populate Pandas/Numpy's datetime64[ns] values into Access tables? Do I need to convert them into SQL_TIMESTAMP and how?

As illustrated in this excellent answer, you'll probably need to convert the numpy.datetime64 values to Python datetime values, perhaps like this:

def dt64_to_datetime(dt64):
    if np.isnat(dt64):
        return None
    else:
        unix_epoch = np.datetime64(0, 's')
        one_second = np.timedelta64(1, 's')
        seconds_since_epoch = (dt64 - unix_epoch) / one_second
        return datetime.utcfromtimestamp(seconds_since_epoch)

Example usage:

dt_ns = np.datetime64('2017-10-24 05:34:20.123456').astype('datetime64[ns]')
print(repr(dt_ns))  # numpy.datetime64('2017-10-24T05:34:20.123456000')
print(f'dt_ns.dtype: {dt_ns.dtype}')  # dt_ns.dtype: datetime64[ns]
dt = dt64_to_datetime(dt_ns)
print(repr(dt))  # datetime.datetime(2017, 10, 24, 5, 34, 20, 123456)

sql = "UPDATE tablename SET datetimefield = ? WHERE id=1"
params = (dt,)
crsr.execute(sql, params)

(Tested with pyodbc 4.0.21 and Access 2010.)


问:
How to disable default box shadow /border-color in Google-chrome
The default border color for active input tags in Google chrome is yellow, how do i disable it?

How do i change the color in css?

答:
You can do it with two css properties: border or outline.

```<code>.bordered
{
  border:1px solid your_color !important;
}

or

.bordered
{
outline:1px green solid !important;
}
</code>```

This is because most of browsers has own css rules which you need to override saying to browser my rule is !important.

--Edit

You can also press Ctrl + Shift + I to display developer tools for Chrome and find css which makes problems.

ContentLicense: CC BY-SA 2.5

Body:
You can do it with two css properties: border or outline.

.bordered
{
  border:1px solid your_color !important;
}

or

.bordered
{
outline:1px green solid !important;
}

This is because most of browsers has own css rules which you need to override saying to browser my rule is !important.

--Edit

You can also press Ctrl + Shift + I to display developer tools for Chrome and find css which makes problems.


问:
Podio .NET View.Items always returns zero
Using the Podio.NET library (Podio.Async), I am trying to get a Podio View object using the ViewService.GetView() method. The Podio View object represents a predefined view, or set of filters, within a Podio Application.

One of the properties of the Podio View object (PodioAPI.Models.View) is the Items property, as in var noOfItems = myView.Items. However, this field always seems to return zero for me.

I guess that I can make a call to ItemService.FilterItemsByView() using the view-id, which in turn returns a PodioCollection<Item> object that has a FilteredItems property that can be used to get the number of items, but this would mean an additional call.

Does anyone have any thoughts or information that may help me?

Thanks for taking the time to read my question, and I hope that you can help, or others find this helpful.

Kaine

Example code

```<code>
    class Program
    {
        const string CLIENT_ID = "[Your Client Id]";
        const string CLIENT_SECRET = "[Your Client Secret]";
        const int APP_ID = [Your App Id];
        const string APP_TOKEN = "[Your App Token]";
        const string VIEW_NAME = "[Your View Id]";

        static void Main(string[] args)
        {
            Task.Run(async () => { await Go(); }).GetAwaiter().GetResult();
            Console.ReadKey();
        }

        static async Task Go()
        {
            var client = await GetClient();
            var views = await GetViews(client);
            var view = await GetView(client);
            var viewItems = await GetViewItems(client, view);
        }

        static async Task<View> GetView(Podio client)
        {
            var view = await client.ViewService.GetView(APP_ID, VIEW_NAME);
            Console.WriteLine("View Name: {0}, Id: {1}, Items: {2}",view.Name, view.ViewId, view.Items);
            return view;
        }

        static async Task<List<View>> GetViews(Podio client)
        {
            var views = await client.ViewService.GetViews(APP_ID);
            Console.WriteLine("Views: " + views.Count);
            foreach (var view in views)
            {
                Console.WriteLine(" - ({0}) {1}", view.ViewId, view.Name);
            }
            return views;
        }

        static async Task<List<Item>> GetViewItems(Podio client, View view)
        {
            Console.WriteLine("View Items: " + view.Items);   // This always return 0
            var itemList = new List<Item>();
            var itemsRemaining = true;
            var offset = 0;
            while (itemsRemaining)
            {
                var colItems = await client.ItemService.FilterItemsByView(appId: APP_ID, viewId: Int32.Parse(view.ViewId), offset: offset);
                Console.WriteLine(" Downloaded: {0} to {1}", offset, offset + colItems.Items.Count());
                itemList.AddRange(colItems.Items);
                offset += colItems.Items.Count();

                if (offset >= colItems.Filtered)
                {
                    itemsRemaining = false;
                    break;
                }
            }
            Console.WriteLine("Total View Items Downloaded: " + itemList.Count);
            return itemList;
        }

        static async Task<Podio> GetClient()
        {
            var client = new Podio(CLIENT_ID, CLIENT_SECRET);
            var auth = await client.AuthenticateWithApp(APP_ID, APP_TOKEN);
            Console.WriteLine("Auth expires in: " + auth.ExpiresIn);
            return client;
        }
    }
</code>```

答:
There are 2 similar methods:

Get Views: https://developers.podio.com/doc/views/get-views-27460

This method is returning items for each view returned

```<code>"items": The number of items matching the view
</code>```

Get View: https://developers.podio.com/doc/views/get-view-27450

This method is not returning items parameter, but you can still get that from groupings param (if there is any grouping). Otherwise - number of items in view is not returned.

```<code>"groupings": individual groups data, if grouping is present, otherwise {}
    {
      "total": total count of items in all groups,
      "groups": [{
        "count": items count of the single group,
</code>```

In case if there are no groupings you'll have to call https://developers.podio.com/doc/items/filter-items-by-view-4540284. And then use filtered response value.

```<code> "filtered": Total number of items matching the filter,
</code>```

If you only need number of filtered items - please add limit=1 parameter to your request.

Body:
Using the Podio.NET library (Podio.Async), I am trying to get a Podio View object using the ViewService.GetView() method. The Podio View object represents a predefined view, or set of filters, within a Podio Application.

One of the properties of the Podio View object (PodioAPI.Models.View) is the Items property, as in var noOfItems = myView.Items. However, this field always seems to return zero for me.

I guess that I can make a call to ItemService.FilterItemsByView() using the view-id, which in turn returns a PodioCollection<Item> object that has a FilteredItems property that can be used to get the number of items, but this would mean an additional call.

Does anyone have any thoughts or information that may help me?

Thanks for taking the time to read my question, and I hope that you can help, or others find this helpful.

Kaine

Example code

    class Program
    {
        const string CLIENT_ID = "[Your Client Id]";
        const string CLIENT_SECRET = "[Your Client Secret]";
        const int APP_ID = [Your App Id];
        const string APP_TOKEN = "[Your App Token]";
        const string VIEW_NAME = "[Your View Id]";

        static void Main(string[] args)
        {
            Task.Run(async () => { await Go(); }).GetAwaiter().GetResult();
            Console.ReadKey();
        }

        static async Task Go()
        {
            var client = await GetClient();
            var views = await GetViews(client);
            var view = await GetView(client);
            var viewItems = await GetViewItems(client, view);
        }

        static async Task<View> GetView(Podio client)
        {
            var view = await client.ViewService.GetView(APP_ID, VIEW_NAME);
            Console.WriteLine("View Name: {0}, Id: {1}, Items: {2}",view.Name, view.ViewId, view.Items);
            return view;
        }

        static async Task<List<View>> GetViews(Podio client)
        {
            var views = await client.ViewService.GetViews(APP_ID);
            Console.WriteLine("Views: " + views.Count);
            foreach (var view in views)
            {
                Console.WriteLine(" - ({0}) {1}", view.ViewId, view.Name);
            }
            return views;
        }

        static async Task<List<Item>> GetViewItems(Podio client, View view)
        {
            Console.WriteLine("View Items: " + view.Items);   // This always return 0
            var itemList = new List<Item>();
            var itemsRemaining = true;
            var offset = 0;
            while (itemsRemaining)
            {
                var colItems = await client.ItemService.FilterItemsByView(appId: APP_ID, viewId: Int32.Parse(view.ViewId), offset: offset);
                Console.WriteLine(" Downloaded: {0} to {1}", offset, offset + colItems.Items.Count());
                itemList.AddRange(colItems.Items);
                offset += colItems.Items.Count();

                if (offset >= colItems.Filtered)
                {
                    itemsRemaining = false;
                    break;
                }
            }
            Console.WriteLine("Total View Items Downloaded: " + itemList.Count);
            return itemList;
        }

        static async Task<Podio> GetClient()
        {
            var client = new Podio(CLIENT_ID, CLIENT_SECRET);
            var auth = await client.AuthenticateWithApp(APP_ID, APP_TOKEN);
            Console.WriteLine("Auth expires in: " + auth.ExpiresIn);
            return client;
        }
    }

Body:
There are 2 similar methods:

Get Views: https://developers.podio.com/doc/views/get-views-27460

This method is returning items for each view returned

"items": The number of items matching the view

Get View: https://developers.podio.com/doc/views/get-view-27450

This method is not returning items parameter, but you can still get that from groupings param (if there is any grouping). Otherwise - number of items in view is not returned.

"groupings": individual groups data, if grouping is present, otherwise {}
    {
      "total": total count of items in all groups,
      "groups": [{
        "count": items count of the single group,

In case if there are no groupings you'll have to call https://developers.podio.com/doc/items/filter-items-by-view-4540284. And then use filtered response value.

 "filtered": Total number of items matching the filter,

If you only need number of filtered items - please add limit=1 parameter to your request.


问:
HTML Different styles

Can anyone tell me what is the difference between the two styles of html code written below.

```<code>return '<div id='suggestionId' class="autocomplete-suggestion">No Message Found</div>';
</code>```

Vs

```<code>var autoCompleteSuggestion;
 autoCompleteSuggestion = $('<div/>').attr({id: 'suggestionId'}).addClass('suggestion').html('No Message Found');
return autoCompleteSuggestion;
</code>```

Results are same, the below mentioned script what kind of scripting is it called. Would like to know more

答:
First of all your first script wont work because you use

```<code> return '<div id='suggestionId' class="autocomplete-suggestion">No Message Found</div>'; //you should use id="suggestionId".
</code>```

The first code is a javascript code returns a string which contains tags and attributes of a div.

the second code is written in JQuery and returns a string built by JQuery functions.

The result (if there is no syntax error) will be the same.

Title: HTML Different styles

Body:
Can anyone tell me what is the difference between the two styles of html code written below.

return '
No Message Found
';

Vs

var autoCompleteSuggestion;
 autoCompleteSuggestion = $('
').attr({id: 'suggestionId'}).addClass('suggestion').html('No Message Found');
return autoCompleteSuggestion;

Results are same, the below mentioned script what kind of scripting is it called. Would like to know more

Body:
First of all your first script wont work because you use

 return '<div id='suggestionId' class="autocomplete-suggestion">No Message Found</div>'; //you should use id="suggestionId".

The first code is a javascript code returns a string which contains tags and attributes of a div.

the second code is written in JQuery and returns a string built by JQuery functions.

The result (if there is no syntax error) will be the same.


问:
User engagement with Screen-Off events with Beacons
We want to incorporate beacon technology in our apps to create user engagement with screen-off events.

In the present use case, we assume that the end-user will be in constant movement.

So far, we have tested two different approaches.

Kontakt SDK/Android Beacon Library in order to be constantly scanning for beacons. Using the UUID (assuming we are using Eddystone), we can associate it with a cached message that we have retrieved for our back-end. However this ends up eating a lot of battery.

Nearby Messages/Nearby Awareness this had potential, since it has a beacon dashboard to easily configure the attachments on each beacon and it has the "same" implementation on both iOS and Android. However, after reading the documentation and after numerous tests, we could not retrieve beacon attachments if we had the screen off. The only possible way was for the user to be still in front of the beacon for 3 minutes (depending on the smart-phone and energy settings) and it goes against our premise that the user is in constant movement, so the scan might be triggered when the user is not near the beacon.

Also: using Nearby Messages on iOS we had the desired behaviour: the app would discover the beacons when using the Nearby Messages if both the app and the API was configured for background usage.

Thus, we ask:

Is there a way to use Nearby API with screen-off events? Like constantly scheduling a scan?

What other alternatives do we have, that can be used cross-platform between iOS and Android? (so that we can try to assure a similar behaviour between platforms)

EDIT:
Upon further reading, we came to the conclusion that BLE beacon scanning causes minimal impact on the battery when used correctly (emphasis on the correctly, we will have to change the heuristics on our side), see : this.
The question then remains: why can't we have background scans in the nearby api without Nearby Messages own notifications, so that we can assert that the user passed near a beacon? What intrigued us is that this works just fine on iOS...

答:
The Nearby API scans on a schedule of its choosing, including screen on events.  You do not have the flexibility of customizing Nearby scanning rules for your app, as it is designed to be a service that runs for all apps on the phone.  When using Nearby, you must accept this limitation.

The Android Beacon Library is open source and allows flexible configurations of when you scan.  If you find your configuration uses too much battery for your use case you can adjust this.  The default settings have been designed for a good tradeoff between power usage and quick detection, so these are recommended.  If you find the default settings don't work for you there are many different ways you can set it up.  The simplest way is by adjusting its scanPeriod and betweenScanPeriod for the background.  But there are many other ways to customize its scanning behavior.

You should note, however, that a "constantly scheduling a scan" (as mentioned in your question) will use up a lot of power if in low latency mode.  The Android Beacon library default is to do a constant scan in low power mode, when the app is in the background and no beacons are around.   On most devices, this yields detections within 5 seconds and reasonable power usage similar to cell standby.

It's hard to offer more suggestions without knowing the configuration you used with the Android Beacon Library, the test conditions in place, and how much power consumption was witnessed. If you can provide this information, I might be able to help more.

Full disclosure:  I am the lead developer on the Android Beacon Library open source project.


问:
Setting up a personal (Java) workspace: What do I need?
I want to set up a personal workspace on my home machine. I mainly intend to use it for Java development on home projects. Which tools do you recommend me to use? (I prefer free tools, since this is just for home use.)

I hope you could recommend some tools for me, and I'd be grateful if you could give me a brief comparison of some tools in each category. For example, I'm thinking about source control and issue tracking tools, but any other categories are welcome.

I also hope to get some information about the ability to move between suggested tools (e.g. migrate between CVS and SVN), and even between operating systems if applicable. (I'm currently using Windows Vista, but I may want to switch to Linux sometime soon.) Maybe even information about how easy it would be to move the project to an open-source repository (e.g. SF.net).

Thank you.

(P.S. Any comments on how to enhance/clarify my question are more than welcome.)

答:
In the free tools space, Eclipse and NetBeans are the primary IDE contenders. IDEA is also available for free for open source developement and a lot of people swear by it. Depending on your background, you may find NetBeans more intuitive than Eclipse. Eclipse has a certain way of looking at the world that is a little different than a lot of other IDEs, especially if you're coming from a Visual Studio background. All three have good built-in support for CVS and SVN as well as integrated debuggers.

I personally like Eclipse. I find it much more responsive and more powerful than NetBeans. NetBeans has made a lot of progress over the last few years though.

If you're going to be doing Swing development, I would say that the GUI editor in NetBeans is better than anything available in Eclipse. In the area of web service development I've also had a lot more success with NetBeans. For straight Java code, I still prefer Eclipse though.

The question of moving between source control systems is a separate issue from development environment, in my opinion. Move the code then check a fresh copy out from the new server.

OwnerDisplayName: Hosam Aly

OwnerDisplayName: Dave Ray


问:
Importing Newtype(s) from another module
I'm learning PureScript lately and did a small application that draws a cube on the screen. All is well and I had a few newtypes defined in the top of the Main module as follows:

```<code>newtype Vec2 = Vec2
    {
        x :: Number
    ,   y :: Number
    }

newtype Vec3 = Vec3
    {
        x :: Number
    ,   y :: Number
    ,   z :: Number
    }
</code>```

I also got some functions that does transformations such as perspectiveDivide etc., that I want to move to another module Transforms just to organize better. So I moved these types to the Transforms module, and exported them.

```<code>module Transforms (Vec2, Vec3, perspectiveDivide) where
</code>```

and the above types follows this.

Now I tried to import these in the main module with the selective import feature, but it didn't work.

```<code>import Transforms (Vec2, Vec3, perspectiveDivide)
</code>```

but it still gave me an error when trying to use a function projectToScreen which was still in the main module. The error is like this:

in module Main   at src/Main.purs line 30, column 10 - line 30, column
  18

```<code>Unknown data constructor Vec3
</code>```

See
  https://github.com/purescript/documentation/blob/master/errors/UnknownName.md
  for more information,   or to contribute content related to this
  error.

I'm both new to functional programming and also PureScript. What does this error mean?

答:
module Transforms (Vec2, Vec3, perspectiveDivide) where only exports the type constructors.

You want to use Vec2(..) to export the data constructors as well. The same syntax works for the imports.

Body:
I'm learning PureScript lately and did a small application that draws a cube on the screen. All is well and I had a few newtypes defined in the top of the Main module as follows:

newtype Vec2 = Vec2
    {
        x :: Number
    ,   y :: Number
    }

newtype Vec3 = Vec3
    {
        x :: Number
    ,   y :: Number
    ,   z :: Number
    }

I also got some functions that does transformations such as perspectiveDivide etc., that I want to move to another module Transforms just to organize better. So I moved these types to the Transforms module, and exported them.

module Transforms (Vec2, Vec3, perspectiveDivide) where

and the above types follows this.

Now I tried to import these in the main module with the selective import feature, but it didn't work.

import Transforms (Vec2, Vec3, perspectiveDivide)

but it still gave me an error when trying to use a function projectToScreen which was still in the main module. The error is like this:

in module Main   at src/Main.purs line 30, column 10 - line 30, column
  18

Unknown data constructor Vec3

See
  https://github.com/purescript/documentation/blob/master/errors/UnknownName.md
  for more information,   or to contribute content related to this
  error.

I'm both new to functional programming and also PureScript. What does this error mean?