问:
Scala - have List of String, must split by comma, and put into Map
I have a List of the form: ("string,num", "string,num", ...)

I have found solutions online for how to do this with a single string, but have not been able to adapt it to a list of strings.

Also, numerical values should be cast to Int/Double before being mapped.

I would appreciate any help.

答:
This is a perfect job for a fold

```<code>// Your input
val lines = List("a,1", "b,2", "gretzky,99", "tyler,11")

// Fold over the lines, and insert them into a map
val map = lines.foldLeft(Map.empty[String, Int]) {
  case (map, line) =>

    // Split the line on the comma and separate the two parts
    val Array(string, num) = line.split(",")

    // Add new entry to the map
    map + (string -> num.toInt)
}

println(map)
</code>```

Output:

```<code>Map(a -> 1, b -> 2, gretzky -> 99, tyler -> 11)
</code>```

Body:
This is a perfect job for a fold

// Your input
val lines = List("a,1", "b,2", "gretzky,99", "tyler,11")

// Fold over the lines, and insert them into a map
val map = lines.foldLeft(Map.empty[String, Int]) {
  case (map, line) =>

    // Split the line on the comma and separate the two parts
    val Array(string, num) = line.split(",")

    // Add new entry to the map
    map + (string -> num.toInt)
}

println(map)

Output:

Map(a -> 1, b -> 2, gretzky -> 99, tyler -> 11)


来源: stackexchange

问:
Continue on Null Value of Result (Nodejs, Puppeteer)
I'm just starting to play around with Puppeteer (Headless Chrome) and Nodejs. I'm scraping some test sites, and things work great when all the values are present, but if the value is missing I get an error like:

Cannot read property 'src' of null  (so in the code below, the first two passes might have all values, but the third pass, there is no picture, so it just errors out).

Before I was using if(!picture) continue; but I think it's not working now because of the for loop.

Any help would be greatly appreciated, thanks!

```<code>for (let i = 1; i <= 3; i++) {
//...Getting to correct page and scraping it three times
  const result = await page.evaluate(() => {
      let title = document.querySelector('h1').innerText;
      let article = document.querySelector('.c-entry-content').innerText;
      let picture = document.querySelector('.c-picture img').src;

      if (!document.querySelector('.c-picture img').src) {
        let picture = 'No Link';     }  //throws error

      let source = "The Verge";
      let categories = "Tech";

      if (!picture)
                continue;  //throws error

      return {
        title,
        article,
        picture,
        source,
        categories
      }
    });
}
</code>```

答:
```<code>let picture = document.querySelector('.c-picture img').src;

if (!document.querySelector('.c-picture img').src) {
    let picture = 'No Link';     }  //throws error
</code>```

If there is no picture, then document.querySelector() returns null, which does not have a src property. You need to check that your query found an element before trying to read the src property.

Moving the null-check to the top of the function has the added benefit of saving unnecessary calculations when you are just going to bail out anyway.

```<code>async function scrape3() {
  // ...
  for (let i = 1; i <= 3; i++) {
  //...Getting to correct page and scraping it three times
    const result = await page.evaluate(() => {
        const pictureElement = document.querySelector('.c-picture img');

        if (!pictureElement) return null;

        const picture = pictureElement.src;
        const title = document.querySelector('h1').innerText;
        const article = document.querySelector('.c-entry-content').innerText;

        const source = "The Verge";
        const categories = "Tech";

        return {
          title,
          article,
          picture,
          source,
          categories
        }
    });

    if (!result) continue;

    // ... do stuff with result
  }
</code>```

Answering comment question: "Is there a way just to skip anything blank, and return the rest?"

Yes. You just need to check the existence of each element that could be missing before trying to read a property off of it. In this case we can omit the early return since you're always interested in all the results.

```<code>async function scrape3() {
  // ...
  for (let i = 1; i <= 3; i++) {
    const result = await page.evaluate(() => {
        const img = document.querySelector('.c-picture img');
        const h1 = document.querySelector('h1');
        const content = document.querySelector('.c-entry-content');

        const picture = img ? img.src : '';
        const title = h1 ? h1.innerText : '';
        const article = content ? content.innerText : '';
        const source = "The Verge";
        const categories = "Tech";

        return {
          title,
          article,
          picture,
          source,
          categories
        }
    });
    // ...
  }
}
</code>```

Further thoughts

Since I'm still on this question, let me take this one step further, and refactor it a bit with some higher level techniques you might be interested in. Not sure if this is exactly what you are after, but it should give you some ideas about writing more maintainable code.

```<code>// Generic reusable helper to return an object property
// if object exists and has property, else a default value
//
// This is a curried function accepting one argument at a
// time and capturing each parameter in a closure.
//
const maybeGetProp = default => key => object =>
  (object && object.hasOwnProperty(key)) ? object.key : default

// Pass in empty string as the default value
//
const getPropOrEmptyString = maybeGetProp('')

// Apply the second parameter, the property name, making 2
// slightly different functions which have a default value
// and a property name pre-loaded. Both functions only need
// an object passed in to return either the property if it
// exists or an empty string.
//
const maybeText = getPropOrEmptyString('innerText')
const maybeSrc = getPropOrEmptyString('src')

async function scrape3() {
  // ...

  // The _ parameter name is acknowledging that we expect a
  // an argument passed in but saying we plan to ignore it.
  //
  const evaluate = _ => page.evaluate(() => {

    // Attempt to retrieve the desired elements
    //
    const img = document.querySelector('.c-picture img');
    const h1 = document.querySelector('h1')
    const content = document.querySelector('.c-entry-content')

    // Return the results, with empty string in
    // place of any missing properties.
    //
    return {
      title: maybeText(h1),
      article: maybeText(article),
      picture: maybeSrc(img),
      source: 'The Verge',
      categories: 'Tech'
    }
  }))

  // Start with an empty array of length 3
  //
  const evaluations = Array(3).fill()

    // Then map over that array ignoring the undefined
    // input and return a promise for a page evaluation
    //
    .map(evaluate)

  // All 3 scrapes are occuring concurrently. We'll
  // wait for all of them to finish.
  //
  const results = await Promise.all(evaluations)

  // Now we have an array of results, so we can
  // continue using array methods to iterate over them
  // or otherwise manipulate or transform them
  //
  return results
    .filter(result => result.title && result.picture)
    .forEach(result => {
      //
      // Do something with each result
      //
    })
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm just starting to play around with Puppeteer (Headless Chrome) and Nodejs. I'm scraping some test sites, and things work great when all the values are present, but if the value is missing I get an error like:

Cannot read property 'src' of null  (so in the code below, the first two passes might have all values, but the third pass, there is no picture, so it just errors out).

Before I was using if(!picture) continue; but I think it's not working now because of the for loop.

Any help would be greatly appreciated, thanks!

for (let i = 1; i <= 3; i++) {
//...Getting to correct page and scraping it three times
  const result = await page.evaluate(() => {
      let title = document.querySelector('h1').innerText;
      let article = document.querySelector('.c-entry-content').innerText;
      let picture = document.querySelector('.c-picture img').src;

      if (!document.querySelector('.c-picture img').src) {
        let picture = 'No Link';     }  //throws error

      let source = "The Verge";
      let categories = "Tech";

      if (!picture)
                continue;  //throws error

      return {
        title,
        article,
        picture,
        source,
        categories
      }
    });
}

Body:
let picture = document.querySelector('.c-picture img').src;

if (!document.querySelector('.c-picture img').src) {
    let picture = 'No Link';     }  //throws error

If there is no picture, then document.querySelector() returns null, which does not have a src property. You need to check that your query found an element before trying to read the src property.

Moving the null-check to the top of the function has the added benefit of saving unnecessary calculations when you are just going to bail out anyway.

async function scrape3() {
  // ...
  for (let i = 1; i <= 3; i++) {
  //...Getting to correct page and scraping it three times
    const result = await page.evaluate(() => {
        const pictureElement = document.querySelector('.c-picture img');

        if (!pictureElement) return null;

        const picture = pictureElement.src;
        const title = document.querySelector('h1').innerText;
        const article = document.querySelector('.c-entry-content').innerText;

        const source = "The Verge";
        const categories = "Tech";

        return {
          title,
          article,
          picture,
          source,
          categories
        }
    });

    if (!result) continue;

    // ... do stuff with result
  }

Answering comment question: "Is there a way just to skip anything blank, and return the rest?"

Yes. You just need to check the existence of each element that could be missing before trying to read a property off of it. In this case we can omit the early return since you're always interested in all the results.

async function scrape3() {
  // ...
  for (let i = 1; i <= 3; i++) {
    const result = await page.evaluate(() => {
        const img = document.querySelector('.c-picture img');
        const h1 = document.querySelector('h1');
        const content = document.querySelector('.c-entry-content');

        const picture = img ? img.src : '';
        const title = h1 ? h1.innerText : '';
        const article = content ? content.innerText : '';
        const source = "The Verge";
        const categories = "Tech";

        return {
          title,
          article,
          picture,
          source,
          categories
        }
    });
    // ...
  }
}

Further thoughts

Since I'm still on this question, let me take this one step further, and refactor it a bit with some higher level techniques you might be interested in. Not sure if this is exactly what you are after, but it should give you some ideas about writing more maintainable code.

// Generic reusable helper to return an object property
// if object exists and has property, else a default value
//
// This is a curried function accepting one argument at a
// time and capturing each parameter in a closure.
//
const maybeGetProp = default => key => object =>
  (object && object.hasOwnProperty(key)) ? object.key : default

// Pass in empty string as the default value
//
const getPropOrEmptyString = maybeGetProp('')

// Apply the second parameter, the property name, making 2
// slightly different functions which have a default value
// and a property name pre-loaded. Both functions only need
// an object passed in to return either the property if it
// exists or an empty string.
//
const maybeText = getPropOrEmptyString('innerText')
const maybeSrc = getPropOrEmptyString('src')

async function scrape3() {
  // ...

  // The _ parameter name is acknowledging that we expect a
  // an argument passed in but saying we plan to ignore it.
  //
  const evaluate = _ => page.evaluate(() => {

    // Attempt to retrieve the desired elements
    //
    const img = document.querySelector('.c-picture img');
    const h1 = document.querySelector('h1')
    const content = document.querySelector('.c-entry-content')

    // Return the results, with empty string in
    // place of any missing properties.
    //
    return {
      title: maybeText(h1),
      article: maybeText(article),
      picture: maybeSrc(img),
      source: 'The Verge',
      categories: 'Tech'
    }
  }))

  // Start with an empty array of length 3
  //
  const evaluations = Array(3).fill()

    // Then map over that array ignoring the undefined
    // input and return a promise for a page evaluation
    //
    .map(evaluate)

  // All 3 scrapes are occuring concurrently. We'll
  // wait for all of them to finish.
  //
  const results = await Promise.all(evaluations)

  // Now we have an array of results, so we can
  // continue using array methods to iterate over them
  // or otherwise manipulate or transform them
  //
  return results
    .filter(result => result.title && result.picture)
    .forEach(result => {
      //
      // Do something with each result
      //
    })
}

ContentLicense: CC BY-SA 4.0


问:
My erlang code not printing as expected
```<code>**
-module(shubham).

