答:
When I do web applications I love to use bootstrap. It gives me a bunch of css classes out of the box that help me create a responsive frontend that will do what I need it to on any screen size. Long story short, I would use media queries, the bootstrap layout grid, or a combination of both.

There are many tutorials on youtube. This guy shows how the basics work for the bootstrap layout grid. https://youtu.be/GDwWmrpCa30

Media queries are useful when you need your UI to do something different based on the current device screen size. This can be used without the need for bootstrap, but can also be used with bootstrap to make really responsive apps. There are also countless tutorials on youtube for that also, but here is a good one to check out. https://youtu.be/2KL-z9A56SQ

Media Query Example:

```<code>@media only screen
and (*Your threshold criteria goes here* EXAMPLE:  max-width : 1000px) {
  //css goes here with whatever css you want to fire at this threshold
}
</code>```

Let me know if I can be of further assistance. Good luck.

Title: Text is Hidden When Window Resizes

Body:
I'm building a website for class, based on a provided template, and I'm struggling to make it so that my text will move as the window gets resized (right now, resizing the window obscures the text and associated buttons).

Ideally, I'd like for the page to be anchored in such a way that the focus remains on the text/buttons - and by extension, the bottom right corner of the image - as the window is resized.

Here is my HTML:

<!DOCTYPE html>

        <meta name="viewport" content="width=device-width, inital-scale=1.0">

        <link rel="stylesheet", type="text/css", href="Vendors/css/normalize.css">
        <link rel="stylesheet", type="text/css", href="Vendors/css/grid.css">
        <link rel="stylesheet", type="text/css", href="Vendors/css/ionicons.min.css">
        <link rel="stylesheet", type="text/css", href="Resources/css/style.css">
        <link rel="stylesheet", type="text/css", href="Resources/css/queries.css">
        <link href='http://fonts.googleapis.com/css?family=Lato:100,300,400,300italic' rel='stylesheet' type='text/css'>

        <title>Whitetail Acres Tree Farm</title>

Food Delivery

How it Works

Our Cities

Sign up

Schedule
 Your Visit!

                I'm hungry
                Show me more

And here is my CSS:

/* Universal Reset*/
*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

html
{
    background-color: #ffffff;
    color: #555;
    font-family: 'Lato', 'Arial', sans-serif;
    font-size: 20px;
    font-weight: 300;
    text-rendering: optimizeLegibility;
}

.clearfix {zoom: 1}
.clearfix:after {
    content: '.';
    clear: both;
    display: block;
    height: 0;
    visibility: hidden;
}

header{
    background-image: url(img/hero.jpg);
    background-size: cover;
    background-position:bottom, right;
    height: 100vh;
    background-attachment:inherit;
}

.hero-text-box{
    position: absolute;
    width:1080px;
    top:80%;
    left:55%;
    text-align: right;
    transform: translate(-50%, -50%);
}

.row{
    max-width: 1140px;
    margin:0 auto;
}

section{
    padding: 80px 0;
}

