问:
Finding if an SSH connection succeeded
I am trying to make my program connect to another computer using SSH.  It would be generic (the user would provide the hostname, IP, and password), so keys can't be used.  This is the code I have so far:

```<code>func terminalSSH(host:String, password:String, IP:String) {
    let pipe = Pipe()
    let args = ["-p", password, "ssh", "\(host)@\(IP)"]
    let task = Process()
    task.launchPath = "/usr/local/bin/sshpass"
    task.arguments = args
    task.standardOutput = pipe

    task.launch()

    let data = pipe.fileHandleForReading.readDataToEndOfFile()
    let output = NSString(data: data, encoding: String.Encoding.utf8.rawValue)

    print(output)

}
</code>```

My issue is that I can't see if the connection was successful using sshpass.  I want the user to be notified the moment the connection succeeded or failed.  Also, it seems like sshpass is the only command I can use to SSH because Terminal forces the user to input the password.  I know this code works to establish a connection because the system.log on my test target computer displays it.  Thanks.

答:
Firstly, you should not be using sshpass and a plain text password, but private keys.

To get the tasks exit code, you can use the following:

```<code>task.waitUntilExit()
let status = task.terminationStatus
</code>```

Do know however, that waitUntilExit will block the return of this method until the session has ended.

Whether the session ends in 10 minutes, or immediately due to an error, you can evaluate the terminationStatus to see how the program exited.

If the return code is 0, everything exited nicely; if there is a non-zero value, you can take different actions based on the reason for failure.

```<code>task.waitUntilExit()

let status = task.terminationStatus
if status == 0 {

    print("Graceful exit.")
} else {

    print("Failed with code " + status)
}
</code>```

Detecting and responding to a successful connection will be more difficult here, as the waitUntilExit call may block for as long as the ssh session is open.

You also have the option of using a loop, and checking task.isRunning.

Title: Finding if an SSH connection succeeded

Body:
I am trying to make my program connect to another computer using SSH.  It would be generic (the user would provide the hostname, IP, and password), so keys can't be used.  This is the code I have so far:

func terminalSSH(host:String, password:String, IP:String) {
    let pipe = Pipe()
    let args = ["-p", password, "ssh", "\(host)@\(IP)"]
    let task = Process()
    task.launchPath = "/usr/local/bin/sshpass"
    task.arguments = args
    task.standardOutput = pipe

    task.launch()

    let data = pipe.fileHandleForReading.readDataToEndOfFile()
    let output = NSString(data: data, encoding: String.Encoding.utf8.rawValue)

    print(output)

}

My issue is that I can't see if the connection was successful using sshpass.  I want the user to be notified the moment the connection succeeded or failed.  Also, it seems like sshpass is the only command I can use to SSH because Terminal forces the user to input the password.  I know this code works to establish a connection because the system.log on my test target computer displays it.  Thanks.

Body:
Firstly, you should not be using sshpass and a plain text password, but private keys.

To get the tasks exit code, you can use the following:

task.waitUntilExit()
let status = task.terminationStatus

Do know however, that waitUntilExit will block the return of this method until the session has ended.

Whether the session ends in 10 minutes, or immediately due to an error, you can evaluate the terminationStatus to see how the program exited.

If the return code is 0, everything exited nicely; if there is a non-zero value, you can take different actions based on the reason for failure.

task.waitUntilExit()

let status = task.terminationStatus
if status == 0 {

    print("Graceful exit.")
} else {

    print("Failed with code " + status)
}

Detecting and responding to a successful connection will be more difficult here, as the waitUntilExit call may block for as long as the ssh session is open.

You also have the option of using a loop, and checking task.isRunning.


来源: stackexchange

问:
Bootstrap Modal Popup Not Clickable
Using Bootstrap to add a modal popup. Upon clicking the trigger button, the modal is dark and unclickable. Any idea what's causing this or where to look?

```<code><!-- Button trigger modal -->
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>
</code>```

application.js

```<code>//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require miracle/jquery.noconflict
//= require miracle/modernizr.2.8.3.min
//= require miracle/jquery-migrate-1.2.1.min
//= require miracle/jquery-ui.1.11.2.min
//= require bootstrap
//= require turbolinks
//= require magnific-popup/jquery.magnific-popup.min
//= require miracle/jquery.stellar.min
//= require miracle/waypoints.min
//= require owl-carousel/owl.carousel.min
//= require jquery.sky.carousel/jquery.sky.carousel-1.0.2
//= require miracle/jquery.plugins
//= require miracle/main
//= require_tree .
</code>```

答:
i solved the same problem when i add data-backdrop="false" in my modal like this:</p>

```<code><div class="modal fade" id="userGoing" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" data-backdrop="false">
</code>```

ContentLicense: CC BY-SA 3.0

Title: Bootstrap Modal Popup Not Clickable

Body:
Using Bootstrap to add a modal popup. Upon clicking the trigger button, the modal is dark and unclickable. Any idea what's causing this or where to look?

<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  Launch demo modal
</button>

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Modal title

        ...

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

application.js

//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require miracle/jquery.noconflict
//= require miracle/modernizr.2.8.3.min
//= require miracle/jquery-migrate-1.2.1.min
//= require miracle/jquery-ui.1.11.2.min
//= require bootstrap
//= require turbolinks
//= require magnific-popup/jquery.magnific-popup.min
//= require miracle/jquery.stellar.min
//= require miracle/waypoints.min
//= require owl-carousel/owl.carousel.min
//= require jquery.sky.carousel/jquery.sky.carousel-1.0.2
//= require miracle/jquery.plugins
//= require miracle/main
//= require_tree .

Body:
i solved the same problem when i add data-backdrop="false" in my modal like this:

<div class="modal fade" id="userGoing" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" data-backdrop="false">


问:
Check if entry to panda dataframe is unique when index might be the same
I have a panda DataFrame that I want to add rows to. The Dataframe looks like this:

```<code>   col1  col2
a     1     5
b     2     6
c     3     7
</code>```

I want to add rows to the dataframe, but only if they are unique. The problem is that some new rows might have the same index, but different values in the columns. If this is the case, I somehow need to know.

Some example rows to be added and the desired result:

row 1:

```<code>   col1  col2
a     1     5
</code>```

desired row 1 result: Not added - it is already in the dataframe

row 2:

```<code>   col1  col2
a     9     9
</code>```

desired row 2 result: something like,

```<code>print('non-unique entries for index a')
</code>```

row 3:

```<code>   col1  col2
d     4     4
</code>```

desired row 3 result: just add the row to the dataframe.

答:
the easy option would be to merge all rows and then keep the unique ones via the dataframe method drop_duplicates

However, this option doesn't report a warning / error when a duplicate row is appended.

drop_duplicates doesn't consider indexes, so the dataframe must be reset before dropping the duplicates, and set back after:

```<code>import pandas as pd
# set up data frame
df = pd.DataFrame({'col1': [1, 2, 3], 'col2':[5, 6, 7]}, index=['a', 'b', 'c'])
# set up row to be appended
row = pd.DataFrame({'col1':[3], 'col2': [7]}, index=['c'])
# append row (don't care if it's duplicate)
df = df.append([row])
# drop duplicatesdf2 = df2.reset_index()
df2 = df2.drop_duplicates()
df2 = df2.set_index('index')
</code>```

if the warning message is an absolute requirement, we can write a function to that effect that checks if a row is duplicate via a merge operation and appends the row only if it is unique.

```<code>def append_unique(df, row):
    d = df.reset_index()
    r = row.reset_index()
    if d.merge(r, on=list(d.columns), how='inner').empty:
        d2 = d.append(r)
        d2 = d2.set_index('index')
        return d2
    print('non-unique entries for index a')
    return df

df2 = append_unique(df2, row)
</code>```

Body:
I have a panda DataFrame that I want to add rows to. The Dataframe looks like this:

   col1  col2
a     1     5
b     2     6
c     3     7

I want to add rows to the dataframe, but only if they are unique. The problem is that some new rows might have the same index, but different values in the columns. If this is the case, I somehow need to know.

Some example rows to be added and the desired result:

row 1:

   col1  col2
a     1     5

desired row 1 result: Not added - it is already in the dataframe

row 2:

   col1  col2
a     9     9

desired row 2 result: something like,

print('non-unique entries for index a')

row 3:

   col1  col2
d     4     4

desired row 3 result: just add the row to the dataframe.

Body:
the easy option would be to merge all rows and then keep the unique ones via the dataframe method drop_duplicates

However, this option doesn't report a warning / error when a duplicate row is appended.

drop_duplicates doesn't consider indexes, so the dataframe must be reset before dropping the duplicates, and set back after:

import pandas as pd
# set up data frame
df = pd.DataFrame({'col1': [1, 2, 3], 'col2':[5, 6, 7]}, index=['a', 'b', 'c'])
# set up row to be appended
row = pd.DataFrame({'col1':[3], 'col2': [7]}, index=['c'])
# append row (don't care if it's duplicate)
df = df.append([row])
# drop duplicatesdf2 = df2.reset_index()
df2 = df2.drop_duplicates()
df2 = df2.set_index('index')

if the warning message is an absolute requirement, we can write a function to that effect that checks if a row is duplicate via a merge operation and appends the row only if it is unique.

def append_unique(df, row):
    d = df.reset_index()
    r = row.reset_index()
    if d.merge(r, on=list(d.columns), how='inner').empty:
        d2 = d.append(r)
        d2 = d2.set_index('index')
        return d2
    print('non-unique entries for index a')
    return df