-export([call/0, hi/0, guy/0]).

call() ->   hi().

hi() -> guy();

hi() -> io: fwrite("This is hi \n").

guy() -> io:fwrite("This is A guy\n").**
</code>```

It should print "This is A guy" and then " This is hi" but only prints guy()

答:
You should use , instead of ; after the fourth line and remove hi() -> like below:

```<code> -module(shubham).
 -export([call/0, hi/0, guy/0]).
 call() -> hi().
 hi() -> guy(),
 io:fwrite("This is hi \n").
 guy() -> io:fwrite("This is A guy\n").
</code>```

Title: My erlang code not printing as expected

Body:
**
-module(shubham).

-export([call/0, hi/0, guy/0]).

call() ->   hi().

hi() -> guy();

hi() -> io: fwrite("This is hi \n").

guy() -> io:fwrite("This is A guy\n").**

It should print "This is A guy" and then " This is hi" but only prints guy()

Body:
You should use , instead of ; after the fourth line and remove hi() -> like below:

 -module(shubham).
 -export([call/0, hi/0, guy/0]).
 call() -> hi().
 hi() -> guy(),
 io:fwrite("This is hi \n").
 guy() -> io:fwrite("This is A guy\n").


问:
File is already use in some other process
Here I want to delete  line in a textfiles  containg  specific string like "21309#003" where item1 is a filename but It shows runtime exception that item1 (file) is already use in some process.How I Solve this problem.I am new in .net C#.</p>

```<code>    private void button1_Click(object sender, EventArgs e)
    {
        var selectedItems = listBox1.SelectedItems.Cast<String>().ToList();
        foreach (var item in selectedItems)
        {
            listBox1.Items.Remove(item);

        }

        foreach (var item1 in selectedItems)
        {
            listBox1.Items.Remove(item1);
            string line = null;
            //string line_to_delete = "the line i want to delete";

           using (StreamReader reader = new StreamReader(item1))
            //item1=  "C:\\IMP2711\\textpresent.txt"
            {

                using (StreamWriter writer = new StreamWriter(item1))
                {
                    while ((line = reader.ReadLine()) != null)
                   {
                        //if (String.Compare(line, @"*21349#003*") == 0)

                       //if (!line.Contains("21349#003") )
                       if (!line.StartsWith("21349#003"))
                       {**strong text**

                           writer.WriteLine(line);
                       }

                    }
                }
</code>```

答: If your file is small first read it to memory and then try to write on it, you have two stream on the same file, a file can share between multiple streams but you can not modify a file when it is open by another stream,  if your file is huge and you can not moved to memory you can create a temp file and write to temp file when your reading finished replacing original file with temp file and removing temp file.</p>

Body:
Here I want to delete  line in a textfiles  containg  specific string like "21309#003" where item1 is a filename but It shows runtime exception that item1 (file) is already use in some process.How I Solve this problem.I am new in .net C#.

    private void button1_Click(object sender, EventArgs e)
    {
        var selectedItems = listBox1.SelectedItems.Cast<String>().ToList();
        foreach (var item in selectedItems)
        {
            listBox1.Items.Remove(item);

        }

        foreach (var item1 in selectedItems)
        {
            listBox1.Items.Remove(item1);
            string line = null;
            //string line_to_delete = "the line i want to delete";

           using (StreamReader reader = new StreamReader(item1))
            //item1=  "C:\\IMP2711\\textpresent.txt"
            {

                using (StreamWriter writer = new StreamWriter(item1))
                {
                    while ((line = reader.ReadLine()) != null)
                   {
                        //if (String.Compare(line, @"*21349#003*") == 0)

                       //if (!line.Contains("21349#003") )
                       if (!line.StartsWith("21349#003"))
                       {**strong text**

                           writer.WriteLine(line);
                       }

                    }
                }


问:
wx.Frame error when calling one script from another
The following is a bit of copied code from another question, it works fine as a standalone app, but the pop-up right-click menu references frame_1 which is not available if "if name == 'main':" is false, as it is when the program is called by another. What should this reference be changed to?
Thanks.

```<code>import wx

import sys
sys.path.append("..")

from ObjectListView import ObjectListView, ColumnDefn

### 2. Launcher creates wxMenu. ###
menu_titles = [ "Open",
                "Properties",
                "Rename",
                "Delete" ]

menu_title_by_id = {}
for title in menu_titles:
    menu_title_by_id[ wx.NewId() ] = title

class Track(object):
    """
    Simple minded object that represents a song in a music library
    """
    def __init__(self, title, artist, album):
        self.title = title
        self.artist = artist
        self.album = album

def GetTracks():
    """
    Return a collection of tracks
    """
    return [
        Track("Sweet Lullaby", "Deep Forest", "Deep Forest"),
        Track("Losing My Religion", "U2", "Out of Time"),
        Track("En el Pais de la Libertad", "Leon Gieco", "Leon Gieco"),
    ]

class MyFrame(wx.Frame):

    def __init__(self, *args, **kwds):
        wx.Frame.__init__(self, *args, **kwds)

        self.Init()

    def Init(self):
        self.InitModel()
        self.InitWidgets()
        self.InitObjectListView()

    def InitModel(self):
        self.songs = GetTracks()

    def InitWidgets(self):
        panel = wx.Panel(self, -1)
        sizer_1 = wx.BoxSizer(wx.VERTICAL)
        sizer_1.Add(panel, 1, wx.ALL | wx.EXPAND)
        self.SetSizer(sizer_1)

        self.myOlv = ObjectListView(panel, -1, style=wx.LC_REPORT | wx.SUNKEN_BORDER)
        sizer_2 = wx.BoxSizer(wx.VERTICAL)
        sizer_2.Add(self.myOlv, 1, wx.ALL | wx.EXPAND, 4)
        panel.SetSizer(sizer_2)

        self.Layout()

    def InitObjectListView(self):
        self.myOlv.SetColumns([
            ColumnDefn("Title", "left", 120, "title"),
            ColumnDefn("Artist", "left", 100, "artist"),
            ColumnDefn("Album", "left", 100, "album")
        ])
        self.myOlv.SetObjects(self.songs)

        self.myOlv.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.RightClick)

    def RightClick(self, event):
        # record what was clicked
        self.list_item_clicked = self.myOlv.GetSelectedObject()

        menu = wx.Menu()
        menu.Bind(wx.EVT_MENU, self.MenuSelectionCb)

        for (id_, title) in menu_title_by_id.items():
            ### 3. Launcher packs menu with Append. ###
            menu.Append(id_, title)

        ### 5. Launcher displays menu with call to PopupMenu, invoked on the source component, passing event's GetPoint. ###
        # self.frame.PopupMenu( menu, event.GetPoint() )
        frame_1.PopupMenu(menu, event.GetPoint())
        menu.Destroy()  # destroy to avoid mem leak

    def MenuSelectionCb(self, event):
        # do something
        operation = menu_title_by_id[ event.GetId() ]
        target = self.list_item_clicked.title
        print 'Perform "%(operation)s" on "%(target)s."' % vars()

class MyPopupMenu(wx.Menu):

    def __init__(self, parent):
        super(MyPopupMenu, self).__init__()

        self.parent = parent

        mmi = wx.MenuItem(self, wx.NewId(), 'Minimize')
        self.AppendItem(mmi)
        self.Bind(wx.EVT_MENU, self.OnMinimize, mmi)

        cmi = wx.MenuItem(self, wx.NewId(), 'Close')
        self.AppendItem(cmi)
        self.Bind(wx.EVT_MENU, self.OnClose, cmi)

    def OnMinimize(self, e):
        self.parent.Iconize()

    def OnClose(self, e):
        self.parent.Close()

if __name__ == '__main__':
    app = wx.App(True)
    wx.InitAllImageHandlers()
    frame_1 = MyFrame(None, -1, "ObjectListView Track Test")
    app.SetTopWindow(frame_1)
    frame_1.Show()
    app.MainLoop()
</code>```

答:
If you are going to import your code into another module, then you will just need to instantiate that frame in your new main application's code. Let's save your code as olv_tracks.py. Now import it like I do in the following code:

```<code>import wx
import olv_tracks

class MyFrame(wx.Frame):

    def __init__(self):
        wx.Frame.__init__(self, None, title='Main App')
        panel = wx.Panel(self)

        self.Show()

        # show other frame
        frame = olv_tracks.MyFrame(None, -1, "ObjectListView Track Test")
        frame.Show()

if __name__ == '__main__':
    app = wx.App(False)
    frame = MyFrame()
    app.MainLoop()
</code>```

Now you just instantiate the frame the same way you did in your code.

Also, you need to change the reference to frame_1 in your RightClick method to self. So instead of frame_1.PopupMenu(menu, event.GetPoint()), it should be self.PopupMenu(menu, event.GetPoint())

Body:
The following is a bit of copied code from another question, it works fine as a standalone app, but the pop-up right-click menu references frame_1 which is not available if "if name == 'main':" is false, as it is when the program is called by another. What should this reference be changed to?
Thanks.

import wx

import sys
sys.path.append("..")

from ObjectListView import ObjectListView, ColumnDefn

### 2. Launcher creates wxMenu. ###
menu_titles = [ "Open",
                "Properties",
                "Rename",
                "Delete" ]

menu_title_by_id = {}
for title in menu_titles:
    menu_title_by_id[ wx.NewId() ] = title

class Track(object):
    """
    Simple minded object that represents a song in a music library
    """
    def __init__(self, title, artist, album):
        self.title = title
        self.artist = artist
        self.album = album

def GetTracks():
    """
    Return a collection of tracks
    """
    return [
        Track("Sweet Lullaby", "Deep Forest", "Deep Forest"),
        Track("Losing My Religion", "U2", "Out of Time"),
        Track("En el Pais de la Libertad", "Leon Gieco", "Leon Gieco"),
    ]

class MyFrame(wx.Frame):

    def __init__(self, *args, **kwds):
        wx.Frame.__init__(self, *args, **kwds)

        self.Init()

    def Init(self):
        self.InitModel()
        self.InitWidgets()
        self.InitObjectListView()

    def InitModel(self):
        self.songs = GetTracks()

    def InitWidgets(self):
        panel = wx.Panel(self, -1)
        sizer_1 = wx.BoxSizer(wx.VERTICAL)
        sizer_1.Add(panel, 1, wx.ALL | wx.EXPAND)
        self.SetSizer(sizer_1)

        self.myOlv = ObjectListView(panel, -1, style=wx.LC_REPORT | wx.SUNKEN_BORDER)
        sizer_2 = wx.BoxSizer(wx.VERTICAL)
        sizer_2.Add(self.myOlv, 1, wx.ALL | wx.EXPAND, 4)
        panel.SetSizer(sizer_2)

        self.Layout()

    def InitObjectListView(self):
        self.myOlv.SetColumns([
            ColumnDefn("Title", "left", 120, "title"),
            ColumnDefn("Artist", "left", 100, "artist"),
            ColumnDefn("Album", "left", 100, "album")
        ])
        self.myOlv.SetObjects(self.songs)

        self.myOlv.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.RightClick)

    def RightClick(self, event):
        # record what was clicked
        self.list_item_clicked = self.myOlv.GetSelectedObject()

        menu = wx.Menu()
        menu.Bind(wx.EVT_MENU, self.MenuSelectionCb)

        for (id_, title) in menu_title_by_id.items():
            ### 3. Launcher packs menu with Append. ###
            menu.Append(id_, title)

        ### 5. Launcher displays menu with call to PopupMenu, invoked on the source component, passing event's GetPoint. ###
        # self.frame.PopupMenu( menu, event.GetPoint() )
        frame_1.PopupMenu(menu, event.GetPoint())
        menu.Destroy()  # destroy to avoid mem leak

    def MenuSelectionCb(self, event):
        # do something
        operation = menu_title_by_id[ event.GetId() ]
        target = self.list_item_clicked.title
        print 'Perform "%(operation)s" on "%(target)s."' % vars()

class MyPopupMenu(wx.Menu):

    def __init__(self, parent):
        super(MyPopupMenu, self).__init__()

        self.parent = parent

        mmi = wx.MenuItem(self, wx.NewId(), 'Minimize')
        self.AppendItem(mmi)
        self.Bind(wx.EVT_MENU, self.OnMinimize, mmi)

        cmi = wx.MenuItem(self, wx.NewId(), 'Close')
        self.AppendItem(cmi)
        self.Bind(wx.EVT_MENU, self.OnClose, cmi)

    def OnMinimize(self, e):
        self.parent.Iconize()

    def OnClose(self, e):
        self.parent.Close()

if __name__ == '__main__':
    app = wx.App(True)
    wx.InitAllImageHandlers()
    frame_1 = MyFrame(None, -1, "ObjectListView Track Test")
    app.SetTopWindow(frame_1)
    frame_1.Show()
    app.MainLoop()

Body:
If you are going to import your code into another module, then you will just need to instantiate that frame in your new main application's code. Let's save your code as olv_tracks.py. Now import it like I do in the following code:

import wx
import olv_tracks

class MyFrame(wx.Frame):

    def __init__(self):
        wx.Frame.__init__(self, None, title='Main App')
        panel = wx.Panel(self)

        self.Show()

        # show other frame
        frame = olv_tracks.MyFrame(None, -1, "ObjectListView Track Test")
        frame.Show()

if __name__ == '__main__':
    app = wx.App(False)
    frame = MyFrame()
    app.MainLoop()

Now you just instantiate the frame the same way you did in your code.

Also, you need to change the reference to frame_1 in your RightClick method to self. So instead of frame_1.PopupMenu(menu, event.GetPoint()), it should be self.PopupMenu(menu, event.GetPoint())


问:
Force SSL for http requests in Rails
I'm working on a platform built with Ruby(v2.1.2) on Rails(v4.1.6) and we're trying to enforce SSL. How do I go about doing this?

So far, I have force_ssl

```<code># application_controller.rb

force_ssl if: :ssl_configured?

def ssl_configured?
  return false if params[:controller] == 'high_voltage/pages'
  (Rails.env.development? || Rails.env.test?) ? false : true
end
</code>```

Which seems to work because when I try to do http://www.somecoolsite.com, it then automatically becomes https://www.somecolesite.com.

However, if I try to submit a JSON post request to the API portion of our platform, and the URL is http://, the post request is somehow returning the results of a get request instead. But when I change the URL to https://, the post request works as expected. How would I go about fixing this so that if a client accidentally submits their request as http://, it is rewritten to https://?

Thanks!

答: Have you looked at using config.force_ssl = true in your production environment config? This is far more all-encompassing, but can lead to other issues as well.

Title: Force SSL for http requests in Rails

Body:
I'm working on a platform built with Ruby(v2.1.2) on Rails(v4.1.6) and we're trying to enforce SSL. How do I go about doing this?

So far, I have force_ssl

# application_controller.rb

force_ssl if: :ssl_configured?

def ssl_configured?
  return false if params[:controller] == 'high_voltage/pages'
  (Rails.env.development? || Rails.env.test?) ? false : true
end

Which seems to work because when I try to do http://www.somecoolsite.com, it then automatically becomes https://www.somecolesite.com.

However, if I try to submit a JSON post request to the API portion of our platform, and the URL is http://, the post request is somehow returning the results of a get request instead. But when I change the URL to https://, the post request works as expected. How would I go about fixing this so that if a client accidentally submits their request as http://, it is rewritten to https://?

Thanks!


问:
ConstraintLayout: Create a button that fills space after a RecyclerView
I have a horizontal RecyclerView inside a ConstraintLayout. I want to place a button at the end of the RecyclerView. When the recycler is empty, the button should expand to all available space. When items are added to the recycler, the button should squeeze down to a minimum.

There are some new additions to ConstraintLayout 1.1.0, like layout_constraintWidth_min, but I don't get it working. Is it supposed to work the way I intend?

Here are the relevant attributes, not including height:

```<code><android.support.v7.widget.RecyclerView
    android:id="@+id/horizontal_recycler"
    android:layout_width="wrap_content"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toStartOf="@+id/add">
</android.support.v7.widget.RecyclerView>
</code>```

and

```<code><Button
   android:id="@+id/add"
   android:layout_width="0dp"
   app:layout_constraintWidth_min="80dp"
   app:layout_constraintStart_toEndOf="@+id/horizontal_recycler"
   app:layout_constraintEnd_toEndOf="parent">
</Button>
</code>```

答:
So here is my solution.

```<code><android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="wrap_content"
        android:layout_height="200dp"
        android:layout_marginEnd="80dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="80dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="ADD"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/recyclerView"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>
</code>```

Please note that in order to keep the recyclerView from squishing the button the margin end on the recycler should equal the button with plus any padding and margin you see fit to have.

Body:
I have a horizontal RecyclerView inside a ConstraintLayout. I want to place a button at the end of the RecyclerView. When the recycler is empty, the button should expand to all available space. When items are added to the recycler, the button should squeeze down to a minimum.

There are some new additions to ConstraintLayout 1.1.0, like layout_constraintWidth_min, but I don't get it working. Is it supposed to work the way I intend?

Here are the relevant attributes, not including height:

<android.support.v7.widget.RecyclerView
    android:id="@+id/horizontal_recycler"
    android:layout_width="wrap_content"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toStartOf="@+id/add">
</android.support.v7.widget.RecyclerView>

and

<Button
   android:id="@+id/add"
   android:layout_width="0dp"
   app:layout_constraintWidth_min="80dp"
   app:layout_constraintStart_toEndOf="@+id/horizontal_recycler"
   app:layout_constraintEnd_toEndOf="parent">
</Button>

Body:
So here is my solution.

<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="wrap_content"
        android:layout_height="200dp"
        android:layout_marginEnd="80dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="80dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="ADD"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/recyclerView"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

Please note that in order to keep the recyclerView from squishing the button the margin end on the recycler should equal the button with plus any padding and margin you see fit to have.


答:
Here's a purrr-based approach:

library(purrr)

mylist <- list(7,
               c(10, 11, 12, 211, 446, 469),
               c(10, 11, 12, 13),
               c(11, 12, 13, 215),
               c(15, 16),
               c(15, 17, 216, 225))

result <- mylist %>%
    # check whether any numbers of an element are in any of the elements
    map(~map_lgl(mylist, compose(any, `%in%`), .x)) %>%
    unique() %>%    # drop duplicated groups
    map(~reduce(mylist[.x], union))    # subset lst by group and collapse subgroups

str(result)
#> List of 3
#>  $ : num 7
#>  $ : num [1:8] 10 11 12 211 446 469 13 215
#>  $ : num [1:5] 15 16 17 216 225
```

<p>The logic here is similar to Ronak's answer; I just find this easier to read. If you like, you could write the last line as <code>map(~unique(flatten_dbl(mylist[.x])))</code> or split it into <code>map(~mylist[.x]) %>% simplify_all() %>% map(unique)</code>.</p>

<p>For the indices of which element is aggregated to which group, just call <code>which</code> on the elements used for subsetting:</p>

<pre class="lang-r prettyprint-override"><code>mylist %>%
    map(~map_lgl(mylist, compose(any, `%in%`), .x)) %>%
    unique() %>%
    map(which) %>%
    str()
#> List of 3
#>  $ : int 1
#>  $ : int [1:3] 2 3 4
#>  $ : int [1:2] 5 6
</code>```

An alternative logic for the whole thing is to make the list nested instead of the calls, which means the self-join is up front (with cross2), there's no subsetting later, and most of the functions are just set operations:

mylist %>%
    map(cross2, mylist) %>%
    modify_depth(2, reduce, ~if(length(intersect(.x, .y)) > 0) sort(union(.x, .y))) %>%
    map(reduce, union) %>%
    unique()
```

<p>or using <code>cross2</code>'s <code>.filter</code> parameter,</p>

<pre class="lang-r prettyprint-override"><code>mylist %>%
    map(cross2, mylist, ~length(intersect(.x, .y)) == 0) %>%
    map(compose(sort, unique, unlist)) %>%
    unique()
</code>```

which could be condensed to

mylist %>%
    map(function(element) sort(unique(unlist(cross2(element, mylist, ~length(intersect(.x, .y)) == 0))))) %>%
    unique()
```

These approaches don't drop duplicate groups until the end, though, so they're likely less efficient.

Title: Merging list with common elements

Body:
I have a list

[[1]]
[1] 7

[[2]]
[1] 10 11 12 211 446 469

[[3]]
[1] 10 11 12 13

[[4]]
[1] 11 12 13 215

[[5]]
[1] 15 16

[[6]]
[1] 15 17 216 225

I want to merge list slices that have common elements, and index which list slices have been merged. My desired output is below.

$`1`
[1] 7

$`2`, `3`, `4`
[1] 10 11 12 13 211 215 446 469

$`5`,`6`
[1] 15 16 17 216 225

(I've put the original list slice indices as new list names, but any form of output is fine.)

Reproducible data:

mylist <- list(7, c(10, 11, 12, 211, 446, 469), c(10, 11, 12, 13), c(11,
12, 13, 215), c(15, 16), c(15, 17, 216, 225))

Body:
Here's a purrr-based approach:

library(purrr)

mylist <- list(7,
               c(10, 11, 12, 211, 446, 469),
               c(10, 11, 12, 13),
               c(11, 12, 13, 215),
               c(15, 16),
               c(15, 17, 216, 225))

result <- mylist %>%
    # check whether any numbers of an element are in any of the elements
    map(~map_lgl(mylist, compose(any, `%in%`), .x)) %>%
    unique() %>%    # drop duplicated groups
    map(~reduce(mylist[.x], union))    # subset lst by group and collapse subgroups

str(result)
#> List of 3
#>  $ : num 7
#>  $ : num [1:8] 10 11 12 211 446 469 13 215
#>  $ : num [1:5] 15 16 17 216 225

The logic here is similar to Ronak's answer; I just find this easier to read. If you like, you could write the last line as map(~unique(flatten_dbl(mylist[.x]))) or split it into map(~mylist[.x]) %>% simplify_all() %>% map(unique).

For the indices of which element is aggregated to which group, just call which on the elements used for subsetting:

mylist %>%
    map(~map_lgl(mylist, compose(any, `%in%`), .x)) %>%
    unique() %>%
    map(which) %>%
    str()
#> List of 3
#>  $ : int 1
#>  $ : int [1:3] 2 3 4
#>  $ : int [1:2] 5 6

An alternative logic for the whole thing is to make the list nested instead of the calls, which means the self-join is up front (with cross2), there's no subsetting later, and most of the functions are just set operations:

mylist %>%
    map(cross2, mylist) %>%
    modify_depth(2, reduce, ~if(length(intersect(.x, .y)) > 0) sort(union(.x, .y))) %>%
    map(reduce, union) %>%
    unique()

or using cross2's .filter parameter,

mylist %>%
    map(cross2, mylist, ~length(intersect(.x, .y)) == 0) %>%
    map(compose(sort, unique, unlist)) %>%
    unique()

which could be condensed to

mylist %>%
    map(function(element) sort(unique(unlist(cross2(element, mylist, ~length(intersect(.x, .y)) == 0))))) %>%
    unique()

These approaches don't drop duplicate groups until the end, though, so they're likely less efficient.


问:
Which is a good approach to test Ninject bindings?
We use ninject in all our projects, and as you will know, sometimes it becomes hard to test if the kernel would be able to resolve every type at execution time, because sometimes control gets lost when the magnitude of bindings and autobindings (through ninject extensions) is high.

So, what I'm asking here is how can I know  that my kernel, after loading all modules and bindings, will be able to resolve every type ? Do you do any kind of Unit Test? Or you just make acceptation tests of the application, at execution time? Any suggestion will be great :)

答:
So, what I'm asking here is how can I know that my kernel, after
  loading all modules and bindings, will be able to resolve every type ?
  Do you do any kind of Unit Test?

I test this by looping over each of the bindings in my module(s) and checking that the Kernel can return something for them:

```<code>[Test]
public void AllModuleBindingsTest()
{
    var kernel = new StandardKernel(new MyNinjectModule())
    foreach (var binding in new MyNinjectModule().Bindings)
    {
        var result = kernel.Get(binding.Service);
        Assert.NotNull(result, $"Could not get {binding.Service}");
    }
}
</code>```

Body:
So, what I'm asking here is how can I know that my kernel, after
  loading all modules and bindings, will be able to resolve every type ?
  Do you do any kind of Unit Test?

I test this by looping over each of the bindings in my module(s) and checking that the Kernel can return something for them:

[Test]
public void AllModuleBindingsTest()
{
    var kernel = new StandardKernel(new MyNinjectModule())
    foreach (var binding in new MyNinjectModule().Bindings)
    {
        var result = kernel.Get(binding.Service);
        Assert.NotNull(result, $"Could not get {binding.Service}");
    }
}


问:
It is possible to make this change to a certain color
I am trying to change the color of the ball when it hits any side of the wall.
I can make it change color but it goes back to the original color afterwards.

This is the section of code I'm dealing with. I need some help. Is there a way to keep the color change?

If you go all the way down the code you can see the comment part //initial ball color. I am sure that part of the code is the reason why it goes back to the original color and does not change color. Is there a way to keep the color that it changes too when it hits the wall?

```<code>public void paint (Graphics g) {
    g.drawRect(rectLeftX, rectTopY,
               rectRightX - rectLeftX, rectBottomY - rectTopY);

    r=new Random();

    for (int n = 1; n < 500 ; n++) {

        Color backgroundColour = getBackground();
        g.setColor(backgroundColour);
        g.fillOval(x, y, diameter, diameter);

        if (x + xChange <= rectLeftX)
        {
            xChange = -xChange;
            g.setColor(new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256)));
            g.fillOval (x, y, diameter, diameter);

        }
        if(x+xChange + diameter >= rectRightX)
        {
            xChange = -xChange;
            g.setColor(new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256)));
            g.fillOval (x, y, diameter, diameter);
        }

        if (y+yChange <= rectTopY)
        {
            yChange = -yChange;
            g.setColor(new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256)));
           g.fillOval (x, y, diameter, diameter);
        }
        if(y + yChange + diameter >= rectBottomY)
        {
            yChange = -yChange;
            g.setColor(new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256)));
           g.fillOval (x, y, diameter, diameter);
        }

        x = x + xChange;
        y = y + yChange;

        // initial ball color
         g.setColor(get());
         g.fillOval (x, y, diameter, diameter);

        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            g.drawString("sleep exception", 20, 20);
        }

    }
}
</code>```

答:
I think this code does what you are looking for.

```<code>import javax.swing.*;
import java.awt.*;
import java.util.Random;

public class CGBouncingBall extends JFrame {

    // Define named-constants
    private static final int CANVAS_WIDTH = 640;
    private static final int CANVAS_HEIGHT = 480;
    private static final int UPDATE_INTERVAL = 50; // milliseconds
    Random r;
    Color ballColor = Color.BLUE;

    private DrawCanvas canvas;  // the drawing canvas (an inner class extends JPanel)

    // Attributes of moving object
    private int x = 100;     // top-left (x, y)
    private int y = 100;
    private int size = 250;  // width and height
    private int xSpeed = 3;  // moving speed in x and y directions
    private int ySpeed = 5;  // displacement per step in x and y

    // Constructor to setup the GUI components and event handlers
    public CGBouncingBall() {
        canvas = new DrawCanvas();
        canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));
        this.setContentPane(canvas);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.pack();
        this.setTitle("Bouncing Ball");
        this.setVisible(true);

        // Create a new thread to run update at regular interval
        Thread updateThread = new Thread() {
            @Override
            public void run() {
                while (true) {
                    update();   // update the (x, y) position
                    repaint();  // Refresh the JFrame. Called back paintComponent()
                    try {
                        // Delay and give other thread a chance to run
                        Thread.sleep(UPDATE_INTERVAL);  // milliseconds
                    } catch (InterruptedException ignore) {
                }
            }
        }
    };
    updateThread.start(); // called back run()
}

// Update the (x, y) position of the moving object
public void update() {
    x += xSpeed;
    y += ySpeed;
    r=new Random();
    if (x > CANVAS_WIDTH - size || x < 0) {
        xSpeed = -xSpeed;
        ballColor = new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256));
    }
    if (y > CANVAS_HEIGHT - size || y < 0) {
        ySpeed = -ySpeed;
        ballColor = new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256));
    }
}

// Define Inner class DrawCanvas, which is a JPanel used for custom drawing
class DrawCanvas extends JPanel {
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);  // paint parent's background
        setBackground(Color.BLACK);
        g.setColor(ballColor);
        g.fillOval(x, y, size, size);  // draw a circle
    }
}

// The entry main method
public static void main(String[] args) {
    // Run GUI codes in Event-Dispatching thread for thread safety
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            new CGBouncingBall(); // Let the constructor do the job
        }
    });
}
}
</code>```

Body:
I am trying to change the color of the ball when it hits any side of the wall.
I can make it change color but it goes back to the original color afterwards.

This is the section of code I'm dealing with. I need some help. Is there a way to keep the color change?

If you go all the way down the code you can see the comment part //initial ball color. I am sure that part of the code is the reason why it goes back to the original color and does not change color. Is there a way to keep the color that it changes too when it hits the wall?

public void paint (Graphics g) {
    g.drawRect(rectLeftX, rectTopY,
               rectRightX - rectLeftX, rectBottomY - rectTopY);

    r=new Random();

    for (int n = 1; n < 500 ; n++) {

        Color backgroundColour = getBackground();
        g.setColor(backgroundColour);
        g.fillOval(x, y, diameter, diameter);

        if (x + xChange <= rectLeftX)
        {
            xChange = -xChange;
            g.setColor(new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256)));
            g.fillOval (x, y, diameter, diameter);

        }
        if(x+xChange + diameter >= rectRightX)
        {
            xChange = -xChange;
            g.setColor(new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256)));
            g.fillOval (x, y, diameter, diameter);
        }

        if (y+yChange <= rectTopY)
        {
            yChange = -yChange;
            g.setColor(new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256)));
           g.fillOval (x, y, diameter, diameter);
        }
        if(y + yChange + diameter >= rectBottomY)
        {
            yChange = -yChange;
            g.setColor(new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256)));
           g.fillOval (x, y, diameter, diameter);
        }

        x = x + xChange;
        y = y + yChange;

        // initial ball color
         g.setColor(get());
         g.fillOval (x, y, diameter, diameter);

        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            g.drawString("sleep exception", 20, 20);
        }

    }
}