.box{

    padding: 1%;

Body:
When I do web applications I love to use bootstrap. It gives me a bunch of css classes out of the box that help me create a responsive frontend that will do what I need it to on any screen size. Long story short, I would use media queries, the bootstrap layout grid, or a combination of both.

There are many tutorials on youtube. This guy shows how the basics work for the bootstrap layout grid. https://youtu.be/GDwWmrpCa30

Media queries are useful when you need your UI to do something different based on the current device screen size. This can be used without the need for bootstrap, but can also be used with bootstrap to make really responsive apps. There are also countless tutorials on youtube for that also, but here is a good one to check out. https://youtu.be/2KL-z9A56SQ

Media Query Example:

@media only screen
and (*Your threshold criteria goes here* EXAMPLE:  max-width : 1000px) {
  //css goes here with whatever css you want to fire at this threshold
}

Let me know if I can be of further assistance. Good luck.


来源: stackexchange

问:
How can I check if an object is of a certain type at runtime in C#?
How can I check if an object is of a certain type at runtime in C#?</p>

答:
you can also use switch/case in c# 7 (pattern matching).

```<code>string DoubleMe(Object o)
{
    switch (o)
    {
        case String s:
            return s + s;
        case Int32 i:
            return (i + i).ToString();
        default:
            return "type which cannot double.";
    }
}

void Main()
{
    var s= "Abc";
    var i= 123;
    var now = DateTime.Now;

    DoubleMe(s).Dump();
    DoubleMe(i).Dump();
    DoubleMe(now).Dump();
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
you can also use switch/case in c# 7 (pattern matching).

string DoubleMe(Object o)
{
    switch (o)
    {
        case String s:
            return s + s;
        case Int32 i:
            return (i + i).ToString();
        default:
            return "type which cannot double.";
    }
}

void Main()
{
    var s= "Abc";
    var i= 123;
    var now = DateTime.Now;

    DoubleMe(s).Dump();
    DoubleMe(i).Dump();
    DoubleMe(now).Dump();
}


问:
Python elegant assignment based on True/False values
I have a variable I want to set depending on the values in three booleans. The most straight-forward way is an if statement followed by a series of elifs:

```<code>if a and b and c:
    name = 'first'
elif a and b and not c:
    name = 'second'
elif a and not b and c:
    name = 'third'
elif a and not b and not c:
    name = 'fourth'
elif not a and b and c:
    name = 'fifth'
elif not a and b and not c:
    name = 'sixth'
elif not a and not b and c:
    name = 'seventh'
elif not a and not b and not c:
    name = 'eighth'
</code>```

This is a bit awkward, and I'm wondering if there's a more Pythonic way to handle this problem. A couple of ideas come to mind.

Dictionary hack:

```<code>name = {a and b and c: 'first',
        a and b and not c: 'second',
        a and not b and c: 'third',
        a and not b and not c: 'fourth',
        not a and b and c: 'fifth',
        not a and b and not c: 'sixth',
        not a and not b and c: 'seventh',
        not a and not b and not c: 'eighth'}[True]
</code>```

I call it a hack because I'm not too wild about seven of the keys being False and overriding each other.

And/or magic

```<code>name = (a and b and c and 'first' or
        a and b and not c and 'second' or
        a and not b and c and 'third' or
        a and not b and not c and 'fourth' or
        not a and b and c and 'fifth' or
        not a and b and not c and 'sixth' or
        not a and not b and c and 'seventh' or
        not a and not b and not c and 'eighth')
</code>```

This works because Python ands and ors return the last value to be evaluated, but you have to know that in order to understand this otherwise bizarre code.

None of these three options is very satisfying. What do you recommend?

答:
What about nested ifs - it means you don't have to check everything several times and reads clearer to me (although maybe not quite as clever as some of the other answers):</p>

```<code>if a:
    if b:
        if c:
            name="first"
        else:
            name="second"
    else:
        if c:
            name="third"
        else:
            name="fourth"
else:
    if b:
        if c:
            name="fifth"
        else:
            name="sixth"
    else:
        if c:
            name="seventh"
        else:
            name="eighth"
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a variable I want to set depending on the values in three booleans. The most straight-forward way is an if statement followed by a series of elifs:

if a and b and c:
    name = 'first'
elif a and b and not c:
    name = 'second'
elif a and not b and c:
    name = 'third'
elif a and not b and not c:
    name = 'fourth'
elif not a and b and c:
    name = 'fifth'
elif not a and b and not c:
    name = 'sixth'
elif not a and not b and c:
    name = 'seventh'
elif not a and not b and not c:
    name = 'eighth'

This is a bit awkward, and I'm wondering if there's a more Pythonic way to handle this problem. A couple of ideas come to mind.

Dictionary hack:

name = {a and b and c: 'first',
        a and b and not c: 'second',
        a and not b and c: 'third',
        a and not b and not c: 'fourth',
        not a and b and c: 'fifth',
        not a and b and not c: 'sixth',
        not a and not b and c: 'seventh',
        not a and not b and not c: 'eighth'}[True]

I call it a hack because I'm not too wild about seven of the keys being False and overriding each other.

And/or magic

name = (a and b and c and 'first' or
        a and b and not c and 'second' or
        a and not b and c and 'third' or
        a and not b and not c and 'fourth' or
        not a and b and c and 'fifth' or
        not a and b and not c and 'sixth' or
        not a and not b and c and 'seventh' or
        not a and not b and not c and 'eighth')

This works because Python ands and ors return the last value to be evaluated, but you have to know that in order to understand this otherwise bizarre code.

None of these three options is very satisfying. What do you recommend?

Body:
What about nested ifs - it means you don't have to check everything several times and reads clearer to me (although maybe not quite as clever as some of the other answers):

if a:
    if b:
        if c:
            name="first"
        else:
            name="second"
    else:
        if c:
            name="third"
        else:
            name="fourth"
else:
    if b:
        if c:
            name="fifth"
        else:
            name="sixth"
    else:
        if c:
            name="seventh"
        else:
            name="eighth"


问:
Issues with Grade Build
Everytime I try to create a new Activity, i get this error:

```<code>Error:(28, 13)Failed to resolve: com.google.maps.android:android-maps-utils:0.5.+
</code>```

Any possible solutions?

答:
Just remove the .+ at the end of this line:

```<code>compile 'com.google.maps.android:android-maps-utils:0.5.+'
</code>```

to

```<code>compile 'com.google.maps.android:android-maps-utils:0.5'
</code>```

Title: Issues with Grade Build

Body:
Everytime I try to create a new Activity, i get this error:

Error:(28, 13)Failed to resolve: com.google.maps.android:android-maps-utils:0.5.+

Any possible solutions?

Body:
Just remove the .+ at the end of this line:

compile 'com.google.maps.android:android-maps-utils:0.5.+'

to

compile 'com.google.maps.android:android-maps-utils:0.5'


问:
`as.complex(-1)^(1/3)` gives positive real part
I am having a problem with R.

```<code>> as.complex(-1)^(1/3)
[1] 0.5+0.8660254i
</code>```

This is certainly wrong as the real part is positive. Can anyone tell me the cause and solution?

N.B. A similar thing happens when I use polyroot(c(1,0,0,1)).

答:
I suspect that R computes z^a as exp(a * log(z)).

The value exp(z) is uniquely defined for any z, but there are many possible values to choose for log(z). I suspect that for a complex number z = r * exp(i * theta) with -pi < theta <= pi and r a positive real, R sets log(z) = log(r) + 1i * theta.

This gives (-1)^(1/3) = exp((1/3) * log(-1)) = exp(pi * 1i / 3) = 0.5+0.8660254i.

If R chose a different value for the logarithm, for example if it set log(-1) = 3 * pi * 1i, then you would get instead

```<code>(-1)^(1/3) = exp(3 * pi * 1i / 3) = -1,
</code>```

the answer you expected. Why doesn't R give you this value? Because then for the sake of consistency, log(e^(theta * 1i)) would have to be defined as 1i * theta + 2 * pi * 1i for -pi < theta <= pi.

Body:
I am having a problem with R.

> as.complex(-1)^(1/3)
[1] 0.5+0.8660254i

This is certainly wrong as the real part is positive. Can anyone tell me the cause and solution?

N.B. A similar thing happens when I use polyroot(c(1,0,0,1)).

Body:
I suspect that R computes z^a as exp(a * log(z)).

The value exp(z) is uniquely defined for any z, but there are many possible values to choose for log(z). I suspect that for a complex number z = r * exp(i * theta) with -pi < theta <= pi and r a positive real, R sets log(z) = log(r) + 1i * theta.

This gives (-1)^(1/3) = exp((1/3) * log(-1)) = exp(pi * 1i / 3) = 0.5+0.8660254i.

If R chose a different value for the logarithm, for example if it set log(-1) = 3 * pi * 1i, then you would get instead

(-1)^(1/3) = exp(3 * pi * 1i / 3) = -1,

the answer you expected. Why doesn't R give you this value? Because then for the sake of consistency, log(e^(theta * 1i)) would have to be defined as 1i * theta + 2 * pi * 1i for -pi < theta <= pi.


问:
SQL Server 2016 T-SQL convert comma string to inner join database name(s)
I have a value for one of my columns that looks like this:

```<code>ID   | userPerms | Name      | DOB
-----+-----------+-----------+----------
5985 |1,3,4      |Bob Barker |12/12/1923
895  |1,2        |Bill Gates |10/14/1955
5897 |1,2,4      |Steve Jobs |02/24/1955
</code>```

That column being the userPerms column.

I need to be able to Inner Join with the userPerm table associated with those numbers.

My query is currently:

```<code>SELECT
    uT.employeeID + '|' + uT.lastFirstMiddle + '|' + uT.ntName + '|' + uT.email + '|' +
    uT.firstName  + '|' + uT.lastName        + '|' + uT.active + '|' + uT.userPerms + '|' +
    uT.userPermPages
FROM
    usersTbl AS uT
INNER JOIN
    usersPermissions AS uP ON uP.id = uT.userPerms
WHERE
    uT.id = 1
</code>```

Naturally it won't work since the data has commas in it.

So what I am looking for in the output:

```<code>ID   | userPerms        | Name      | DOB
-----+------------------+-----------+------------
5985 |Read,Upload,Admin |Bob Barker |12/12/1923
895  |Read,Write        |Bill Gates |10/14/1955
5897 |Read,Write,Admin  |Steve Jobs |02/24/1955
</code>```

Does anyone know how to split these out so that the inner join would then work as designed?

UPDATE 1

I got it working but:

It does not combine the userPerms into the original string

```<code>SELECT
    uT.employeeID + '|' + uT.lastFirstMiddle + '|' + uT.ntName + '|' +
    uT.email + '|' + uT.firstName + '|' + uT.lastName + '|' + uT.active,
    (
        SELECT
            ',' + uP.type
        FROM
            usersPermissions AS uP
        WHERE
            ',' + uT.userPerms + ','
        LIKE
            '%,' + cast(uP.id AS nvarchar(20)) + ',%'
        FOR
            XML PATH(''), TYPE
    ).value('substring(text()[1], 2)', 'varchar(max)') AS userPerms,
    (
        SELECT
            ',' + uP.name
        FROM
            pagePermissions AS uP
        WHERE
            ',' + uT.userPerms + ','
        LIKE
            '%,' + cast(uP.id AS nvarchar(20)) + ',%'
        FOR
            XML PATH(''), TYPE
    ).value('substring(text()[1], 2)', 'varchar(max)') AS userPermPages
FROM
    usersTbl as uT
WHERE
    uT.id = '1';
</code>```

答:
Not great DB Design to a list of IDs like that.  It's better to use a relation table to store the many to many relationship.  That said, this might work:

```<code>SELECT
    uT.employeeID + '|' + uT.lastFirstMiddle + '|' + uT.ntName + '|' + uT.email + '|' +
    uT.firstName  + '|' + uT.lastName        + '|' + uT.active + '|' + uT.userPerms + '|' +
    uT.userPermPages
FROM
    usersTbl AS uT
INNER JOIN
    usersPermissions AS uP
    ON ','+uT.userPerms+',' like '%,'+uP.id+',%'
WHERE
    uT.id = 1
</code>```

The idea is to add commas to the beginning and end of uT.userPerms and use the like operator to join to any occurance of uP.id (also surrounded with commas) in uT.userPerms.

Body:
I have a value for one of my columns that looks like this:

ID   | userPerms | Name      | DOB
-----+-----------+-----------+----------
5985 |1,3,4      |Bob Barker |12/12/1923
895  |1,2        |Bill Gates |10/14/1955
5897 |1,2,4      |Steve Jobs |02/24/1955

That column being the userPerms column.

I need to be able to Inner Join with the userPerm table associated with those numbers.

My query is currently:

SELECT
    uT.employeeID + '|' + uT.lastFirstMiddle + '|' + uT.ntName + '|' + uT.email + '|' +
    uT.firstName  + '|' + uT.lastName        + '|' + uT.active + '|' + uT.userPerms + '|' +
    uT.userPermPages
FROM
    usersTbl AS uT
INNER JOIN
    usersPermissions AS uP ON uP.id = uT.userPerms
WHERE
    uT.id = 1

Naturally it won't work since the data has commas in it.

So what I am looking for in the output:

ID   | userPerms        | Name      | DOB
-----+------------------+-----------+------------
5985 |Read,Upload,Admin |Bob Barker |12/12/1923
895  |Read,Write        |Bill Gates |10/14/1955
5897 |Read,Write,Admin  |Steve Jobs |02/24/1955

Does anyone know how to split these out so that the inner join would then work as designed?

UPDATE 1

I got it working but:

It does not combine the userPerms into the original string

SELECT
    uT.employeeID + '|' + uT.lastFirstMiddle + '|' + uT.ntName + '|' +
    uT.email + '|' + uT.firstName + '|' + uT.lastName + '|' + uT.active,
    (
        SELECT
            ',' + uP.type
        FROM
            usersPermissions AS uP
        WHERE
            ',' + uT.userPerms + ','
        LIKE
            '%,' + cast(uP.id AS nvarchar(20)) + ',%'
        FOR
            XML PATH(''), TYPE
    ).value('substring(text()[1], 2)', 'varchar(max)') AS userPerms,
    (
        SELECT
            ',' + uP.name
        FROM
            pagePermissions AS uP
        WHERE
            ',' + uT.userPerms + ','
        LIKE
            '%,' + cast(uP.id AS nvarchar(20)) + ',%'
        FOR
            XML PATH(''), TYPE
    ).value('substring(text()[1], 2)', 'varchar(max)') AS userPermPages
FROM
    usersTbl as uT
WHERE
    uT.id = '1';

Body:
Not great DB Design to a list of IDs like that.  It's better to use a relation table to store the many to many relationship.  That said, this might work:

SELECT
    uT.employeeID + '|' + uT.lastFirstMiddle + '|' + uT.ntName + '|' + uT.email + '|' +
    uT.firstName  + '|' + uT.lastName        + '|' + uT.active + '|' + uT.userPerms + '|' +
    uT.userPermPages
FROM
    usersTbl AS uT
INNER JOIN
    usersPermissions AS uP
    ON ','+uT.userPerms+',' like '%,'+uP.id+',%'
WHERE
    uT.id = 1

The idea is to add commas to the beginning and end of uT.userPerms and use the like operator to join to any occurance of uP.id (also surrounded with commas) in uT.userPerms.


问:
Array of objects as property
I know how to initialise an array of objects:

```<code>arrayOfA(3,2) = ClassA();

for i = 1:3
    for j = 1:2
        arrayofA(i,j) = ClassA(...);
    end
end
</code>```

but when I try this for a property:

```<code>classdef ClassB

properties
    arrayOfA;
    ...
end

methods
    %% Constructor
    function b = ClassB(...)
        b.arrayOfA(3,2) = ClassA();  % Error!
        ...
    end
end
</code>```

I get the exception Conversion to double from ClassA is not possible.

I have read that when a default value for a property is not provided, it is initialised to an empty array of doubles. This explains the exception, but how do I set the default value of arrayOfA such that I can fill it with objects?

I have tried:

```<code>properties
    arrayOfA(3,2) = ClassA;
</code>```

but this gives the exception Unbalanced or unexpected parenthesis or bracket.

Edit: I am using MATLAB R2015b, which turns out to affect the solution - see below.

答:
Starting in version R2016a, you can restrict the property type like so:

```<code>classdef ClassB
properties
  arrayOfA ClassA
  ...
end
methods
  % Constructor
  function b = ClassB(...)
    b.arrayOfA(3, 2) = ClassA();
    ...
  end
end
</code>```

Note there's no = sign. This will require that values assigned to this property must be of class ClassA, of any size.

Starting in version R2017a, you can also restrict the size as per the documentation here:

```<code>classdef ClassB
properties
  arrayOfA(3, 2) ClassA
  ...
end
...
</code>```

Title: Array of objects as property

Body:
I know how to initialise an array of objects:

arrayOfA(3,2) = ClassA();

for i = 1:3
    for j = 1:2
        arrayofA(i,j) = ClassA(...);
    end
end

but when I try this for a property:

classdef ClassB

properties
    arrayOfA;
    ...
end

methods
    %% Constructor
    function b = ClassB(...)
        b.arrayOfA(3,2) = ClassA();  % Error!
        ...
    end
end

I get the exception Conversion to double from ClassA is not possible.

I have read that when a default value for a property is not provided, it is initialised to an empty array of doubles. This explains the exception, but how do I set the default value of arrayOfA such that I can fill it with objects?

I have tried:

properties
    arrayOfA(3,2) = ClassA;

but this gives the exception Unbalanced or unexpected parenthesis or bracket.

Edit: I am using MATLAB R2015b, which turns out to affect the solution - see below.

Body:
Starting in version R2016a, you can restrict the property type like so:

classdef ClassB
properties
  arrayOfA ClassA
  ...
end
methods
  % Constructor
  function b = ClassB(...)
    b.arrayOfA(3, 2) = ClassA();
    ...
  end
end

Note there's no = sign. This will require that values assigned to this property must be of class ClassA, of any size.

Starting in version R2017a, you can also restrict the size as per the documentation here:

classdef ClassB
properties
  arrayOfA(3, 2) ClassA
  ...
end
...


问:
parsing a cv file
I want to write a code either in Java or PHP (Codeigniter) to extract information such as email and phone number of a user uploading hbis resume or cv to the site. Basically I want to build a cv parser.

Need help for this.

thanks

EDIT
The cv format will be in doc.

答:
Ditto AlexR. If ALL you want to find is email address and phone number, you could scan for strings of characters in the appropriate format. A couple of simple regular expressions could do that fairly reliably. Even that wouldn't be 100%. If someone included, "Learned Java@Technocorp. US citizen." etc, you might easily be fooled into thinking that's an email address of "java@technocorp.us". Okay, that's a strained example, but it's the sort of thing that shoots down natural language parsing.

If you want more than that, there is no easy answer. You could search for keywords, like to find where he went to school you could look for the words "college" or "university". But even then, someone might put "Graduate of Foobar College" or "College: Foobar" or "BA from Foobar" or many many other possible formats.

Title: parsing a cv file


问:
Move navigation drawer icon (hamburger)
I need to move navigation drawer icon (hamburger) from action bar to tab layout to make it look like provided for example. That should be performed on list scroll. Is there any possibility to move views from action bar to tab layout?

Action bar

Expected result

答:
You can include a tabLayout in a toolbar like this:</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="pin"
            android:background="@color/colorPrimary"
            android:layout_weight="1">
            <android.support.design.widget.TabLayout
                android:id="@+id/tabs"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_gravity="top"
                app:tabIndicatorColor="@color/colorAccent"
                app:tabMaxWidth="0dp"
                app:tabGravity="fill"
                app:tabMode="scrollable"
                android:background="@color/colorPrimary" />
        </android.support.v7.widget.Toolbar>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</android.support.design.widget.CoordinatorLayout>
</code>```

Title: Move navigation drawer icon (hamburger)

Body:
You can include a tabLayout in a toolbar like this:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="pin"
            android:background="@color/colorPrimary"
            android:layout_weight="1">
            <android.support.design.widget.TabLayout
                android:id="@+id/tabs"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_gravity="top"
                app:tabIndicatorColor="@color/colorAccent"
                app:tabMaxWidth="0dp"
                app:tabGravity="fill"
                app:tabMode="scrollable"
                android:background="@color/colorPrimary" />
        </android.support.v7.widget.Toolbar>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</android.support.design.widget.CoordinatorLayout>


问:
Video overlay issue
I'd like to create a video overlay. It works great in Chrome with https://stackoverflow.com/a/30310041/8254123, but has some issues in Safari. When I add controls to the video tag and want to pause the video, Safari returns this error:

Unhandled Promise Rejection: [object DOMError]

If I remove the controls attribute it works, but I need controls and don't want to add custom controls.

jQuery('.video_home_1').click(function() {
  if (jQuery(this).children("video").get(0).paused) {
    jQuery(this).children("video").get(0).play();
    jQuery(this).find(".playpause").fadeOut();
    jQuery(this).find(".home_video_overlay").fadeOut();
  } else {
    jQuery(this).children("video").get(0).pause();
    jQuery(this).find(".playpause").fadeIn();
    jQuery(this).find(".home_video_overlay").fadeIn();
    jQuery(this).children(".home_video_overlay").css('background', 'transparent');
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.video_home_1 {
  display: table;
  width: auto;
  position: relative;
  width: auto;
  height: 425px;
}

.video_home_1 .playpause {
  background: url(https://www.squaresigns.com/wp-content/uploads/2017/11/play.png) 58% 50% no-repeat;
  background-repeat: no-repeat;
  width: 100px;
  height: 100px;
  position: absolute;
  left: 0%;
  right: 0%;
  background-size: 64px 64px;
  top: 0%;
  bottom: 0%;
  z-index: 100;
  margin: auto;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, .3);
}

.video_home_1 .home_video_overlay {
  position: absolute;
  z-index: 2;
  top: 0;
  left: 0;
  width: 100%;
  height: 425px;
  background-repeat: no-repeat;
  background-position: center;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  background-size: cover;
  cursor: pointer;
}

.video_home_1 video {
  height: 425px;
  width: auto;
  padding-right: 4px;
}</code>```

  <video controls>
    <source type="video/mp4" src="https://www.squaresigns.com/wp-content/uploads/2017/11/SquareSigns.mp4">
    <source type="video/webm" src="https://www.squaresigns.com/wp-content/uploads/2017/11/SquareSigns.webm">
  </video>

```

答:
You may need to set controls="true" as in this answer.

```<code><div class="video_home_1">
  <video controls="true">
    <source type="video/mp4" src="https://www.squaresigns.com/wp-content/uploads/2017/11/SquareSigns.mp4">
    <source type="video/webm" src="https://www.squaresigns.com/wp-content/uploads/2017/11/SquareSigns.webm">
  </video>
  <div class="home_video_overlay" style="background-image: url('https://www.squaresigns.com/wp-content/uploads/2017/11/cover.png');">
    <div class="playpause"></div>
  </div>
</div>
</code>```

Title: Video overlay issue

Body:
I'd like to create a video overlay. It works great in Chrome with https://stackoverflow.com/a/30310041/8254123, but has some issues in Safari. When I add controls to the video tag and want to pause the video, Safari returns this error:

Unhandled Promise Rejection: [object DOMError]

If I remove the controls attribute it works, but I need controls and don't want to add custom controls.

jQuery('.video_home_1').click(function() {
  if (jQuery(this).children("video").get(0).paused) {
    jQuery(this).children("video").get(0).play();
    jQuery(this).find(".playpause").fadeOut();
    jQuery(this).find(".home_video_overlay").fadeOut();
  } else {
    jQuery(this).children("video").get(0).pause();
    jQuery(this).find(".playpause").fadeIn();
    jQuery(this).find(".home_video_overlay").fadeIn();
    jQuery(this).children(".home_video_overlay").css('background', 'transparent');
  }
});

.video_home_1 {
  display: table;
  width: auto;
  position: relative;
  width: auto;
  height: 425px;
}

.video_home_1 .playpause {
  background: url(https://www.squaresigns.com/wp-content/uploads/2017/11/play.png) 58% 50% no-repeat;
  background-repeat: no-repeat;
  width: 100px;
  height: 100px;
  position: absolute;
  left: 0%;
  right: 0%;
  background-size: 64px 64px;
  top: 0%;
  bottom: 0%;
  z-index: 100;
  margin: auto;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, .3);
}

.video_home_1 .home_video_overlay {
  position: absolute;
  z-index: 2;
  top: 0;
  left: 0;
  width: 100%;
  height: 425px;
  background-repeat: no-repeat;
  background-position: center;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  background-size: cover;
  cursor: pointer;
}

.video_home_1 video {
  height: 425px;
  width: auto;
  padding-right: 4px;
}

  <video controls>
    <source type="video/mp4" src="https://www.squaresigns.com/wp-content/uploads/2017/11/SquareSigns.mp4">
    <source type="video/webm" src="https://www.squaresigns.com/wp-content/uploads/2017/11/SquareSigns.webm">
  </video>

Body:
You may need to set controls="true" as in this answer.

<div class="video_home_1">
  <video controls="true">
    <source type="video/mp4" src="https://www.squaresigns.com/wp-content/uploads/2017/11/SquareSigns.mp4">
    <source type="video/webm" src="https://www.squaresigns.com/wp-content/uploads/2017/11/SquareSigns.webm">
  </video>
  <div class="home_video_overlay" style="background-image: url('https://www.squaresigns.com/wp-content/uploads/2017/11/cover.png');">
    <div class="playpause"></div>
  </div>
</div>


问:
Setting a property value by reflection from DataGridView value
I've a DataGridView, and I want to change collection who connect to this list when cell value has been changed, using CellEndEdit event:

```<code>var p = wareList[e.RowIndex].GetType().GetProperties()[e.ColumnIndex];

object value = dataGreadView[e.ColumnIndex, e.RowIndex].Value;

p.SetValue(typeof(Ware), Convert.ChangeType(value, p.PropertyType));
</code>```

But at the last line I got exeption System.Reflection.TargetException: "The object does not match the end type."

答:
SetValue() takes the object to set the value on.

Your property is not defined on System.Type, so passing a System.Type gives an error.

You need to pass an object that actually has your property.

Body:
I've a DataGridView, and I want to change collection who connect to this list when cell value has been changed, using CellEndEdit event:

var p = wareList[e.RowIndex].GetType().GetProperties()[e.ColumnIndex];

object value = dataGreadView[e.ColumnIndex, e.RowIndex].Value;

p.SetValue(typeof(Ware), Convert.ChangeType(value, p.PropertyType));

But at the last line I got exeption System.Reflection.TargetException: "The object does not match the end type."


问:
Npgsql - generation ddl scripts from Entity Framework's data model
I've crated a data model in VS 2010 and now I want to generate a DDL scripts for my PostgreSQL database. I've registered a Npgsql provider in the .NET 4.0 profile machine.config file and created proper connection string in app.config file but still I cannot find a Npgsql provider on a provider's list when I'm trying to write model to database. </p>

<p>Thanks in advance for any help. </p>

答: Unfortunately, Npgsql doesn't have support for vs.net 2010 design time. You will need to use edmgen command line tool. Sorry for that... :(</p>

Body:
I've crated a data model in VS 2010 and now I want to generate a DDL scripts for my PostgreSQL database. I've registered a Npgsql provider in the .NET 4.0 profile machine.config file and created proper connection string in app.config file but still I cannot find a Npgsql provider on a provider's list when I'm trying to write model to database.

Thanks in advance for any help.


问:
Git workflow for a modelling task with data updates
I am looking to kick off a modelling/forecasting task with the aid of git. I want to set up a git architecture to facilitate this, but am having some issues.

Goal: At the end of the modelling task in region/subregion branchs (human revisions needed, human revision = commit), merge down to master to have all of the forecasts available for review with what version of the code and dataset it was run on. If revisions need to be made later on, a modeller should be able to branch out from when the exact forecast was completed and work on it with the correct (possibly older) version of the code.

Issue: The data and code version can change. Older model runs will likley not be compatible with older code/data (for example, in region 1, code version 1 and data version 2 may be used, but in region 2, code 4 and data 6), and at the end of the project, forecasts must be able to be reproduced.

My solution:  It seems to be against the philosophy of git, but every time there is a dataset or code update, place it in master and append a version number to the file name. Have region/subregion branches and tag every forecast completion commit  Then when the forecast is completed, merge down to master, and add another file that states what version the code and data was run on. If a revision needs to be made, find the tag of completion, and remodel with the proper version of the code, merge back in to region and then down to master. If a model needs to be reproduced, run it with the correct code/data (from the additional file created).

Is this the best way to go about using git to track this process, or is there a better/simpler way? Will this process work, or are there unintended issues that may arise because of it?

答:
The data and code version can change

That means you have two sets of files, with a strong coupling, but with their own evolution within that coupling.

That is a job for Git submodules: you put the code and the data each in their own separate git repository, and you reference a fixed SHA1 for each in a main parent repo:

```<code>parent/
  code/
  data/
</code>```

That way, from the parent repo, you can make a branch in which both code and data will change. When the forecast is completed, what you are merging to master (in parent) are the latest SHA1 of code and data.

The interest of submodules is that you record in the parent repo the exact SHA1 of the data repo which is supposed to be compatible with the code repo.

And you completely avoid any "hack" like renaming files.

Body:
The data and code version can change

That means you have two sets of files, with a strong coupling, but with their own evolution within that coupling.

That is a job for Git submodules: you put the code and the data each in their own separate git repository, and you reference a fixed SHA1 for each in a main parent repo:

parent/
  code/
  data/

That way, from the parent repo, you can make a branch in which both code and data will change. When the forecast is completed, what you are merging to master (in parent) are the latest SHA1 of code and data.

The interest of submodules is that you record in the parent repo the exact SHA1 of the data repo which is supposed to be compatible with the code repo.

And you completely avoid any "hack" like renaming files.


问:
Assign variable in pytorch
I'd like to know if it is possble to the following code, but now using pytorch, where dtype = torch.cuda.FloatTensor. There's the code straight python (using numpy): Basically I want to get the value of x that produces the min value of fitness.

```<code>import numpy as np
import random as rand
xmax, xmin       = 5, -5
pop              = 30
x                = (xmax-xmin)*rand.random(pop,1)
y                = x**2
[minz, indexmin] = np.amin(y), np.argmin(y)
best             = x[indexmin]
</code>```

This is my attempt to do it:

```<code>import torch
dtype = torch.cuda.FloatTensor
def fit (x):
    return  x**2
def main():
    pop              = 30
    xmax, xmin       = 5, -5
    x                = (xmax-xmin)*torch.rand(pop, 1).type(dtype)+xmin
    y                = fit(x)
    [miny, indexmin] = torch.min(y,0)
    best             = x[indexmin]
main()
</code>```

The last part where I define the variable best as the value of x with index equal to indexmin it doesn't work. What am I doing wrong here.

The following messenge appears: RuntimeError:

```<code>expecting vector of indices at /opt/conda/conda-bld/pytorch_1501971235237/work/pytorch-0.1.12/torch/lib/THC/generic/THCTensorIndex.cu:405
</code>```

答:
You can simply do as follows.</p>

```<code>import torch
dtype = torch.cuda.FloatTensor
def main():
    pop, xmax, xmin  = 30, 5, -5
    x                = (xmax-xmin)*torch.rand(pop, 1).type(dtype)+xmin
    y                = torch.pow(x, 2)
    [miny, indexmin] = y.min(0)
    best             = x.squeeze()[indexmin] # squeeze x to make it 1d

main()
</code>```

Title: Assign variable in pytorch

Body:
I'd like to know if it is possble to the following code, but now using pytorch, where dtype = torch.cuda.FloatTensor. There's the code straight python (using numpy): Basically I want to get the value of x that produces the min value of fitness.

import numpy as np
import random as rand
xmax, xmin       = 5, -5
pop              = 30
x                = (xmax-xmin)*rand.random(pop,1)
y                = x**2
[minz, indexmin] = np.amin(y), np.argmin(y)
best             = x[indexmin]

This is my attempt to do it:

import torch
dtype = torch.cuda.FloatTensor
def fit (x):
    return  x**2
def main():
    pop              = 30
    xmax, xmin       = 5, -5
    x                = (xmax-xmin)*torch.rand(pop, 1).type(dtype)+xmin
    y                = fit(x)
    [miny, indexmin] = torch.min(y,0)
    best             = x[indexmin]
main()

The last part where I define the variable best as the value of x with index equal to indexmin it doesn't work. What am I doing wrong here.

The following messenge appears: RuntimeError:

expecting vector of indices at /opt/conda/conda-bld/pytorch_1501971235237/work/pytorch-0.1.12/torch/lib/THC/generic/THCTensorIndex.cu:405

Body:
You can simply do as follows.

import torch
dtype = torch.cuda.FloatTensor
def main():
    pop, xmax, xmin  = 30, 5, -5
    x                = (xmax-xmin)*torch.rand(pop, 1).type(dtype)+xmin
    y                = torch.pow(x, 2)
    [miny, indexmin] = y.min(0)
    best             = x.squeeze()[indexmin] # squeeze x to make it 1d

main()


问:
How to make footer stick to the bottom
I am having a problem with my footer. I am trying to force it to the bottom, but it always looks ugly.

Here is the code:

```<code><div id="footer">
<div class="container">
    <div class="row">
        <h3 class="footertext">About Us:</h3>
        <br>
          <div class="col-md-4">
            <center>
              <img src="http://oi60.tinypic.com/w8lycl.jpg" class="img-circle" alt="the-brains">
              <br>
              <h4 class="footertext">Programmer</h4>
              <p class="footertext">You can thank all the crazy programming here to this guy.<br>
            </center>
          </div>
          <div class="col-md-4">
            <center>
              <img src="http://oi60.tinypic.com/2z7enpc.jpg" class="img-circle" alt="...">
              <br>
              <h4 class="footertext">Artist</h4>
              <p class="footertext">All the images here are hand drawn by this man.<br>
            </center>
          </div>
          <div class="col-md-4">
            <center>
              <img src="http://oi61.tinypic.com/307n6ux.jpg" class="img-circle" alt="...">
              <br>
              <h4 class="footertext">Designer</h4>
              <p class="footertext">This pretty site and the copy it holds are all thanks to this guy.<br>
            </center>
          </div>
        </div>
        <div class="row">

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

I tried to use

```<code><div class="footer navbar-fixed-bottom">
</code>```

but in that case my text ,which is located over the footer, get overlapped by footer

Here is css I used:

```<code>    #footer {
padding-top: 100px
  position: absolute;
  bottom: 0;
  width: 100%;
  /* Sets the fixed height of the footer here */
  height: 280px;
  background:
  /* color overlay */
    linear-gradient(
      rgba(240, 212, 0, 0.45),
      rgba(0, 0, 0, 0.45)
    ),
    /* image to overlay */
    url(222.png);
}
.footertext {
  color: #ffffff;
}
</code>```

Here is what I mean by ugly. I did try to set html and body height as 100% in css

答:
Its

not

you mistypes a -

Title: How to make footer stick to the bottom

Body:
I am having a problem with my footer. I am trying to force it to the bottom, but it always looks ugly.

Here is the code:

About Us:

Programmer

You can thank all the crazy programming here to this guy.

Artist

All the images here are hand drawn by this man.

Designer

This pretty site and the copy it holds are all thanks to this guy.

I tried to use

but in that case my text ,which is located over the footer, get overlapped by footer

Here is css I used:

    #footer {
padding-top: 100px
  position: absolute;
  bottom: 0;
  width: 100%;
  /* Sets the fixed height of the footer here */
  height: 280px;
  background:
  /* color overlay */
    linear-gradient(
      rgba(240, 212, 0, 0.45),
      rgba(0, 0, 0, 0.45)
    ),
    /* image to overlay */
    url(222.png);
}
.footertext {
  color: #ffffff;
}

