问:
Html5 image Pixelation load
In my website, images are loaded from top to bottom, how can I change it so the images will load in Pixelation, like on Google Maps when are you zooming in?</p>

答:
Or if you want a pixelating/rendering blur, you could look here: https://www.google.com/amp/s/jmperezperez.com/medium-image-progressive-loading-placeholder/amp/

Here is what is going on:

Render a div where the image will be displayed. Medium uses a  with a padding-bottom set to a percentage, which corresponds to the aspect ratio of the image. Thus, they prevent reflows while the images are loaded since everything is rendered in its final position. This has also been referred to as intrinsic placeholders.

Load a tiny version of the image. At the moment, they seem to be requesting small JPEG thumbnails with a very low quality (e.g. 20%). The markup for this small image is returned in the initial HTML as an , so the browser starts fetching them right away.

Once the image is loaded, it is drawn in a . Then, the image data is taken and passed through a custom blur() function You can see it, a bit scrambled, in the main-base.bundle JS file. This function is similar, though not identical, to StackBlur‘s blur function. At the same time, the main image is requested.

Once the main image is loaded, it is shown and the canvas is hidden.

All the transitions are quite smooth, thanks to the CSS animations applied.

An example fromo the page:

```<code><figure name="7012" id="7012" class="graf--figure graf--layoutFillWidth graf-after--h4">
  <div class="aspectRatioPlaceholder is-locked">
    <div class="aspect-ratio-fill" style="padding-bottom: 66.7%;"></div>
    <div class="progressiveMedia js-progressiveMedia graf-image is-canvasLoaded is-imageLoaded" data-image-id="1*sg-uLNm73whmdOgKlrQdZA.jpeg" data-width="2000" data-height="1333" data-scroll="native">
      <img src="https://cdn-images-1.medium.com/freeze/max/27/1*sg-uLNm73whmdOgKlrQdZA.jpeg?q=20" crossorigin="anonymous" class="progressiveMedia-thumbnail js-progressiveMedia-thumbnail">
        <canvas class="progressiveMedia-canvas js-progressiveMedia-canvas" width="75" height="47"></canvas>
        <img class="progressiveMedia-image js-progressiveMedia-image __web-inspector-hide-shortcut__" data-src="https://cdn-images-1.medium.com/max/1800/1*sg-uLNm73whmdOgKlrQdZA.jpeg" src="https://cdn-images-1.medium.com/max/1800/1*sg-uLNm73whmdOgKlrQdZA.jpeg">
        <noscript class="js-progressiveMedia-inner"><img class="progressiveMedia-noscript js-progressiveMedia-inner" src="https://cdn-images-1.medium.com/max/1800/1*sg-uLNm73whmdOgKlrQdZA.jpeg"></noscript>
    </div>
  </div>
</figure>
</code>```

Or you could check out this CodePen That JMPerez set up, in an atempt to recreate the effect himself.

I'm sorry about my first answer if its not what you were looking for.

Title: Html5 image Pixelation load

Body:
Or if you want a pixelating/rendering blur, you could look here: https://www.google.com/amp/s/jmperezperez.com/medium-image-progressive-loading-placeholder/amp/

Here is what is going on:

Render a div where the image will be displayed. Medium uses a  with a padding-bottom set to a percentage, which corresponds to the aspect ratio of the image. Thus, they prevent reflows while the images are loaded since everything is rendered in its final position. This has also been referred to as intrinsic placeholders.

Load a tiny version of the image. At the moment, they seem to be requesting small JPEG thumbnails with a very low quality (e.g. 20%). The markup for this small image is returned in the initial HTML as an , so the browser starts fetching them right away.

Once the image is loaded, it is drawn in a . Then, the image data is taken and passed through a custom blur() function You can see it, a bit scrambled, in the main-base.bundle JS file. This function is similar, though not identical, to StackBlur‘s blur function. At the same time, the main image is requested.

Once the main image is loaded, it is shown and the canvas is hidden.

All the transitions are quite smooth, thanks to the CSS animations applied.

An example fromo the page:

<figure name="7012" id="7012" class="graf--figure graf--layoutFillWidth graf-after--h4">
  <div class="aspectRatioPlaceholder is-locked">
    <div class="aspect-ratio-fill" style="padding-bottom: 66.7%;"></div>
    <div class="progressiveMedia js-progressiveMedia graf-image is-canvasLoaded is-imageLoaded" data-image-id="1*sg-uLNm73whmdOgKlrQdZA.jpeg" data-width="2000" data-height="1333" data-scroll="native">
      <img src="https://cdn-images-1.medium.com/freeze/max/27/1*sg-uLNm73whmdOgKlrQdZA.jpeg?q=20" crossorigin="anonymous" class="progressiveMedia-thumbnail js-progressiveMedia-thumbnail">
        <canvas class="progressiveMedia-canvas js-progressiveMedia-canvas" width="75" height="47"></canvas>
        <img class="progressiveMedia-image js-progressiveMedia-image __web-inspector-hide-shortcut__" data-src="https://cdn-images-1.medium.com/max/1800/1*sg-uLNm73whmdOgKlrQdZA.jpeg" src="https://cdn-images-1.medium.com/max/1800/1*sg-uLNm73whmdOgKlrQdZA.jpeg">
        <noscript class="js-progressiveMedia-inner">&lt;img class="progressiveMedia-noscript js-progressiveMedia-inner" src="https://cdn-images-1.medium.com/max/1800/1*sg-uLNm73whmdOgKlrQdZA.jpeg"&gt;</noscript>
    </div>
  </div>
</figure>

Or you could check out this CodePen That JMPerez set up, in an atempt to recreate the effect himself.

I'm sorry about my first answer if its not what you were looking for.


来源: stackexchange

问:
Is it possible to conditionally load libraries in Lua?
I'm making a script for mpv, and in it I load the mpv library like this:

```<code>-- script.lua

local mp = require('mp')
</code>```

I'm using the busted unit test framework to write tests for this, and they're contained in a separate file, like this:

```<code>-- script-tests.lua

describe('my script unit tests', function()
    local script = require('script')

    it('...', function()
        assert.is_true(true)
    end)
end)
</code>```

The problem occurs when I run the unit tests, I get this:

./script.lua:1: module 'mp' not found:No LuaRocks module found for mp

I understand mp is available when my script is run within mpv, but not when I run my unit tests. Is there any way to stop this require when running the unit tests? or am I thinking about this in the wrong way?

Solution