df2 = append_unique(df2, row)


问:
Python Manual/Isolated/Portable Windows Installation
I thought it is an easy question but I spent a lot of google time to find the answer with no luck. Hope you can help me.

My company has a large SW system on windows which is portable, meaning copy some folders, add some folder to windows path and you are ready to go.

No registry, no dll in system directory, no shortcuts, Nothing!

I want to start using python 3.x in our system in the same paradigm. I also want the ability to add to this distribution a  pip/conda 3rd packages from time to time.

I don't want to install python msi on all the systems.

I don't want to pack it to standalone executable like py2exe and pyinstaller or use special python distribution like PyWin32.

Somehow, I couldn't find a formal official solution for that.

The closest thing was here but no pip is supported, python is minimal, and the system isolation is "almost".

3.8. Embedded Distribution New in version 3.5.

The embedded distribution is a ZIP file containing a minimal Python
  environment. It is intended for acting as part of another application,
  rather than being directly accessed by end-users.

When extracted, the embedded distribution is (almost) fully isolated
  from the user’s system, including environment variables, system
  registry settings, and installed packages. The standard library is
  included as pre-compiled and optimized .pyc files in a ZIP, and
  python3.dll, python36.dll, python.exe and pythonw.exe are all
  provided. Tcl/tk (including all dependants, such as Idle), pip and the
  Python documentation are not included.

Note The embedded distribution does not include the Microsoft C
  Runtime and it is the responsibility of the application installer to
  provide this. The runtime may have already been installed on a user’s
  system previously or automatically via Windows Update, and can be
  detected by finding ucrtbase.dll in the system directory. Third-party
  packages should be installed by the application installer alongside
  the embedded distribution. Using pip to manage dependencies as for a
  regular Python installation is not supported with this distribution,
  though with some care it may be possible to include and use pip for
  automatic updates. In general, third-party packages should be treated
  as part of the application (“vendoring”) so that the developer can
  ensure compatibility with newer versions before providing updates to
  users.

Any ideas?
Thanks.

答:
How about... installing Python in one machine and replicate that installation on others computers?

Usually, I install Python in a Windows Virtualbox machine (Microsoft usually give it for free to try it or for testing old Internet Explorer versions).

Then I copy the Python directory to my Windows machine (the real host) and usually works. This makes possible to using various python versions.

Did you try to complete the Python Embedded Distribution? Usually they not come with Tkinter, but once I could copy files and put in this distribution in a way that works. Try it too.


问:
Method not being triggered from razor view
I am using ASP.NET MVC 3 with the razor view engine.

I have the following method in my NewsController:

```<code>public JsonResult GetAllNews()
{
   var items = newsService.FindAll();
   var jsonResult = Json(items);

   return jsonResult;
}
</code>```

In my view I want to try and call this method to populate my YUI datatable.  I put a breakpoint on the first line of this method but the breakpoint is not hit.  Here is my code in the view to call this method:

```<code>var newsDataSource = YAHOO.util.DataSource('@Url.Action("GetAllNews");');
</code>```

I even tried:

```<code>var newsDataSource = YAHOO.util.DataSource("/News/GetAllNews/");
</code>```

Both don't seem to work.

Here is my datatable code:

```<code><div id="grdNews"></div>

<script type="text/javascript">
   // News grid
   var newsColumnDefs = [
      { key: "id", label: "Identifier" },
      { key: "title", label: "Title" },
      { key: "body", label: "Body" }
   ];

   //var newsDataSource = YAHOO.util.DataSource('@Url.Action("GetAllNews");');
   var newsDataSource = YAHOO.util.DataSource("/News/GetAllNews/");
   newsDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
   newsDataSource.responseSchema = {
      fields: [
         { key: "id" },
         { key: "title" },
         { key: "body" }
      ]
   };

   var myDataTable = new YAHOO.widget.DataTable("grdNews", newsColumnDefs, newsDataSource);
</script>
</code>```

What am I doing wrong?

答:
Don't forget to make this method return JSON for GET requests as well:

```<code>public JsonResult GetAllNews()
{
   var items = newsService.FindAll();
   return Json(items, JsonRequestBehavior.AllowGet);
}
</code>```

Also setting a datasource doesn't mean that it will invoke the method. Maybe there's some other part of your code that's problematic. Install FireBug and see if an AJAX request is sent.

UPDATE:

Now that the question has been clarified and you are talking about YUI datatable, here's a full working example:

Controller:

```<code>public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult GetAllNews()
    {
        var news = new[]
        {
            new { id = 1, title = "title 1", body = "body 1" },
            new { id = 2, title = "title 2", body = "body 2" },
            new { id = 3, title = "title 3", body = "body 3" },
        };
        return Json(new
        {
            Result = news
        }, JsonRequestBehavior.AllowGet);
    }
}
</code>```

View (~/Views/Home/Index.cshtml):