Here is what I mean by ugly. I did try to set html and body height as 100% in css

Body:
Its <div class="footer navbar fixed-bottom">

not <div class="footer navbar-fixed-bottom">

you mistypes a -


问:
how do I convert the first letter of every word in a list from upper case to lower case?
how do I convert the first letter of each of the below from upper case to lowere case?

For example SentMessage would become sentMessage and NotAttemptedCreditLimitReached would become notAttemptedCreditLimitReached ... etc

list of words below. They are just in a text file.

```<code>SentMessage
DeliverySucceeded
DeliveryFailed
DeliveryTimedOut
NotAttemptedCreditLimitReached
NotAttemptedChargingFailure
SubscriptionFailed
SentReportSMDeliveryStatus
FailedToSendReportSMDeliveryStatus
ReportSMSucceeded
ReportSMFailed
</code>```

Was looking at doing it notepadd++ initially, but open to other suggestions bash/python ... etc

EDIT1 - the solution

```<code>$ cat testw
SentMessage
DeliverySucceeded
DeliveryFailed
DeliveryTimedOut
NotAttemptedCreditLimitReached
NotAttemptedChargingFailure
SubscriptionFailed
SentReportSMDeliveryStatus
FailedToSendReportSMDeliveryStatus
ReportSMSucceeded
ReportSMFailed
$ sed -i 's/[A-Z]/\L&/' testw
$ cat testw
sentMessage
deliverySucceeded
deliveryFailed
deliveryTimedOut
notAttemptedCreditLimitReached
notAttemptedChargingFailure
subscriptionFailed
sentReportSMDeliveryStatus
failedToSendReportSMDeliveryStatus
reportSMSucceeded
reportSMFailed
</code>```