Body:
I think this code does what you are looking for.

import javax.swing.*;
import java.awt.*;
import java.util.Random;

public class CGBouncingBall extends JFrame {

    // Define named-constants
    private static final int CANVAS_WIDTH = 640;
    private static final int CANVAS_HEIGHT = 480;
    private static final int UPDATE_INTERVAL = 50; // milliseconds
    Random r;
    Color ballColor = Color.BLUE;

    private DrawCanvas canvas;  // the drawing canvas (an inner class extends JPanel)

    // Attributes of moving object
    private int x = 100;     // top-left (x, y)
    private int y = 100;
    private int size = 250;  // width and height
    private int xSpeed = 3;  // moving speed in x and y directions
    private int ySpeed = 5;  // displacement per step in x and y

    // Constructor to setup the GUI components and event handlers
    public CGBouncingBall() {
        canvas = new DrawCanvas();
        canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));
        this.setContentPane(canvas);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.pack();
        this.setTitle("Bouncing Ball");
        this.setVisible(true);

        // Create a new thread to run update at regular interval
        Thread updateThread = new Thread() {
            @Override
            public void run() {
                while (true) {
                    update();   // update the (x, y) position
                    repaint();  // Refresh the JFrame. Called back paintComponent()
                    try {
                        // Delay and give other thread a chance to run
                        Thread.sleep(UPDATE_INTERVAL);  // milliseconds
                    } catch (InterruptedException ignore) {
                }
            }
        }
    };
    updateThread.start(); // called back run()
}