```<code>@{
    ViewBag.Title = "Home Page";
}

<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.8.2r1/build/fonts/fonts-min.css" />
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.8.2r1/build/datatable/assets/skins/sam/datatable.css" />
<script type="text/javascript" src="http://yui.yahooapis.com/2.8.2r1/build/yahoo-dom-event/yahoo-dom-event.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.8.2r1/build/connection/connection-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.8.2r1/build/json/json-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.8.2r1/build/element/element-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.8.2r1/build/datasource/datasource-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.8.2r1/build/datatable/datatable-min.js"></script>

<script type="text/javascript">
    var newsColumnDefs = [
        { key: "id", label: "Identifier" },
        { key: "title", label: "Title" },
        { key: "body", label: "Body" }
    ];

    var newsDataSource = new YAHOO.util.DataSource('@Url.Action("GetAllNews")');
    newsDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
    newsDataSource.responseSchema = {
        resultsList: 'Result',
        fields: [ "id", "title", "body" ]
    };

    var myDataTable = new YAHOO.widget.DataTable("grdNews", newsColumnDefs, newsDataSource);
</script>

<div id="grdNews"></div>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am using ASP.NET MVC 3 with the razor view engine.

I have the following method in my NewsController:

public JsonResult GetAllNews()
{
   var items = newsService.FindAll();
   var jsonResult = Json(items);

   return jsonResult;
}

In my view I want to try and call this method to populate my YUI datatable.  I put a breakpoint on the first line of this method but the breakpoint is not hit.  Here is my code in the view to call this method:

var newsDataSource = YAHOO.util.DataSource('@Url.Action("GetAllNews");');

I even tried:

var newsDataSource = YAHOO.util.DataSource("/News/GetAllNews/");

Both don't seem to work.

Here is my datatable code:

What am I doing wrong?

Body:
Don't forget to make this method return JSON for GET requests as well:

public JsonResult GetAllNews()
{
   var items = newsService.FindAll();
   return Json(items, JsonRequestBehavior.AllowGet);
}

Also setting a datasource doesn't mean that it will invoke the method. Maybe there's some other part of your code that's problematic. Install FireBug and see if an AJAX request is sent.

UPDATE:

Now that the question has been clarified and you are talking about YUI datatable, here's a full working example:

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult GetAllNews()
    {
        var news = new[]
        {
            new { id = 1, title = "title 1", body = "body 1" },
            new { id = 2, title = "title 2", body = "body 2" },
            new { id = 3, title = "title 3", body = "body 3" },
        };
        return Json(new
        {
            Result = news
        }, JsonRequestBehavior.AllowGet);
    }
}

View (~/Views/Home/Index.cshtml):

@{
    ViewBag.Title = "Home Page";
}

<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.8.2r1/build/fonts/fonts-min.css" />
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.8.2r1/build/datatable/assets/skins/sam/datatable.css" />
<script type="text/javascript" src="http://yui.yahooapis.com/2.8.2r1/build/yahoo-dom-event/yahoo-dom-event.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.8.2r1/build/connection/connection-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.8.2r1/build/json/json-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.8.2r1/build/element/element-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.8.2r1/build/datasource/datasource-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.8.2r1/build/datatable/datatable-min.js"></script>

<script type="text/javascript">
    var newsColumnDefs = [
        { key: "id", label: "Identifier" },
        { key: "title", label: "Title" },
        { key: "body", label: "Body" }
    ];

    var newsDataSource = new YAHOO.util.DataSource('@Url.Action("GetAllNews")');
    newsDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
    newsDataSource.responseSchema = {
        resultsList: 'Result',
        fields: [ "id", "title", "body" ]
    };

    var myDataTable = new YAHOO.widget.DataTable("grdNews", newsColumnDefs, newsDataSource);
</script>

<div id="grdNews"></div>


问:
Whether the flash size of cobalt including run-time resource will keep increasing?
For coablt 10.56829, the built out cobalt binary(QA) has about 21 MB flash size， and the content resource has about 53M flash size， totally about 74 MB, it means it needs about 74M flash size at run time, so is there a chance to reduce the flash size of cobalt? And whether it would keep a limit to avoid the flash size of cobalt which may be keeping increasing in future?</p>

答:
we're actively monitoring Cobalt's package size and trying to keep it as low as possible.  That said, as development occurs, it may of course fluctuate.

If you're interested in reducing your package's total size, one option to explore is to adjust the font package used with your build.  You can set this by adjusting the value of 'cobalt_font_package' in your gyp_configuration.gypi file.  See https://cobalt.googlesource.com/cobalt/+/master/src/cobalt/build/config/base.gypi#97 for more information.


问:
JSON with outer brackets in d3.js?
when i got a JSON file called "test.json" which looks like this:

```<code>[{
"name":"abc",
"parent":"null",
"children":[],
}
]
</code>```

That means with the outer brackets [] wrapping the whole data, it is not possible to use it in d3.js with the hierarchy function:

```<code> d3.json("test.json", function(a) {

    var hierarchy = d3.hierarchy(a),
        links = hierarchy.links()
        nodes = hierarchy.descendants();
</code>```

Now, when i leave the brackets away, which means that "test.json" looks like this, it is possible to use the file:

```<code>{
"name":"abc",
"parent":"null",
"children":[],
}
</code>```

Now, my question is: Is this a specific problem of d3.js in general, maybe with the combination of the hierarchy function or it is always not working, when wrap the whole file with brackets []?

答:
The outer brackets signify an array. To get the object / map inside them, index it out:

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

So if a is:

```<code>[   {
        "name": "abc",
        "parent": "null",
        "children": []
    }
]
</code>```

Then a[0] is just

```<code>{
    "name": "abc",
    "parent": "null",
    "children": []
}
</code>```

Title: JSON with outer brackets in d3.js?

Body:
when i got a JSON file called "test.json" which looks like this:

[{
"name":"abc",
"parent":"null",
"children":[],
}
]

That means with the outer brackets [] wrapping the whole data, it is not possible to use it in d3.js with the hierarchy function:

 d3.json("test.json", function(a) {

    var hierarchy = d3.hierarchy(a),
        links = hierarchy.links()
        nodes = hierarchy.descendants();

Now, when i leave the brackets away, which means that "test.json" looks like this, it is possible to use the file:

{
"name":"abc",
"parent":"null",
"children":[],
}

Now, my question is: Is this a specific problem of d3.js in general, maybe with the combination of the hierarchy function or it is always not working, when wrap the whole file with brackets []?

Body:
The outer brackets signify an array. To get the object / map inside them, index it out:

a[0]

So if a is:

[   {
        "name": "abc",
        "parent": "null",
        "children": []
    }
]

Then a[0] is just

{
    "name": "abc",
    "parent": "null",
    "children": []
}


问:
programmatically set up a @PersistenceContext
How can I pro grammatically set up a @PersistenceContext so that I can get the configuration (jDBC Url, Driver Class , etc.) from a simple properties file (so the users can simply modify this file) instead of the bigger and more complex persistence.xml file?

What I have read is that using Persistence.createEntityManagerFactory("bla", properties) will be completly useless because then @PersistenceContext(unitName = "bla") will never work (and it does not work, giving NPEs ...).

I know there are many tutorials but they all use the persistence.xml with an hard coded database type (Oracle, MySQL, ...) and no one explained how I can set up this managed bean programaitcally?

答:
Given that you have provided an ejb tag I assume that you're executing in a complete Java EE environment.

Your users should never have to touch the persistence.xml because it would normally be configured with a datasource reference:

```<code><persistence-unit name="bla" transaction-type="JTA">
   <jta-data-source>java:jboss/datasources/BlaDS</jta-data-source>
   ...
</code>```

The users then use the tools provided by their Java EE server implementation to create the data source.

Most implementations provide both GUI and CLI tools for performing this task.

For example in WildFly a CLI script might look like:

```<code># Execute offline
embed-server --server-config=standalone.xml

deploy postgresql-42.0.0.jre7.jar

# Add the application datasource
data-source add \
    --name=BlaDS \
    --driver-name=postgresql-42.0.0.jre7.jar \
    --connection-url=jdbc:postgresql://bladb-host:5432/bladb \
    --jndi-name=java:jboss/datasources/BlaDS \
    --user-name=bla \
    --password=bla-password \
    --use-ccm=false \
    --min-pool-size=10 \
    --max-pool-size=25 \
    --pool-prefill=true \
    --blocking-timeout-wait-millis=5000 \
    --new-connection-sql="set datestyle = ISO, European;"
</code>```

Normally users would need the ability to control other database connection related attributes like connection pools sizes, etc as shown.

Body:
Given that you have provided an ejb tag I assume that you're executing in a complete Java EE environment.

Your users should never have to touch the persistence.xml because it would normally be configured with a datasource reference:

<persistence-unit name="bla" transaction-type="JTA">
   <jta-data-source>java:jboss/datasources/BlaDS</jta-data-source>
   ...

The users then use the tools provided by their Java EE server implementation to create the data source.

Most implementations provide both GUI and CLI tools for performing this task.

For example in WildFly a CLI script might look like:

# Execute offline
embed-server --server-config=standalone.xml

deploy postgresql-42.0.0.jre7.jar

# Add the application datasource
data-source add \
    --name=BlaDS \
    --driver-name=postgresql-42.0.0.jre7.jar \
    --connection-url=jdbc:postgresql://bladb-host:5432/bladb \
    --jndi-name=java:jboss/datasources/BlaDS \
    --user-name=bla \
    --password=bla-password \
    --use-ccm=false \
    --min-pool-size=10 \
    --max-pool-size=25 \
    --pool-prefill=true \
    --blocking-timeout-wait-millis=5000 \
    --new-connection-sql="set datestyle = ISO, European;"

Normally users would need the ability to control other database connection related attributes like connection pools sizes, etc as shown.


问:
Laravel Eloquent model update according to condition of field value null or existing
I am trying to update Laravel Eloquent model like this.

```<code>Res_Reservations::where('time_id', $time['id'])
                ->where('date',  $bus['date'])
                ->where('valid',  config('config.TYPE_SCHEDULE_UNREMOVED'))
                ->where(function($query) use($time, $notesAdd) {
                    $query->whereNull('reason', function($query) use ($time, $notesAdd) {
                        return $query->update([
                            'time_id' => $time['move'],
                            'reason' => $notesAdd
                        ]);
                    })
                    ->orWhere('reason', '=', '', function($query) use ($time, $notesAdd) {
                        return $query->update([
                            'time_id' => $time['move'],
                            'reason' => $notesAdd
                        ]);
                    })
                    ->orWhere('reason', '<>', '', function($query) use ($time, $notesAdd) {
                        return $query->update([
                            'time_id' => $time['move'],
                            'reason' => DB::raw("CONCAT(reason, \r\n'" . $notesAdd . "')")
                        ]);
                    });
                });
</code>```

But it does not working.

In other words, I want to update as below.

if 'reason' is null or emptystring

```<code>Res_Reservations::where('time_id', $time['id'])
                ->where('date',  $bus['date'])
                ->where('valid',  config('config.TYPE_SCHEDULE_UNREMOVED'))
                ->update([
                    'time_id' => $time['move'],
                    'reason' => $notesAdd
                ]);
</code>```

else

```<code>Res_Reservations::where('time_id', $time['id'])
                ->where('date',  $bus['date'])
                ->where('valid',  config('config.TYPE_SCHEDULE_UNREMOVED'))
                ->update([
                    'time_id' => $time['move'],
                    'reason' => DB::raw("CONCAT(reason, '\r\n" . $notesAdd . "')")
                ]);
</code>```

What is my mistake? And how can I make statements simpler? Please let me know~

答:
It is wrong to use update function inside the callback of where function

You have to do it in 2 queries like:

```<code>Res_Reservations::where('time_id', $time['id'])
    ->where('date', $bus['date'])
    ->where('valid', config('config.TYPE_SCHEDULE_UNREMOVED'))
    ->where(function ($query
    {
        $query->where('reason', null)
            ->orWhere('reason', '');
    })
    ->update([
        'time_id' => $time['move'],
        'reason'  => $notesAdd,
    ]);

Res_Reservations::where('time_id', $time['id'])
    ->where('date', $bus['date'])
    ->where('valid', config('config.TYPE_SCHEDULE_UNREMOVED'))
    ->where('reason', '!=',  null)
    ->where('reason', '!=' '');
    ->update([
        'time_id' => $time['move'],
        'reason'  => DB::raw('CONCAT(reason, "\r\n' . $notesAdd . '")'),
    ]);
</code>```

Body:
I am trying to update Laravel Eloquent model like this.

Res_Reservations::where('time_id', $time['id'])
                ->where('date',  $bus['date'])
                ->where('valid',  config('config.TYPE_SCHEDULE_UNREMOVED'))
                ->where(function($query) use($time, $notesAdd) {
                    $query->whereNull('reason', function($query) use ($time, $notesAdd) {
                        return $query->update([
                            'time_id' => $time['move'],
                            'reason' => $notesAdd
                        ]);
                    })
                    ->orWhere('reason', '=', '', function($query) use ($time, $notesAdd) {
                        return $query->update([
                            'time_id' => $time['move'],
                            'reason' => $notesAdd
                        ]);
                    })
                    ->orWhere('reason', '<>', '', function($query) use ($time, $notesAdd) {
                        return $query->update([
                            'time_id' => $time['move'],
                            'reason' => DB::raw("CONCAT(reason, \r\n'" . $notesAdd . "')")
                        ]);
                    });
                });

But it does not working.

In other words, I want to update as below.

if 'reason' is null or emptystring

Res_Reservations::where('time_id', $time['id'])
                ->where('date',  $bus['date'])
                ->where('valid',  config('config.TYPE_SCHEDULE_UNREMOVED'))
                ->update([
                    'time_id' => $time['move'],
                    'reason' => $notesAdd
                ]);

else

Res_Reservations::where('time_id', $time['id'])
                ->where('date',  $bus['date'])
                ->where('valid',  config('config.TYPE_SCHEDULE_UNREMOVED'))
                ->update([
                    'time_id' => $time['move'],
                    'reason' => DB::raw("CONCAT(reason, '\r\n" . $notesAdd . "')")
                ]);

What is my mistake? And how can I make statements simpler? Please let me know~

Body:
It is wrong to use update function inside the callback of where function

You have to do it in 2 queries like:

Res_Reservations::where('time_id', $time['id'])
    ->where('date', $bus['date'])
    ->where('valid', config('config.TYPE_SCHEDULE_UNREMOVED'))
    ->where(function ($query
    {
        $query->where('reason', null)
            ->orWhere('reason', '');
    })
    ->update([
        'time_id' => $time['move'],
        'reason'  => $notesAdd,
    ]);

Res_Reservations::where('time_id', $time['id'])
    ->where('date', $bus['date'])
    ->where('valid', config('config.TYPE_SCHEDULE_UNREMOVED'))
    ->where('reason', '!=',  null)
    ->where('reason', '!=' '');
    ->update([
        'time_id' => $time['move'],
        'reason'  => DB::raw('CONCAT(reason, "\r\n' . $notesAdd . '")'),
    ]);


问:
For loop to eliminate columns in multiple dfs
I've got about 10 dataframes. For the example, here are two:

```<code>name <- c("A", "B", "C")
name.footnote <- c("this", "that", "the other")
class <- c("one", "two", "three")
class.footnote <- c("blank", "blank", "blank")

df1 <- data.frame(name, name.footnote, class, class.footnote)
df2 <- data.frame(name, name.footnote, class, class.footnote)
</code>```

When I eliminate columns from them one at a time, my code works fine.

```<code>library(dplyr)
df1 <- select(df1, -ends_with("footnote"))
</code>```

I'd like to write a loop to process both dfs with less code, but can't get my loop working right. I keep getting the same error message:

```<code>Error in UseMethod("select_") :   no applicable method for 'select_'
 applied to an object of class "character".
</code>```

See a few of the many loop codes I've tried, below. What am I missing?

```<code>listofDfs <- list("df1","df2")
</code>```

1.

```<code>lapply(listofDfs, function(df){
  df <- select(df, -ends_with("footnote"))
  return(df)
  }
)
</code>```

2.

```<code>for (i in listofDfs){
  i <- select(i, -ends_with("footnote"))
}
</code>```

答:
Try dropping the quotes when defining your list listofDfs <- list(df1,df2). As the error states, when you have the quotes the elements of your list are character instead of the data.frame that select() is expecting.

```<code>library(dplyr)

listofDfs <- list(df1,df2)

#using lapply
list_out1 <- lapply(listofDfs, function(df){
  df <- select(df, -ends_with("footnote"))
  return(df)
})

#using for loop
list_out2 <- vector("list", length(listofDfs))
for (i in seq_along(listofDfs)){
  list_out2[[i]] <- select(listofDfs[[i]], -ends_with("footnote"))
}
</code>```

follow up per comment

you can use get and assign to work with your original character list and manipulate the dfs in your global environment while iterating.

```<code>listofDfs <- list('df1','df2')

invisible(lapply(listofDfs, function(i){
  df <- select(get(i, globalenv()), -ends_with("footnote"))
  assign(i, df, envir = globalenv())
}))

for (i in listofDfs){
  df <- select(get(i, globalenv()), -ends_with("footnote"))
  assign(i, df, envir = globalenv())
}
</code>```

Body:
I've got about 10 dataframes. For the example, here are two:

name <- c("A", "B", "C")
name.footnote <- c("this", "that", "the other")
class <- c("one", "two", "three")
class.footnote <- c("blank", "blank", "blank")

df1 <- data.frame(name, name.footnote, class, class.footnote)
df2 <- data.frame(name, name.footnote, class, class.footnote)

When I eliminate columns from them one at a time, my code works fine.

library(dplyr)
df1 <- select(df1, -ends_with("footnote"))

I'd like to write a loop to process both dfs with less code, but can't get my loop working right. I keep getting the same error message:

Error in UseMethod("select_") :   no applicable method for 'select_'
 applied to an object of class "character".

See a few of the many loop codes I've tried, below. What am I missing?

listofDfs <- list("df1","df2")

1.

lapply(listofDfs, function(df){
  df <- select(df, -ends_with("footnote"))
  return(df)
  }
)

2.

for (i in listofDfs){
  i <- select(i, -ends_with("footnote"))
}

Body:
Try dropping the quotes when defining your list listofDfs <- list(df1,df2). As the error states, when you have the quotes the elements of your list are character instead of the data.frame that select() is expecting.

library(dplyr)

listofDfs <- list(df1,df2)

#using lapply
list_out1 <- lapply(listofDfs, function(df){
  df <- select(df, -ends_with("footnote"))
  return(df)
})

#using for loop
list_out2 <- vector("list", length(listofDfs))
for (i in seq_along(listofDfs)){
  list_out2[[i]] <- select(listofDfs[[i]], -ends_with("footnote"))
}

follow up per comment

you can use get and assign to work with your original character list and manipulate the dfs in your global environment while iterating.

listofDfs <- list('df1','df2')

invisible(lapply(listofDfs, function(i){
  df <- select(get(i, globalenv()), -ends_with("footnote"))
  assign(i, df, envir = globalenv())
}))

for (i in listofDfs){
  df <- select(get(i, globalenv()), -ends_with("footnote"))
  assign(i, df, envir = globalenv())
}


问:
Re-run an html
```

However, the problem I'm running into is that the script only runs when the webpage initially loads, and then never again. Since I'm adding more tags in an API call and then updating the list via the props, it means I'm left with a bunch of  tags that don't get converted when the call returns.

I've inspected the React console & html and can confirm the tags are there, it's just that the dynamically converted tags don't show up as pins.

I've already tried using jquery and document.appendChild() to add/get the script in componentDidUpdate(), but it doesn't seem to be working. Anybody have any clue how I can get around this?

答:
Try using:a do-while in your script:

```<code>var repeat = 0
Do {
// Your code goes here
repeat = repeat + 1
} while(repeat <= 10)
</code>```

Note: replace 10 with times you want the script to repeat

If you wan't to add a rule to this (so it only runs when...) do:

```<code>var repeat = 'yes'
Do {
// Your code goes here
} while(repeat == 'yes')
</code>```

Now your code will only run when repeat is equal to yes

In action

```<code><a href="javascript:repeat = 'no'">Stop repeating</a>
<a href="javascript:repeat = 'yes'">Start repeating</a>
<script>
var repeat = 'yes'
Do {
// Your code goes here
If(var1 == var2) { repeat = 'no' }
} while(repeat == 'yes')
</script>
</code>```

ContentLicense: CC BY-SA 4.0

Title: Re-run an html <script> in React

Body:
I'm making a component in React that has Facebook data pulled from an API call. The API call returns and updates a list, which render() will then populate with  tags that are supposed to be converted to actual images by a script from Facebook's website. Something like this:

My html file includes this script, which I assume runs through the HTML code and converts the tags to something viewable.

However, the problem I'm running into is that the script only runs when the webpage initially loads, and then never again. Since I'm adding more tags in an API call and then updating the list via the props, it means I'm left with a bunch of  tags that don't get converted when the call returns.

I've inspected the React console & html and can confirm the tags are there, it's just that the dynamically converted tags don't show up as pins.

I've already tried using jquery and document.appendChild() to add/get the script in componentDidUpdate(), but it doesn't seem to be working. Anybody have any clue how I can get around this?

Body:
Try using:a do-while in your script:

var repeat = 0
Do {
// Your code goes here
repeat = repeat + 1
} while(repeat <= 10)

Note: replace 10 with times you want the script to repeat

If you wan't to add a rule to this (so it only runs when...) do:

var repeat = 'yes'
Do {
// Your code goes here
} while(repeat == 'yes')

Now your code will only run when repeat is equal to yes

In action

<a href="javascript:repeat = 'no'">Stop repeating</a>
<a href="javascript:repeat = 'yes'">Start repeating</a>
<script>
var repeat = 'yes'
Do {
// Your code goes here
If(var1 == var2) { repeat = 'no' }
} while(repeat == 'yes')
</script>


问:
Class Not Found Exception - Xamarin Android
I get this error when I build my Xamarin.Android project.

```<code>06-05 12:42:15.322 I/MonoDroid(30682): UNHANDLED EXCEPTION:
06-05 12:42:15.380 I/MonoDroid(30682): Java.Lang.ClassNotFoundException: Didn't find class "md565316a0900a9b0d8bca349e28cad6b91.AndroidVPNConnection_LaunchVPNServiceConnection" on path: DexPathList[[zip file "/data/app/com.redcheetah-1/base.apk"],nativeLibraryDirectories=[/data/app/com.redcheetah-1/lib/arm, /vendor/lib, /system/lib]]
06-05 12:42:15.380 I/MonoDroid(30682):   at Java.Interop.JniEnvironment+Types.FindClass (System.String classname) [0x00114] in <bd30a18775d94dc8b6263aecd1ca9077>:0
06-05 12:42:15.380 I/MonoDroid(30682):   at Java.Interop.JniType..ctor (System.String classname) [0x00006] in <bd30a18775d94dc8b6263aecd1ca9077>:0
06-05 12:42:15.380 I/MonoDroid(30682):   at Java.Interop.JniPeerMembers+JniInstanceMethods..ctor (System.Type declaringType) [0x00064] in <bd30a18775d94dc8b6263aecd1ca9077>:0
06-05 12:42:15.380 I/MonoDroid(30682):   at Java.Interop.JniPeerMembers+JniInstanceMethods.GetConstructorsForType (System.Type declaringType) [0x0002c] in <bd30a18775d94dc8b6263aecd1ca9077>:0
06-05 12:42:15.380 I/MonoDroid(30682):   at Java.Interop.JniPeerMembers+JniInstanceMethods.StartCreateInstance (System.String constructorSignature, System.Type declaringType, Java.Interop.JniArgumentValue* parameters) [0x00032] in <bd30a18775d94dc8b6263aecd1ca9077>:0
06-05 12:42:15.380 I/MonoDroid(30682):   at Java.Lang.Object..ctor () [0x0001f] in /Users/builder/data/lanes/4695/9dbc4c53/source/xamarin-android/src/Mono.Android/obj/Release/android-23/mcw/Java.Lang.Object.cs:30
06-05 12:42:15.380 I/MonoDroid(30682):   at SwiftAndroidLib.AndroidVPNConnection+LaunchVPNServiceConnection..ctor (SwiftAndroidLib.AndroidVPNConnection outerInstance) [0x00000] in C:\WorkSpace\RC\ClientApp\SwiftLib\SwiftAndroidLib\AndroidVPNConnectionJavaBindingLib.cs:349
06-05 12:42:15.380 I/MonoDroid(30682):   at SwiftAndroidLib.AndroidVPNConnection..ctor () [0x00034] in C:\WorkSpace\RC\ClientApp\SwiftLib\SwiftAndroidLib\AndroidVPNConnectionJavaBindingLib.cs:39
06-05 12:42:15.380 I/MonoDroid(30682):   at SwiftCommonLib.SwiftBaseApp.RegisterPlatformSpecificServices () [0x0001e] in C:\WorkSpace\RC\ClientApp\SwiftLib\SwiftAndroidLib\SwiftAndroidApp.cs:81
06-05 12:42:15.380 I/MonoDroid(30682):   at SwiftCommonLib.SwiftBaseApp+<RegisterPlatformServices>d__15.MoveNext () [0x0007f] in C:\WorkSpace\RC\ClientApp\SwiftLib\SwiftCommonLib\SwiftBaseApp.cs:41
06-05 12:42:15.380 I/MonoDroid(30682): --- End of stack trace from previous location where exception was thrown ---
06-05 12:42:15.380 I/MonoDroid(30682):   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Users/builder/jenkins/workspace/xamarin-android/xamarin-android/external/mono/mcs/class/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:151
06-05 12:42:15.380 I/MonoDroid(30682):   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00037] in /Users/builder/jenkins/workspace/xamarin-android/xamarin-android/external/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:187
06-05 12:42:15.380 I/MonoDroid(30682):   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in /Users/builder/jenkins/workspace/xamarin-android/xamarin-android/external/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:156
06-05 12:42:15.380 I/MonoDroid(30682):   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in /Users/builder/jenkins/workspace/xamarin-android/xamarin-android/external/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:128
06-05 12:42:15.380 I/MonoDroid(30682):   at System.Runtime.CompilerServices.TaskAwaiter.GetResult () [0x00000] in /Users/builder/jenkins/workspace/xamarin-android/xamarin-android/external/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:113
06-05 12:42:15.380 I/MonoDroid(30682):   at RedCheetah.RedCheetahApp+<RegisterPlatformServices>d__2.MoveNext () [0x00020] in C:\WorkSpace\RC\ClientApp\RedCheetah\RedCheetah.XFormsApp\RedCheetahApp.cs:39
06-05 12:42:15.380 I/MonoDroid(30682): --- End of stack trace from previous location where exception was thrown ---
06-05 12:42:15.380 I/MonoDroid(30682):   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Users/builder/jenkins/workspace/xamarin-android/xamarin-android/external/mono/mcs/class/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:151
06-05 12:42:15.380 I/MonoDroid(30682):   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00037] in /Users/builder/jenkins/workspace/xamarin-android/xamarin-android/external/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:187
06-05 12:42:15.380 I/MonoDroid(30682):   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in /Users/builder/jenkins/workspace/xamarin-android/xamarin-android/external/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:156
06-05 12:42:15.380 I/MonoDroid(30682):   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in /Users/builder/jenkins/workspace/xamarin-android/xamarin-android/external/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:128
06-05 12:42:15.380 I/MonoDroid(30682):   at System.Runtime.CompilerServices.TaskAwaiter.GetResult () [0x00000] in /Users/builder/jenkins/workspace/xamarin-android/xamarin-android/external/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:113
06-05 12:42:15.380 I/MonoDroid(30682):   at SwiftCommonLib.SwiftBaseApp+<Init>d__14.MoveNext () [0x0002b] in C:\WorkSpace\RC\ClientApp\SwiftLib\SwiftCommonLib\SwiftBaseApp.cs:20
06-05 12:42:15.380 I/MonoDroid(30682): --- End of stack trace from previous location where exception was thrown ---
06-05 12:42:15.380 I/MonoDroid(30682):   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Users/builder/jenkins/workspace/xamarin-android/xamarin-android/external/mono/mcs/class/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:151
06-05 12:42:15.380 I/MonoDroid(30682):   at System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.<ThrowAsync>b__6_0 (System.Object state) [0x00000] in /Users/builder/jenkins/workspace/xamarin-android/xamarin-android/external/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/AsyncMethodBuilder.cs:1018
06-05 12:42:15.380 I/MonoDroid(30682):   at Android.App.SyncContext+<>c__DisplayClass2_0.<Post>b__0 () [0x00000] in /Users/builder/data/lanes/4695/9dbc4c53/source/xamarin-android/src/Mono.Android/Android.App/SyncContext.cs:35
06-05 12:42:15.381 I/MonoDroid(30682):   at Java.Lang.Thread+RunnableImplementor.Run () [0x00008] in /Users/builder/data/lanes/4695/9dbc4c53/source/xamarin-android/src/Mono.Android/Java.Lang/Thread.cs:36
06-05 12:42:15.381 I/MonoDroid(30682):   at Java.Lang.IRunnableInvoker.n_Run (System.IntPtr jnienv, System.IntPtr native__this) [0x00008] in /Users/builder/data/lanes/4695/9dbc4c53/source/xamarin-android/src/Mono.Android/obj/Release/android-23/mcw/Java.Lang.IRunnable.cs:81
06-05 12:42:15.381 I/MonoDroid(30682):   at (wrapper dynamic-method) System.Object:1b051e2f-3dbb-406a-ba95-3384e34e8ded (intptr,intptr)
06-05 12:42:15.381 I/MonoDroid(30682):   --- End of managed Java.Lang.ClassNotFoundException stack trace ---
06-05 12:42:15.381 I/MonoDroid(30682): java.lang.ClassNotFoundException: Didn't find class "md565316a0900a9b0d8bca349e28cad6b91.AndroidVPNConnection_LaunchVPNServiceConnection" on path: DexPathList[[zip file "/data/app/com.redcheetah-1/base.apk"],nativeLibraryDirectories=[/data/app/com.redcheetah-1/lib/arm, /vendor/lib, /system/lib]]
06-05 12:42:15.381 I/MonoDroid(30682):  at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
06-05 12:42:15.381 I/MonoDroid(30682):  at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
06-05 12:42:15.381 I/MonoDroid(30682):  at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
06-05 12:42:15.381 I/MonoDroid(30682):  at md53843fcbd823548032cdc16788941cea6.MainActivity.n_onCreate(Native Method)
06-05 12:42:15.381 I/MonoDroid(30682):  at md53843fcbd823548032cdc16788941cea6.MainActivity.onCreate(MainActivity.java:32)
06-05 12:42:15.381 I/MonoDroid(30682):  at android.app.Activity.performCreate(Activity.java:6092)
06-05 12:42:15.381 I/MonoDroid(30682):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1112)
06-05 12:42:15.381 I/MonoDroid(30682):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2467)
06-05 12:42:15.381 I/MonoDroid(30682):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2594)
06-05 12:42:15.381 I/MonoDroid(30682):  at android.app.ActivityThread.access$800(ActivityThread.java:177)
06-05 12:42:15.381 I/MonoDroid(30682):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1469)
06-05 12:42:15.381 I/MonoDroid(30682):  at android.os.Handler.dispatchMessage(Handler.java:111)
06-05 12:42:15.381 I/MonoDroid(30682):  at android.os.Looper.loop(Looper.java:194)
06-05 12:42:15.381 I/MonoDroid(30682):  at android.app.ActivityThread.main(ActivityThread.java:5627)
06-05 12:42:15.381 I/MonoDroid(30682):  at java.lang.reflect.Method.invoke(Native Method)
06-05 12:42:15.381 I/MonoDroid(30682):  at java.lang.reflect.Method.invoke(Method.java:372)
06-05 12:42:15.381 I/MonoDroid(30682):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
06-05 12:42:15.381 I/MonoDroid(30682):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
06-05 12:42:15.381 I/MonoDroid(30682):  Suppressed: java.lang.ClassNotFoundException: md565316a0900a9b0d8bca349e28cad6b91.AndroidVPNConnection_LaunchVPNServiceConnection
06-05 12:42:15.381 I/MonoDroid(30682):      at java.lang.Class.classForName(Native Method)
06-05 12:42:15.381 I/MonoDroid(30682):      at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
06-05 12:42:15.381 I/MonoDroid(30682):      at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
06-05 12:42:15.381 I/MonoDroid(30682):      at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
06-05 12:42:15.381 I/MonoDroid(30682):      ... 16 more
06-05 12:42:15.381 I/MonoDroid(30682):  Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available
06-05 12:42:15.394 D/Mono    (30682): Assembly Ref addref HockeySDK.AndroidBindings[0xb46eba60] -> System[0x9c9daee0]: 10
</code>```

I have tried the following things:

Reinstall Xamarin

Cleaned and Rebuilt the solution (Builds successfully)

I also enabled Diagnostic output in MSBuild.

Please, How do I fix this error?

答: Issue Fixed, I needed to inherit Java.Lang.Oject in my CSharp class i.e the class being refereed to in my error message. I needed to do this because my class also inherited from some Java based Lib. </p>

Body:
I get this error when I build my Xamarin.Android project.

06-05 12:42:15.322 I/MonoDroid(30682): UNHANDLED EXCEPTION:
06-05 12:42:15.380 I/MonoDroid(30682): Java.Lang.ClassNotFoundException: Didn't find class "md565316a0900a9b0d8bca349e28cad6b91.AndroidVPNConnection_LaunchVPNServiceConnection" on path: DexPathList[[zip file "/data/app/com.redcheetah-1/base.apk"],nativeLibraryDirectories=[/data/app/com.redcheetah-1/lib/arm, /vendor/lib, /system/lib]]
06-05 12:42:15.380 I/MonoDroid(30682):   at Java.Interop.JniEnvironment+Types.FindClass (System.String classname) [0x00114] in <bd30a18775d94dc8b6263aecd1ca9077>:0
06-05 12:42:15.380 I/MonoDroid(30682):   at Java.Interop.JniType..ctor (System.String classname) [0x00006] in <bd30a18775d94dc8b6263aecd1ca9077>:0
06-05 12:42:15.380 I/MonoDroid(30682):   at Java.Interop.JniPeerMembers+JniInstanceMethods..ctor (System.Type declaringType) [0x00064] in <bd30a18775d94dc8b6263aecd1ca9077>:0
06-05 12:42:15.380 I/MonoDroid(30682):   at Java.Interop.JniPeerMembers+JniInstanceMethods.GetConstructorsForType (System.Type declaringType) [0x0002c] in <bd30a18775d94dc8b6263aecd1ca9077>:0
06-05 12:42:15.380 I/MonoDroid(30682):   at Java.Interop.JniPeerMembers+JniInstanceMethods.StartCreateInstance (System.String constructorSignature, System.Type declaringType, Java.Interop.JniArgumentValue* parameters) [0x00032] in <bd30a18775d94dc8b6263aecd1ca9077>:0
06-05 12:42:15.380 I/MonoDroid(30682):   at Java.Lang.Object..ctor () [0x0001f] in /Users/builder/data/lanes/4695/9dbc4c53/source/xamarin-android/src/Mono.Android/obj/Release/android-23/mcw/Java.Lang.Object.cs:30
06-05 12:42:15.380 I/MonoDroid(30682):   at SwiftAndroidLib.AndroidVPNConnection+LaunchVPNServiceConnection..ctor (SwiftAndroidLib.AndroidVPNConnection outerInstance) [0x00000] in C:\WorkSpace\RC\ClientApp\SwiftLib\SwiftAndroidLib\AndroidVPNConnectionJavaBindingLib.cs:349
06-05 12:42:15.380 I/MonoDroid(30682):   at SwiftAndroidLib.AndroidVPNConnection..ctor () [0x00034] in C:\WorkSpace\RC\ClientApp\SwiftLib\SwiftAndroidLib\AndroidVPNConnectionJavaBindingLib.cs:39
06-05 12:42:15.380 I/MonoDroid(30682):   at SwiftCommonLib.SwiftBaseApp.RegisterPlatformSpecificServices () [0x0001e] in C:\WorkSpace\RC\ClientApp\SwiftLib\SwiftAndroidLib\SwiftAndroidApp.cs:81
06-05 12:42:15.380 I/MonoDroid(30682):   at SwiftCommonLib.SwiftBaseApp+<RegisterPlatformServices>d__15.MoveNext () [0x0007f] in C:\WorkSpace\RC\ClientApp\SwiftLib\SwiftCommonLib\SwiftBaseApp.cs:41
06-05 12:42:15.380 I/MonoDroid(30682): --- End of stack trace from previous location where exception was thrown ---
06-05 12:42:15.380 I/MonoDroid(30682):   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Users/builder/jenkins/workspace/xamarin-android/xamarin-android/external/mono/mcs/class/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:151
06-05 12:42:15.380 I/MonoDroid(30682):   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00037] in /Users/builder/jenkins/workspace/xamarin-android/xamarin-android/external/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:187
06-05 12:42:15.380 I/MonoDroid(30682):   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in /Users/builder/jenkins/workspace/xamarin-android/xamarin-android/external/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:156
06-05 12:42:15.380 I/MonoDroid(30682):   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in /Users/builder/jenkins/workspace/xamarin-android/xamarin-android/external/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:128
06-05 12:42:15.380 I/MonoDroid(30682):   at System.Runtime.CompilerServices.TaskAwaiter.GetResult () [0x00000] in /Users/builder/jenkins/workspace/xamarin-android/xamarin-android/external/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:113
06-05 12:42:15.380 I/MonoDroid(30682):   at RedCheetah.RedCheetahApp+<RegisterPlatformServices>d__2.MoveNext () [0x00020] in C:\WorkSpace\RC\ClientApp\RedCheetah\RedCheetah.XFormsApp\RedCheetahApp.cs:39
06-05 12:42:15.380 I/MonoDroid(30682): --- End of stack trace from previous location where exception was thrown ---
06-05 12:42:15.380 I/MonoDroid(30682):   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Users/builder/jenkins/workspace/xamarin-android/xamarin-android/external/mono/mcs/class/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:151
06-05 12:42:15.380 I/MonoDroid(30682):   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00037] in /Users/builder/jenkins/workspace/xamarin-android/xamarin-android/external/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:187
06-05 12:42:15.380 I/MonoDroid(30682):   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in /Users/builder/jenkins/workspace/xamarin-android/xamarin-android/external/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:156
06-05 12:42:15.380 I/MonoDroid(30682):   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in /Users/builder/jenkins/workspace/xamarin-android/xamarin-android/external/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:128
06-05 12:42:15.380 I/MonoDroid(30682):   at System.Runtime.CompilerServices.TaskAwaiter.GetResult () [0x00000] in /Users/builder/jenkins/workspace/xamarin-android/xamarin-android/external/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:113
06-05 12:42:15.380 I/MonoDroid(30682):   at SwiftCommonLib.SwiftBaseApp+<Init>d__14.MoveNext () [0x0002b] in C:\WorkSpace\RC\ClientApp\SwiftLib\SwiftCommonLib\SwiftBaseApp.cs:20
06-05 12:42:15.380 I/MonoDroid(30682): --- End of stack trace from previous location where exception was thrown ---
06-05 12:42:15.380 I/MonoDroid(30682):   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Users/builder/jenkins/workspace/xamarin-android/xamarin-android/external/mono/mcs/class/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:151
06-05 12:42:15.380 I/MonoDroid(30682):   at System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.<ThrowAsync>b__6_0 (System.Object state) [0x00000] in /Users/builder/jenkins/workspace/xamarin-android/xamarin-android/external/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/AsyncMethodBuilder.cs:1018
06-05 12:42:15.380 I/MonoDroid(30682):   at Android.App.SyncContext+<>c__DisplayClass2_0.<Post>b__0 () [0x00000] in /Users/builder/data/lanes/4695/9dbc4c53/source/xamarin-android/src/Mono.Android/Android.App/SyncContext.cs:35
06-05 12:42:15.381 I/MonoDroid(30682):   at Java.Lang.Thread+RunnableImplementor.Run () [0x00008] in /Users/builder/data/lanes/4695/9dbc4c53/source/xamarin-android/src/Mono.Android/Java.Lang/Thread.cs:36
06-05 12:42:15.381 I/MonoDroid(30682):   at Java.Lang.IRunnableInvoker.n_Run (System.IntPtr jnienv, System.IntPtr native__this) [0x00008] in /Users/builder/data/lanes/4695/9dbc4c53/source/xamarin-android/src/Mono.Android/obj/Release/android-23/mcw/Java.Lang.IRunnable.cs:81
06-05 12:42:15.381 I/MonoDroid(30682):   at (wrapper dynamic-method) System.Object:1b051e2f-3dbb-406a-ba95-3384e34e8ded (intptr,intptr)
06-05 12:42:15.381 I/MonoDroid(30682):   --- End of managed Java.Lang.ClassNotFoundException stack trace ---
06-05 12:42:15.381 I/MonoDroid(30682): java.lang.ClassNotFoundException: Didn't find class "md565316a0900a9b0d8bca349e28cad6b91.AndroidVPNConnection_LaunchVPNServiceConnection" on path: DexPathList[[zip file "/data/app/com.redcheetah-1/base.apk"],nativeLibraryDirectories=[/data/app/com.redcheetah-1/lib/arm, /vendor/lib, /system/lib]]
06-05 12:42:15.381 I/MonoDroid(30682):  at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
06-05 12:42:15.381 I/MonoDroid(30682):  at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
06-05 12:42:15.381 I/MonoDroid(30682):  at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
06-05 12:42:15.381 I/MonoDroid(30682):  at md53843fcbd823548032cdc16788941cea6.MainActivity.n_onCreate(Native Method)
06-05 12:42:15.381 I/MonoDroid(30682):  at md53843fcbd823548032cdc16788941cea6.MainActivity.onCreate(MainActivity.java:32)
06-05 12:42:15.381 I/MonoDroid(30682):  at android.app.Activity.performCreate(Activity.java:6092)
06-05 12:42:15.381 I/MonoDroid(30682):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1112)
06-05 12:42:15.381 I/MonoDroid(30682):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2467)
06-05 12:42:15.381 I/MonoDroid(30682):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2594)
06-05 12:42:15.381 I/MonoDroid(30682):  at android.app.ActivityThread.access$800(ActivityThread.java:177)
06-05 12:42:15.381 I/MonoDroid(30682):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1469)
06-05 12:42:15.381 I/MonoDroid(30682):  at android.os.Handler.dispatchMessage(Handler.java:111)
06-05 12:42:15.381 I/MonoDroid(30682):  at android.os.Looper.loop(Looper.java:194)
06-05 12:42:15.381 I/MonoDroid(30682):  at android.app.ActivityThread.main(ActivityThread.java:5627)
06-05 12:42:15.381 I/MonoDroid(30682):  at java.lang.reflect.Method.invoke(Native Method)
06-05 12:42:15.381 I/MonoDroid(30682):  at java.lang.reflect.Method.invoke(Method.java:372)
06-05 12:42:15.381 I/MonoDroid(30682):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
06-05 12:42:15.381 I/MonoDroid(30682):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
06-05 12:42:15.381 I/MonoDroid(30682):  Suppressed: java.lang.ClassNotFoundException: md565316a0900a9b0d8bca349e28cad6b91.AndroidVPNConnection_LaunchVPNServiceConnection
06-05 12:42:15.381 I/MonoDroid(30682):      at java.lang.Class.classForName(Native Method)
06-05 12:42:15.381 I/MonoDroid(30682):      at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
06-05 12:42:15.381 I/MonoDroid(30682):      at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
06-05 12:42:15.381 I/MonoDroid(30682):      at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
06-05 12:42:15.381 I/MonoDroid(30682):      ... 16 more
06-05 12:42:15.381 I/MonoDroid(30682):  Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available
06-05 12:42:15.394 D/Mono    (30682): Assembly Ref addref HockeySDK.AndroidBindings[0xb46eba60] -> System[0x9c9daee0]: 10