答:
If you have gnu sed then use:

```<code>sed -i 's/[A-Z]/\L&/' file
</code>```

[A-Z] will match first upper case letter

& is back-reference of matched string by pattern (in this case single upper case letter)

\L converts given back-reference to lowercase

Body:
how do I convert the first letter of each of the below from upper case to lowere case?

For example SentMessage would become sentMessage and NotAttemptedCreditLimitReached would become notAttemptedCreditLimitReached ... etc

list of words below. They are just in a text file.

SentMessage
DeliverySucceeded
DeliveryFailed
DeliveryTimedOut
NotAttemptedCreditLimitReached
NotAttemptedChargingFailure
SubscriptionFailed
SentReportSMDeliveryStatus
FailedToSendReportSMDeliveryStatus
ReportSMSucceeded
ReportSMFailed

Was looking at doing it notepadd++ initially, but open to other suggestions bash/python ... etc

EDIT1 - the solution

$ cat testw
SentMessage
DeliverySucceeded
DeliveryFailed
DeliveryTimedOut
NotAttemptedCreditLimitReached
NotAttemptedChargingFailure
SubscriptionFailed
SentReportSMDeliveryStatus
FailedToSendReportSMDeliveryStatus
ReportSMSucceeded
ReportSMFailed
$ sed -i 's/[A-Z]/\L&/' testw
$ cat testw
sentMessage
deliverySucceeded
deliveryFailed
deliveryTimedOut
notAttemptedCreditLimitReached
notAttemptedChargingFailure
subscriptionFailed
sentReportSMDeliveryStatus
failedToSendReportSMDeliveryStatus
reportSMSucceeded
reportSMFailed