In the end I created a stub mp (trying to use a global flag like Adam suggested, but it wouldn't work). Here it is:

```<code>-- script.lua

local plugin = {}
local mpv_loaded, mp = pcall(require, 'mp')

plugin.mp = mp

---------------------------------------------------------------------
-- Stub MPV library for unit tests
if not mpv_loaded then
    plugin.mp = {}

    function plugin.mp.osd_message(message)
        plugin.mp.message = message
    end

    function plugin.mp.log(level, message)
        -- stub
    end

    function plugin.mp.add_forced_key_binding(...)
        -- stub
    end

    function plugin.mp.remove_key_binding(...)
        -- stub
    end
end

---------------------------------------------------------------------
-- Display message on screen.
function plugin:show_message(message)
    self.mp.osd_message(message)
end

return plugin
</code>```

```<code>-- script-tests.lua

describe('my script unit tests', function()
    local plugin = require('script')

    it('...', function()
        message = 'It is better to play than do nothing.'
        plugin:show_message(message)

        assert.is_same(plugin.mp.message, message)
    end)

end)
</code>```

答:
If all you care about is a conditional require, meaning something to catch the require error:</p>

```<code>local mpv_loaded, mp = pcall(function() return require 'mp' end)

if not mpv_loaded then
    -- handle the bad require, in this case 'mp' holds the error message
else
    -- 'mp' contains the lib as it normally would
end
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm making a script for mpv, and in it I load the mpv library like this:

-- script.lua

local mp = require('mp')

I'm using the busted unit test framework to write tests for this, and they're contained in a separate file, like this:

-- script-tests.lua

describe('my script unit tests', function()
    local script = require('script')

    it('...', function()
        assert.is_true(true)
    end)
end)

The problem occurs when I run the unit tests, I get this:

./script.lua:1: module 'mp' not found:No LuaRocks module found for mp

I understand mp is available when my script is run within mpv, but not when I run my unit tests. Is there any way to stop this require when running the unit tests? or am I thinking about this in the wrong way?

Solution

In the end I created a stub mp (trying to use a global flag like Adam suggested, but it wouldn't work). Here it is:

-- script.lua

local plugin = {}
local mpv_loaded, mp = pcall(require, 'mp')

plugin.mp = mp

---------------------------------------------------------------------
-- Stub MPV library for unit tests
if not mpv_loaded then
    plugin.mp = {}

    function plugin.mp.osd_message(message)
        plugin.mp.message = message
    end

    function plugin.mp.log(level, message)
        -- stub
    end

    function plugin.mp.add_forced_key_binding(...)
        -- stub
    end

    function plugin.mp.remove_key_binding(...)
        -- stub
    end
end

---------------------------------------------------------------------
-- Display message on screen.
function plugin:show_message(message)
    self.mp.osd_message(message)
end

return plugin

-- script-tests.lua

describe('my script unit tests', function()
    local plugin = require('script')

    it('...', function()
        message = 'It is better to play than do nothing.'
        plugin:show_message(message)

        assert.is_same(plugin.mp.message, message)
    end)

end)

Body:
If all you care about is a conditional require, meaning something to catch the require error:

local mpv_loaded, mp = pcall(function() return require 'mp' end)

if not mpv_loaded then
    -- handle the bad require, in this case 'mp' holds the error message
else
    -- 'mp' contains the lib as it normally would
end


问:
why does the center point of GID_ZOOM changes?
Once the Windows Zoom gestures starts why would the position of the center point change in the same gesture for subsequent GID_ZOOM messages?

I don't have a touch screen so I tried to simulate the zoom gesture. It gives me the same center point whether I obtain the center point in GF_BEGIN or GF_END.

However when I looked at windows sample over here Microsoft-classic-samples repository, GestureEngine.cpp. They are re-calculating the center by taking the average of 2 ptsLocation(s),

```<code>        // We read here the second point of the gesture. This is middle point between
        // fingers in this new position.
        _ptSecond.x = gi.ptsLocation.x;
        _ptSecond.y = gi.ptsLocation.y;
        ScreenToClient(hWnd,&_ptSecond);

        // We have to calculate zoom center point
        ptZoomCenter.x = (_ptFirst.x + _ptSecond.x)/2;
        ptZoomCenter.y = (_ptFirst.y + _ptSecond.y)/2;
</code>```

I am confused why plsLocation would change for the same gesture i.e. before we receive the GF_END message?

答:
Microsoft-classic-samples forum "Location of the center of the zoom in GID_ZOOM Gesture" is exactly what I was looking for. I am posting the answer if someone doesn't want to go through the link.

Human beings are not very good at moving two fingers at exactly the
  same rate outwards. There is usually some error, which can cause the
  center to shift slightly. (For example, when I do a pinch gesture, my
  index finger moves faster than my thumb.)

ContentLicense: CC BY-SA 4.0

Body:
Once the Windows Zoom gestures starts why would the position of the center point change in the same gesture for subsequent GID_ZOOM messages?

I don't have a touch screen so I tried to simulate the zoom gesture. It gives me the same center point whether I obtain the center point in GF_BEGIN or GF_END.

However when I looked at windows sample over here Microsoft-classic-samples repository, GestureEngine.cpp. They are re-calculating the center by taking the average of 2 ptsLocation(s),

        // We read here the second point of the gesture. This is middle point between
        // fingers in this new position.
        _ptSecond.x = gi.ptsLocation.x;
        _ptSecond.y = gi.ptsLocation.y;
        ScreenToClient(hWnd,&_ptSecond);

        // We have to calculate zoom center point
        ptZoomCenter.x = (_ptFirst.x + _ptSecond.x)/2;
        ptZoomCenter.y = (_ptFirst.y + _ptSecond.y)/2;

I am confused why plsLocation would change for the same gesture i.e. before we receive the GF_END message?


问:
How do I apply a Font Theme in React Material-UI?
I'm trying to apply a google font to my Material UI react project, but can't seem to get it to take.  I'm using Material UI 0.14.2.

My index.html font load:
<link href='https://fonts.googleapis.com/css?family=PT+Sans:400,700' rel='stylesheet' type='text/css'>

My component where I apply the theme:

```<code>import ThemeManager from 'material-ui/lib/styles/theme-manager';
import LightRawTheme from 'material-ui/lib/styles/raw-themes/light-raw-theme';

const App = React.createClass({

    childContextTypes: {
        muiTheme: React.PropTypes.object,
    },
    getChildContext: function() {
        return {
            muiTheme: ThemeManager.modifyRawThemeFontFamily(ThemeManager.getMuiTheme(LightRawTheme), 'PT Sans, sans-serif')
        }
    },

...etc etc

}
</code>```

答:
If you're just looking to change the font of your material-ui theme, change muiTheme in the MuiThemeProvider provider component. The docs have an example here: http://www.material-ui.com/#/customization/themes

Should look something like this:

App.css

```<code>/* Load in your font */
@import url('https://fonts.googleapis.com/css?family=Lato');
</code>```

App.js

```<code>// App.js
import './App.css'
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';

const font = "'Lato', sans-serif";

const muiTheme = getMuiTheme({
  fontFamily: font
});

function App(props) {
  return(
    <MuiThemeProvider muiTheme={muiTheme}>
      <div style={{fontFamily: font}}>...</div>
    </MuiThemeProvider>
  );
}
</code>```

Note most of the components had to have their fonts updated, but I added fontFamily to the enclosing div (as seen above) as well in order for all to be updated (headers specifically for me).

If you're wondering what else you can override, it is probably easiest to just look at the code (https://github.com/callemall/material-ui/blob/master/src/styles/getMuiTheme.js) where it is defined

Body:
I'm trying to apply a google font to my Material UI react project, but can't seem to get it to take.  I'm using Material UI 0.14.2.

My index.html font load:
<link href='https://fonts.googleapis.com/css?family=PT+Sans:400,700' rel='stylesheet' type='text/css'>

My component where I apply the theme:

import ThemeManager from 'material-ui/lib/styles/theme-manager';
import LightRawTheme from 'material-ui/lib/styles/raw-themes/light-raw-theme';

const App = React.createClass({

    childContextTypes: {
        muiTheme: React.PropTypes.object,
    },
    getChildContext: function() {
        return {
            muiTheme: ThemeManager.modifyRawThemeFontFamily(ThemeManager.getMuiTheme(LightRawTheme), 'PT Sans, sans-serif')
        }
    },

...etc etc

}

Body:
If you're just looking to change the font of your material-ui theme, change muiTheme in the MuiThemeProvider provider component. The docs have an example here: http://www.material-ui.com/#/customization/themes

Should look something like this:

App.css

/* Load in your font */
@import url('https://fonts.googleapis.com/css?family=Lato');

App.js

// App.js
import './App.css'
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';

const font = "'Lato', sans-serif";

const muiTheme = getMuiTheme({
  fontFamily: font
});

function App(props) {
  return(
    <MuiThemeProvider muiTheme={muiTheme}>
      <div style={{fontFamily: font}}>...</div>
    </MuiThemeProvider>
  );
}

Note most of the components had to have their fonts updated, but I added fontFamily to the enclosing div (as seen above) as well in order for all to be updated (headers specifically for me).

If you're wondering what else you can override, it is probably easiest to just look at the code (https://github.com/callemall/material-ui/blob/master/src/styles/getMuiTheme.js) where it is defined


问:
jQuery boxy Question
i using a jquery boxy to call my captche overlay:

```<code><script>
$(document).ready(function()    {
    var zahl1 = Math.floor(Math.random()*11);
    var zahl2 = Math.floor(Math.random()*31);

    //$("#cap").html("Wie viel ist "+zahl1+" + "+zahl2+"? <input type='text' id='answer' />");

    $("#shortbutton").live("click", function()  {
        ask();
        return false;
    });
});

function ask()
{
    zahl1 = Math.floor(Math.random()*11);
    zahl2 = Math.floor(Math.random()*31);
    var sum = zahl1 + zahl2;
    new Boxy.ask("Wie viel ist "+zahl1+" + "+zahl2+"? <input type='text' id='answ' />",
        ["Ok"],

        function(val) {

            if($("#answ").val() == (zahl1 + zahl2))
            {
                $("#form").submit();
            }
            else
            {
                ask();
                return false;
            }
        },

        {title: "Captcha"}
    );
}
</script>
</code>```

The code is a bit unclean... function call them selfts... i know... but how can i let call the "OK" event on Enter Press...

So you write the answer and press Enter... and it checks.

Have some an idea?

答:
You could programmatically click the 'Ok' button on the box:

```<code>$("#answ").live("keydown", function(event) {
    if (event.which === 13) {
        $(this)
            .parent()
            .siblings("form")
            .children("input:button").click();
    }
});
</code>```

Using live to listen to events no matter when the input is created.  You may have to modify selector under the check for the enter key if you have more than one input of type button (if you add a "Cancel" button for example).

Check out a working example here: http://jsfiddle.net/andrewwhitaker/Z2qeh/

Note: I tried refactoring your anonymous callback method into its own method that could be called by both the Boxy object and the keydown listener, but I couldn't get the interaction quite the same as clicking the "Ok" button.

ContentLicense: CC BY-SA 2.5

Title: jQuery boxy Question

Body:
i using a jquery boxy to call my captche overlay:

The code is a bit unclean... function call them selfts... i know... but how can i let call the "OK" event on Enter Press...

So you write the answer and press Enter... and it checks.

Have some an idea?

Body:
You could programmatically click the 'Ok' button on the box:

$("#answ").live("keydown", function(event) {
    if (event.which === 13) {
        $(this)
            .parent()
            .siblings("form")
            .children("input:button").click();
    }
});

Using live to listen to events no matter when the input is created.  You may have to modify selector under the check for the enter key if you have more than one input of type button (if you add a "Cancel" button for example).

Check out a working example here: http://jsfiddle.net/andrewwhitaker/Z2qeh/

Note: I tried refactoring your anonymous callback method into its own method that could be called by both the Boxy object and the keydown listener, but I couldn't get the interaction quite the same as clicking the "Ok" button.


问:
Serving single page React app from Google Cloud Storage
I am trying to serve a React app from Google Cloud Storage. I built the React project and uploaded the contents of the build/ directory to Google Cloud Storage. I made sure every file inside is publicly accessible. However when I go to my Google Cloud bucket link http://storage.googleapis.com/BUCKET_NAME/, I get some XML about a permission error:

```<code><Error>
<Code>AccessDenied</Code>
<Message>Access denied.</Message>
<Details>
Anonymous users does not have storage.objects.list access to bucket BUCKET_NAME.
</Details>
</Error>
</code>```

Then, I tried to navigate to the URL http://storage.googleapis.com/BUCKET_NAME/index.html, which brings up a blank page. In the JS console, there are errors:

```<code>index.html:1 GET http://storage.googleapis.com/static/css/main.9a0fe4f1.css
index.html:1 GET http://storage.googleapis.com/static/js/main.871fec8f.js
</code>```

These errors look like the BUCKET_NAME is not in the URL that was fetched. However, my built index.html is referencing them relatively, as so:

```<code><script type="text/javascript" src="/static/js/main.871fec8f.js"></script>
</code>```

I'm not sure what's going on, there are two issues. First is that index.html is not the default served page when going to the bucket URL. Second issue is that the relative paths don't seem to be resolving the right URL. Any help is appreciated.

答: This was a problem on my end. This method should work.</p>

Body:
I am trying to serve a React app from Google Cloud Storage. I built the React project and uploaded the contents of the build/ directory to Google Cloud Storage. I made sure every file inside is publicly accessible. However when I go to my Google Cloud bucket link http://storage.googleapis.com/BUCKET_NAME/, I get some XML about a permission error:

<Error>
AccessDenied
<Message>Access denied.</Message>

Anonymous users does not have storage.objects.list access to bucket BUCKET_NAME.

</Error>

Then, I tried to navigate to the URL http://storage.googleapis.com/BUCKET_NAME/index.html, which brings up a blank page. In the JS console, there are errors:

index.html:1 GET http://storage.googleapis.com/static/css/main.9a0fe4f1.css
index.html:1 GET http://storage.googleapis.com/static/js/main.871fec8f.js

These errors look like the BUCKET_NAME is not in the URL that was fetched. However, my built index.html is referencing them relatively, as so:

I'm not sure what's going on, there are two issues. First is that index.html is not the default served page when going to the bucket URL. Second issue is that the relative paths don't seem to be resolving the right URL. Any help is appreciated.


问:
appium how to override capabilities
Any ideas on the following.

My standard capabilities are set to open my native application.

```<code>capabilities.setCapability("app", app.getAbsolutePath());
</code>```

This is defined in a method with @BeforeMethod annotation (TestNG)

I have one specific test I want to start in Chrome. How can I acheive this ? Can I override in some way the capabilities for one specific test ?

答:
TestNG lets you pass parameters directly to your test methods in two different ways:

With testng.xml

With Data Providers

Consider this feature and maybe implement your own Data Provider which will provide separate configuration to your specific test method. In this way you even could prepare and start appium server with different configuration and capabilities for each test method

Title: appium how to override capabilities

Body:
Any ideas on the following.

My standard capabilities are set to open my native application.

capabilities.setCapability("app", app.getAbsolutePath());

This is defined in a method with @BeforeMethod annotation (TestNG)

I have one specific test I want to start in Chrome. How can I acheive this ? Can I override in some way the capabilities for one specific test ?


问:
Reversing a Linked List Template Class
I am trying to reverse a Linked List created using the built in Linked List class from java.  Is the below implementation something that is viable?  Moreover, in an actual software engineering environment would developers use the template class or their own?  Thanks!</p>

```<code>LinkedList<String> example1 = new LinkedList<>();
example1.add("Ben");
example1.add("Sam");
example1.add("Kyle");
Object objectArr[];
String stringArr[];
objectArr =  example1.toArray();
stringArr = Arrays.copyOf(objectArr, objectArr.length, String[].class);
ArrayList<String> newList = new ArrayList<String>(Arrays.asList(stringArr));
Collections.reverse(newList);
example1.clear();
example1.addAll(newList);
</code>```

答:
Is the below implementation something that is viable?

Not really as you implemented it, because all you need to do in order to reverse a LinkedList object is invoking the Collections.reverse(List<?> list) static method directly without the need for creating two arrays and one ArrayList then rebuild the LinkedList.

in an actual software engineering environment would developers use the template class or their own?

It depends on what you want to achieve, a neat way is use what Java provided to you and use the reverse() method. But if the performance is the issue

From Documentation (my emphasis):

public static void reverse(List<?> list)
  Reverses the order of the elements in the specified list.
  This method runs in linear time.

That means: the more the List grows, the longer is the time. So for example a list that contains 10 elements will take two times the time needed for a list with 5 elements and so on.

The question here is: can we improve the performance. I am not sure if I can answer this question properly, but I created a simple test to compare between 3 ways of reversing (of course other users may have other improved ideas of how to reverse), and here is the results:

```<code>import java.util.Collections;
import java.util.LinkedList;

public class LinkedListReversePerformance {

    static LinkedList<String> list1 = new LinkedList<>();
    static LinkedList<String> list2 = new LinkedList<>();
    static LinkedList<String> list3 = new LinkedList<>();
    static long startTime, endTime;

    public static void main(String[] args){

        // populate the lists, each with 1 hundred thousand item!
        for(int i =0 ;i<100000; i++){
            list1.add(String.valueOf(i));
            list2.add(String.valueOf(i));
            list3.add(String.valueOf(i));
        }

        // create temporary list
        LinkedList<String> temp = new LinkedList<>();

        startTime = System.currentTimeMillis();
        // run for loop to add the items from list1 to temp in reverse order
        for(int i=9999; i>=0; i--){
            temp.add(list1.get(i));
        }
        // clear list1 then add temp
        list1.clear();
        list1.addAll(temp);
        endTime = System.currentTimeMillis();

        System.out.println("Using For Loop and clearing old list: " + (endTime-startTime) + " Millisecond");

        // re-initialize temp and populate it again in reverse order
        temp = new LinkedList<>();

        startTime = System.currentTimeMillis();
        for(int i=9999; i>=0; i--){
            temp.add(list2.get(i));
        }

        // re-initialize list2 and add temp using the constructor option
        list2 = new LinkedList<>(temp);
        endTime = System.currentTimeMillis();
        System.out.println("Using For Loop and reconstruct the old list: " + (endTime-startTime) + " Millisecond");

        startTime = System.currentTimeMillis();
        // use the reverse static method provided by Java Collections Class
        Collections.reverse(list3);
        endTime = System.currentTimeMillis();
        System.out.println("Using Collection.reverse(): " + (endTime-startTime) + " Millisecond");

    }
}
</code>```

Result

```<code>Using For Loop and clearing old list: 875 Millisecond
Using For Loop and reconstruct the old list: 859 Millisecond
Using Collection.reverse(): 31 Millisecond
</code>```

As you can see, Collection.reverse() still the fastest among them.
As a result, I believe that Java provided best ways to reverse or sort in regard of the performance and memory.
But I'm still open to correction.

Title: Reversing a Linked List Template Class

Body:
I am trying to reverse a Linked List created using the built in Linked List class from java.  Is the below implementation something that is viable?  Moreover, in an actual software engineering environment would developers use the template class or their own?  Thanks!

LinkedList<String> example1 = new LinkedList<>();
example1.add("Ben");
example1.add("Sam");
example1.add("Kyle");
Object objectArr[];
String stringArr[];
objectArr =  example1.toArray();
stringArr = Arrays.copyOf(objectArr, objectArr.length, String[].class);
ArrayList<String> newList = new ArrayList<String>(Arrays.asList(stringArr));
Collections.reverse(newList);
example1.clear();
example1.addAll(newList);

Body:
Is the below implementation something that is viable?

Not really as you implemented it, because all you need to do in order to reverse a LinkedList object is invoking the Collections.reverse(List<?> list) static method directly without the need for creating two arrays and one ArrayList then rebuild the LinkedList.

in an actual software engineering environment would developers use the template class or their own?

It depends on what you want to achieve, a neat way is use what Java provided to you and use the reverse() method. But if the performance is the issue

From Documentation (my emphasis):

public static void reverse(List<?> list)
  Reverses the order of the elements in the specified list.
  This method runs in linear time.

That means: the more the List grows, the longer is the time. So for example a list that contains 10 elements will take two times the time needed for a list with 5 elements and so on.

The question here is: can we improve the performance. I am not sure if I can answer this question properly, but I created a simple test to compare between 3 ways of reversing (of course other users may have other improved ideas of how to reverse), and here is the results:

import java.util.Collections;
import java.util.LinkedList;

public class LinkedListReversePerformance {

    static LinkedList<String> list1 = new LinkedList<>();
    static LinkedList<String> list2 = new LinkedList<>();
    static LinkedList<String> list3 = new LinkedList<>();
    static long startTime, endTime;

    public static void main(String[] args){

        // populate the lists, each with 1 hundred thousand item!
        for(int i =0 ;i<100000; i++){
            list1.add(String.valueOf(i));
            list2.add(String.valueOf(i));
            list3.add(String.valueOf(i));
        }

        // create temporary list
        LinkedList<String> temp = new LinkedList<>();

        startTime = System.currentTimeMillis();
        // run for loop to add the items from list1 to temp in reverse order
        for(int i=9999; i>=0; i--){
            temp.add(list1.get(i));
        }
        // clear list1 then add temp
        list1.clear();
        list1.addAll(temp);
        endTime = System.currentTimeMillis();

        System.out.println("Using For Loop and clearing old list: " + (endTime-startTime) + " Millisecond");

        // re-initialize temp and populate it again in reverse order
        temp = new LinkedList<>();

        startTime = System.currentTimeMillis();
        for(int i=9999; i>=0; i--){
            temp.add(list2.get(i));
        }

        // re-initialize list2 and add temp using the constructor option
        list2 = new LinkedList<>(temp);
        endTime = System.currentTimeMillis();
        System.out.println("Using For Loop and reconstruct the old list: " + (endTime-startTime) + " Millisecond");

        startTime = System.currentTimeMillis();
        // use the reverse static method provided by Java Collections Class
        Collections.reverse(list3);
        endTime = System.currentTimeMillis();
        System.out.println("Using Collection.reverse(): " + (endTime-startTime) + " Millisecond");

    }
}

Result

Using For Loop and clearing old list: 875 Millisecond
Using For Loop and reconstruct the old list: 859 Millisecond
Using Collection.reverse(): 31 Millisecond

As you can see, Collection.reverse() still the fastest among them.
As a result, I believe that Java provided best ways to reverse or sort in regard of the performance and memory.
But I'm still open to correction.


问:
iOS mobile: scrolling in iFrame within scroll-able parent
I'm experiencing an issue in mobile iOS safari where scrolling in a div that contains an iFrame is impossible when dragging inside the iFrame itself:

#outside{
height: 400px;
width: 200px;
background: blue;
overflow: scroll;
}

.space{
  height: 200px;
  width: 200px;
  background: red;
}

iframe{
height: 1000px;
width: 200px;
background-color: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>The green section is the iFrame.... Scrolling on the green section in iOS mobile is the issue

<div id="outside">
<div class="space"></div>
<iframe>

</iframe>
<div class="space"></div>
</div></code>```

So, when dragging on the iFrame, since it has no scroll, it should scroll the parent, but instead, the whole page is scrolled.

Any known workarounds for this bug? It is already working on Android.

答:
Place your s in wrappers with -webkit-overflow-scrolling: touch;

.iContainer {
  -webkit-overflow-scrolling: touch;
}
```

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#outside {
  height: 400px;
  width: 200px;
  background: blue;
  overflow: scroll;
}

.space {
  height: 200px;
  width: 200px;
  background: red;
}

iframe {
  height: 1000px;
  width: 200px;
  background-color: green;
  border: none;
  display:block;
}

iContainer {
  -webkit-overflow-scrolling: touch;
}</code>```

The green section is the iFrame.... Scrolling on the green section in iOS mobile is the issue

```

Special note: Using this in conjunction with position:relative on  causes IoS devices to sometimes block the scroll. Letting it fully revert from it's "bounce" fixes it, but it still feels wrong and buggy.

So make sure you don't have any set position on your  or . Took me a bit to debug this quite recently.

Body:
I'm experiencing an issue in mobile iOS safari where scrolling in a div that contains an iFrame is impossible when dragging inside the iFrame itself:

#outside{
height: 400px;
width: 200px;
background: blue;
overflow: scroll;
}

.space{
  height: 200px;
  width: 200px;
  background: red;
}

iframe{
height: 1000px;
width: 200px;
background-color: green;
}

The green section is the iFrame.... Scrolling on the green section in iOS mobile is the issue

So, when dragging on the iFrame, since it has no scroll, it should scroll the parent, but instead, the whole page is scrolled.

Any known workarounds for this bug? It is already working on Android.

Body:
Place your <iframe>s in wrappers with -webkit-overflow-scrolling: touch;

.iContainer {
  -webkit-overflow-scrolling: touch;
}

#outside {
  height: 400px;
  width: 200px;
  background: blue;
  overflow: scroll;
}

.space {
  height: 200px;
  width: 200px;
  background: red;
}

iframe {
  height: 1000px;
  width: 200px;
  background-color: green;
  border: none;
  display:block;
}

iContainer {
  -webkit-overflow-scrolling: touch;
}

The green section is the iFrame.... Scrolling on the green section in iOS mobile is the issue

<div id="outside">
  <div class="space"></div>
  <div class="iContainer">
    <iframe>
    </iframe>
  </div>
  <div class="space"></div>
</div>

Special note: Using this in conjunction with position:relative on <body> causes IoS devices to sometimes block the scroll. Letting it fully revert from it's "bounce" fixes it, but it still feels wrong and buggy.

So make sure you don't have any set position on your <body> or <html>. Took me a bit to debug this quite recently.


问:
Real time update with Angular 2 and Node js
In Angular 2 I have a navbar and I show how many unread messages the person has. When the person clicks the message, it marks it as read. My database is marked as read, but the navbar doesn't update until I refresh the page entirely.

What can I do to solve this problem?

答:
Assuming the you have a navbar Component into a HomePage Component, then in you home-page.ts file there has to be a variable:

let isMessageRead: boolean = false;
```

<p>You should then bind the navbar in home-page.html with the <code>isMessageRead</code> variable that should look like this:</p>

<pre class="lang-html prettyprint-override"><code><navbar [read]="isMessageRead"></navbar>
</code>```

Body:
Assuming the you have a navbar Component into a HomePage Component, then in you home-page.ts file there has to be a variable:

let isMessageRead: boolean = false;

You should then bind the navbar in home-page.html with the isMessageRead variable that should look like this:

<navbar [read]="isMessageRead"></navbar>


问:
Keep the method somewhere on the view page, instead of calling it several times
It's such that I have a method that I call 7 times and I would like the code to be made nicer and at the same time easy to read and understand.

How can I hold it somewhere?

Just pt, I'll do like this.

```<code>@if(HelperToTables.ContentText.ContentIdValue.GetInfoContentInfo.GetColBool(Model.HiddenId) == true)
     {
         @Html.Raw("col-md-8");
     }
     else if(HelperToTables.ContentText.ContentIdValue.GetInfoContentInfo.GetColBool(Model.HiddenId) == false)
     {
         @Html.Raw("col-md-12");
     }
</code>```

Basically, I think that you could do this here but it does not work in any way.

Note that I do it for example on the index.cshtml page.

答:
Just store the value in a variable.  In this example I use a variable named flag.

```<code>@var flag = HelperToTables.ContentText.ContentIdValue.GetInfoContentInfo.GetColBool(Model.HiddenId);

@if (flag)
{
    @Html.Raw("col-md-8");
}
else
{
    @Html.Raw("col-md-12");
}
</code>```

Body:
It's such that I have a method that I call 7 times and I would like the code to be made nicer and at the same time easy to read and understand.

How can I hold it somewhere?

Just pt, I'll do like this.

@if(HelperToTables.ContentText.ContentIdValue.GetInfoContentInfo.GetColBool(Model.HiddenId) == true)
     {
         @Html.Raw("col-md-8");
     }
     else if(HelperToTables.ContentText.ContentIdValue.GetInfoContentInfo.GetColBool(Model.HiddenId) == false)
     {
         @Html.Raw("col-md-12");
     }

Basically, I think that you could do this here but it does not work in any way.

Note that I do it for example on the index.cshtml page.

Body:
Just store the value in a variable.  In this example I use a variable named flag.

@var flag = HelperToTables.ContentText.ContentIdValue.GetInfoContentInfo.GetColBool(Model.HiddenId);

@if (flag)
{
    @Html.Raw("col-md-8");
}
else
{
    @Html.Raw("col-md-12");
}


问:
Fail to get DB connection from camel route
I am noticing a very strange behavior when running an Apache camel route like below:

```<code>from("direct:daily-extract")
        .id("direct:daily-extract")
        .setHeader("runDate", constant("20170606"))
        .to("sql-stored:pkg_etls.load_exchange_rates(VARCHAR ${headers.runDate})?dataSource=#myDataSource")
....
</code>```

Now I can observe the following:

I have an integration test for this route and it is running OK

I run this route as a standalone java app on my windows developer machine and it is running OK

When installed on a linux machine on a test environment it blows up with the exception below

org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is java.sql.SQLException: Cannot create PoolableConnectionFactory (IO Error: Connection reset)

Other routes that use exactly the same data source run perfectly on the same linux machine. In fact myDataSource is configured in only one place.

Can you please help me with any suggestions as whatever I tried did not work.

What I tried so far without any luck was:

Updated camel version to the latest: 2.19.0

Tried two ojdbc7 versions: 12.1.0.2 and 12.1.0.1

Used two data sources: oracle.jdbc.pool.OracleDataSource and org.apache.commons.dbcp2.BasicDataSource

Thank you in advance.

UPDATE 1:

There is no oracle client installed on the linux box. Here is my data source configuration:

```<code><bean id="myDataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
    <property name="poolPreparedStatements" value="true" />
    <property name="url" value="${db.url}" />
    <property name="username" value="${db.username}" />
    <property name="password" value="${db.password}" />
</bean>
</code>```

答:
This was a very odd behavior and thanks google, we would be dead without you :-)
The explanation and fix is on this Oracle Community Article.</p>

Body:
I am noticing a very strange behavior when running an Apache camel route like below:

from("direct:daily-extract")
        .id("direct:daily-extract")
        .setHeader("runDate", constant("20170606"))
        .to("sql-stored:pkg_etls.load_exchange_rates(VARCHAR ${headers.runDate})?dataSource=#myDataSource")
....

Now I can observe the following:

I have an integration test for this route and it is running OK

I run this route as a standalone java app on my windows developer machine and it is running OK

When installed on a linux machine on a test environment it blows up with the exception below

org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is java.sql.SQLException: Cannot create PoolableConnectionFactory (IO Error: Connection reset)

Other routes that use exactly the same data source run perfectly on the same linux machine. In fact myDataSource is configured in only one place.

Can you please help me with any suggestions as whatever I tried did not work.

What I tried so far without any luck was:

Updated camel version to the latest: 2.19.0

Tried two ojdbc7 versions: 12.1.0.2 and 12.1.0.1

Used two data sources: oracle.jdbc.pool.OracleDataSource and org.apache.commons.dbcp2.BasicDataSource

Thank you in advance.

UPDATE 1:

There is no oracle client installed on the linux box. Here is my data source configuration:

<bean id="myDataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
    <property name="poolPreparedStatements" value="true" />
    <property name="url" value="${db.url}" />
    <property name="username" value="${db.username}" />
    <property name="password" value="${db.password}" />
</bean>


问:
Represent Flowchart-specified Algorithms in Haskell
I'm confronted with the task of implementing algorithms (mostly business logic style) expressed as flowcharts. I'm aware that flowcharts are not the best algorithm representation due to its spaghetti-code property (would this be a use-case for CPS?), but I'm stuck with the specification expressed as flowcharts.

Although I could transform the flowcharts into more appropriate equivalent representations before implementing them, that could make it harder to "recognize" the orginal flow-chart in the resulting implementation, so I was hoping there is some way to directly represent flowchart-algorithms as (maybe monadic) EDSLs in Haskell, so that the semblance to the original flowchart-specification would be (more) obvious.

答: Assuming there's "global" state within the flowchart, then that makes sense to package up into a state monad. At least then, unlike how you're doing it now, each call doesn't need any parameters, so can be read as a) modify state, b) conditional on current state, jump.</p>


问:
Only printing last line of txt file when reading into struct array in C
I am reading from a txt file into an array of structures. Example txt:

```<code>-4.5 -1 0 0
4.0 1 0 0
8 0 1 2
12.1 0 -6 1
-3.2 2.5 -3.0 4
</code>```

The 4 values of each line correspond to the 4 values in the structure. The file may contain up to 100 lines (MAX is defined as 100). With the following code I am trying to store each line into the respective index of the struct array and then print:

```<code>FILE *fileName = NULL;
typedef struct chargeData_struct {
    double Q, x, y, z;
} ChargeData;
ChargeData values[MAX], *p = values;

fileName = fopen("charge2.txt", "r");
if (fileName == NULL)
{
    printf("ERROR: Could not open file.");
}

int k = 0;
while (fscanf(fileName, "%lf %lf %lf %lf", &p[k].Q, &p[k].x, &p[k].y, &p[k].z) != EOF);
{
    printf("%f %f %f %f\n", p[k].Q, p[k].x, p[k].y, p[k].z);
    k++;
}
fclose(fileName);
</code>```

However, only the last line of the txt file is printed. Is the same index of the struct array being overwritten each time?

答:
You are using an extra semicolon which makes all the trouble, here:

```<code>while (fscanf(...) != EOF);
{
   ...
</code>```

Remove it and you should be fine.

What happens with your code is that while(..); is equivalent to this:

```<code>while(...)
{
    ; // do nothing
}
</code>```

thus does not enter the body (the one you think is the body) of your loop (since the actual body does nothing). However scanf() continues to parse the file, and then this section of your code executes:

```<code>{
    printf("%f %f %f %f\n", p[k].Q, p[k].x, p[k].y, p[k].z);
    k++;
}
</code>```

independently, where the curly braces are treated like they wanted to state scope.

Body:
I am reading from a txt file into an array of structures. Example txt:

-4.5 -1 0 0
4.0 1 0 0
8 0 1 2
12.1 0 -6 1
-3.2 2.5 -3.0 4

The 4 values of each line correspond to the 4 values in the structure. The file may contain up to 100 lines (MAX is defined as 100). With the following code I am trying to store each line into the respective index of the struct array and then print:

FILE *fileName = NULL;
typedef struct chargeData_struct {
    double Q, x, y, z;
} ChargeData;
ChargeData values[MAX], *p = values;

fileName = fopen("charge2.txt", "r");
if (fileName == NULL)
{
    printf("ERROR: Could not open file.");
}

int k = 0;
while (fscanf(fileName, "%lf %lf %lf %lf", &p[k].Q, &p[k].x, &p[k].y, &p[k].z) != EOF);
{
    printf("%f %f %f %f\n", p[k].Q, p[k].x, p[k].y, p[k].z);
    k++;
}
fclose(fileName);

However, only the last line of the txt file is printed. Is the same index of the struct array being overwritten each time?

Body:
You are using an extra semicolon which makes all the trouble, here:

while (fscanf(...) != EOF);
{
   ...

Remove it and you should be fine.

What happens with your code is that while(..); is equivalent to this:

while(...)
{
    ; // do nothing
}

thus does not enter the body (the one you think is the body) of your loop (since the actual body does nothing). However scanf() continues to parse the file, and then this section of your code executes:

{
    printf("%f %f %f %f\n", p[k].Q, p[k].x, p[k].y, p[k].z);
    k++;
}

independently, where the curly braces are treated like they wanted to state scope.


问:
Linking Types in Scala
I have a class of objects which either have one type of ID or another:

```<code>sealed trait ItemId
case class NumericId(id: Int) extends ItemId
case class StringId(id: String) extends ItemId

sealed trait Item {
  def id: ItemId
}

case class ItemWithNumericId(id: NumericId) extends Item
case class ItemWithStringId(id: StringId) extends Item
</code>```

I'd like to create an interface for some sort of service which retrieves items:

```<code>trait ItemService[IdType <: ItemId, ItemType <: Item] {
  def get(id: IdType): ItemType
}
</code>```

How do I link the ItemId type with the Item type to put a constraint on ItemServices to not allow something like:

```<code>class SillyItemService extends ItemService[NumericId, ItemWithStringId] {
  def get(id: NumericId): ItemWithStringId = ???
}
</code>```

I've realised I can add generic types to the Item class:

```<code>sealed trait ItemId
case class NumericId(id: Int) extends ItemId
case class StringId(id: String) extends ItemId

sealed trait Item[Id <: ItemId] {
  def id: Id
}

case class ItemWithNumericId(id: NumericId) extends Item[NumericId]
case class ItemWithStringId(id: StringId) extends Item[StringId]

trait ItemService[IdType <: ItemId, ItemType <: Item[IdType]] {
  def get(id: IdType): ItemType
}
</code>```

which is OK but It's super verbose. Ideally, the service would only have a single generic type.

Thanks very much for any answers/input.

答:
Path dependant types are one option which is covered by the other answer, but for the purposes of flexibility I would personally go with implicits/context bounds in this case.

```<code>trait Proof[IdType <: ItemId, ItemType <: Item[IdType]]

trait ItemService[IdType <: ItemId, ItemType <: Item[IdType]] {
  def get(id: IdType)(implicit ev: Proof[IdType, ItemType])
}
</code>```

You can also make trait an abstract class to hoist the declaration of the implicit proof, or whatever other party trick from the many available lets you sidestep the need to include the evidence on every method on the service.

Then I'd make a companion object for Proof and list the correlations feasible within your domain.

```<code>object Proof {
  implicit numericProof: Proof[NumericId, ItemWithNumericId] = new Proof[NumericId, ItemWithNumericId] {}
  ...
}
</code>```

At this point you don't really care what your service looks like, though f bounded polymorphism may later allow you for super fine grained control, as you can specialise implicits for specific implementations as well as create ambiguous proofs where you want to give compile time errors for things that aren't meant to be mixed together.

Title: Linking Types in Scala

Body:
I have a class of objects which either have one type of ID or another:

sealed trait ItemId
case class NumericId(id: Int) extends ItemId
case class StringId(id: String) extends ItemId

sealed trait Item {
  def id: ItemId
}

case class ItemWithNumericId(id: NumericId) extends Item
case class ItemWithStringId(id: StringId) extends Item

I'd like to create an interface for some sort of service which retrieves items:

trait ItemService[IdType <: ItemId, ItemType <: Item] {
  def get(id: IdType): ItemType
}

How do I link the ItemId type with the Item type to put a constraint on ItemServices to not allow something like:

class SillyItemService extends ItemService[NumericId, ItemWithStringId] {
  def get(id: NumericId): ItemWithStringId = ???
}

I've realised I can add generic types to the Item class:

sealed trait ItemId
case class NumericId(id: Int) extends ItemId
case class StringId(id: String) extends ItemId

sealed trait Item[Id <: ItemId] {
  def id: Id
}

case class ItemWithNumericId(id: NumericId) extends Item[NumericId]
case class ItemWithStringId(id: StringId) extends Item[StringId]

trait ItemService[IdType <: ItemId, ItemType <: Item[IdType]] {
  def get(id: IdType): ItemType
}

which is OK but It's super verbose. Ideally, the service would only have a single generic type.

Thanks very much for any answers/input.

Body:
Path dependant types are one option which is covered by the other answer, but for the purposes of flexibility I would personally go with implicits/context bounds in this case.

trait Proof[IdType <: ItemId, ItemType <: Item[IdType]]

trait ItemService[IdType <: ItemId, ItemType <: Item[IdType]] {
  def get(id: IdType)(implicit ev: Proof[IdType, ItemType])
}

You can also make trait an abstract class to hoist the declaration of the implicit proof, or whatever other party trick from the many available lets you sidestep the need to include the evidence on every method on the service.

Then I'd make a companion object for Proof and list the correlations feasible within your domain.

object Proof {
  implicit numericProof: Proof[NumericId, ItemWithNumericId] = new Proof[NumericId, ItemWithNumericId] {}
  ...
}

At this point you don't really care what your service looks like, though f bounded polymorphism may later allow you for super fine grained control, as you can specialise implicits for specific implementations as well as create ambiguous proofs where you want to give compile time errors for things that aren't meant to be mixed together.


Title: How to Melt single column in R

Body:
How to melt single column from T1 to  T2.

T1
Mar-17  T2
328  Mar-17 328
29.57  Mar-17 29.57
38.483  Mar-17 38.483
31.26  Mar-17 31.26
37.3  Mar-17 37.3
60.026  Mar-17 60.026
47.059  Mar-17 47.059
40.215  Mar-17 40.215
51.79  Mar-17 51.79
45.284  Mar-17 45.284
41.271  Mar-17 41.271
42.411  Mar-17 42.411

 and what id I should use to get output in T4 from T3

T3
Mar-17 Apr-17  T4
328 396  Mar-17 328
29.57 216.57  Mar-17 29.57
38.483 116.483  Mar-17 38.483
31.26 168.26  Mar-17 31.26
37.3 128.3  Mar-17 37.3
60.026 82.026  Mar-17 60.026
47.059 113.059  Mar-17 47.059
40.215 165.215  Mar-17 40.215
51.79 80.79  Mar-17 51.79
45.284 185.284  Mar-17 45.284
41.271 183.271  Mar-17 41.271
42.411 204.411  Mar-17 42.411
   Apr-17 396
   Apr-17 216.57
   Apr-17 116.483
   Apr-17 168.26
   Apr-17 128.3
   Apr-17 82.026
   Apr-17 113.059
   Apr-17 165.215
   Apr-17 80.79
   Apr-17 185.284
   Apr-17 183.271
   Apr-17 204.411

When I am using stack

T2 <- stack(T1)

it is giving error message

Error in rep.int(names(x), lengths(x)) : invalid 'times' value

Body:
I'm able to reproduce your error when I do not have column names (but rather have Mar-17 and Apr-17 as the first observation) so I am assuming that this is how your data is structured. If Mar-17 and Apr-17 are your column names, stack() should work.

In this case, you could set your variable names to be the values in the first row and then use stack() on everything excluding the first row:

names(T1) <- T1[1,]
T2 <- stack(T1[-1, , drop = F])

head(T2)
#       values    ind
#1     328 Mar-17
#2   29.57 Mar-17
#3  38.483 Mar-17
#4   31.26 Mar-17
#5    37.3 Mar-17
#6  60.026 Mar-17

names(T3) <- T3[1,]
T4 <- stack(T3[-1,])

head(T4)
#  values    ind
#1    328 Mar-17
#2  29.57 Mar-17
#3 38.483 Mar-17
#4  31.26 Mar-17
#5   37.3 Mar-17
#6 60.026 Mar-17

Data:

T1 <- structure(list(c("Mar-17", "328", "29.57", "38.483", "31.26",
          "37.3", "60.026", "47.059", "40.215", "51.79", "45.284", "41.271",
          "42.411")), class = "data.frame", row.names = c(NA, -13L))

T3 <- structure(list(c("Mar-17", "328", "29.57", "38.483", "31.26",
          "37.3", "60.026", "47.059", "40.215", "51.79", "45.284", "41.271",
          "42.411"), c("Apr-17", "396", "216.57", "116.483", "168.26",
          "128.3", "82.026", "113.059", "165.215", "80.79", "185.284",
          "183.271", "204.411")), row.names = c(NA, -13L), class = "data.frame")


问:
Map projection with longitude values 0-360
I am trying to plot a world map with longitude coordinates 0, 360. When i do so, either longitude points start from mid-map, or the projection of the map is thrown off. Here is an example:

```<code>ggplot() +
      geom_polygon(data = world_map, aes(x=long, y = lat, group=group)) +
      coord_fixed(1.3) + coord_equal(xlim = c(0, 360), ylim = c(-90, 90))
</code>```

I would like for the longitude to read 0 to 360 with the full map projection.

答:
You can use the "world2" map from the maps package, which has range [0,360]:
    ggplot() +
      geom_polygon(data = fortify(maps::map("world2",plot=FALSE,fill=TRUE)), aes(x=long, y = lat, group=group)) +
      coord_fixed(1.3) + coord_equal(xlim = c(0, 360), ylim = c(-90, 90))

Alternatively, if you want the freedom to have any shift of the map, maps v3.2.0 (just uploaded to CRAN) will allow you to do

```<code>myworld = maps::map(wrap=c(0,360), plot=FALSE, fill=TRUE)
    ggplot() +
      geom_polygon(data = fortify(maps::map("world2",plot=FALSE,fill=TRUE)), aes(x=long, y = lat, group=group)) +
      coord_fixed(1.3) + coord_equal(xlim = c(0, 360), ylim = c(-90, 90))
</code>```

Body:
I am trying to plot a world map with longitude coordinates 0, 360. When i do so, either longitude points start from mid-map, or the projection of the map is thrown off. Here is an example:

ggplot() +
      geom_polygon(data = world_map, aes(x=long, y = lat, group=group)) +
      coord_fixed(1.3) + coord_equal(xlim = c(0, 360), ylim = c(-90, 90))

I would like for the longitude to read 0 to 360 with the full map projection.

Body:
You can use the "world2" map from the maps package, which has range [0,360]:
    ggplot() +
      geom_polygon(data = fortify(maps::map("world2",plot=FALSE,fill=TRUE)), aes(x=long, y = lat, group=group)) +
      coord_fixed(1.3) + coord_equal(xlim = c(0, 360), ylim = c(-90, 90))

Alternatively, if you want the freedom to have any shift of the map, maps v3.2.0 (just uploaded to CRAN) will allow you to do

myworld = maps::map(wrap=c(0,360), plot=FALSE, fill=TRUE)
    ggplot() +
      geom_polygon(data = fortify(maps::map("world2",plot=FALSE,fill=TRUE)), aes(x=long, y = lat, group=group)) +
      coord_fixed(1.3) + coord_equal(xlim = c(0, 360), ylim = c(-90, 90))


问:
Alternative way to code without loops in R and reduce looping time
I have 2 datasets with text data. dataset1: clusters11 and dataset2: transactns11. I am using For loop in the code and it takes more time to process the data. So can anyone suggest how I can reduce the time taken. Please go through the below sample datasets and the code I am using.

```<code>dataset1: clusters11
cluster_id  clusters
1   A,B,C
2   A,B
3   B,C
4   C,D,E
5   B,C,D
6   D,E,F
7   A,D,F
8   B,G,H
9   B,C,F
10  G,H,M
11  A,H,N
12  B,C,M

dataset2: transactns11
unique_id   skills
221 A,B,C
223 A,B
224 B,C
225 C,D,E,F
226 B,C,D,M
227 D,E,F,A
228 A,D,F
229 B,G,H
230 B,C,F,A
231 G,H,M
232 A,H,N
233 B,C,M
234 A,B,C
235 A,B
236 B,C
237 C,D,E
238 B,C,D
239 D,E,F
</code>```

I want to have my output:out_df like this( which ever cluster in clusters11 file matches 100% with the skills in transactns11 should appear as comma separate by cluster_id, with the column name matching_values in the output.

```<code>unique_id   skills  matching_values
221 A,B,C   1,2,3
223 A,B 2
224 B,C 3
225 C,D,E,F 4,6
226 B,C,D,M 3,5,12
227 D,E,F,A 6,7
228 A,D,F   7
229 B,G,H   8
230 B,C,F,A 1,2,3,9
231 G,H,M   10
232 A,H,N   11
233 B,C,M   3,12
234 A,B,C   1,2,3
235 A,B 2
236 B,C 3
237 C,D,E   4
238 B,C,D   3,5
239 D,E,F   6
</code>```

For this I have code and it is working fine with me

```<code>  out_df <- data.frame(matrix(0, ncol = 3, nrow = nrow(transactns11)))
  colnames(out_df) <- c("unique_id", "skills", "matching_values")

  transactns11$skills=as.character(transactns11$skills)
  clusters11$clusters=as.character(clusters11$clusters)

  for(n in 1:nrow(transactns11)) {

    trans1 <- strsplit(transactns11$skills[n], ",")
    trans1
    transvect <- unlist(trans1)
    transvect

    matching_clusters <- c("")
    out_df$unique_id[n] <- as.character(transactns11$unique_id[n])
    out_df$skills[n] <- transactns11$skills[n]

    for(i in 1:nrow(clusters11)) {

      cluster1 <- strsplit(clusters11$clusters[i],",")
      cluster1
      clustervect <- unlist(cluster1)
      clustervect

      if(length(intersect(transvect,clustervect)) == length(clustervect)) {
        matching_clusters <- paste(matching_clusters, clusters11$cluster_id[i], sep = ",")
      }
    }
    matching_clusters <- substring(matching_clusters,2)
    out_df$matching_values[n] <- matching_clusters
  }
</code>```

Problem is that, the code takes more time when the recods of the 2 files are more like 10000 or 20000( time taken will be 15 to 20 hrs).
Can any one please suggest how I can avoid this loops or any other method I can follow to improve the code and reduce the huge time taken to process.
Thanks in Advance.
Regards,
hari

答:
I would use apply family of functions because it is base R:

```<code>clusters11 <- data.frame(cluster_id = seq(1:12),
                         clusters = c('A,B,C','A,B','B,C','C,D,E','B,C,D','D,E,F','A,D,F',
                                    'B,G,H','B,C,F','G,H,M','A,H,N','B,C,M'))
transactions11 <- data.frame(unique_id = c(221, seq(223,239, by = 1)),
                             skills = c('A,B,C', 'A,B', 'B,C', 'C,D,E,F', 'B,C,D,M',
                                        'D,E,F,A', 'A,D,F', 'B,G,H', 'B,C,F,A', 'G,H,M',
                                        'A,H,N', 'B,C,M', 'A,B,C', 'A,B', 'B,C', 'C,D,E',
                                        'B,C,D', 'D,E,F'))

s <- apply(sapply(as.character(clusters11$clusters), grepl,
           as.character(transactions11$skills)), 1, which)

d.list <- sapply(as.character(clusters11$clusters), strsplit, "\\,")

tf.tab  <- lapply(d.list, function(x) apply(sapply(x, function(x)
                  grepl(x, transactions11$skills)), 1, all, TRUE))

d.matrix <- do.call(cbind, tf.tab)

transactions11 <- data.frame(transactions11,
                   matching_values = apply(d.matrix, 1, function(x) paste(which(x == TRUE),
                                           collapse = ",")))

> transactions11
   unique_id  skills matching_values
1        221   A,B,C           1,2,3
2        223     A,B               2
3        224     B,C               3
4        225 C,D,E,F             4,6
5        226 B,C,D,M          3,5,12
6        227 D,E,F,A             6,7
7        228   A,D,F               7
8        229   B,G,H               8
9        230 B,C,F,A         1,2,3,9
10       231   G,H,M              10
11       232   A,H,N              11
12       233   B,C,M            3,12
13       234   A,B,C           1,2,3
14       235     A,B               2
15       236     B,C               3
16       237   C,D,E               4
17       238   B,C,D             3,5
18       239   D,E,F               6
</code>```

This should work much faster than a loop.

Body:
I have 2 datasets with text data. dataset1: clusters11 and dataset2: transactns11. I am using For loop in the code and it takes more time to process the data. So can anyone suggest how I can reduce the time taken. Please go through the below sample datasets and the code I am using.

dataset1: clusters11
cluster_id  clusters
1   A,B,C
2   A,B
3   B,C
4   C,D,E
5   B,C,D
6   D,E,F
7   A,D,F
8   B,G,H
9   B,C,F
10  G,H,M
11  A,H,N
12  B,C,M

dataset2: transactns11
unique_id   skills
221 A,B,C
223 A,B
224 B,C
225 C,D,E,F
226 B,C,D,M
227 D,E,F,A
228 A,D,F
229 B,G,H
230 B,C,F,A
231 G,H,M
232 A,H,N
233 B,C,M
234 A,B,C
235 A,B
236 B,C
237 C,D,E
238 B,C,D
239 D,E,F

I want to have my output:out_df like this( which ever cluster in clusters11 file matches 100% with the skills in transactns11 should appear as comma separate by cluster_id, with the column name matching_values in the output.

unique_id   skills  matching_values
221 A,B,C   1,2,3
223 A,B 2
224 B,C 3
225 C,D,E,F 4,6
226 B,C,D,M 3,5,12
227 D,E,F,A 6,7
228 A,D,F   7
229 B,G,H   8
230 B,C,F,A 1,2,3,9
231 G,H,M   10
232 A,H,N   11
233 B,C,M   3,12
234 A,B,C   1,2,3
235 A,B 2
236 B,C 3
237 C,D,E   4
238 B,C,D   3,5
239 D,E,F   6

For this I have code and it is working fine with me

  out_df <- data.frame(matrix(0, ncol = 3, nrow = nrow(transactns11)))
  colnames(out_df) <- c("unique_id", "skills", "matching_values")

  transactns11$skills=as.character(transactns11$skills)
  clusters11$clusters=as.character(clusters11$clusters)

  for(n in 1:nrow(transactns11)) {

    trans1 <- strsplit(transactns11$skills[n], ",")
    trans1
    transvect <- unlist(trans1)
    transvect

    matching_clusters <- c("")
    out_df$unique_id[n] <- as.character(transactns11$unique_id[n])
    out_df$skills[n] <- transactns11$skills[n]

    for(i in 1:nrow(clusters11)) {

      cluster1 <- strsplit(clusters11$clusters[i],",")
      cluster1
      clustervect <- unlist(cluster1)
      clustervect

      if(length(intersect(transvect,clustervect)) == length(clustervect)) {
        matching_clusters <- paste(matching_clusters, clusters11$cluster_id[i], sep = ",")
      }
    }
    matching_clusters <- substring(matching_clusters,2)
    out_df$matching_values[n] <- matching_clusters
  }

Problem is that, the code takes more time when the recods of the 2 files are more like 10000 or 20000( time taken will be 15 to 20 hrs).
Can any one please suggest how I can avoid this loops or any other method I can follow to improve the code and reduce the huge time taken to process.
Thanks in Advance.
Regards,
hari

Body:
I would use apply family of functions because it is base R:

clusters11 <- data.frame(cluster_id = seq(1:12),
                         clusters = c('A,B,C','A,B','B,C','C,D,E','B,C,D','D,E,F','A,D,F',
                                    'B,G,H','B,C,F','G,H,M','A,H,N','B,C,M'))
transactions11 <- data.frame(unique_id = c(221, seq(223,239, by = 1)),
                             skills = c('A,B,C', 'A,B', 'B,C', 'C,D,E,F', 'B,C,D,M',
                                        'D,E,F,A', 'A,D,F', 'B,G,H', 'B,C,F,A', 'G,H,M',
                                        'A,H,N', 'B,C,M', 'A,B,C', 'A,B', 'B,C', 'C,D,E',
                                        'B,C,D', 'D,E,F'))

s <- apply(sapply(as.character(clusters11$clusters), grepl,
           as.character(transactions11$skills)), 1, which)

d.list <- sapply(as.character(clusters11$clusters), strsplit, "\\,")

tf.tab  <- lapply(d.list, function(x) apply(sapply(x, function(x)
                  grepl(x, transactions11$skills)), 1, all, TRUE))

d.matrix <- do.call(cbind, tf.tab)

transactions11 <- data.frame(transactions11,
                   matching_values = apply(d.matrix, 1, function(x) paste(which(x == TRUE),
                                           collapse = ",")))

> transactions11
   unique_id  skills matching_values
1        221   A,B,C           1,2,3
2        223     A,B               2
3        224     B,C               3
4        225 C,D,E,F             4,6
5        226 B,C,D,M          3,5,12
6        227 D,E,F,A             6,7
7        228   A,D,F               7
8        229   B,G,H               8
9        230 B,C,F,A         1,2,3,9
10       231   G,H,M              10
11       232   A,H,N              11
12       233   B,C,M            3,12
13       234   A,B,C           1,2,3
14       235     A,B               2
15       236     B,C               3
16       237   C,D,E               4
17       238   B,C,D             3,5
18       239   D,E,F               6

This should work much faster than a loop.


问:
Trouble accessing control using JQuery
How do I use JQuery on a Web Forms Master Page to access the value of an HTML text input control, which resides in an Ajax Control Toolkit accordion pane, which resides on a Web Forms Content Page?

I have a Master Page called Site.Master and the Content Page is goes into a placeholder called MainContent. A few visuals:

Site.Master:

```<code><body>
  <form runat="server">
    <asp:ScriptManager runat="server">
      <scripts>...</scripts>
    </asp:ScriptManager>

    <div class="container body-content">
      <asp:ContentPlaceHolder ID="MainContent" runat="server">
    </asp:ContentPlaceHolder>
...
</code>```

Here is my accordion (which lives in a content page (Default.aspx); the content page lives in the MainContent placeholder above):

```<code><ajaxToolkit:Accordion
    ID="Accordion1"
    runat="server"
    HeaderCssClass="accordionHeader"
    HeaderSelectedCssClass="accordionHeaderSelected"
    max-height="300px"
    ContentCssClass="accordionContent"
    AutoSize="None"
    FadeTransitions="true"
    TransitionDuration="250"
    FramesPerSecond="40"
    EnableViewState="true"
    RequireOpenedPane="false"
    SuppressHeaderPostbacks="true">
    <Panes>
...
        <ajaxToolkit:AccordionPane
            ID="AccordionPane1"
            runat="server">
            <Header>
                Use a list
            </Header>
            <Content>
                <asp:UpdatePanel ID="UpdatePanel3" runat="server">
                    <ContentTemplate>
                        <div class="row">
                            <div class="col-lg-6">
                                <div class="file-upload-container">
                                    <div class="input-group">
                                        ...
                                        <input
                                            class="form-control"
                                            id="Text03"
                                            placeholder="Browse or enter a file"
                                            runat="server"
                                            style="border: none"
                                            type="text" />
                                    </div>
                                    ...
                                </div>
                            </div>
                        </div>
                    </ContentTemplate>
                </asp:UpdatePanel>
            </Content>
        </ajaxToolkit:AccordionPane>
    </Panes>
</ajaxToolkit:Accordion>
</code>```

Here is my JQuery that takes the text result of an HTML file input and copies it into the appropriate HTML text input (Text03, above):

```<code><script type="text/javascript">
    $(document).ready(function () {
        $("#file-upload-button").change(function () {
            var fileName = $(this).val().split("\\").pop();
            var txtBoxID= <%# MainContent.FindControl("Text2").ClientID %>;
            $(txtBoxID).val(fileName);
        });
        $("#file-upload-button2").change(function () {
            var fileName = $(this).val().split("\\").pop();
            var txtBoxID= <%# MainContent.FindControl("Text03").ClientID %>;
            $(txtBoxID).val(fileName);
        });
        ...
    });
</script>
</code>```

It works fine with only the "Text2" function. But when I try to add the "Text03" function, it gives me this error, with line 30 being highlighted:

```<code>Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 28:             $("#file-upload-button2").change(function () {
Line 29:                 var fileName = $(this).val().split("\\").pop();
Line 30:                 var txtBoxID= <%# MainContent.FindControl("Text03").ClientID %>;
Line 31:                 $(txtBoxID).val(fileName);
Line 32:             });
</code>```

Is my control somehow not existing? Is there some kind of binding issue? I would appreciate any advice, I've been throwing stones at this for a whole day now. Thanks!

答: You're not going to be able to refer to it directly in code because it is inside a ContentTemplate.  Try adding it as an indicator class instead, like class="form-control text03" and then refer to it via $(".text03").val(fileName); instead.

Title: Trouble accessing control using JQuery

Body:
How do I use JQuery on a Web Forms Master Page to access the value of an HTML text input control, which resides in an Ajax Control Toolkit accordion pane, which resides on a Web Forms Content Page?

I have a Master Page called Site.Master and the Content Page is goes into a placeholder called MainContent. A few visuals:

Site.Master:

  <form runat="server">
    <asp:ScriptManager runat="server">

    </asp:ScriptManager>

      <asp:ContentPlaceHolder ID="MainContent" runat="server">
    </asp:ContentPlaceHolder>
...

Here is my accordion (which lives in a content page (Default.aspx); the content page lives in the MainContent placeholder above):

<ajaxToolkit:Accordion
    ID="Accordion1"
    runat="server"
    HeaderCssClass="accordionHeader"
    HeaderSelectedCssClass="accordionHeaderSelected"
    max-height="300px"
    ContentCssClass="accordionContent"
    AutoSize="None"
    FadeTransitions="true"
    TransitionDuration="250"
    FramesPerSecond="40"
    EnableViewState="true"
    RequireOpenedPane="false"
    SuppressHeaderPostbacks="true">
    <Panes>
...
        <ajaxToolkit:AccordionPane
            ID="AccordionPane1"
            runat="server">

                Use a list

            <Content>
                <asp:UpdatePanel ID="UpdatePanel3" runat="server">
                    <ContentTemplate>

                                        ...
                                        <input
                                            class="form-control"
                                            id="Text03"
                                            placeholder="Browse or enter a file"
                                            runat="server"
                                            style="border: none"
                                            type="text" />

                                    ...

                    </ContentTemplate>
                </asp:UpdatePanel>
            </Content>
        </ajaxToolkit:AccordionPane>
    </Panes>
</ajaxToolkit:Accordion>

Here is my JQuery that takes the text result of an HTML file input and copies it into the appropriate HTML text input (Text03, above):

It works fine with only the "Text2" function. But when I try to add the "Text03" function, it gives me this error, with line 30 being highlighted:

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 28:             $("#file-upload-button2").change(function () {
Line 29:                 var fileName = $(this).val().split("\\").pop();
Line 30:                 var txtBoxID= <%# MainContent.FindControl("Text03").ClientID %>;
Line 31:                 $(txtBoxID).val(fileName);
Line 32:             });

Is my control somehow not existing? Is there some kind of binding issue? I would appreciate any advice, I've been throwing stones at this for a whole day now. Thanks!


问:
C# deploy, problems with folders
I've finished my app and used the visual studio installer to create a package with all the files that aplication need.

But the problem is that, if the user install the program in ProgramFiles directory, it won't start because he needs admin Rigths (This because the program needs sqlServerCe).

How i can avoid this situation?

Another question, if the program has the sqlServer and sqlServerCe in prerequesites it needs the sqlServerCe.dll?

Thanks.

答:
If I'm not mistaken, I believe it is because you need an application manifest. You can specify privilege information this way.

http://msdn.microsoft.com/en-us/library/bb756929.aspx

Title: C# deploy, problems with folders


问:
is there any way for bulk ignore in svn like git ignore file?
I am using SVN for source version system. I use AnkhSVN plugin for Visual Studio 2015 for integrating SVN with the IDE. Now I need a file like git ignore file in svn to bulk ignore. Is there any way?</p>

答:
I want to recommend you to use Visual SVN ans Tortoise SVN, once you have installed this tools Visual SVN call Tortoise SVN when you need to do a commit.

Also you can ignore path and file, but you have to do a commit of this ignore and after you have to do an update to ignore this files.

This is once you have installed Visual SVN:

And this is you can ignore files:

And this is Tortoise when you try to do a Commit:

I spec this help you.


问:
has_many association, store multiple associations in one column
I have two tables, users and roles. What I am trying to do is to create simple association between them, that users can have multiple roles.

In database it should look like that:

Role:

```<code> id | name
-----------
  1 | ADMIN
  2 | USER
</code>```

User

```<code>id | email         | username | roles
-------------------------------------
 1  test@gmail.com    test      [1,2]
</code>```

So far, I came with following code:

```<code>def change do
    create table(:users) do
      add :email, :string
      add :username, :string
      add :roles, references(:roles)
    end
  end

schema "users" do
    field :email, :string
    field :username, :string
    has_many :roles, TimesheetServer.Role

    timestamps()
  end

  def changeset(struct, params \\ %{}) do
     struct
      |> cast(params, [:email, :username])
      |> validate_required([:email, :username])
  end

def change do
    create table(:roles) do
      add :name, :string
      timestamps()
    end
  end

schema "roles" do
    field :name, :string
    belongs_to :users, TimesheetServer.User
    timestamps()
  end
</code>```

Then I am trying to seed database like that:

```<code>User.changeset(
    %User{},%{email: "test@gmail.com", username: "test", roles: [
        %Role{name: "ADMIN"},
        %Role{name: "USER"}
    ]})

    |> Repo.insert
</code>```

Unfortunately, that does not create list of roles in user table, and does not save roles in roles table.

Any help or tips will be much appreciated!

答:
As mentioned in the comment, the above relation has to be defined as many_to_many. To achieve that, there are actually two ways.

First one is to define role schema as embedded_schema, in that case it will be embedded inside the parent (user). That means no db table will be created for role schema.

Second option is to join them through association table. That can look as follows:

migration:

```<code>def change do
 create table(:users) do
   add :email, :string
   add :username, :string
 end

 create table(:roles) do
   add :name, :string, null: false
 end

 create table(:users_roles, primary_key: false) do
  add :user_id, references(:users, on_delete: :delete_all)
  add :role_id, references(:roles, on_delete: :delete_all)
 end

 create unique_index(:users_roles, [:user_id, :role_id])
end
</code>```

user schema:

```<code> schema "users" do
  field :email, :string
  field :username, :string
  many_to_many :roles, TimesheetServer.Role, join_through: "users_roles"
 end

  def changeset(struct, params \\ %{}) do
   struct
    |> cast(params, [:email, :username])
    |> validate_required([:email, :username])
  end
end
</code>```

role schema:

```<code>   schema "roles" do
     field :name, :string
     many_to_many :users, TimesheetServer.User, join_through: "users_roles"
   end

   def changeset(struct, params \\ %{}) do
     struct
     |> cast(params, [:name])
     |> validate_required([:name])
   end
</code>```

Now the association can be build in following way:

```<code>    user = Repo.get!(User, user_id) |> Repo.preload(:roles)
    role = Repo.get!(Role, role_id)

    user_changeset = Changeset.change(user)
                         |> Changeset.put_assoc(:roles, [role | user.roles])
</code>```

That will result in having three tables:

User:

```<code>id | email         | username |
-------------------------------
 1  test@gmail.com    test
</code>```

Role:

```<code> id | name
-----------
  1 | ADMIN
  2 | USER
</code>```

users_roles:

```<code>user_id | role_id
------------------
      1 | 1
------------------
      1 | 2
</code>```

Body:
I have two tables, users and roles. What I am trying to do is to create simple association between them, that users can have multiple roles.

In database it should look like that:

Role:

 id | name
-----------
  1 | ADMIN
  2 | USER

User

id | email         | username | roles
-------------------------------------
 1  test@gmail.com    test      [1,2]

So far, I came with following code:

def change do
    create table(:users) do
      add :email, :string
      add :username, :string
      add :roles, references(:roles)
    end
  end

schema "users" do
    field :email, :string
    field :username, :string
    has_many :roles, TimesheetServer.Role

    timestamps()
  end

  def changeset(struct, params \\ %{}) do
     struct
      |> cast(params, [:email, :username])
      |> validate_required([:email, :username])
  end

def change do
    create table(:roles) do
      add :name, :string
      timestamps()
    end
  end

schema "roles" do
    field :name, :string
    belongs_to :users, TimesheetServer.User
    timestamps()
  end

Then I am trying to seed database like that:

User.changeset(
    %User{},%{email: "test@gmail.com", username: "test", roles: [
        %Role{name: "ADMIN"},
        %Role{name: "USER"}
    ]})

    |> Repo.insert

Unfortunately, that does not create list of roles in user table, and does not save roles in roles table.

Any help or tips will be much appreciated!

Body:
As mentioned in the comment, the above relation has to be defined as many_to_many. To achieve that, there are actually two ways.

First one is to define role schema as embedded_schema, in that case it will be embedded inside the parent (user). That means no db table will be created for role schema.

Second option is to join them through association table. That can look as follows:

migration:

def change do
 create table(:users) do
   add :email, :string
   add :username, :string
 end

 create table(:roles) do
   add :name, :string, null: false
 end

 create table(:users_roles, primary_key: false) do
  add :user_id, references(:users, on_delete: :delete_all)
  add :role_id, references(:roles, on_delete: :delete_all)
 end

 create unique_index(:users_roles, [:user_id, :role_id])
end

user schema:

 schema "users" do
  field :email, :string
  field :username, :string
  many_to_many :roles, TimesheetServer.Role, join_through: "users_roles"
 end

  def changeset(struct, params \\ %{}) do
   struct
    |> cast(params, [:email, :username])
    |> validate_required([:email, :username])
  end
end

role schema:

   schema "roles" do
     field :name, :string
     many_to_many :users, TimesheetServer.User, join_through: "users_roles"
   end

   def changeset(struct, params \\ %{}) do
     struct
     |> cast(params, [:name])
     |> validate_required([:name])
   end

Now the association can be build in following way:

    user = Repo.get!(User, user_id) |> Repo.preload(:roles)
    role = Repo.get!(Role, role_id)

    user_changeset = Changeset.change(user)
                         |> Changeset.put_assoc(:roles, [role | user.roles])

That will result in having three tables:

User:

id | email         | username |
-------------------------------
 1  test@gmail.com    test

Role:

 id | name
-----------
  1 | ADMIN
  2 | USER

users_roles:

user_id | role_id
------------------
      1 | 1
------------------
      1 | 2


问:
Database design for kids chore schema
I'm wondering about best practise to keep a database as tidy as possible. The database is postgresql accessed by express.js/node. It is for a kids chores app that I'm working on and it has the following schema:

```<code>CHILDREN
    id
    name
    points
    rate
    created_at
    updated_at
    user_id

TASKS
    id
    description
    value
    days (boolean array - eg. [0,0,0,0,0,0,0])
    periods (boolean array - eg. [0,0])
    created_at
    updated_at
    user_id

FINISHED TASKS
    id
    task_id
    child_id
    completed (boolean)
    created_at
    updated_at
    period (boolean)
    day (int (0-6))
</code>```

For every individual finished task a row is created in the database. With only 400 children doing chores in there, there are already around 800 rows being added each day to the FINISHED TASKS table.

I have two questions:

Is there a  more efficient way of storing FINISHED TASKS either for a full day per child or similar?

With scale I'm going to end up with potentially tens of thousands of rows per day - is this  acceptable for an app like this?

答:
Having a child table related to a task table through an intermediate bridge table is the common way of doing this.  My experience with large hospital applications is that once tables start to have millions of rows and performance is degrading, the applications typically archive the "finished tasks" into a separate archive table.  You would maybe end up with two tables, one called 'active tasks' that contains tasks where 'completed' is false and once the task is finished, the row is moved into the archived 'finished tasks' table.

Depending on how much effort you want to put into future proofing the application, this could be done now to prevent having to revisit this.

Title: Database design for kids chore schema

Body:
I'm wondering about best practise to keep a database as tidy as possible. The database is postgresql accessed by express.js/node. It is for a kids chores app that I'm working on and it has the following schema:

CHILDREN
    id
    name
    points
    rate
    created_at
    updated_at
    user_id

TASKS
    id
    description
    value
    days (boolean array - eg. [0,0,0,0,0,0,0])
    periods (boolean array - eg. [0,0])
    created_at
    updated_at
    user_id

FINISHED TASKS
    id
    task_id
    child_id
    completed (boolean)
    created_at
    updated_at
    period (boolean)
    day (int (0-6))

For every individual finished task a row is created in the database. With only 400 children doing chores in there, there are already around 800 rows being added each day to the FINISHED TASKS table.

I have two questions:

Is there a  more efficient way of storing FINISHED TASKS either for a full day per child or similar?

With scale I'm going to end up with potentially tens of thousands of rows per day - is this  acceptable for an app like this?


答:
As far I Understand, You call HelperToTables.ContentText.ContentIdValue.GetInfoContentInfo.GetColBool(Model.HiddenId) this function many times from the view; Now you want to store the result in any variable then use the variable all the places.

If it is then try this:

```<code>@{
    var variableName = HelperToTables.ContentText.ContentIdValue.GetInfoContentInfo.GetColBool(Model.HiddenId);
}

@if(variableName == true)
{
   // do your stuff
}
else if(variableName == false)
{
    // do your stuff
}
</code>```

Title: Keep the method somewhere on the view page, instead of calling it several times

Body:
It's such that I have a method that I call 7 times and I would like the code to be made nicer and at the same time easy to read and understand.

How can I hold it somewhere?

Just pt, I'll do like this.

@if(HelperToTables.ContentText.ContentIdValue.GetInfoContentInfo.GetColBool(Model.HiddenId) == true)
     {
         @Html.Raw("col-md-8");
     }
     else if(HelperToTables.ContentText.ContentIdValue.GetInfoContentInfo.GetColBool(Model.HiddenId) == false)
     {
         @Html.Raw("col-md-12");
     }

Basically, I think that you could do this here but it does not work in any way.

Note that I do it for example on the index.cshtml page.

Body:
As far I Understand, You call HelperToTables.ContentText.ContentIdValue.GetInfoContentInfo.GetColBool(Model.HiddenId) this function many times from the view; Now you want to store the result in any variable then use the variable all the places.

If it is then try this:

@{
    var variableName = HelperToTables.ContentText.ContentIdValue.GetInfoContentInfo.GetColBool(Model.HiddenId);
}

@if(variableName == true)
{
   // do your stuff
}
else if(variableName == false)
{
    // do your stuff
}


问:
Sum multiple BigDecimals to a Map<String, BigDecimal>
I'm trying to sum multiple BigDecimals from a List. Currently, I'm using two streams, but would like to have only one stream if possible. I'm unsure how I can rewrite below in a performant way.

```<code>BigDecimal totalCharges = tableRowDataList.stream()
            .map(el -> el.getSums().getCharges())
            .reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal totalFees = tableRowDataList.stream()
            .map(el -> el.getSums().getFees())
            .reduce(BigDecimal.ZERO, BigDecimal::add);
</code>```

As you can see, the streams are doing basically the same, only the call to getCharges/getFees differ.

What is the best way to get a resulting Map<String, BigDecimal> from above? (Where key would be charges/fees)

答:
Try StreamEx:

```<code>Optional<Entry<BigDecimal, BigDecimal>> res = StreamEx.of(tableRowDataList)
            .map(e -> e.getSums())
            .mapToEntry(s -> s.getCharges(), s -> s.getFees())
            .reduce((a, b) -> {
                a.getKey().add(b.getKey());
                b.getKey().add(b.getValue());
                return a;
            });
</code>```

I think we should try to avoid creating those tiny helper classes. Otherwise, you will run into the trouble of maintaining tens/hundreds tiny classes.

Body:
I'm trying to sum multiple BigDecimals from a List. Currently, I'm using two streams, but would like to have only one stream if possible. I'm unsure how I can rewrite below in a performant way.

BigDecimal totalCharges = tableRowDataList.stream()
            .map(el -> el.getSums().getCharges())
            .reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal totalFees = tableRowDataList.stream()
            .map(el -> el.getSums().getFees())
            .reduce(BigDecimal.ZERO, BigDecimal::add);

As you can see, the streams are doing basically the same, only the call to getCharges/getFees differ.

What is the best way to get a resulting Map<String, BigDecimal> from above? (Where key would be charges/fees)

Body:
Try StreamEx:

Optional<Entry<BigDecimal, BigDecimal>> res = StreamEx.of(tableRowDataList)
            .map(e -> e.getSums())
            .mapToEntry(s -> s.getCharges(), s -> s.getFees())
            .reduce((a, b) -> {
                a.getKey().add(b.getKey());
                b.getKey().add(b.getValue());
                return a;
            });

I think we should try to avoid creating those tiny helper classes. Otherwise, you will run into the trouble of maintaining tens/hundreds tiny classes.


答:
```<code>library(janitor)

mydf %>%
  clean_names()
</code>```

The clean_names function in janitor package will remove any characters that are not lower-case letters, underscores, or numbers. It may convert the periods to underscores though, so if your goal is to get rid of that character completely the gsub solution will work best.

Title: Remove dots from column names

Body:
I have a dataframe with several columns and I want to remove the dots on the column name. The data is as follows:

structure(list(JulDay = c(260.0208435, 260.0416565, 260.0625,
260.0833435, 260.1041565, 260.125), i.46.j.8.k.1 = c(17.99964905,
18.5903511, 22.93223381, 25.75687981, 25.78559113, 25.8169651
), i.47.j.8.k.1 = c(18.36571884, 21.15985107, 24.80698013, 25.75730324,
25.78366089, 25.65381622), i.48.j.8.k.1 = c(18.45543289, 22.02331543,
24.99463654, 25.5712738, 25.64232635, 25.66119385), i.46.j.8.k.2 = c(17.99798965,
18.60897827, 22.95389748, 25.75719261, 25.78653336, 25.81692505
), i.47.j.8.k.2 = c(18.36762619, 21.17233467, 24.82248497, 25.75767899,
25.7840023, 25.64115906), i.48.j.8.k.2 = c(18.45938683, 22.04619026,
24.9859066, 25.56440544, 25.63998032, 25.66089439), i.46.j.8.k.3 = c(17.99430084,
17.92090797, 19.67384911, 21.70389938, 23.67287827, 24.04380417
), i.47.j.8.k.3 = c(18.36631203, 19.82550049, 21.42166328, 23.76496887,
24.87460899, 25.41026688), i.48.j.8.k.3 = c(18.44684792, 20.60981369,
22.68632317, 24.1877079, 25.12503052, 24.99880028), i.46.j.8.k.4 = c(17.98368073,
17.92047691, 18.11532974, 18.67082596, 20.23210907, 21.7181263
), i.47.j.8.k.4 = c(18.33089066, 18.41581535, 18.53464127, 19.18972206,
20.14752388, 20.11002922), i.48.j.8.k.4 = c(18.21522522, 18.52231598,
19.21397209, 19.58755302, 20.11982536, 21.28104591)), .Names = c("JulDay",
"i.46.j.8.k.1", "i.47.j.8.k.1", "i.48.j.8.k.1", "i.46.j.8.k.2",
"i.47.j.8.k.2", "i.48.j.8.k.2", "i.46.j.8.k.3", "i.47.j.8.k.3",
"i.48.j.8.k.3", "i.46.j.8.k.4", "i.47.j.8.k.4", "i.48.j.8.k.4"
), row.names = c(NA, 6L), class = "data.frame")

Can anyone let me know how to remove the dots from column names ?

I want something like i46j8k1, i47j8k1, i48j8k1.

For this simple data set I could manually replace the name, but I need to do this for several data sets.

Body:
library(janitor)

mydf %>%
  clean_names()

The clean_names function in janitor package will remove any characters that are not lower-case letters, underscores, or numbers. It may convert the periods to underscores though, so if your goal is to get rid of that character completely the gsub solution will work best.


问:
How do you generate a random number in C#?
I would like to generate a random floating point number between 2 values.  What is the best way to do this in C#?</p>

答:
```<code>// generate a random number starting with 5 and less than 15
Random r = new Random();
int num = r.Next(5, 15);
</code>```

For doubles you can replace Next with NextDouble

OwnerDisplayName: Lane

LastEditorDisplayName: MrValdez

Body:
// generate a random number starting with 5 and less than 15
Random r = new Random();
int num = r.Next(5, 15);

For doubles you can replace Next with NextDouble

OwnerDisplayName: Ryan Farley


问:
Dynamically building table rows, where in user can type in data using angular JS
When someone select a date range from a dropdown, for example

1/1/2017 - 1/7/2017

I want to paint

```<code>Date        Column1 Column2 Column3

1/1/2017    ----    ----    ----
1/2/2017
1/3/2017
1/4/2017
1/5/2017
1/6/2017
1/7/2017    ----    ----    ----
</code>```

The user will type in the text boxes (please assume "----" as text
  boxes).

Similarly, when the date range gets changed, for example

2/2/2017 - 2/9/2017

```<code>Date        Column1 Column2 Column3

2/2/2017    ----    ----    ----
2/3/2017
2/4/2017
2/5/2017
2/6/2017
2/7/2017
2/8/2017
2/9/2017   ----     ----    ----
</code>```

I have not used angular much,beginner here, i can use limitTo filter to limit 7 rows, any sample approaches?

答:
The ngRepeat is your friend here...

https://www.w3schools.com/angular/angular_tables.asp

Take a look what happens in the ```</code>-tag if you type in one of the inputs. Will this work for you?</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-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<div ng-app="myApp" ng-controller="customersCtrl">

<table>
  <tr ng-repeat="x in dateRange">
    <td>{{ x.date }}</td>
    <td>{{ x.name }}</td>
    <td><input type="text" ng-model="x.input"></td>
    <td><input type="text" ng-model="x.input2"></td>
  </tr>
</table>

```{{ dateRange | json }}```
</div>

<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
    $scope.dateRange = [
      {
        date: '2/2/2017',
        name: 'Wonderfull Day'
      },
      {
        date: '2/3/2017',
        name: 'Bad Day'
      },
      {
        date: '2/4/2017',
        name: 'Better Day'
      }
    ];
});
</script></code>```

Body:
When someone select a date range from a dropdown, for example

1/1/2017 - 1/7/2017

I want to paint

Date        Column1 Column2 Column3

1/1/2017    ----    ----    ----
1/2/2017
1/3/2017
1/4/2017
1/5/2017
1/6/2017
1/7/2017    ----    ----    ----

The user will type in the text boxes (please assume "----" as text
  boxes).

Similarly, when the date range gets changed, for example

2/2/2017 - 2/9/2017

Date        Column1 Column2 Column3

2/2/2017    ----    ----    ----
2/3/2017
2/4/2017
2/5/2017
2/6/2017
2/7/2017
2/8/2017
2/9/2017   ----     ----    ----

I have not used angular much,beginner here, i can use limitTo filter to limit 7 rows, any sample approaches?

Body:
The ngRepeat is your friend here...

https://www.w3schools.com/angular/angular_tables.asp

Take a look what happens in the <pre>-tag if you type in one of the inputs. Will this work for you?

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<div ng-app="myApp" ng-controller="customersCtrl">

<table>
  <tr ng-repeat="x in dateRange">
    <td>{{ x.date }}</td>
    <td>{{ x.name }}</td>
    <td><input type="text" ng-model="x.input"></td>
    <td><input type="text" ng-model="x.input2"></td>
  </tr>
</table>

<pre>{{ dateRange | json }}</pre>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
    $scope.dateRange = [
      {
        date: '2/2/2017',
        name: 'Wonderfull Day'
      },
      {
        date: '2/3/2017',
        name: 'Bad Day'
      },
      {
        date: '2/4/2017',
        name: 'Better Day'
      }
    ];
});
</script>