I have tried the following things:

Reinstall Xamarin

Cleaned and Rebuilt the solution (Builds successfully)

I also enabled Diagnostic output in MSBuild.

Please, How do I fix this error?


问:
debugging deobfuscated javascript
I am trying to reverse-engineer a website I don't own, figuring out how some dumb "encryption" works, in order to be able to carry out some operations automatically, by taking the functionality outside the browser.

One of the files is of particular interest, let's call it javascript.js. It is linked in the HTML document like this

```<code><script src="/javascript.js" type="text/javascript"></script>
</code>```

I have

deobfuscated javascript.js

pretty-printed its code

My question is now, considering that I'm using venkman and firefox, how to replace the on-site obfuscated javascript.js with my own pretty-printed code, in order to learn how it works.

Any other tool beside venkman should do, as long as I can still step through the deobfuscated code.

Additional question (just in case I may come cross this related situation):

How to do the same if the javascript.js would be emdedded inline in the html code like ?

For those of you wondering about how legal this is, my question is not the first about reverse-engineering on SO: https://stackoverflow.com/questions/tagged/reverse-engineering

Apparently there's no problem with those questions, why should there be one with mine?

My objective is to understand the code AND my question is about the TOOLS, as in "where to point and click" or which tool could help me (if venkman cannot).