Body:
If you have gnu sed then use:

sed -i 's/[A-Z]/\L&/' file

[A-Z] will match first upper case letter

& is back-reference of matched string by pattern (in this case single upper case letter)

\L converts given back-reference to lowercase


问:
numpy.diff returning an empty array?
```<code>#python 3.6.3
import numpy as np

time_C0002A/1000
array([[-0.99925  ],
       [-0.99925  ],
       [-0.99925  ],
       ...,
       [ 0.0181095],
       [ 0.0195675],
       [ 0.0205931]])

Fs_log = 1 / np.diff(time_C0002A/1000)
</code>```

When I enter it in to see what it returns, it is given as an empty array

```<code>Fs_log
array([], shape=(9063,0), dtype = float64)
</code>```

I am expecting an array to be returned and have confirmed with a different example, any idea what could be occurring and how I should remedy this? i believe it is an issue with the axis along which diff is taken but I am not sure what it should be defined as, example:

```<code>np.diff(time_C0002A/1000, axis = 0)
</code>```

But I am not sure? Input appreciated!

答:
Your time_C0002A array has a shape of (n,1).  np.diff take the difference over the last axis by default, in your case of length 1.  You can specify the axis as an argument.

```<code>np.diff(time_C0002A/1000, axis=0)
</code>```

Title: numpy.diff returning an empty array?

Body:
#python 3.6.3
import numpy as np

time_C0002A/1000
array([[-0.99925  ],
       [-0.99925  ],
       [-0.99925  ],
       ...,
       [ 0.0181095],
       [ 0.0195675],
       [ 0.0205931]])

Fs_log = 1 / np.diff(time_C0002A/1000)

When I enter it in to see what it returns, it is given as an empty array

Fs_log
array([], shape=(9063,0), dtype = float64)

I am expecting an array to be returned and have confirmed with a different example, any idea what could be occurring and how I should remedy this? i believe it is an issue with the axis along which diff is taken but I am not sure what it should be defined as, example:

np.diff(time_C0002A/1000, axis = 0)

But I am not sure? Input appreciated!

Body:
Your time_C0002A array has a shape of (n,1).  np.diff take the difference over the last axis by default, in your case of length 1.  You can specify the axis as an argument.

np.diff(time_C0002A/1000, axis=0)


问:
fade in then fadout in jquery for some seconds
I was wondering if I can make my div do something just to look more attractive . However , I want my div to fade in then go back normally automatically . I tried fade in for seconds with a function ,, but I need it to be back quickly . How can this be done ? Any help ? Thankyou </p>

```<code>$(document).ready(function() {
   window.setTimeout("fadeMyDiv();", 3000); //call fade in 3 seconds
 }
)

function fadeMyDiv() {
   $("#test").fadeOut('slow')

}
</code>```

答:
jQuery's fadeIn and fadeOut accept another parameter which is a callback function that get called when the fade in/out is done. You can use it like:

```<code>var $div = $("#test");
$div.fadeIn("slow", function() {
    $div.fadeOut("slow");
});
</code>```

And you can use delay to make a delay between the fade in and out:

```<code>$("#test").fadeIn("slow")     // fade in
          .delay(1000)        // wait 1000 ms (1 second)
          .fadeOut("slow");   // fade out
</code>```

Loop forever:

```<code>var $div = $("#test");
setInterval(function() {
    $div.fadeIn("slow", function() { $div.fadeOut("slow"); });
}, 2000);
</code>```

Body:
I was wondering if I can make my div do something just to look more attractive . However , I want my div to fade in then go back normally automatically . I tried fade in for seconds with a function ,, but I need it to be back quickly . How can this be done ? Any help ? Thankyou

$(document).ready(function() {
   window.setTimeout("fadeMyDiv();", 3000); //call fade in 3 seconds
 }
)

function fadeMyDiv() {
   $("#test").fadeOut('slow')

}

Body:
jQuery's fadeIn and fadeOut accept another parameter which is a callback function that get called when the fade in/out is done. You can use it like:

var $div = $("#test");
$div.fadeIn("slow", function() {
    $div.fadeOut("slow");
});

And you can use delay to make a delay between the fade in and out:

$("#test").fadeIn("slow")     // fade in
          .delay(1000)        // wait 1000 ms (1 second)
          .fadeOut("slow");   // fade out

Loop forever:

var $div = $("#test");
setInterval(function() {
    $div.fadeIn("slow", function() { $div.fadeOut("slow"); });
}, 2000);


问:
How to add objects to a pointer
I'm trying to figure out how does a vector adds more objects after it has already "Created" some:

```<code>int *ptr;
ptr = new int;
</code>```

How after using that, can you add more objects to that pointer? (make it an array). Thanks!

答:
You can't make it an array, you can only point it to one.

So when you do this:

```<code>int *ptr;
ptr = new int;
</code>```

you have pointed pointer ptr to newly created integer. You can delete it and create array, and point ptr to that array:

```<code>delete ptr;
ptr = new int[5];
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to add objects to a pointer

Body:
I'm trying to figure out how does a vector adds more objects after it has already "Created" some:

int *ptr;
ptr = new int;

How after using that, can you add more objects to that pointer? (make it an array). Thanks!

Body:
You can't make it an array, you can only point it to one.

So when you do this:

int *ptr;
ptr = new int;

you have pointed pointer ptr to newly created integer. You can delete it and create array, and point ptr to that array:

delete ptr;
ptr = new int[5];


问:
Make st_make_valid in sf package work (windows)
I am currently trying to get the sf::st_make_valid() function work under R 3.3.3 (Windows).

My problem is that the sf package does not build against the liblwgeom library. To install liblwgeom under windows, I tried installing the osgeo4w that according to its installation options lists the liblwgeom library. Still, after installing the liblwgeom through the osgeo4w installer, sf does not recognize the liblwgeom library.

From sf documentation on valid functionality:
It is only available if the package was linked against liblwgeom, which is currently not the case for
the binary CRAN distributions; see the package source code repository for instructions how to
install liblwgeom

Any suggestions?

```<code>install.packages("sf")
library(sf)
Linking to GEOS 3.5.0, GDAL 2.1.1, proj.4 4.9.3
</code>```

If sf recognized the liblwgeom library, it should be indicated when loading the sf package.

Anyone has experience with how to enable st_make_valid functionality in the sf package and how to install liblwgeom on Windows?

答: If you have rtools installed, you should now be able to get this by installing package lwgeom from https://github.com/r-spatial/lwgeom/

Body:
I am currently trying to get the sf::st_make_valid() function work under R 3.3.3 (Windows).

My problem is that the sf package does not build against the liblwgeom library. To install liblwgeom under windows, I tried installing the osgeo4w that according to its installation options lists the liblwgeom library. Still, after installing the liblwgeom through the osgeo4w installer, sf does not recognize the liblwgeom library.

From sf documentation on valid functionality:
It is only available if the package was linked against liblwgeom, which is currently not the case for
the binary CRAN distributions; see the package source code repository for instructions how to
install liblwgeom

Any suggestions?

install.packages("sf")
library(sf)
Linking to GEOS 3.5.0, GDAL 2.1.1, proj.4 4.9.3

If sf recognized the liblwgeom library, it should be indicated when loading the sf package.

Anyone has experience with how to enable st_make_valid functionality in the sf package and how to install liblwgeom on Windows?


问:
TINYINT column values switch to true and 1
I have been facing this weird issue where a table column is TINYINT. When I query the table on my local I get records with column values as true or false. I put code on production and it gets true or false values sometimes. But all of a sudden the values switch from true or false to either 0 or 1. I am not sure why this happens. Any insight on this issue would be great.

Please note that my TINYINT column has values that are either 1 or 0 only.

So there is this hash I am creating from the records wherein against every key I am storing the corresponding TINYINT column values, which looks like:

```<code>@content_map: {1=>true, 338=>true, 375=>false}
</code>```

On local the hash looks like above.

On production the hash looks like:

```<code>@content_map: {1=>true, 338=>true, 375=>false}
</code>```

and sometimes after few reloads like:

```<code>@content_map: {1=>0, 338=>1, 375=>0}
</code>```

So the hash values keep changing on production, this is what I don't understand. It should either always be true or it should always be 1.

How I am creating the @cotent_map:

```<code>@content_map = Hash.new
</code>```

Here is a select query on the table with column free of type TINYINT

```<code>@list = Action.all.select("id, free")