// Update the (x, y) position of the moving object
public void update() {
    x += xSpeed;
    y += ySpeed;
    r=new Random();
    if (x > CANVAS_WIDTH - size || x < 0) {
        xSpeed = -xSpeed;
        ballColor = new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256));
    }
    if (y > CANVAS_HEIGHT - size || y < 0) {
        ySpeed = -ySpeed;
        ballColor = new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256));
    }
}

// Define Inner class DrawCanvas, which is a JPanel used for custom drawing
class DrawCanvas extends JPanel {
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);  // paint parent's background
        setBackground(Color.BLACK);
        g.setColor(ballColor);
        g.fillOval(x, y, size, size);  // draw a circle
    }
}

// The entry main method
public static void main(String[] args) {
    // Run GUI codes in Event-Dispatching thread for thread safety
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            new CGBouncingBall(); // Let the constructor do the job
        }
    });
}
}


问:
Export data from firebase to bigQuery?
I have a couple apps using firebase under a project.

I just set up a bigquery which has the project linked.

Under firebase project setting, i see all my apps are currently linking to bigquery. And there is a link i can click on that says "View dataset"

However, it looks like whenever I click on that "View Dataset", the bigquery page doesn't contain any table for my apps?

Is there anything I need to do after the linking, to explicitly instruct firebase to export data to bigquery? Or instruct bigquery to import data form firebase?