答:
This is going to be very difficult, if not impossible, to do without using browser debugging / extension features like GreaseMonkey or Chrome's Extension API. The reason being that if you don't get involved in the page load sequence, the obfuscated code will already have been run, setting up JavaScript objects, event handlers, etc., etc. You'd have to ensure that your new script replaced those objects and event handlers, which would be complicated and difficult.

With GreaseMonkey or Chrome Extensions or similar on whatever browser you're using, I'd expect it to be possible to detect the page loading script X and replace it with your local script Y. These things run at that level, they get involved in the process.

But despite your goals being aboveboard, debugging on someone else's site is a bad idea. If you introduce a bug through the deobfuscation process, or in the process of trying to understand the code, well that may at least waste time at the other end. I wouldn't be happy with people trying to do it on a site I was running. (That said, a site should be able to handle anything a client throws at it, because you can't trust anything coming from the client side.)

Instead of debugging on their site, I'd probably do my best to record (via Firebug or Chrome/Safari's Dev Tools, etc.) a sample ajax interaction, and then set up a dummy page on my own local server that would simply echo that interaction, playback style. Then you can experiment to your heart's content without risking throwing weird stuff at the site in question. I'd consider it unethical for me to play around in that way with someone else's site, whether they should be able to handle it or not.

Title: debugging deobfuscated javascript