@list.map {|i| @content_map[i.id] = i.free}
</code>```

答:
MySQL does not have boolean data type. It uses tinyint instead. There is no way it uses t or f for that type.

```<code>mysql> create table foo( boolboa BOOLEAN DEFAULT false );
Query OK, 0 rows affected (0,26 sec)

mysql> describe foo;
+---------+------------+------+-----+---------+-------+
| Field   | Type       | Null | Key | Default | Extra |
+---------+------------+------+-----+---------+-------+
| boolboa | tinyint(1) | YES  |     | 0       |       |
+---------+------------+------+-----+---------+-------+
1 row in set (0,01 sec)

mysql> insert into foo values(true);
Query OK, 1 row affected (0,05 sec)

mysql> insert into foo values('4');
Query OK, 1 row affected (0,05 sec)

mysql> insert into foo values(4);
Query OK, 1 row affected (0,02 sec)

mysql> select * from foo;
+---------+
| boolboa |
+---------+
|       1 |
|       4 |
|       4 |
+---------+
3 rows in set (0,00 sec)
</code>```

From MySQL documentation.

BOOL, BOOLEAN

These types are synonyms for TINYINT(1). A value of zero is considered
  false. Nonzero values are considered true:

And more crazy parts

```<code>mysql> select * from foo where boolboa = true;
+---------+
| boolboa |
+---------+
|       1 |
+---------+
1 row in set (0,00 sec)

mysql> select * from foo where boolboa != false;
+---------+
| boolboa |
+---------+
|       1 |
|       4 |
|       4 |
+---------+
3 rows in set (0,00 sec)

mysql> select not false is true;
+-------------------+
| not false is true |
+-------------------+
|                 1 |
+-------------------+

mysql> select (not false is true) = true;
+----------------------------+
| (not false is true) = true |
+----------------------------+
|                          1 |
+----------------------------+
</code>```

Before I run the query below I was afraid of that MySQL will return "90% 1, 10% 0". Thanksgod, it didn't -))

```<code>mysql> select true != false;
+---------------+
| true != false |
+---------------+
|             1 |
+---------------+
1 row in set (0,00 sec)
</code>```

CONCLUSION:

MySQL engine itself even does not know what is true, what is not false, what should be considered as nonzero, what does nonzero mean etc.. So do not expect much consistency on that issue -))

Body:
I have been facing this weird issue where a table column is TINYINT. When I query the table on my local I get records with column values as true or false. I put code on production and it gets true or false values sometimes. But all of a sudden the values switch from true or false to either 0 or 1. I am not sure why this happens. Any insight on this issue would be great.

Please note that my TINYINT column has values that are either 1 or 0 only.

So there is this hash I am creating from the records wherein against every key I am storing the corresponding TINYINT column values, which looks like:

@content_map: {1=>true, 338=>true, 375=>false}

On local the hash looks like above.

On production the hash looks like:

@content_map: {1=>true, 338=>true, 375=>false}

and sometimes after few reloads like:

@content_map: {1=>0, 338=>1, 375=>0}

So the hash values keep changing on production, this is what I don't understand. It should either always be true or it should always be 1.

How I am creating the @cotent_map:

@content_map = Hash.new

Here is a select query on the table with column free of type TINYINT

@list = Action.all.select("id, free")

@list.map {|i| @content_map[i.id] = i.free}

Body:
MySQL does not have boolean data type. It uses tinyint instead. There is no way it uses t or f for that type.

mysql> create table foo( boolboa BOOLEAN DEFAULT false );
Query OK, 0 rows affected (0,26 sec)

mysql> describe foo;
+---------+------------+------+-----+---------+-------+
| Field   | Type       | Null | Key | Default | Extra |
+---------+------------+------+-----+---------+-------+
| boolboa | tinyint(1) | YES  |     | 0       |       |
+---------+------------+------+-----+---------+-------+
1 row in set (0,01 sec)

mysql> insert into foo values(true);
Query OK, 1 row affected (0,05 sec)

mysql> insert into foo values('4');
Query OK, 1 row affected (0,05 sec)

mysql> insert into foo values(4);
Query OK, 1 row affected (0,02 sec)

mysql> select * from foo;
+---------+
| boolboa |
+---------+
|       1 |
|       4 |
|       4 |
+---------+
3 rows in set (0,00 sec)

From MySQL documentation.

BOOL, BOOLEAN

These types are synonyms for TINYINT(1). A value of zero is considered
  false. Nonzero values are considered true:

And more crazy parts

mysql> select * from foo where boolboa = true;
+---------+
| boolboa |
+---------+
|       1 |
+---------+
1 row in set (0,00 sec)

mysql> select * from foo where boolboa != false;
+---------+
| boolboa |
+---------+
|       1 |
|       4 |
|       4 |
+---------+
3 rows in set (0,00 sec)

mysql> select not false is true;
+-------------------+
| not false is true |
+-------------------+
|                 1 |
+-------------------+

mysql> select (not false is true) = true;
+----------------------------+
| (not false is true) = true |
+----------------------------+
|                          1 |
+----------------------------+

Before I run the query below I was afraid of that MySQL will return "90% 1, 10% 0". Thanksgod, it didn't -))

mysql> select true != false;
+---------------+
| true != false |
+---------------+
|             1 |
+---------------+
1 row in set (0,00 sec)

CONCLUSION:

MySQL engine itself even does not know what is true, what is not false, what should be considered as nonzero, what does nonzero mean etc.. So do not expect much consistency on that issue -))


问:
spring data mongodb mapping dynamic field
I've this model in my java class

```<code>@Document
public class Template {

    private String type;

    private String code;

    @Version
    Long version;
}
</code>```

I need to add a new field, named template, and map this field as dynamic in other words I would model a document like this

```<code>{
  _id: 'id'
  type:'myType',
  code:'myCode'
  template:{
    someFiled:[
      {
        subField1:'value1',
        subField2:'value2'
      },
      {
        sub1Field1:'1value1',
        sub1Field2:'1value2'
      }
      .......................
    ],
    otherField:[
      {
        otherField1:'value1',
        otherField2:'value2'
      }
    ],
    .........
  },
  version:1000L
}
</code>```

There is any way to annotated a field as dynamic?

SOLUTION

```<code>    @Document
    public class Template {

        private String type;

        private String code;

        private Map<String, Object> template;

        @Version
        Long version;
    }
</code>```

答:
I found out a perfect solution. take my project for example:

```<code>@Data
@Document(collection = "logs")
public class Log {
    @Id
    private String id;
    private Object data;

    // data field can be a string
    public void setData(String str) {
        data = str;
    }
    // data field can be a {}
    public void setData(JsonObject jsonObject) {
        data = new BasicDBObject(jsonObject.getMap());
    }
    // data can be a []
    public void setData(JsonArray jsonArray) {
        BasicDBList list = new BasicDBList();
        list.addAll(jsonArray.getList());
        data = list;
    }
}
</code>```

declare the data field as type of Object, implement 3 kind of setter for it.

Here are the test case:

```<code>@RunWith(SpringRunner.class)
@SpringBootTest
public class LogRepositoryTest {

    @Autowired
    private LogRepository logRepository;