Or do i just need to wait?

答: Firebase syncs new data to BigQuery periodically, so data won't be available immediately after linking. After the first sync to BigQuery, the datasets will be available.</p>

Title: Export data from firebase to bigQuery?


问:
How can i print a rdfs label with Jena
Hi i have create a new ontology for relate Drugs and diseases; now i query its for recovering the name of Drug related a particular disease.
My code is:

public class Main {

```<code>public static void main(String[] args) {

    org.apache.log4j.Logger.getRootLogger().setLevel(org.apache.log4j.Level.OFF);
    FileManager.get().addLocatorClassLoader(Main.class.getClassLoader());
    Model model = FileManager.get().loadModel("Drugs_Diseases.owl");
    String strQuery = "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> "+
                       "PREFIX des: <http://www.entrez.com/> "+
                       "SELECT DISTINCT ?subject ?object "
                       + "WHERE {   "
                       + "?subject des:isDrugOfDisease ?object .  "
                       + "?object rdfs:label ?label . "
                       + "FILTER regex(str(?label), \"pain\") }";

    Query query = QueryFactory.create(strQuery);
    QueryExecution execQuery = QueryExecutionFactory.create(query, model);
    try{
        ResultSet results = execQuery.execSelect();

        while(results.hasNext()){
            QuerySolution sol = results.nextSolution();
            RDFNode node = sol.get("subject");
            String stringPrint = node.asNode().toString();
            System.out.println(stringPrint);
        }
    } finally {
        execQuery.close();

}}
}
</code>```

The results of this query is:

```<code>http://www.entrez.com/DAP000017
http://www.entrez.com/DAP000021
</code>```

but my intent is to have:

```<code>Diazepam
Dextropropoxyphene
</code>```

in OWL i have:

```<code> <owl:Class rdf:about="http://www.entrez.com/DAP000021">
    <entrez:isDrugOfDisease>
      <owl:Class rdf:about="http://orpha.net/ORDO/Orphanet_#DIS_ID_75"/>
    </entrez:isDrugOfDisease>
    <entrez:id>DAP000021</entrez:id>
    <rdfs:label>Diazepam</rdfs:label>
  </owl:Class>
</code>```

答:
SPARQL only returns what you select, thus, you have to select the label in the SPARQL query of course:

SELECT DISTINCT ?drug ?disease ?drugLabel WHERE
 ?drug des:isDrugOfDisease ?disease .
 ?drug rdfs:label ?drugLabel .
 ?disease rdfs:label ?label .
 FILTER regex(str(?label), \"pain\")
}
```

<p>In the code, get the label from the solution object:</p>

<pre class="lang-java prettyprint-override"><code>while(results.hasNext()){
        QuerySolution sol = results.nextSolution();
        RDFNode node = sol.get("drug");
        String stringPrint = node.asNode().toString();
        System.out.println(stringPrint);
        // label
        String label = sol.getLiteral("drugLabel").getLexicalForm();
        System.out.println(label);
}
</code>```

Note, I changed the variable names. In general, it's easier to read and understand a query if you use meaningful names for the variables.

Title: How can i print a rdfs label with Jena

Body:
Hi i have create a new ontology for relate Drugs and diseases; now i query its for recovering the name of Drug related a particular disease.
My code is:

public class Main {

public static void main(String[] args) {

    org.apache.log4j.Logger.getRootLogger().setLevel(org.apache.log4j.Level.OFF);
    FileManager.get().addLocatorClassLoader(Main.class.getClassLoader());
    Model model = FileManager.get().loadModel("Drugs_Diseases.owl");
    String strQuery = "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> "+
                       "PREFIX des: <http://www.entrez.com/> "+
                       "SELECT DISTINCT ?subject ?object "
                       + "WHERE {   "
                       + "?subject des:isDrugOfDisease ?object .  "
                       + "?object rdfs:label ?label . "
                       + "FILTER regex(str(?label), \"pain\") }";

    Query query = QueryFactory.create(strQuery);
    QueryExecution execQuery = QueryExecutionFactory.create(query, model);
    try{
        ResultSet results = execQuery.execSelect();

        while(results.hasNext()){
            QuerySolution sol = results.nextSolution();
            RDFNode node = sol.get("subject");
            String stringPrint = node.asNode().toString();
            System.out.println(stringPrint);
        }
    } finally {
        execQuery.close();

}}
}

The results of this query is:

http://www.entrez.com/DAP000017
http://www.entrez.com/DAP000021

but my intent is to have:

Diazepam
Dextropropoxyphene

in OWL i have:

 <owl:Class rdf:about="http://www.entrez.com/DAP000021">
    <entrez:isDrugOfDisease>
      <owl:Class rdf:about="http://orpha.net/ORDO/Orphanet_#DIS_ID_75"/>
    </entrez:isDrugOfDisease>
    <entrez:id>DAP000021</entrez:id>
    <rdfs:label>Diazepam</rdfs:label>
  </owl:Class>

Body:
SPARQL only returns what you select, thus, you have to select the label in the SPARQL query of course:

SELECT DISTINCT ?drug ?disease ?drugLabel WHERE
 ?drug des:isDrugOfDisease ?disease .
 ?drug rdfs:label ?drugLabel .
 ?disease rdfs:label ?label .
 FILTER regex(str(?label), \"pain\")
}

In the code, get the label from the solution object:

while(results.hasNext()){
        QuerySolution sol = results.nextSolution();
        RDFNode node = sol.get("drug");
        String stringPrint = node.asNode().toString();
        System.out.println(stringPrint);
        // label
        String label = sol.getLiteral("drugLabel").getLexicalForm();
        System.out.println(label);
}

Note, I changed the variable names. In general, it's easier to read and understand a query if you use meaningful names for the variables.


问:
How to properly reallocate a two-dimensional array in C?
I am trying to load two double numbers from input into a two-dimensional array that is dynamically reallocated by each user input.

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

int main(int argc, char** argv) {

    int count;
    double number1, number2, **numbers;

    while (scanf("%lf,%lf", number1, number2) != EOF) {

        count++;
        numbers = (double**) realloc(numbers, count * 2 * sizeof (double));
        if (numbers == NULL) {
            exit(1);
        }
        numbers[count][0] = number1;
        numbers[count][1] = number2;
    }

    return 0;
}
</code>```

The program compiles without problems, but it fails every time I try to store a value in the array (it is likely a memory problem).

Can someone show me how to properly reallocate the two-dimensional array in my program?

Body:
I am trying to load two double numbers from input into a two-dimensional array that is dynamically reallocated by each user input.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char** argv) {

    int count;
    double number1, number2, **numbers;

    while (scanf("%lf,%lf", number1, number2) != EOF) {

        count++;
        numbers = (double**) realloc(numbers, count * 2 * sizeof (double));
        if (numbers == NULL) {
            exit(1);
        }
        numbers[count][0] = number1;
        numbers[count][1] = number2;
    }

    return 0;
}

The program compiles without problems, but it fails every time I try to store a value in the array (it is likely a memory problem).

Can someone show me how to properly reallocate the two-dimensional array in my program?

Body:
#include <stdio.h>
#include <stdlib.h>

void agregar_int(int **,int);
void agregar_char(char **,int);
char **tz=NULL;
int **tr=0;
int a;

int  main(void){
    a=2;
    for (a=1;a<100;a++)
    {
        agregar_int(tr,a);
    }
    for (a=1;a<100;a++)
    {
        agregar_char(tz,a);
    }
}

agregar_int (int **tr,int a)
{
    printf ("%d----------------------------------------------\n",a);
    tr = (int**) realloc (tr, (a+1) * sizeof(*tr));
    tr[a] = (int *) malloc (5 * sizeof(int));
    tr[a][0]=a; tr[a][1]=a;tr[a][2]=a;tr[a][3]=a;tr[a][4]=a;
    printf("%d \t %d \t %d \t %d \t %d  \n",tr[a][0],tr[a][1],tr[a][2],tr[a][3],tr[a][4]);
}

agregar_char (char **tz,int a)
{
    printf ("%d----------------------------------------------\n",a);
    tz = (char**) realloc (tz, (a+1) * sizeof(*tz));
    tz[a] = (char *) malloc (7 * sizeof(char));
    tz[a][0]='E'; tz[a][1]='s';tz[a][2]='t';tz[a][3]='e';tz[a][4]='b',tz[a][5]='a',tz[a][6]='n';
    printf("%c%c%c%c%c%c%c \n",tz[a][0],tz[a][1],tz[a][2],tz[a][3],tz[a][4],tz[a][5],tz[a][6]);
}


问:
Managing jQuery plugin dependency in webpack
I'm using Webpack in my application, in which I create two entry points - bundle.js for all my JavaScript files/codes, and vendors.js for all libraries like jQuery and React. What do I do in order to use plugins which have jQuery as their dependencies and I want to have them also in vendors.js? What if those plugins have multiple dependencies?

Currently I'm trying to use this jQuery plugin here - https://github.com/mbklein/jquery-elastic. The Webpack documentation mentions providePlugin and imports-loader. I used providePlugin, but still the jQuery object is not available. Here is how my webpack.config.js looks like-

```<code>var webpack = require('webpack');
var bower_dir = __dirname + '/bower_components';
var node_dir = __dirname + '/node_modules';
var lib_dir = __dirname + '/public/js/libs';

var config = {
    addVendor: function (name, path) {
        this.resolve.alias[name] = path;
        this.module.noParse.push(new RegExp(path));
    },
    plugins: [
        new webpack.ProvidePlugin({
            $: "jquery",
            jquery: "jQuery",
            "window.jQuery": "jquery"
        }),
        new webpack.optimize.CommonsChunkPlugin('vendors', 'vendors.js', Infinity)
    ],
    entry: {
        app: ['./public/js/main.js'],
        vendors: ['react','jquery']
    },
    resolve: {
        alias: {
            'jquery': node_dir + '/jquery/dist/jquery.js',
            'jquery.elastic': lib_dir + '/jquery.elastic.source.js'
        }
    },
    output: {
        path: './public/js',
        filename: 'bundle.js'
    },
    module: {
        loaders: [
            { test: /\.js$/, loader: 'jsx-loader' },
            { test: /\.jquery.elastic.js$/, loader: 'imports-loader' }
        ]
    }
};
config.addVendor('react', bower_dir + '/react/react.min.js');
config.addVendor('jquery', node_dir + '/jquery/dist/jquery.js');
config.addVendor('jquery.elastic', lib_dir +'/jquery.elastic.source.js');

module.exports = config;
</code>```

But in spite of this, it still throws an error in the browser console:

Uncaught ReferenceError: jQuery is not defined

Similarly, when I use the imports-loader, it throws an error,

require is not defined'

in this line:

```<code>var jQuery = require("jquery")
</code>```

However, I could use the same plugin when I don't add it to my vendors.js file and instead required it in the normal AMD way as how I include my other JavaScript code files, like-

```<code>define(
[
    'jquery',
    'react',
    '../../common-functions',
    '../../libs/jquery.elastic.source'
],function($,React,commonFunctions){
    $("#myInput").elastic() //It works

});
</code>```

But this is not what I want to do, as this would mean that jquery.elastic.source.js is bundled along with my JavaScript code in bundle.js, and I want all my jQuery plugins to be in the vendors.js bundle. So how do I go about achieving this?

答:
This works for me on the webpack.config.js

```<code>    new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery',
        'window.jQuery': 'jquery'
    }),