Body:
I am trying to reverse-engineer a website I don't own, figuring out how some dumb "encryption" works, in order to be able to carry out some operations automatically, by taking the functionality outside the browser.

One of the files is of particular interest, let's call it javascript.js. It is linked in the HTML document like this

I have

deobfuscated javascript.js

pretty-printed its code

My question is now, considering that I'm using venkman and firefox, how to replace the on-site obfuscated javascript.js with my own pretty-printed code, in order to learn how it works.

Any other tool beside venkman should do, as long as I can still step through the deobfuscated code.

Additional question (just in case I may come cross this related situation):

How to do the same if the javascript.js would be emdedded inline in the html code like ?

For those of you wondering about how legal this is, my question is not the first about reverse-engineering on SO: https://stackoverflow.com/questions/tagged/reverse-engineering

Apparently there's no problem with those questions, why should there be one with mine?

My objective is to understand the code AND my question is about the TOOLS, as in "where to point and click" or which tool could help me (if venkman cannot).


问:
How to replace/shuffle one column with another in R?
I am very new to R and I was wondering that is there way to shuffle two columns in matrix?
I have a matrix of 800 x 12. I want to replace column 1 by column 2 and column 2 by column 1. Can anyone help me, please?</p>

答:
```<code>x <- matrix(1:15,5,3) # create 5x3 matrix
x[,c(1,2)] <- x[,c(2,1)] # exchange columns 1 and 2
</code>```