    @Test
    public void test() {
        Log strLog = new Log();
        strLog.setData("string here");
        logRepository.save(strLog);
        Log objLog = new Log();
        objLog.setData(new JsonObject().put("key", "value").put("obj", new JsonObject()));
        logRepository.save(objLog);
        Log aryLog = new Log();
        aryLog.setData(new JsonArray().add("a").add("b").add("c"));
        logRepository.save(aryLog);
    }
}
</code>```

And the result:

```<code>{
        "_id" : ObjectId("5a09fa46a15b065268a0a157"),
        "_class" : "ltd.linkcon.spider.domain.Log",
        "data" : "string here"
}
{
        "_id" : ObjectId("5a09fa46a15b065268a0a158"),
        "_class" : "ltd.linkcon.spider.domain.Log",
        "data" : {
                "key" : "value",
                "obj" : [ ]
        }
}
{
        "_id" : ObjectId("5a09fa46a15b065268a0a159"),
        "_class" : "ltd.linkcon.spider.domain.Log",
        "data" : [
                "a",
                "b",
                "c"
        ]
}
</code>```

Body:
I've this model in my java class

@Document
public class Template {

    private String type;

    private String code;

    @Version
    Long version;
}

I need to add a new field, named template, and map this field as dynamic in other words I would model a document like this

{
  _id: 'id'
  type:'myType',
  code:'myCode'
  template:{
    someFiled:[
      {
        subField1:'value1',
        subField2:'value2'
      },
      {
        sub1Field1:'1value1',
        sub1Field2:'1value2'
      }
      .......................
    ],
    otherField:[
      {
        otherField1:'value1',
        otherField2:'value2'
      }
    ],
    .........
  },
  version:1000L
}

There is any way to annotated a field as dynamic?

SOLUTION

    @Document
    public class Template {

        private String type;

        private String code;

        private Map<String, Object> template;

        @Version
        Long version;
    }

Body:
I found out a perfect solution. take my project for example:

@Data
@Document(collection = "logs")
public class Log {
    @Id
    private String id;
    private Object data;

    // data field can be a string
    public void setData(String str) {
        data = str;
    }
    // data field can be a {}
    public void setData(JsonObject jsonObject) {
        data = new BasicDBObject(jsonObject.getMap());
    }
    // data can be a []
    public void setData(JsonArray jsonArray) {
        BasicDBList list = new BasicDBList();
        list.addAll(jsonArray.getList());
        data = list;
    }
}

declare the data field as type of Object, implement 3 kind of setter for it.

Here are the test case:

@RunWith(SpringRunner.class)
@SpringBootTest
public class LogRepositoryTest {

    @Autowired
    private LogRepository logRepository;

    @Test
    public void test() {
        Log strLog = new Log();
        strLog.setData("string here");
        logRepository.save(strLog);
        Log objLog = new Log();
        objLog.setData(new JsonObject().put("key", "value").put("obj", new JsonObject()));
        logRepository.save(objLog);
        Log aryLog = new Log();
        aryLog.setData(new JsonArray().add("a").add("b").add("c"));
        logRepository.save(aryLog);
    }
}

And the result:

{
        "_id" : ObjectId("5a09fa46a15b065268a0a157"),
        "_class" : "ltd.linkcon.spider.domain.Log",
        "data" : "string here"
}
{
        "_id" : ObjectId("5a09fa46a15b065268a0a158"),
        "_class" : "ltd.linkcon.spider.domain.Log",
        "data" : {
                "key" : "value",
                "obj" : [ ]
        }
}
{
        "_id" : ObjectId("5a09fa46a15b065268a0a159"),
        "_class" : "ltd.linkcon.spider.domain.Log",
        "data" : [
                "a",
                "b",
                "c"
        ]
}


问:
SQL Returning remaining rows
I have a table of on hand quantity for a list of parts. I have a second table with a series of order ship dates and required quantities.

I want to return the ship date of the next order that we will not have anymore inventory for.

For example:

Table 1, our on hand quantity for parts A, B, and C:

```<code>Name   Qty-Have
A      10
B      10
C      5
</code>```

Table 2, Next two months of future orders for parts A, B, and C:

```<code>Name   Due          Qty-Need
A      11/10/17     4
A      11/15/17     6
A      11/20/17     3
A      11/25/17     10
B      11/12/17     4
B      12/15/17     4
B      12/29/17     4
C      11/10/17     7
</code>```

Result, the earliest order date for when we will have insufficient inventory:

```<code>Name   Next Due         Qty-Want
A      11/20/17         13
B      12/29/17         2
C      11/10/17         2
</code>```

I know I can do a grouping of Table 2 and subtract inventory to get Qty-Want, but I do not know how to get the next shipment date of the next uncovered order.

The first two orders of part A we have inventory, and I would like to know that we do not have enough for the third order, due 11/20/17 and we should make 13 parts to cover all remaining demand.

答:
you could use a sum window function to compute a running total by 'name', and observe where it goes negative:

```<code>select ord.name,
       ord.due,
       ord.qty,
       q.qty - ord.ord_sum inventory
from (  select *,
                sum(qty) over (partition by name order by Due) ord_sum
        from fut_orders ) ord
inner join quantity q
    on ord.name = q.name
</code>```

order by ord.name, ord.due

Title: SQL Returning remaining rows

Body:
I have a table of on hand quantity for a list of parts. I have a second table with a series of order ship dates and required quantities.

I want to return the ship date of the next order that we will not have anymore inventory for.

For example:

Table 1, our on hand quantity for parts A, B, and C:

Name   Qty-Have
A      10
B      10
C      5

Table 2, Next two months of future orders for parts A, B, and C:

Name   Due          Qty-Need
A      11/10/17     4
A      11/15/17     6
A      11/20/17     3
A      11/25/17     10
B      11/12/17     4
B      12/15/17     4
B      12/29/17     4
C      11/10/17     7

Result, the earliest order date for when we will have insufficient inventory:

Name   Next Due         Qty-Want
A      11/20/17         13
B      12/29/17         2
C      11/10/17         2

I know I can do a grouping of Table 2 and subtract inventory to get Qty-Want, but I do not know how to get the next shipment date of the next uncovered order.

The first two orders of part A we have inventory, and I would like to know that we do not have enough for the third order, due 11/20/17 and we should make 13 parts to cover all remaining demand.

Body:
you could use a sum window function to compute a running total by 'name', and observe where it goes negative:

select ord.name,
       ord.due,
       ord.qty,
       q.qty - ord.ord_sum inventory
from (  select *,
                sum(qty) over (partition by name order by Due) ord_sum
        from fut_orders ) ord
inner join quantity q
    on ord.name = q.name

order by ord.name, ord.due


问:
How to set Spinner default value to null?
I'm trying to get a Spinner to load up with no selected value. Once the user selects a value it then takes them to another page.

This is proving to be a problem because at present, the page just loads straight away before the user gets a choice to choose.

My spinner class is set up the same way as Google's: http://developer.android.com/resources/tutorials/views/hello-spinner.html

So basically, is it possible have a spinner that loads with nothing selected because at present, it loads the first item in my string array.

答:
In my case, although size '2' is displayed in the spinner, nothing happens till some selection is done!

I have an xml file (data_sizes.xml) which lists all the spinner values.

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="chunks">
        <item>2</item>
        <item>4</item>
        <item>8</item>
        <item>16</item>
        <item>32</item>
    </string-array>
</resources>
</code>```

In main.xml file: Spinner element

```<code><Spinner android:id="@+id/spinnerSize"
android:layout_marginLeft="50px"
android:layout_width="fill_parent"
android:drawSelectorOnTop="true"
android:layout_marginTop="5dip"
android:prompt="@string/SelectSize"
android:layout_marginRight="30px"
android:layout_height="35px" />
</code>```

Then in my java code, I added:

In my activity: Declaration

```<code>Spinner spinnerSize;
ArrayAdapter adapter;
</code>```

In a public void function - initControls(): Definition

```<code>spinnerSize = (Spinner)findViewById(R.id.spinnerSize);
adapter = ArrayAdapter.createFromResource(this, R.array.chunks, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerSize.setAdapter(adapter);
spinnerSize.setOnItemSelectedListener(new MyOnItemSelectedListener());
</code>```

My spinner listener:

/* Spinner Listener */

```<code>class MyOnItemSelectedListener implements OnItemSelectedListener {

    public void onItemSelected(AdapterView<?> parent,
        View view, int pos, long id) {
        chunkSize = new Integer(parent.getItemAtPosition(pos).toString()).intValue();
    }
    public void onNothingSelected(AdapterView<?> parent) {
      // Dummy
    }
}
</code>```

Body:
In my case, although size '2' is displayed in the spinner, nothing happens till some selection is done!

I have an xml file (data_sizes.xml) which lists all the spinner values.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="chunks">
        <item>2</item>
        <item>4</item>
        <item>8</item>
        <item>16</item>
        <item>32</item>
    </string-array>
</resources>

In main.xml file: Spinner element

<Spinner android:id="@+id/spinnerSize"
android:layout_marginLeft="50px"
android:layout_width="fill_parent"
android:drawSelectorOnTop="true"
android:layout_marginTop="5dip"
android:prompt="@string/SelectSize"
android:layout_marginRight="30px"
android:layout_height="35px" />

Then in my java code, I added:

In my activity: Declaration

Spinner spinnerSize;
ArrayAdapter adapter;

In a public void function - initControls(): Definition