</code>```

in another javascript or into HTML add:

```<code>global.jQuery = require('jquery');
</code>```

Body:
I'm using Webpack in my application, in which I create two entry points - bundle.js for all my JavaScript files/codes, and vendors.js for all libraries like jQuery and React. What do I do in order to use plugins which have jQuery as their dependencies and I want to have them also in vendors.js? What if those plugins have multiple dependencies?

Currently I'm trying to use this jQuery plugin here - https://github.com/mbklein/jquery-elastic. The Webpack documentation mentions providePlugin and imports-loader. I used providePlugin, but still the jQuery object is not available. Here is how my webpack.config.js looks like-

var webpack = require('webpack');
var bower_dir = __dirname + '/bower_components';
var node_dir = __dirname + '/node_modules';
var lib_dir = __dirname + '/public/js/libs';

var config = {
    addVendor: function (name, path) {
        this.resolve.alias[name] = path;
        this.module.noParse.push(new RegExp(path));
    },
    plugins: [
        new webpack.ProvidePlugin({
            $: "jquery",
            jquery: "jQuery",
            "window.jQuery": "jquery"
        }),
        new webpack.optimize.CommonsChunkPlugin('vendors', 'vendors.js', Infinity)
    ],
    entry: {
        app: ['./public/js/main.js'],
        vendors: ['react','jquery']
    },
    resolve: {
        alias: {
            'jquery': node_dir + '/jquery/dist/jquery.js',
            'jquery.elastic': lib_dir + '/jquery.elastic.source.js'
        }
    },
    output: {
        path: './public/js',
        filename: 'bundle.js'
    },
    module: {
        loaders: [
            { test: /\.js$/, loader: 'jsx-loader' },
            { test: /\.jquery.elastic.js$/, loader: 'imports-loader' }
        ]
    }
};
config.addVendor('react', bower_dir + '/react/react.min.js');
config.addVendor('jquery', node_dir + '/jquery/dist/jquery.js');
config.addVendor('jquery.elastic', lib_dir +'/jquery.elastic.source.js');

module.exports = config;

But in spite of this, it still throws an error in the browser console:

Uncaught ReferenceError: jQuery is not defined

Similarly, when I use the imports-loader, it throws an error,

require is not defined'

in this line:

var jQuery = require("jquery")

However, I could use the same plugin when I don't add it to my vendors.js file and instead required it in the normal AMD way as how I include my other JavaScript code files, like-

define(
[
    'jquery',
    'react',
    '../../common-functions',
    '../../libs/jquery.elastic.source'
],function($,React,commonFunctions){
    $("#myInput").elastic() //It works

});

But this is not what I want to do, as this would mean that jquery.elastic.source.js is bundled along with my JavaScript code in bundle.js, and I want all my jQuery plugins to be in the vendors.js bundle. So how do I go about achieving this?

Body:
This works for me on the webpack.config.js

    new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery',
        'window.jQuery': 'jquery'
    }),

in another javascript or into HTML add:

global.jQuery = require('jquery');


问:
redigo different pool connect to single server
so, i have a necessity to connect to 3 redis server. i create 3 connection pool, and initialize each of them.
but redigo seems only connected to single redis server, although i get the connection using different pool.

using redigo, here's my code below

import (
    "fmt"
    "time"
    "github.com/garyburd/redigo/redis"
)

var poolA *redis.Pool
var poolB *redis.Pool
var poolC *redis.Pool

func main() {
    poolA = &redis.Pool{}
    poolB = &redis.Pool{}
    poolC = &redis.Pool{}

    connections := []string{"localhost:6379", "localhost2:6379", "localhost3:6379"}

    for k, v := range connections {
        redisPool := &redis.Pool{
            Dial: func() (redis.Conn, error) {
                return redis.Dial("tcp", v)
            },
            TestOnBorrow: func(c redis.Conn, t time.Time) error {
                if time.Since(t) < time.Minute {
                    return nil
                }
                _, err := c.Do("PING")
                return err
            },
            IdleTimeout: time.Duration(10) * time.Second,
            MaxActive:   100,
            MaxIdle:     100 / 2,
            Wait:        true,
        }

        if k == 0 {
            fmt.Println("poolA:", v)
            poolA = redisPool
        }
        if k == 1 {
            fmt.Println("poolB:", v)
            poolB = redisPool
        }
        if k == 2 {
            fmt.Println("poolC:", v)
            poolC = redisPool
        }
    }

    con := poolA.Get()
    defer con.Close()
    count, err := redis.Int(con.Do("SADD", "any:test", 3246))
    if err != nil {
        fmt.Println("error querying redis:", err.Error())
    }
    fmt.Println("count=", count)

    con2 := poolB.Get()
    defer con2.Close()
    count, err = redis.Int(con2.Do("SADD", "any:test", 3246))
    if err != nil {
        fmt.Println("error querying redis:", err.Error())
    }
    fmt.Println("count=", count)

    con3 := poolC.Get()
    defer con3.Close()
    count, err = redis.Int(con3.Do("SADD", "any:test", 3246))
    if err != nil {
        fmt.Println("error querying redis:", err.Error())
    }
    fmt.Println("count=", count)
}
```

<p>the problem is, all 3 pools are connecting to the last server/connection, resulting just as below.
any idea? </p>

```poolA: localhost:6379
poolB: localhost2:6379
poolC: localhost3:6379
error querying redis: dial tcp: lookup localhost3: no such host
count= 0
error querying redis: dial tcp: lookup localhost3: no such host
count= 0
error querying redis: dial tcp: lookup localhost3: no such host
count= 0

Process finished with exit code 0
```

答:
The dial functions use the single variable v.  The functions use the last value assigned to v when called.

To fix the problem, declare a variable inside the scope of the for loop and use that variable in the dial function:

```<code>for k, v := range connections {
    v := v // Declare variable scoped inside for loop
    redisPool := &redis.Pool{
        Dial: func() (redis.Conn, error) {
            return redis.Dial("tcp", v)  // uses variable scoped inside for loop
        },
    ...
</code>```

Separate from this issue, the pool settings don't make sense. Because the pool is configured to discard connections that have been idle for 10 seconds, the test on borrow function never pings the server.

Body:
so, i have a necessity to connect to 3 redis server. i create 3 connection pool, and initialize each of them.
but redigo seems only connected to single redis server, although i get the connection using different pool.

using redigo, here's my code below

import (
    "fmt"
    "time"
    "github.com/garyburd/redigo/redis"
)

var poolA *redis.Pool
var poolB *redis.Pool
var poolC *redis.Pool

func main() {
    poolA = &redis.Pool{}
    poolB = &redis.Pool{}
    poolC = &redis.Pool{}

    connections := []string{"localhost:6379", "localhost2:6379", "localhost3:6379"}

    for k, v := range connections {
        redisPool := &redis.Pool{
            Dial: func() (redis.Conn, error) {
                return redis.Dial("tcp", v)
            },
            TestOnBorrow: func(c redis.Conn, t time.Time) error {
                if time.Since(t) < time.Minute {
                    return nil
                }
                _, err := c.Do("PING")
                return err
            },
            IdleTimeout: time.Duration(10) * time.Second,
            MaxActive:   100,
            MaxIdle:     100 / 2,
            Wait:        true,
        }

        if k == 0 {
            fmt.Println("poolA:", v)
            poolA = redisPool
        }
        if k == 1 {
            fmt.Println("poolB:", v)
            poolB = redisPool
        }
        if k == 2 {
            fmt.Println("poolC:", v)
            poolC = redisPool
        }
    }

    con := poolA.Get()
    defer con.Close()
    count, err := redis.Int(con.Do("SADD", "any:test", 3246))
    if err != nil {
        fmt.Println("error querying redis:", err.Error())
    }
    fmt.Println("count=", count)

    con2 := poolB.Get()
    defer con2.Close()
    count, err = redis.Int(con2.Do("SADD", "any:test", 3246))
    if err != nil {
        fmt.Println("error querying redis:", err.Error())
    }
    fmt.Println("count=", count)

    con3 := poolC.Get()
    defer con3.Close()
    count, err = redis.Int(con3.Do("SADD", "any:test", 3246))
    if err != nil {
        fmt.Println("error querying redis:", err.Error())
    }
    fmt.Println("count=", count)
}

the problem is, all 3 pools are connecting to the last server/connection, resulting just as below.
any idea?

poolA: localhost:6379
poolB: localhost2:6379
poolC: localhost3:6379
error querying redis: dial tcp: lookup localhost3: no such host
count= 0
error querying redis: dial tcp: lookup localhost3: no such host
count= 0
error querying redis: dial tcp: lookup localhost3: no such host
count= 0

Process finished with exit code 0

Body:
The dial functions use the single variable v.  The functions use the last value assigned to v when called.

To fix the problem, declare a variable inside the scope of the for loop and use that variable in the dial function:

for k, v := range connections {
    v := v // Declare variable scoped inside for loop
    redisPool := &redis.Pool{
        Dial: func() (redis.Conn, error) {
            return redis.Dial("tcp", v)  // uses variable scoped inside for loop
        },
    ...

Separate from this issue, the pool settings don't make sense. Because the pool is configured to discard connections that have been idle for 10 seconds, the test on borrow function never pings the server.


问:
PHPUnit Database Testing: How To Use Dataset Per Test?
I want to seed a database table(s) with data, perform some operations using the library I'm building, and finally test those table(s) against another dataset of expected values. I'm using yaml files.

So far I can get this working with this code:

```<code>/* ... */

public function getDataSet() {
  return new \PHPUnit_Extensions_Database_DataSet_YamlDataSet('path/to/yaml/data');
}

/* ... */

public function testFoo() {
  // setup state and run operations

  // load expected data to test against
  $expected = new \PHPUnit_Extensions_Database_DataSet_YamlDataSet('path/to/expected/yaml');
  static::assertTablesEqual($expected->getTable('foo'), $this-getConnection()->createDataSet('foo'));
}
</code>```

I would like to just be able to do

```<code>// fooSeedData.yml
foo:
  - id: 1
  # ...

// fooExpectedData.yml
foo_test1:
# ...

foo_test2:
# ...

// fooTest.php
public function foo_test1() {
  /* ... */
  $expected->getTable('foo_test1')
  /* ... */
}

public function foo_test2() {
  /* ... */
  $expected->getTable('foo_test2')
  /* ... */
}
</code>```

but static::assertTablesEqual($expected, $actual); compares table names along with the data. Requiring a dataset file per test. Having numerous dataset files seems excessive which makes me think I'm doing something wrong.

Is there a way to do this? Am I using phpunit/dbunit wrong? If so how should I be doing this? Any help is appreciated!

答:
I ended up using array datasets per @xmike's recommendation.

```<code>$expected = new \PHPUnit_Extensions_Database_DataSet_ArrayDataSet([
  'table' => [
    ['column' => 'value'] // row
  ]
])

static::assertTablesEqual(/* ... */) // run tests against array dataset
</code>```

This has a couple of nice advantages. Firstly I don't have to use external data files and can keep data in next to the tests. And secondly this is just way simpler and easier to understand.

Body:
I want to seed a database table(s) with data, perform some operations using the library I'm building, and finally test those table(s) against another dataset of expected values. I'm using yaml files.

So far I can get this working with this code:

/* ... */

public function getDataSet() {
  return new \PHPUnit_Extensions_Database_DataSet_YamlDataSet('path/to/yaml/data');
}

/* ... */

public function testFoo() {
  // setup state and run operations

  // load expected data to test against
  $expected = new \PHPUnit_Extensions_Database_DataSet_YamlDataSet('path/to/expected/yaml');
  static::assertTablesEqual($expected->getTable('foo'), $this-getConnection()->createDataSet('foo'));
}

I would like to just be able to do

// fooSeedData.yml
foo:
  - id: 1
  # ...

// fooExpectedData.yml
foo_test1:
# ...

foo_test2:
# ...

// fooTest.php
public function foo_test1() {
  /* ... */
  $expected->getTable('foo_test1')
  /* ... */
}

public function foo_test2() {
  /* ... */
  $expected->getTable('foo_test2')
  /* ... */
}

but static::assertTablesEqual($expected, $actual); compares table names along with the data. Requiring a dataset file per test. Having numerous dataset files seems excessive which makes me think I'm doing something wrong.

Is there a way to do this? Am I using phpunit/dbunit wrong? If so how should I be doing this? Any help is appreciated!

Body:
I ended up using array datasets per @xmike's recommendation.

$expected = new \PHPUnit_Extensions_Database_DataSet_ArrayDataSet([
  'table' => [
    ['column' => 'value'] // row
  ]
])

static::assertTablesEqual(/* ... */) // run tests against array dataset

This has a couple of nice advantages. Firstly I don't have to use external data files and can keep data in next to the tests. And secondly this is just way simpler and easier to understand.


问:
C++ template returning tuple with typename-values
In my journey to implement a template-based linked-list which works with key/value-pairs I want to implement a "popHead()"-method. However, I can't get it to compile.

```<code>/**
 * Removes the first element in the list and returns it.
 * @return first element, nullptr if list is empty
 */
std::tuple<K, V> popHead() {
    auto tmp = head;
    if (tmp) {
        if (tmp->next) {
            head = tmp->next;
        } else {
            head = nullptr;
        }
        return new std::tuple(tmp->key, tmp->value);
    }

    return nullptr;
};
</code>```

This doesn't work because a type-specified is expected. Ok so it doesn't know what kind of type the values contained by the tuple should have.. however.. this doesn't work either:

```<code>return new std::tuple<K, V>(tmp->key, tmp->value);
</code>```

How do I return a tuple with types <K, V>?

答:
Maybe

```<code>return {tmp->key, tmp->value};
</code>```

?

Or, maybe, you want return a pointer to a std::tuple<K, V> ?

In this case

```<code>return new std::tuple<K, V>(tmp->key, tmp->value);
</code>```

should work but you have to modify the return type

```<code>std::tuple<K, V> * popHead()
// --------------^ *pointer* to tuple
</code>```

Body:
In my journey to implement a template-based linked-list which works with key/value-pairs I want to implement a "popHead()"-method. However, I can't get it to compile.

/**
 * Removes the first element in the list and returns it.
 * @return first element, nullptr if list is empty
 */
std::tuple<K, V> popHead() {
    auto tmp = head;
    if (tmp) {
        if (tmp->next) {
            head = tmp->next;
        } else {
            head = nullptr;
        }
        return new std::tuple(tmp->key, tmp->value);
    }

    return nullptr;
};

This doesn't work because a type-specified is expected. Ok so it doesn't know what kind of type the values contained by the tuple should have.. however.. this doesn't work either:

return new std::tuple<K, V>(tmp->key, tmp->value);

How do I return a tuple with types <K, V>?

Body:
Maybe

return {tmp->key, tmp->value};

?

Or, maybe, you want return a pointer to a std::tuple<K, V> ?

In this case

return new std::tuple<K, V>(tmp->key, tmp->value);

should work but you have to modify the return type

std::tuple<K, V> * popHead()
// --------------^ *pointer* to tuple


问:
Pass content of div element to action with asp core 2.0 form
I have an asp core form that transfers data to my "Create" action. I have inputs with "asp-for" attribute to initialize specific columns in my db and i have a "Content" column which i want to initialize by fetching innerText from  element. So how can i send innerText at the time when i submit form and to send it all together to the action? And is it possible to create custom asp core tag that would fetch innerText? Thanks.

```<code><form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="row">
    <div class="container">
        <div class="row" id="preview">
            <div id="result">

            </div>
            <div class="settings">
                <label><input type="button" id="myBtn" />Додати кнопку</label>
                @Html.Partial("_ModalBoxPartial")
                <label><input type="checkbox" checked="checked" id="auto-generate" />Auto-generate</label>
                <label><input type="checkbox" checked="checked" id="save-as-practice" />Save for practice</label>
            </div>
        </div>
        <div class="row">
       <div class="col-md-12" id="editor-wrapper" style="background-
            color:pink;">
       </div>
    </div>
    <div class="col-md-4">
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <input type="text" id="" name="module" />
        <div class="form-group">
            <div class="col-md-10">
                <textarea id="translation" name="translation"></textarea>
            </div>
        </div>
        <div class="form-group">
            <label asp-for="Title" class="control-label"></label>
            <input asp-for="Title" class="form-control" />
            <span asp-validation-for="Title" class="text-danger"></span>
        </div>

        <div class="form-group">
            <label asp-for="KeyWords" class="control-label"></label>
            <input asp-for="KeyWords" class="form-control" />
            <span asp-validation-for="KeyWords" class="text-danger"></span>
        </div>
        <div class="form-group">
            <label asp-for="CategoryId" class="control-label"></label>
            <select asp-for="CategoryId" class="form-control" asp-items="ViewBag.CategoryId"></select>
        </div>
        <div class="form-group">
            <label asp-for="ShowCaseText" class="control-label"></label>
            <input asp-for="ShowCaseText" class="form-control" />
            <span asp-validation-for="ShowCaseText" class="text-danger"></span>
        </div>
        <div class="form-group">
            <label asp-for="ExprId" class="control-label"></label>
            <select asp-for="ExprId" class="form-control" asp-items="ViewBag.ExprId"></select>
        </div>
        <div class="form-group">
            <label asp-for="Image" class="control-label"></label>
            <input asp-for="Image" class="form-control" />
            <span asp-validation-for="Image" class="text-danger"></span>
        </div>
        <div class="form-group">
            <input type="submit" value="Create" class="btn btn-default" id="submitBtn" />
        </div>
    </div>
</div>
</code>```

答:
ASP.NET MVC, and I could say most MVCs frameworks, performs post using HTTP Posts (I know it sounds redundant). It means that it will only post values from enabled input elements. So, from the browser point of view, your div is not different from any other div.

One possible solution is just adding a hidden input with that very same value:

```<code><input asp-for="Foo" class="form-control" type="hidden" />
</code>```

Body:
I have an asp core form that transfers data to my "Create" action. I have inputs with "asp-for" attribute to initialize specific columns in my db and i have a "Content" column which i want to initialize by fetching innerText from  element. So how can i send innerText at the time when i submit form and to send it all together to the action? And is it possible to create custom asp core tag that would fetch innerText? Thanks.

<form asp-action="Create">

                <input type="button" id="myBtn" />Додати кнопку
                @Html.Partial("_ModalBoxPartial")
                <input type="checkbox" checked="checked" id="auto-generate" />Auto-generate
                <input type="checkbox" checked="checked" id="save-as-practice" />Save for practice

        <input type="text" id="" name="module" />

                <textarea id="translation" name="translation"></textarea>

            <input asp-for="Title" class="form-control" />

            <input asp-for="KeyWords" class="form-control" />

            <select asp-for="CategoryId" class="form-control" asp-items="ViewBag.CategoryId"></select>

            <input asp-for="ShowCaseText" class="form-control" />

            <select asp-for="ExprId" class="form-control" asp-items="ViewBag.ExprId"></select>

            <input asp-for="Image" class="form-control" />

            <input type="submit" value="Create" class="btn btn-default" id="submitBtn" />

Body:
ASP.NET MVC, and I could say most MVCs frameworks, performs post using HTTP Posts (I know it sounds redundant). It means that it will only post values from enabled input elements. So, from the browser point of view, your div is not different from any other div.

One possible solution is just adding a hidden input with that very same value:

<input asp-for="Foo" class="form-control" type="hidden" />


问:
Timeout in Production but not in Local Rails
I am developing a Rails application.

In a view, I made a form which action is sent to a controller in AJAX by using remote: true

```<code><%= form_tag({controller: "my_controller", action: "my_method"}, {remote: true}) do %>
</code>```

Every thing works fine, but the controller can take a while to compute de result (sometimes more than 100 seconds).

The problem I am facing is that in local environment it works fine, but in production environment, I am getting ERROR 504 GATEWAY_TIMEOUT

Is there a way to make it work in production ?

答:
Is your production Heroku? You need to get this into a background job. As a rule of thumb (at least on Heroku) if it can run longer than 2 seconds it needs to be in a background job.

An easy way to do that is with delayed_job. Here is the starting documentation on that:

Active job basics

Body:
I am developing a Rails application.

In a view, I made a form which action is sent to a controller in AJAX by using remote: true

<%= form_tag({controller: "my_controller", action: "my_method"}, {remote: true}) do %>

Every thing works fine, but the controller can take a while to compute de result (sometimes more than 100 seconds).

The problem I am facing is that in local environment it works fine, but in production environment, I am getting ERROR 504 GATEWAY_TIMEOUT

Is there a way to make it work in production ?


问:
How can I pad an integer with zeros on the left?
How do you left pad an int with zeros when converting to a String in java?

I'm basically looking to pad out integers up to 9999 with leading zeros (e.g. 1 = 0001).

答:
If you for any reason use pre 1.5 Java then may try with Apache Commons Lang method</p>

```<code>org.apache.commons.lang.StringUtils.leftPad(String str, int size, '0')
</code>```

OwnerDisplayName: Omar Kooheji

Body:
If you for any reason use pre 1.5 Java then may try with Apache Commons Lang method

org.apache.commons.lang.StringUtils.leftPad(String str, int size, '0')

OwnerDisplayName: Boris Pavlović


问:
Launching java as a service and specifying the user
As an introduction, let's just say I'm a real noob using linux. I try to do the things right, don't hit me if it's ugly.

So, the problematic. I'm trying to run some jars as webservices on an ubuntu server. I created a specific user (nuxservice) with no pwd. I edited sudoers to enable a few users (myself & root) to sudo using this account with no password.

I then took a lot of inspiration from : http://www.jcgonzalez.com/linux-java-service-wrapper-example

Most is working, only one real problem, my java process seems to not have the right to create its logging files.

I run my services with a classic

```<code>sudo service myservice start/stop/restart
</code>```

The command line that are launching my services are :

```<code>nohup sudo -u nuxservice java -jar myjar.jar myargs
</code>```

When I do a ps -ef, the services are launches with my nuxservice user.

When I do ls -ld, nuxservice is the owner and have the rights.

If I launch the command in a terminal myself, it works. When launching as a service, my logs files are not created.

Any clues mates ?

答:
So...

It was kinda silly.

My user rights were fine. Problem is, I did not set the working folder in my script so Java was all lost considering the creation of the folder/files for logging.

All I had to do was adding a little

```<code>cd $PATH_TO_JAR
</code>```

And it was all set !

Body:
As an introduction, let's just say I'm a real noob using linux. I try to do the things right, don't hit me if it's ugly.

So, the problematic. I'm trying to run some jars as webservices on an ubuntu server. I created a specific user (nuxservice) with no pwd. I edited sudoers to enable a few users (myself & root) to sudo using this account with no password.

I then took a lot of inspiration from : http://www.jcgonzalez.com/linux-java-service-wrapper-example

Most is working, only one real problem, my java process seems to not have the right to create its logging files.

I run my services with a classic

sudo service myservice start/stop/restart

The command line that are launching my services are :

nohup sudo -u nuxservice java -jar myjar.jar myargs

When I do a ps -ef, the services are launches with my nuxservice user.

When I do ls -ld, nuxservice is the owner and have the rights.

If I launch the command in a terminal myself, it works. When launching as a service, my logs files are not created.

Any clues mates ?

Body:
So...

It was kinda silly.

My user rights were fine. Problem is, I did not set the working folder in my script so Java was all lost considering the creation of the folder/files for logging.

All I had to do was adding a little

cd $PATH_TO_JAR

And it was all set !


问:
what does this bash script line of code mean
I am new to shell scripting and I found following line of code in a given script.

Could someone explain me with an example what the following line of code means

```<code>Path=`echo $line | awk -F '|' '{print $1}'`
</code>```

答: the default field separator is  ' ', if you have -F , means change default separator to '|' </p>

Body:
I am new to shell scripting and I found following line of code in a given script.

Could someone explain me with an example what the following line of code means

Path=`echo $line | awk -F '|' '{print $1}'`


问:
iOS Fabric Crashlytics Answers Kit not Collecting Data

Problem Summary

UPDATE: I have fixed the issue somehow, I am not sure how. I just deleted the Apps from my dashboard, recreated them, cleaned the Fabrics and Crashlytics Cache and after four or five times trying, it started working out of its own accord. I am still interested in knowing how did it happen and how can it actually be solved without deleting the app altogether.

TL;DR I am not receiving any stats from Answers kit and it looks like Fabric thinks Answers is not installed in my App even though it is. I am not interested in events tracking, I just need the metrics stats.

Problem Explained

Fabric Crashlytics kit comes bundled together with Answers and for most of my Apps, whenever I set up Crashlytics, Answers is set up too and I can see stats on my Fabric Dashboard.

However for a couple of my apps, I can't see the stats and it seems like Answers is disabled. The Dashboard says for viewing stats, Answers is required.

But when I look at my Fabric Mac Client, It says that for this App, Answers kit is installed and enabled.

So let's head back to the web dashboard for the App, all the options for stats are disabled except Crashlytics and the App itself is kind of greyed out unlike other Apps.

And in details it first keeps waiting for "Events" and recommends that I should make a fresh installation of the App (Which I have done a number of times now).

After a while, it says no events were received and it asks me to perform a fresh install and enable debugging mode.

My Configuration

My pod file is:

```<code>pod 'Fabric'
pod 'Crashlytics'
</code>```

I am setting up my Fabric kit in AppDelegate like:

```<code>[Fabric with:@[[Crashlytics class]]];
</code>```

And I have enabled the debugging mod like:

```<code>[[Fabric sharedSDK] setDebug: YES];
</code>```

What I have done so far

Made sure Answers is installed.

Enabled debugging mode. Fabric says it can tell me if Answers is enabled and sending events but I haven't seen any log regarding it. The only three logs I receive are the version number and notifications that Settings have been downloaded and are available for consumption.

Made Fresh Installations

Checked logs of debugging mode which confirm that the settings for Fabric have been downloaded and are ready for consumption.

Added Fastlane Kit to create build deliveries to see if there was some problem with communication between my App and Fabric. The Builds are showing correctly and are being uploaded correctly but again, no Answers.

I have even logged a login event even though I don't need it, just to see if it starts transmitting Answers data.

```<code>[Answers logLoginWithMethod:@"Email"
                        success:@YES
               customAttributes:@{}];
</code>```

There is also this interesting log when App runs:

```<code>[FileManager] Failed to remove file '/var/mobile/Containers/Data/Application/F055EE71-5064-4105-B41D-BD098F28DAA9/Library/Caches/com.crashlytics.data/com.sampleapp.mysampleapp/v3/launchmarker' : Error Domain=NSCocoaErrorDomain Code=4 "“launchmarker” couldn’t be removed." UserInfo={NSUnderlyingError=0x14e6a830 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}, NSFilePath=/var/mobile/Containers/Data/Application/F055EE71-5064-4105-B41D-BD098F28DAA9/Library/Caches/com.crashlytics.data/com.sampleapp.mysampleapp/v3/launchmarker, NSUserStringVariant=(
    Remove
)}
</code>```

It pops up whenever I attempt a fresh install after resetting the simulator. Also, check the settings json in Fabrics Data in Cache. The curious bits here:

```<code>"features": {
    "collect_logged_exceptions": true,
    "collect_reports": false,
    "collect_analytics": false,
    "prompt_enabled": false,
    "push_enabled": true
  }
</code>```

Complete JSON can be seen here.

How can I fix this?

答:
Mike from Fabric here. Yes, Answers is included within Crashlytics, however no data is collected until you enable it on the Fabric dashboard and accept the terms and conditions specific to Answers. What you need to do is include Crashlytics and once the app is active in your dashboard, then head to any other page in the dashboard and enable Answers from the web UI.

After that, we wait for two minutes to see if we see any event data. Usually, running a clean of your app, build and run (or un-install and re-install) will get the data sent over and then make the dashboard visible. As to why it didn't work earlier in your app, it's still unclear to me, but perhaps a race condition or one of our caches didn't propagate the data correctly.

Edit: Added a picture of what the button to enable Answers looks like.

Body:
Problem Summary

UPDATE: I have fixed the issue somehow, I am not sure how. I just deleted the Apps from my dashboard, recreated them, cleaned the Fabrics and Crashlytics Cache and after four or five times trying, it started working out of its own accord. I am still interested in knowing how did it happen and how can it actually be solved without deleting the app altogether.

TL;DR I am not receiving any stats from Answers kit and it looks like Fabric thinks Answers is not installed in my App even though it is. I am not interested in events tracking, I just need the metrics stats.

Problem Explained

Fabric Crashlytics kit comes bundled together with Answers and for most of my Apps, whenever I set up Crashlytics, Answers is set up too and I can see stats on my Fabric Dashboard.

However for a couple of my apps, I can't see the stats and it seems like Answers is disabled. The Dashboard says for viewing stats, Answers is required.

But when I look at my Fabric Mac Client, It says that for this App, Answers kit is installed and enabled.

So let's head back to the web dashboard for the App, all the options for stats are disabled except Crashlytics and the App itself is kind of greyed out unlike other Apps.

And in details it first keeps waiting for "Events" and recommends that I should make a fresh installation of the App (Which I have done a number of times now).

After a while, it says no events were received and it asks me to perform a fresh install and enable debugging mode.

My Configuration

My pod file is:

pod 'Fabric'
pod 'Crashlytics'

I am setting up my Fabric kit in AppDelegate like:

[Fabric with:@[[Crashlytics class]]];

And I have enabled the debugging mod like:

[[Fabric sharedSDK] setDebug: YES];

What I have done so far

Made sure Answers is installed.

Enabled debugging mode. Fabric says it can tell me if Answers is enabled and sending events but I haven't seen any log regarding it. The only three logs I receive are the version number and notifications that Settings have been downloaded and are available for consumption.

Made Fresh Installations

Checked logs of debugging mode which confirm that the settings for Fabric have been downloaded and are ready for consumption.

Added Fastlane Kit to create build deliveries to see if there was some problem with communication between my App and Fabric. The Builds are showing correctly and are being uploaded correctly but again, no Answers.

I have even logged a login event even though I don't need it, just to see if it starts transmitting Answers data.

[Answers logLoginWithMethod:@"Email"
                        success:@YES
               customAttributes:@{}];

There is also this interesting log when App runs:

[FileManager] Failed to remove file '/var/mobile/Containers/Data/Application/F055EE71-5064-4105-B41D-BD098F28DAA9/Library/Caches/com.crashlytics.data/com.sampleapp.mysampleapp/v3/launchmarker' : Error Domain=NSCocoaErrorDomain Code=4 "“launchmarker” couldn’t be removed." UserInfo={NSUnderlyingError=0x14e6a830 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}, NSFilePath=/var/mobile/Containers/Data/Application/F055EE71-5064-4105-B41D-BD098F28DAA9/Library/Caches/com.crashlytics.data/com.sampleapp.mysampleapp/v3/launchmarker, NSUserStringVariant=(
    Remove
)}

It pops up whenever I attempt a fresh install after resetting the simulator. Also, check the settings json in Fabrics Data in Cache. The curious bits here:

"features": {
    "collect_logged_exceptions": true,
    "collect_reports": false,
    "collect_analytics": false,
    "prompt_enabled": false,
    "push_enabled": true
  }

Complete JSON can be seen here.

How can I fix this?