问:
Explaining the math behind an algorithm
Given a sorted array of integers a, find such an integer x that the value of

abs(a[0] - x) + abs(a[1] - x) + ... + abs(a[a.length - 1] - x)
is the smallest possible (here abs denotes the absolute value).
If there are several possible answers, output the smallest one.

Example

For a = [2, 4, 7], the output should be
absoluteValuesSumMinimization(a) = 4.

I was able to solve this by brute forcing it but then i came upon this

```<code>function absoluteValuesSumMinimization(A) {
    return A[Math.ceil(A.length/2)-1];
}
</code>```

looking to learn how/why this works.

答:
Let's assume that we have n1 values where a[i] - x is negative and n2 values where a[i] - x is positive.

If we increase the integer x by one, then the sum of the absolute values increases by n1 - n2.

If we decrease the integer x by one, the total sum of the absolute values increases by n2 - n1.

Therefore, as long as n1 and n2 are not equal, we can decrease the total sum of absolute values by moving x in one direction or the other, depending on whether n1 - n2 is positive or negative.

Thus, at the minimum it is necessary to have n1 = n2, i.e. there need to be same as many a[i] values smaller than x as there are larger than x.

Title: Explaining the math behind an algorithm

Body:
Given a sorted array of integers a, find such an integer x that the value of

abs(a[0] - x) + abs(a[1] - x) + ... + abs(a[a.length - 1] - x)
is the smallest possible (here abs denotes the absolute value).
If there are several possible answers, output the smallest one.

Example

For a = [2, 4, 7], the output should be
absoluteValuesSumMinimization(a) = 4.

I was able to solve this by brute forcing it but then i came upon this

function absoluteValuesSumMinimization(A) {
    return A[Math.ceil(A.length/2)-1];
}

looking to learn how/why this works.


问:
Prime generator using a huge array in C
I'm trying to make a prime number generator using arrays. I started with a 1D array but the max limit on my computer was 250000. So I thought maybe I should make a 2d or more array to go to the next line once this limit is reached to avoid problems on my PC. But I have no idea how to do it. Any help would be welcome. </p>

```<code>#include<stdio.h>
#include<math.h>
#include<stdbool.h>
#include<time.h>
#define LIMIT 250000ul

//prime number generator using arrays

void prime_generator(){

    unsigned long long n;
    printf("How many primes do you want generated : ");
    scanf("%llu", &n);

    unsigned long long p[LIMIT];
    unsigned long long i, j=2;
    unsigned long long num;
    bool isPrime;

    unsigned long long primes_per_line, space_column;
    printf("How many primes do you want displayed per line? : ");
    scanf("%llu", &primes_per_line);
    printf("Enter space : ");
    scanf("%llu", &space_column);

    p[0]=2, p[1]=3;//first two primes
    unsigned long long count = 2;

    clock_t begin = clock();
    for(num = 5;count < n; num=num+2){//only test for odd number
        isPrime = true;
        for(i = 1;i < j && p[i] <= sqrt(num) ;i++){
            if(num%p[i]==0){
                isPrime = false;
                break;//break out of i loop
            }
        }
        if(isPrime == true){
            ++count;
            p[j] = num; //new prime found
            ++j;
        }
    }
    clock_t end = clock();
    double time_spent = (double) (end-begin)/CLOCKS_PER_SEC;

    for(i = 0; i < n; i++){
        if(i!=0 && i % primes_per_line == 0) printf("\n");
        printf("%*llu", space_column, p[i]);
    }

    printf("\nCrunching time is : %.12f", time_spent);
}

int main(void){
    prime_generator();
    return 0;
}
</code>```