spinnerSize = (Spinner)findViewById(R.id.spinnerSize);
adapter = ArrayAdapter.createFromResource(this, R.array.chunks, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerSize.setAdapter(adapter);
spinnerSize.setOnItemSelectedListener(new MyOnItemSelectedListener());

My spinner listener:

/* Spinner Listener */

class MyOnItemSelectedListener implements OnItemSelectedListener {

    public void onItemSelected(AdapterView<?> parent,
        View view, int pos, long id) {
        chunkSize = new Integer(parent.getItemAtPosition(pos).toString()).intValue();
    }
    public void onNothingSelected(AdapterView<?> parent) {
      // Dummy
    }
}


问:
Sonarqube Background Task (too many open files)
We have a large project (~35,000 java files) that currently has about 10,000 issues. About 3 weeks ago, our nightly scan started failing on version sonarqube 6.5. I upgraded to 6.6 and found the same problem. First, it was failing due to heap space. I have upgraded this machine to give it more memory and that seems to have allowed the analysis to finish. Now the scan fails every night during the background task to post the analysis due to "Too many open files". We have upped the limits for open files for the sonar user but that doesn't seem to have any effect.  We have other smaller projects and they all finish easily. It's just this very large project that constantly fails. Has anyone seen this before?

This morning I installed sonarqube 6.7 to see if that fixes it. I'm currently running an analysis but it takes about 3 hours to finish and fail.

We increased the number of open files allowed for the sonar user.

```<code>-sh-4.1$ whoami
sonar
-sh-4.1$ ulimit -Hs
unlimited
-sh-4.1$ ulimit -Hn
1048576
</code>```

Here is the error we are seeing

```<code>org.sonar.server.computation.task.projectanalysis.component.VisitException: Visit of Component {key=applications:sonar:src/main/java/com/MyFileName.java,type=FILE} failed
    at org.sonar.server.computation.task.projectanalysis.component.VisitException.rethrowOrWrap(VisitException.java:44)
    at org.sonar.server.computation.task.projectanalysis.component.VisitorsCrawler.visit(VisitorsCrawler.java:74)
    at org.sonar.server.computation.task.projectanalysis.component.VisitorsCrawler.visitChildren(VisitorsCrawler.java:110)
    at org.sonar.server.computation.task.projectanalysis.component.VisitorsCrawler.visitImpl(VisitorsCrawler.java:97)
    at org.sonar.server.computation.task.projectanalysis.component.VisitorsCrawler.visit(VisitorsCrawler.java:72)
    at org.sonar.server.computation.task.projectanalysis.component.VisitorsCrawler.visitChildren(VisitorsCrawler.java:110)
    at org.sonar.server.computation.task.projectanalysis.component.VisitorsCrawler.visitImpl(VisitorsCrawler.java:97)
    at org.sonar.server.computation.task.projectanalysis.component.VisitorsCrawler.visit(VisitorsCrawler.java:72)
    at org.sonar.server.computation.task.projectanalysis.step.ExecuteVisitorsStep.execute(ExecuteVisitorsStep.java:51)
    at org.sonar.server.computation.task.step.ComputationStepExecutor.executeSteps(ComputationStepExecutor.java:64)
    at org.sonar.server.computation.task.step.ComputationStepExecutor.execute(ComputationStepExecutor.java:52)
    at org.sonar.server.computation.task.projectanalysis.taskprocessor.ReportTaskProcessor.process(ReportTaskProcessor.java:75)
    at org.sonar.ce.taskprocessor.CeWorkerImpl.executeTask(CeWorkerImpl.java:92)
    at org.sonar.ce.taskprocessor.CeWorkerImpl.call(CeWorkerImpl.java:59)
    at org.sonar.ce.taskprocessor.CeWorkerImpl.call(CeWorkerImpl.java:35)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalStateException: Fail to process issues of component 'applications:sonar:src/main/java/com/MyFileName.java'
    at org.sonar.server.computation.task.projectanalysis.issue.IntegrateIssuesVisitor.processIssues(IntegrateIssuesVisitor.java:83)
    at org.sonar.server.computation.task.projectanalysis.issue.IntegrateIssuesVisitor.visitAny(IntegrateIssuesVisitor.java:63)
    at org.sonar.server.computation.task.projectanalysis.component.TypeAwareVisitorWrapper.visitAny(TypeAwareVisitorWrapper.java:82)
    at org.sonar.server.computation.task.projectanalysis.component.VisitorsCrawler.visitNode(VisitorsCrawler.java:117)
    at org.sonar.server.computation.task.projectanalysis.component.VisitorsCrawler.visitImpl(VisitorsCrawler.java:100)
    at org.sonar.server.computation.task.projectanalysis.component.VisitorsCrawler.visit(VisitorsCrawler.java:72)
    ... 21 more
Caused by: java.lang.IllegalStateException: Fail to traverse file: /opt/sonarqube-6.5/temp/ce/6622607282221286408/1421069522563365386/source-11991.txt
    at org.sonar.server.computation.task.projectanalysis.batch.BatchReportReaderImpl.readFileSource(BatchReportReaderImpl.java:153)
    at org.sonar.server.computation.task.projectanalysis.source.SourceLinesRepositoryImpl.readLines(SourceLinesRepositoryImpl.java:45)
    at org.sonar.server.computation.task.projectanalysis.issue.TrackerRawInputFactory$RawLazyInput.loadLineHashSequence(TrackerRawInputFactory.java:80)
    at org.sonar.core.issue.tracking.LazyInput.getLineHashSequence(LazyInput.java:34)
    at org.sonar.server.computation.task.projectanalysis.issue.TrackerRawInputFactory$RawLazyInput.loadIssues(TrackerRawInputFactory.java:105)
    at org.sonar.core.issue.tracking.LazyInput.getIssues(LazyInput.java:50)
    at org.sonar.core.issue.tracking.Tracking.<init>(Tracking.java:46)
    at org.sonar.core.issue.tracking.Tracker.track(Tracker.java:37)
    at org.sonar.server.computation.task.projectanalysis.issue.TrackerExecution.track(TrackerExecution.java:41)
    at org.sonar.server.computation.task.projectanalysis.issue.IntegrateIssuesVisitor.processIssues(IntegrateIssuesVisitor.java:76)
    ... 26 more
Caused by: java.io.FileNotFoundException: /opt/sonarqube-6.5/temp/ce/6622607282221286408/1421069522563365386/source-11991.txt (Too many open files)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at org.apache.commons.io.FileUtils.openInputStream(FileUtils.java:301)
    at org.sonar.server.computation.task.projectanalysis.batch.BatchReportReaderImpl.readFileSource(BatchReportReaderImpl.java:151)
    ... 35 more
</code>```

答: Upgrading to SonarQube 6.7 fixed this error with too many open files. </p>

Body:
We have a large project (~35,000 java files) that currently has about 10,000 issues. About 3 weeks ago, our nightly scan started failing on version sonarqube 6.5. I upgraded to 6.6 and found the same problem. First, it was failing due to heap space. I have upgraded this machine to give it more memory and that seems to have allowed the analysis to finish. Now the scan fails every night during the background task to post the analysis due to "Too many open files". We have upped the limits for open files for the sonar user but that doesn't seem to have any effect.  We have other smaller projects and they all finish easily. It's just this very large project that constantly fails. Has anyone seen this before?

This morning I installed sonarqube 6.7 to see if that fixes it. I'm currently running an analysis but it takes about 3 hours to finish and fail.

We increased the number of open files allowed for the sonar user.

-sh-4.1$ whoami
sonar
-sh-4.1$ ulimit -Hs
unlimited
-sh-4.1$ ulimit -Hn
1048576

Here is the error we are seeing

org.sonar.server.computation.task.projectanalysis.component.VisitException: Visit of Component {key=applications:sonar:src/main/java/com/MyFileName.java,type=FILE} failed
    at org.sonar.server.computation.task.projectanalysis.component.VisitException.rethrowOrWrap(VisitException.java:44)
    at org.sonar.server.computation.task.projectanalysis.component.VisitorsCrawler.visit(VisitorsCrawler.java:74)
    at org.sonar.server.computation.task.projectanalysis.component.VisitorsCrawler.visitChildren(VisitorsCrawler.java:110)
    at org.sonar.server.computation.task.projectanalysis.component.VisitorsCrawler.visitImpl(VisitorsCrawler.java:97)
    at org.sonar.server.computation.task.projectanalysis.component.VisitorsCrawler.visit(VisitorsCrawler.java:72)
    at org.sonar.server.computation.task.projectanalysis.component.VisitorsCrawler.visitChildren(VisitorsCrawler.java:110)
    at org.sonar.server.computation.task.projectanalysis.component.VisitorsCrawler.visitImpl(VisitorsCrawler.java:97)
    at org.sonar.server.computation.task.projectanalysis.component.VisitorsCrawler.visit(VisitorsCrawler.java:72)
    at org.sonar.server.computation.task.projectanalysis.step.ExecuteVisitorsStep.execute(ExecuteVisitorsStep.java:51)
    at org.sonar.server.computation.task.step.ComputationStepExecutor.executeSteps(ComputationStepExecutor.java:64)
    at org.sonar.server.computation.task.step.ComputationStepExecutor.execute(ComputationStepExecutor.java:52)
    at org.sonar.server.computation.task.projectanalysis.taskprocessor.ReportTaskProcessor.process(ReportTaskProcessor.java:75)
    at org.sonar.ce.taskprocessor.CeWorkerImpl.executeTask(CeWorkerImpl.java:92)
    at org.sonar.ce.taskprocessor.CeWorkerImpl.call(CeWorkerImpl.java:59)
    at org.sonar.ce.taskprocessor.CeWorkerImpl.call(CeWorkerImpl.java:35)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalStateException: Fail to process issues of component 'applications:sonar:src/main/java/com/MyFileName.java'
    at org.sonar.server.computation.task.projectanalysis.issue.IntegrateIssuesVisitor.processIssues(IntegrateIssuesVisitor.java:83)
    at org.sonar.server.computation.task.projectanalysis.issue.IntegrateIssuesVisitor.visitAny(IntegrateIssuesVisitor.java:63)
    at org.sonar.server.computation.task.projectanalysis.component.TypeAwareVisitorWrapper.visitAny(TypeAwareVisitorWrapper.java:82)
    at org.sonar.server.computation.task.projectanalysis.component.VisitorsCrawler.visitNode(VisitorsCrawler.java:117)
    at org.sonar.server.computation.task.projectanalysis.component.VisitorsCrawler.visitImpl(VisitorsCrawler.java:100)
    at org.sonar.server.computation.task.projectanalysis.component.VisitorsCrawler.visit(VisitorsCrawler.java:72)
    ... 21 more
Caused by: java.lang.IllegalStateException: Fail to traverse file: /opt/sonarqube-6.5/temp/ce/6622607282221286408/1421069522563365386/source-11991.txt
    at org.sonar.server.computation.task.projectanalysis.batch.BatchReportReaderImpl.readFileSource(BatchReportReaderImpl.java:153)
    at org.sonar.server.computation.task.projectanalysis.source.SourceLinesRepositoryImpl.readLines(SourceLinesRepositoryImpl.java:45)
    at org.sonar.server.computation.task.projectanalysis.issue.TrackerRawInputFactory$RawLazyInput.loadLineHashSequence(TrackerRawInputFactory.java:80)
    at org.sonar.core.issue.tracking.LazyInput.getLineHashSequence(LazyInput.java:34)
    at org.sonar.server.computation.task.projectanalysis.issue.TrackerRawInputFactory$RawLazyInput.loadIssues(TrackerRawInputFactory.java:105)
    at org.sonar.core.issue.tracking.LazyInput.getIssues(LazyInput.java:50)
    at org.sonar.core.issue.tracking.Tracking.<init>(Tracking.java:46)
    at org.sonar.core.issue.tracking.Tracker.track(Tracker.java:37)
    at org.sonar.server.computation.task.projectanalysis.issue.TrackerExecution.track(TrackerExecution.java:41)
    at org.sonar.server.computation.task.projectanalysis.issue.IntegrateIssuesVisitor.processIssues(IntegrateIssuesVisitor.java:76)
    ... 26 more
Caused by: java.io.FileNotFoundException: /opt/sonarqube-6.5/temp/ce/6622607282221286408/1421069522563365386/source-11991.txt (Too many open files)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at org.apache.commons.io.FileUtils.openInputStream(FileUtils.java:301)
    at org.sonar.server.computation.task.projectanalysis.batch.BatchReportReaderImpl.readFileSource(BatchReportReaderImpl.java:151)
    ... 35 more