答:
Your unsigned long long p[LIMIT]; is a local variable (with automatic storage duration) inside your prime_generator function, so it is on the call stack (which is often limited to one or a few megabytes).  Declare it as a static or make it a global variable (in both cases, it gets a static storage duration). Then it could be much larger, but your prime_generator won't be re-entrant anymore (but in your case, you don't care).

Declaring an array as multi-dimensional won't improve its memory size (so won't solve the problem of an excessive call frame size of a variable declared local).

Better yet, use C dynamic memory allocation that is calloc (don't forget to test it against failure, when it returns NULL use perror then exit) and free; beware of memory leaks; tools like valgrind could be helpful. With calloc (or malloc) you'll then grow your virtual address space and be limited by machine and system resources (probably gigabytes).

Avoid buffer overflows. See this.

Read also wikipages on prime numbers and on primality tests. There are more efficient algorithms.

You should be able to compute a million primes (ending with 15485761
15485773
15485783
15485801
15485807
15485837
15485843
15485849
15485857
15485863)
in a few seconds at most (and probably in less than half a second).

Title: Prime generator using a huge array in C

Body:
I'm trying to make a prime number generator using arrays. I started with a 1D array but the max limit on my computer was 250000. So I thought maybe I should make a 2d or more array to go to the next line once this limit is reached to avoid problems on my PC. But I have no idea how to do it. Any help would be welcome.

#include<stdio.h>
#include<math.h>
#include<stdbool.h>
#include<time.h>
#define LIMIT 250000ul

//prime number generator using arrays

void prime_generator(){

    unsigned long long n;
    printf("How many primes do you want generated : ");
    scanf("%llu", &n);

    unsigned long long p[LIMIT];
    unsigned long long i, j=2;
    unsigned long long num;
    bool isPrime;

    unsigned long long primes_per_line, space_column;
    printf("How many primes do you want displayed per line? : ");
    scanf("%llu", &primes_per_line);
    printf("Enter space : ");
    scanf("%llu", &space_column);

    p[0]=2, p[1]=3;//first two primes
    unsigned long long count = 2;

    clock_t begin = clock();
    for(num = 5;count < n; num=num+2){//only test for odd number
        isPrime = true;
        for(i = 1;i < j && p[i] <= sqrt(num) ;i++){
            if(num%p[i]==0){
                isPrime = false;
                break;//break out of i loop
            }
        }
        if(isPrime == true){
            ++count;
            p[j] = num; //new prime found
            ++j;
        }
    }
    clock_t end = clock();
    double time_spent = (double) (end-begin)/CLOCKS_PER_SEC;

    for(i = 0; i < n; i++){
        if(i!=0 && i % primes_per_line == 0) printf("\n");
        printf("%*llu", space_column, p[i]);
    }

    printf("\nCrunching time is : %.12f", time_spent);
}

int main(void){
    prime_generator();
    return 0;
}


问:
OpenAI gym: How to get pixels in CartPole-v0
I would like to access the raw pixels in the OpenAI gym CartPole-v0 environment without opening a render window. How do I do this?

Example code:

```<code>import gym
env = gym.make("CartPole-v0")
env.reset()
img = env.render(mode='rgb_array', close=True) # Returns None
print(img)
img = env.render(mode='rgb_array', close=False)
          # Opens annoying window, but gives me the array that I want
print(img.shape)
</code>```

PS. I am having a hard time finding good documentation for OpenAI gym. Is it just me, or does it simply not exist?

Edit: I don't need to ever open the render video.

答:
Someone offers an answer here:

https://github.com/openai/gym/issues/374

"The atari and doom environments give pixels in their observations (ie, the return value from step). I don't think any other ones do.

render produces different results on different OSes, so they're not part of any official environment for benchmarking purposes. But if you want to create a new environment where the observation is in pixels, you could implement it by wrapping an existing environment and calling render."

I'm also working on getting raw pixels as well and I'm trying to find a way to see if what has been returned is what I expect it is.

The documentation can be found:
https://gym.openai.com/docs

And a forum for discussing OpenAI:
discuss.openai.com

Although its not very lively.

Body:
I would like to access the raw pixels in the OpenAI gym CartPole-v0 environment without opening a render window. How do I do this?

Example code:

import gym
env = gym.make("CartPole-v0")
env.reset()
img = env.render(mode='rgb_array', close=True) # Returns None
print(img)
img = env.render(mode='rgb_array', close=False)
          # Opens annoying window, but gives me the array that I want
print(img.shape)

PS. I am having a hard time finding good documentation for OpenAI gym. Is it just me, or does it simply not exist?

Edit: I don't need to ever open the render video.


问:
Java code skipping the first if condition and is skipping over the others
I am writing a simple program that produces a certain out put when age is less than 13, between 13 and 18 and over 18. My code does not read past the first if statement and I don't know what I am doing wrong.</p>

```<code>import java.io.*;
import java.util.*;
public class Person {
public  int age;

public Person(int initialAge) {
    // Add some more code to run some checks on initialAge
    if (initialAge>-1){
        age=initialAge;
    }
    else
        System.out.println("Age is not valid, setting age to 0. ");
        age=0;
}

public void amIOld() {
    // Write code determining if this person's age is old and print the correct statement:
    if(age<13)
     System.out.println("You are young.");

    else if(age>=13&&age<18)
        System.out.println("You are a teenager.");

   else
    System.out.println("You are old.");

}

public void yearPasses() {
    // Increment this person's age.
    age++;
}
       public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int T = sc.nextInt();
            for (int i = 0; i < T; i++) {
                int age = sc.nextInt();
                Person p = new Person(age);
                p.amIOld();
                for (int j = 0; j < 3; j++) {
                    p.yearPasses();
                }
                p.amIOld();
                System.out.println();
            }
           sc.close();
        }
    }
</code>```

答: In the constructor, regardless to what's the age, you're setting age to 0. It' not inside the else statement. Wrap it with brackets.

Body:
I am writing a simple program that produces a certain out put when age is less than 13, between 13 and 18 and over 18. My code does not read past the first if statement and I don't know what I am doing wrong.

import java.io.*;
import java.util.*;
public class Person {
public  int age;

public Person(int initialAge) {
    // Add some more code to run some checks on initialAge
    if (initialAge>-1){
        age=initialAge;
    }
    else
        System.out.println("Age is not valid, setting age to 0. ");
        age=0;
}

public void amIOld() {
    // Write code determining if this person's age is old and print the correct statement:
    if(age<13)
     System.out.println("You are young.");

    else if(age>=13&&age<18)
        System.out.println("You are a teenager.");

   else
    System.out.println("You are old.");

}

public void yearPasses() {
    // Increment this person's age.
    age++;
}
       public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int T = sc.nextInt();
            for (int i = 0; i < T; i++) {
                int age = sc.nextInt();
                Person p = new Person(age);
                p.amIOld();
                for (int j = 0; j < 3; j++) {
                    p.yearPasses();
                }
                p.amIOld();
                System.out.println();
            }
           sc.close();
        }
    }


问:
c++ Writing to Binary files from multiple inheritance class
I have a case similar to "The diamond of death"

I have class B and C which Virtually Inherit Class A,
and also Class D which Inherit Classes B and C.

```<code>  A
 / \
B   C
 \ /
  D
</code>```

B & C has inherited members, and also their own members.
D has only inherited members.

I'm writing Save method which gets ofstream and should write the Object to a binary file.

And a Load method which gets ifstream and should create the object from a binary file.

The Method are virtual and written in such a way that each class Method handles only that specific class members Load & Save (and uses the inherited classes methods for the rest of the inherited members)

Now when writing the Save method for D, basically I only need to do:

```<code>B.save();
C.save();
</code>```

Obviously this will cause A.save() to be called twice which will cause A to be written to the file twice

I think something like add a saveOnly method to B and C which will save only their members (and not A's) is silly

So I wonder what is the Best Practices for such a case ?

答:
The best practice is to not make diamonds in your class inheritance. That will always cause issues and is best avoided. Evaluate each link in the inheritance and think about whether you could do something different, such as using composition at some point or making the base class a pure virtual interface instead.

If you really want to keep that inheritance, then instead of making A::save() a virtual method, make a protected pure virtual A::onSave() method instead that is expected to be overridden in each derived class. A::save() will do what it needs to do, then call onSave(). B and C will both implement onSave() and do what they need to do, but will not call A::onSave() (because it is pure virtual). D will implement onSave() and will call B::onSave() and C::onSave(). This works around the issue for this case, but you will always run into more issues like this if you make inheritance diamonds like that.

Body:
I have a case similar to "The diamond of death"

I have class B and C which Virtually Inherit Class A,
and also Class D which Inherit Classes B and C.

  A
 / \
B   C
 \ /
  D

B & C has inherited members, and also their own members.
D has only inherited members.

I'm writing Save method which gets ofstream and should write the Object to a binary file.

And a Load method which gets ifstream and should create the object from a binary file.

The Method are virtual and written in such a way that each class Method handles only that specific class members Load & Save (and uses the inherited classes methods for the rest of the inherited members)

Now when writing the Save method for D, basically I only need to do:

B.save();
C.save();

Obviously this will cause A.save() to be called twice which will cause A to be written to the file twice

I think something like add a saveOnly method to B and C which will save only their members (and not A's) is silly

So I wonder what is the Best Practices for such a case ?