问:
getting data from a partial view onto main view
I'm new to the world of ASP.Net MVC and I'm working with a small application that uses many XML files from a web service as its model data. I have an Html page which contains a list of all the tools that are stored in the XML web services. They are within a loop and are clickable links. I also have a partial view which is just a series of text boxes. My goal is to populate the text boxes with information I get from the tool I click while having the list and the text boxes appear on the same page. I have been successful in doing this but so far have only been able to pass the id to a controller which returns my partial view as a completely new page. I'm sure this is a simple solution which may have been answered on here before. What is the best way to go about solving this problem? Below is my model, view(s) and two controllers

Tool Model

```<code>  public class Tool
{
  public int Id { get; set; }
  public string ToolId { get; set; }
  public string Adapter { get; set; }
  public string Description { get; set; }
  public string TNumber { get; set; }
  public List<string> ComponentList { get; set; }
  public List<string> AccessoryList { get; set; }
  public List<KeyValuePair<string, string>> ToolIdDescription { get; set; }
  public List<string> toolList = new List<string>();

}
</code>```

Partial View Controller

```<code>public ActionResult PartialView()
  {
     Tool newTool = new Tool();
     List<string> tools = new List<string>();
     tools = backgroundLoad();
     newTool.ToolIdDescription = new List<KeyValuePair<string, string>>();
     atool.ToolIdDescription = new List<KeyValuePair<string, string>>();
     foreach (string tool in tools)
     {
        newTool.ToolIdDescription = GetToolDescription(tool);
     }

     return View(newTool);
  }
</code>```

Controller to recieve Datasets

```<code>public ActionResult GetDataSet(string id)
  {
     Tool selectedTool = new Tool();
     if (id != null)
     {
        var request =
(HttpWebRequest)WebRequest.Create("http://localhost/DbService/Tool/" + id);
        XmlDocument xml = new XmlDocument();
        Stream aResponsestream;
        string aResult = "";
        using (aResponsestream = request.GetResponse().GetResponseStream())
        using (StreamReader aReader = new StreamReader(aResponsestream,
Encoding.UTF8))
        {
           aResult = aReader.ReadToEnd();
           aResponsestream.Close();
        }
        xml.LoadXml(aResult);
        var Description =
   xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/Description");
        if (Description != null) selectedTool.Description =
Description.InnerText;
        var Adapter =
   xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/Adapter/Name");
        if (Adapter != null) selectedTool.Adapter = Adapter.InnerText;
        var TNumber =
        xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/TNo");
        if (TNumber != null) selectedTool.TNumber = TNumber.InnerText;
        var ToolId =
        xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/ToolId");
        if (ToolId != null) selectedTool.ToolId = ToolId.InnerText;

        return View(selectedTool);
     }
     else return View();

  }
</code>```

View which contains the list

```<code>@model  MiniWeb.Models.Tool

<!DOCTYPE html>
<html>
<head>
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
   <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
   <link href="~/Content/Site.css" rel="stylesheet" />
</head>
<body>
<h2>Tool List</h2>
<div class="table-responsive">
   <table class="table table-hover">
      <thead>
      <tr>
         <th>Id</th>
         <th>Description</th>
      </tr>
      </thead>
      @foreach (var item in Model.ToolIdDescription)
      {

         <tbody>
         <tr>
            <td>@Html.ActionLink(item.Key, "GetDataSet", new { id = item.Key })</td>
            <td>@Html.DisplayFor(modelItem => item.Value)</td>
         </tr>
         </tbody>
      }
   </table>
</div>
</body>
</html>

@Html.Partial("GetDataSet", new MiniWeb.Models.Tool())
</code>```

View which displays the tool information

```<code>@model MiniWeb.Models.Tool

@{
    ViewBag.Title = "GetDataSet";
}
@{
   ViewBag.Title = "Tool";
}
<link href="~/Content/Site.css" rel="stylesheet" />
<h2>Tool Selection </h2>
<div class="Tool">
   <span id ="id">
         @Html.LabelFor(m => Model.ToolId)
         @Html.TextBoxFor(modelItem => Model.ToolId)
   </span>
   <br/>
   <span id="Description">
         @Html.LabelFor(m => Model.Description)
         @Html.TextBoxFor(modelItem => Model.Description)
   </span>
   <br/>
   <span id="Adapter">
         @Html.LabelFor(m=> Model.Adapter)
         @Html.TextBoxFor(modelItem => Model.Adapter)

   </span>
   <br/>
   <span id="Adapter">
         @Html.LabelFor(m => Model.TNumber)
         @Html.TextBoxFor(modelItem => Model.TNumber)
   </span>
   <span>
      <button> Save </button>
   </span>
</div>
</code>```

Sorry for all the code but thank you for reading. I also apologize if this is a really easy solution. I'm just new to ASP.Net and want to develop the best practices instead of doing a hack job on it. Thanks for the help.

答:
You're going to want to create a form on your partial view that will submit the data to the main pages controller.

You can find more information in this article.

Body:
I'm new to the world of ASP.Net MVC and I'm working with a small application that uses many XML files from a web service as its model data. I have an Html page which contains a list of all the tools that are stored in the XML web services. They are within a loop and are clickable links. I also have a partial view which is just a series of text boxes. My goal is to populate the text boxes with information I get from the tool I click while having the list and the text boxes appear on the same page. I have been successful in doing this but so far have only been able to pass the id to a controller which returns my partial view as a completely new page. I'm sure this is a simple solution which may have been answered on here before. What is the best way to go about solving this problem? Below is my model, view(s) and two controllers

Tool Model

  public class Tool
{
  public int Id { get; set; }
  public string ToolId { get; set; }
  public string Adapter { get; set; }
  public string Description { get; set; }
  public string TNumber { get; set; }
  public List<string> ComponentList { get; set; }
  public List<string> AccessoryList { get; set; }
  public List<KeyValuePair<string, string>> ToolIdDescription { get; set; }
  public List<string> toolList = new List<string>();

}

Partial View Controller

public ActionResult PartialView()
  {
     Tool newTool = new Tool();
     List<string> tools = new List<string>();
     tools = backgroundLoad();
     newTool.ToolIdDescription = new List<KeyValuePair<string, string>>();
     atool.ToolIdDescription = new List<KeyValuePair<string, string>>();
     foreach (string tool in tools)
     {
        newTool.ToolIdDescription = GetToolDescription(tool);
     }

     return View(newTool);
  }

Controller to recieve Datasets

public ActionResult GetDataSet(string id)
  {
     Tool selectedTool = new Tool();
     if (id != null)
     {
        var request =
(HttpWebRequest)WebRequest.Create("http://localhost/DbService/Tool/" + id);
        XmlDocument xml = new XmlDocument();
        Stream aResponsestream;
        string aResult = "";
        using (aResponsestream = request.GetResponse().GetResponseStream())
        using (StreamReader aReader = new StreamReader(aResponsestream,
Encoding.UTF8))
        {
           aResult = aReader.ReadToEnd();
           aResponsestream.Close();
        }
        xml.LoadXml(aResult);
        var Description =
   xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/Description");
        if (Description != null) selectedTool.Description =
Description.InnerText;
        var Adapter =
   xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/Adapter/Name");
        if (Adapter != null) selectedTool.Adapter = Adapter.InnerText;
        var TNumber =
        xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/TNo");
        if (TNumber != null) selectedTool.TNumber = TNumber.InnerText;
        var ToolId =
        xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/ToolId");
        if (ToolId != null) selectedTool.ToolId = ToolId.InnerText;

        return View(selectedTool);
     }
     else return View();

  }

View which contains the list

@model  MiniWeb.Models.Tool

<!DOCTYPE html>

   <meta name="viewport" content="width=device-width, initial-scale=1">
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

   <link href="~/Content/Site.css" rel="stylesheet" />

Tool List

         Id
         Description

      @foreach (var item in Model.ToolIdDescription)
      {

            @Html.ActionLink(item.Key, "GetDataSet", new { id = item.Key })
            @Html.DisplayFor(modelItem => item.Value)

      }

@Html.Partial("GetDataSet", new MiniWeb.Models.Tool())

View which displays the tool information

@model MiniWeb.Models.Tool

@{
    ViewBag.Title = "GetDataSet";
}
@{
   ViewBag.Title = "Tool";
}
<link href="~/Content/Site.css" rel="stylesheet" />

Tool Selection

         @Html.LabelFor(m => Model.ToolId)
         @Html.TextBoxFor(modelItem => Model.ToolId)

         @Html.LabelFor(m => Model.Description)
         @Html.TextBoxFor(modelItem => Model.Description)

         @Html.LabelFor(m=> Model.Adapter)
         @Html.TextBoxFor(modelItem => Model.Adapter)

         @Html.LabelFor(m => Model.TNumber)
         @Html.TextBoxFor(modelItem => Model.TNumber)

      <button> Save </button>

Sorry for all the code but thank you for reading. I also apologize if this is a really easy solution. I'm just new to ASP.Net and want to develop the best practices instead of doing a hack job on it. Thanks for the help.


来源: stackexchange

问:
How to fix cascading branches rebasing mess
We have a workflow where only one team member works on several feature branches. Work is such that each next branch is dependent on previous one he did.  The default branch is develop.

Lets say this scenario:

He creates featureA branch, does the work, pushes the branch, and creates a PR on GitHub

He creates featureB branch (based on featureA one), does the work and PRs it

He creates featureC branch, (based on featureB) does the work and PRs it

he creates featureD branch, (based on featureC) does the work and PRs it

None of the PRs are merged yet.

Now, project manager steps in and starts merging. Merge go this way:

Project manager merges featureA into develop

Developer on his side does:

```<code>git checkout develop
git fetch origin
git rebase origin/develop
git checkout featureB
git rebase origin/develop
git push origin featureB
</code>```

At this point of time we get error:

```<code>machine /c/Work/ (featureB)
$ git push origin featureB
To https://github.com/x.git
 ! [rejected]        featureB -> featureB (non-fast-forward)
error: failed to push some refs to 'https://github.com/x.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
</code>```

Why does this happen?

We thought that rebasing featureB on origin/develop (which now after merge contains featureA) would make featureB ready for push. but obviously we see something wrong.

答:
The easiest way to explain what happened is to look at your repo's history.  Here is what (an abridged version of) your history looked like pre-merge:

```<code>*--*--*--* [develop, origin/develop]
          \
           *--*--* [featureA, origin/featureA]
                  \
                   A--B--C [featureB, origin/featureB]
</code>```

And post-merge:

```<code>*--*--*--*---------* [develop, origin/develop]
          \       /
           *--*--*
                  \
                   A--B--C [featureB, origin/featureB]
</code>```

Then you rebased featureB onto develop:

```<code>*--*--*--*---------* [develop, origin/develop]
          \       / \
           *--*--*   A'--B'--C' [featureB]
                  \
                   A--B--C [origin/featureB]
</code>```

Here, A', B', and C', contain the same changes as A, B, and C, respectively, but they are not the same commits, because A' has a different parent commit.

Thus, after each rebase, you must force-push the rebased branch:

```<code>git push --force-with-lease origin featureB
</code>```

(The --force-with-lease ensures that no new commits have been pushed since you last fetched.  While it might not be strictly needed here, it's good to get in the habit of using that over --force.)

As seen in my last graph, any time a branch (such as featureB) and its remote-tracking branch (such as origin/featureB) have diverged, you must force-push.  Thus, you will need to do that any time you have rebased a branch that has already been pushed to the remote.

ContentLicense: CC BY-SA 3.0

Body:
We have a workflow where only one team member works on several feature branches. Work is such that each next branch is dependent on previous one he did.  The default branch is develop.

Lets say this scenario:

He creates featureA branch, does the work, pushes the branch, and creates a PR on GitHub

He creates featureB branch (based on featureA one), does the work and PRs it

He creates featureC branch, (based on featureB) does the work and PRs it

he creates featureD branch, (based on featureC) does the work and PRs it

None of the PRs are merged yet.

Now, project manager steps in and starts merging. Merge go this way:

Project manager merges featureA into develop

Developer on his side does:

git checkout develop
git fetch origin
git rebase origin/develop
git checkout featureB
git rebase origin/develop
git push origin featureB

At this point of time we get error:

machine /c/Work/ (featureB)
$ git push origin featureB
To https://github.com/x.git
 ! [rejected]        featureB -> featureB (non-fast-forward)
error: failed to push some refs to 'https://github.com/x.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

Why does this happen?

We thought that rebasing featureB on origin/develop (which now after merge contains featureA) would make featureB ready for push. but obviously we see something wrong.

Body:
The easiest way to explain what happened is to look at your repo's history.  Here is what (an abridged version of) your history looked like pre-merge:

*--*--*--* [develop, origin/develop]
          \
           *--*--* [featureA, origin/featureA]
                  \
                   A--B--C [featureB, origin/featureB]

And post-merge:

*--*--*--*---------* [develop, origin/develop]
          \       /
           *--*--*
                  \
                   A--B--C [featureB, origin/featureB]

Then you rebased featureB onto develop:

*--*--*--*---------* [develop, origin/develop]
          \       / \
           *--*--*   A'--B'--C' [featureB]
                  \
                   A--B--C [origin/featureB]

Here, A', B', and C', contain the same changes as A, B, and C, respectively, but they are not the same commits, because A' has a different parent commit.

Thus, after each rebase, you must force-push the rebased branch:

git push --force-with-lease origin featureB

(The --force-with-lease ensures that no new commits have been pushed since you last fetched.  While it might not be strictly needed here, it's good to get in the habit of using that over --force.)

As seen in my last graph, any time a branch (such as featureB) and its remote-tracking branch (such as origin/featureB) have diverged, you must force-push.  Thus, you will need to do that any time you have rebased a branch that has already been pushed to the remote.


问:
replace a string with other string in the same line
Vi editor

Input file text format:

```<code>'': hello.Code1
'': hello.Code2
'': hello.Code3
</code>```

Required output text format:

```<code>'Code1': hello.Code1
'Code2': hello.Code2
'Code3': hello.Code3
</code>```

Idea is I have to copy all the values after "." to the single quotes ''. I can use Vi or SED etc. Linux based. or MAC based.
I have more that 2000 lines in the text file
Thanks

答:
You can use a macro in vim. Something like:

```<code>/\.^Mly$?'^MPj0
</code>```

Assuming you're at the start of the first line. Start recording. To record into the q register, hit qq and then:

i) Search for the dot

```<code>/\.^M
</code>```

ii) Go one character to the right, and yank to the end of the line

```<code>ly$
</code>```

iii) Reverse search the quote: '

```<code>?'^M
</code>```

iv) Paste the content and go down a line and move to the start.

```<code>Pj0
</code>```

You can then just repeat the action. Assuming you recorded it in the q register:

```<code>2@q
</code>```

(Note: ^M is <Enter>)

Body:
Vi editor

Input file text format:

'': hello.Code1
'': hello.Code2
'': hello.Code3

Required output text format:

'Code1': hello.Code1
'Code2': hello.Code2
'Code3': hello.Code3

Idea is I have to copy all the values after "." to the single quotes ''. I can use Vi or SED etc. Linux based. or MAC based.
I have more that 2000 lines in the text file
Thanks

Body:
You can use a macro in vim. Something like:

/\.^Mly$?'^MPj0

Assuming you're at the start of the first line. Start recording. To record into the q register, hit qq and then:

i) Search for the dot

/\.^M

ii) Go one character to the right, and yank to the end of the line

ly$

iii) Reverse search the quote: '

?'^M

iv) Paste the content and go down a line and move to the start.

Pj0

You can then just repeat the action. Assuming you recorded it in the q register:

2@q

(Note: ^M is <Enter>)


问:
Documentum DFS, renaming dm_user (user_name attribute)
After changing some user's user_name attribute with DFS Object web service consistency checker fails. It seems Documentum uses user_name as foreign key in other documents and renaming this attribute on dm_user doesn't change all foreign keys of this user.

Anyone knows how to correctly change user_name value and all its 'dependencies'? Is this even possible with DFS?

Oh, I am using .NET c#, so any solution have to be compatible with that.

Consistency checker report:

WARNING CC-0002: User 'FirstName
  LastName' is referenced in dm_group
  with id '1200400186008806' but does
  not have a valid dm_user object
  ....

It goes like this for about 50 users.
after that comes:

WARNING CC-0007: ACL object with
  r_object_id '4500000160051328' has a
  non-existent user 'FirstName LastName'
  ...

and about 50000 more lines for ACL, sysobjects,...

tnx

EDIT: some clarifications

EDIT 2: added consistency checker report

答:
Ok, figured it out:

What you have to do is create new dm_job_request with following attributes:

```<code>            object_name = "UserRename",
            job_name = "dm_UserRename",
            method_name = "dm_UserRename",
            request_completed = false,
            priority = 0,
            arguments_keys = "OldUserName,NewUserName,report_only,unlock_locked_obj".Split(','), //stringarrayproperty
            arguments_values = "test,test123,F,T".Split(',') ////stringarrayproperty
</code>```

After that you manually run dm_userrename job. I tried to set priority to 1 (that was supposed to be "run Now" option) but it didn't automatically start dm_userrename

Hope this helps someone.

ContentLicense: CC BY-SA 2.5

Body:
Ok, figured it out:

What you have to do is create new dm_job_request with following attributes:

            object_name = "UserRename",
            job_name = "dm_UserRename",
            method_name = "dm_UserRename",
            request_completed = false,
            priority = 0,
            arguments_keys = "OldUserName,NewUserName,report_only,unlock_locked_obj".Split(','), //stringarrayproperty
            arguments_values = "test,test123,F,T".Split(',') ////stringarrayproperty

After that you manually run dm_userrename job. I tried to set priority to 1 (that was supposed to be "run Now" option) but it didn't automatically start dm_userrename

Hope this helps someone.


问:
Querying a nested array in Elasticsearch
I have the following data index in Elasticsearch with the following syntax:

```<code>PUT /try1
{
"mappings" : {
  "product" : {
   "properties" : {
     "name": { "type" : "text" },
     "categories": {
       "type": "nested",
       "properties": {
         "range":{"type":"text"}
       }
     }
   }
  }
 }
}
</code>```

The range type has an array of words:["high","medium","low"]
I need to access the range element inside the nested category. I tried using the following syntax:

```<code>GET /try1/product/_search
{
    "query": {
        "nested" : {
            "path" : "categories",
            "query" : {
                "bool" : {
                    "must" : [
                    { "match" : {"categories.range": "low"} }
                    ]
                }
            }
        }
    }

}
</code>```

However, I am getting an error with the message:
 "reason": """failed to create query:...

Can someone please offer a solution to this?

答:
@KGB can you try to make your query slightly differently like this:</p>

```<code>{
    "query": {
        "bool": {
            "must": [
                {
                    "match": {
                        "categories.range": "low"
                    }
                }
            ]
        }
    }
}
</code>```

Body:
I have the following data index in Elasticsearch with the following syntax:

PUT /try1
{
"mappings" : {
  "product" : {
   "properties" : {
     "name": { "type" : "text" },
     "categories": {
       "type": "nested",
       "properties": {
         "range":{"type":"text"}
       }
     }
   }
  }
 }
}

The range type has an array of words:["high","medium","low"]
I need to access the range element inside the nested category. I tried using the following syntax:

GET /try1/product/_search
{
    "query": {
        "nested" : {
            "path" : "categories",
            "query" : {
                "bool" : {
                    "must" : [
                    { "match" : {"categories.range": "low"} }
                    ]
                }
            }
        }
    }

}

However, I am getting an error with the message:
 "reason": """failed to create query:...

Can someone please offer a solution to this?

Body:
@KGB can you try to make your query slightly differently like this:

{
    "query": {
        "bool": {
            "must": [
                {
                    "match": {
                        "categories.range": "low"
                    }
                }
            ]
        }
    }
}


问:
Uncompile Development Asset Pipeline
I was compiling my asset pipeline for my production environment and it did for all my environments. How can I uncompile my asset pipeline for my development environment?

I have checked my config/development environment and cannot find a fix.

Thanks in advance for any help...

答:
For Rails 5:</p>

```<code>$ RAILS_ENV=development bin/rake assets:clobber
</code>```

Title: Uncompile Development Asset Pipeline

Body:
For Rails 5:

$ RAILS_ENV=development bin/rake assets:clobber


问:
Delphi ARC under Firemonkey for Windows
I am watching this video where Marco is talking about Automatic Reference Counting. I already knew that under Android and iOS (Firemonkey) my objects are ref counted so I don't need the try finally block.

Does the reference count implementation work according with the platform (VLC or FMX) or with the OS?

What I mean is:

```<code>var a: TObject;
begin
 a := TObject.Create;
 a.use1;
 a.use2;
end;
</code>```

This is good in Firemonkey if it runs on Android/iOS/Mac, I have no memory leak. But if I ran this under Windows (and I have used Firemonkey) do I still have the memory leak due to no ref count?

Anyway from the video I have understood that a try finally with a call of Free, even under ARC, is not bad usage but it's just useless.

答:
ARC is implemented per OS platform, not GUI framework.

The Android, iOS and Linux compilers use ARC memory management for objects.  The Windows and OSX compilers use the classic manual memory management, where ARC is supported only on interface references, not objects.

VCL is a Windows-only framework, it runs only under classic compilers.

On the other hand, FMX as a cross-platform framework, and uses different memory management systems, depending on which OS platform it runs on.

try...finally Free blocks are indeed useless on ARC compilers (in context of safe-guarding object release in combination with Free method).
However, if you write cross-platform code that must work under both memory management systems, you must use try...finally and Free.

On the other hand, if you write code that only must work under ARC, you can safely omit try...finally and Free.

However, on ARC you may want to use Free (on ARC compiler it translates to nil assignment)  or directly assign nil to object/interface reference if you need to release object at certain point, before it's reference would go out of scope.

There is one important exception to the above rules - TComponent descendants (that includes Firemonkey GUI components and controls) where try...finally Free blocks have to be replaced with try...finally DisposeOf if you are creating and releasing those instances in code.

You can read more at How to free a component in Android / iOS

Important thing to note here: DisposeOf has very specific purpose, it is not universal solution for breaking reference cycles and releasing objects under ARC. Using it blindly in all places can result in memory leaks. More elaborate answer can be found in above Q/A under Pitfalls of DisposeOf

Title: Delphi ARC under Firemonkey for Windows

Body:
I am watching this video where Marco is talking about Automatic Reference Counting. I already knew that under Android and iOS (Firemonkey) my objects are ref counted so I don't need the try finally block.

Does the reference count implementation work according with the platform (VLC or FMX) or with the OS?

What I mean is:

var a: TObject;
begin
 a := TObject.Create;
 a.use1;
 a.use2;
end;

This is good in Firemonkey if it runs on Android/iOS/Mac, I have no memory leak. But if I ran this under Windows (and I have used Firemonkey) do I still have the memory leak due to no ref count?

Anyway from the video I have understood that a try finally with a call of Free, even under ARC, is not bad usage but it's just useless.


问:
RSelenium doesn't open web page
I am working with RSelenium to access a JSON web page. I already configure my machine to open Google Chrome but I have problems to navigate my web page. My code is the following:

```<code>> require(RSelenium)
Loading required package: RSelenium
> remDr <- remoteDriver(browserName = "chrome")
> remDr$open()
[1] "Connecting to remote server"
$applicationCacheEnabled
[1] FALSE

$rotatable
[1] FALSE

$mobileEmulationEnabled
[1] FALSE

$networkConnectionEnabled
[1] TRUE

$chrome
$chrome$userDataDir
[1] "C:\\Users\\fjchauxg\\AppData\\Local\\Temp\\scoped_dir6336_25181"

$takesHeapSnapshot
[1] TRUE

$databaseEnabled
[1] FALSE

$handlesAlerts
[1] TRUE

$hasTouchScreen
[1] TRUE

$version
[1] "58.0.3029.110"

$platform
[1] "XP"

$browserConnectionEnabled
[1] FALSE

$nativeEvents
[1] TRUE

$acceptSslCerts
[1] TRUE

$webdriver.remote.sessionid
[1] "f3bb1468-58e9-427d-82e1-c11c2beedcfe"

$locationContextEnabled
[1] TRUE

$webStorageEnabled
[1] TRUE

$browserName
[1] "chrome"

$takesScreenshot
[1] TRUE

$javascriptEnabled
[1] TRUE

$cssSelectorsEnabled
[1] TRUE

$id
[1] "f3bb1468-58e9-427d-82e1-c11c2beedcfe"

> enlace<-"http://www.la14.com"
> remDr$navigate(enlace)

Selenium message:unknown error: Runtime.executionContextCreated has invalid 'context': {"auxData":{"frameId":"7836.1","isDefault":true},"id":1,"name":"","origin":"://"}
  (Session info: chrome=58.0.3029.110)
  (Driver info: chromedriver=2.11.298604 (75ea2fdb5c87f133a8e1b8da16f6091fb7d5321e),platform=Windows NT 6.1 SP1 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 8 milliseconds
Build info: version: '3.4.0', revision: 'unknown', time: 'unknown'
System info: host: 'FJCHAUXG', ip: '172.16.120.129', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_131'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, chrome={userDataDir=C:\Users\fjchauxg\AppData\Local\Temp\scoped_dir6336_25181}, takesHeapSnapshot=true, databaseEnabled=false, handlesAlerts=true, version=58.0.3029.110, platform=XP, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
Session ID: cf2489a4c083409ed6072ed2f8b9eaf7

Error:   Summary: UnknownError
     Detail: An unknown server-side error occurred while processing the command.
     class: org.openqa.selenium.WebDriverException
     Further Details: run errorDetails method
</code>```

In chrome, I obtain the following message:

It is something refered to extensions in Chrome. I click on cancel and run again:

```<code>> remDr$navigate(enlace)

Selenium message:java.net.SocketException: Connection reset
Build info: version: '3.4.0', revision: 'unknown', time: 'unknown'
System info: host: 'FJCHAUXG', ip: '172.16.120.129', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_131'
Driver info: driver.version: EventFiringWebDriver

Error:   Summary: UnknownError
     Detail: An unknown server-side error occurred while processing the command.
     class: org.openqa.selenium.WebDriverException
     Further Details: run errorDetails method
</code>```

Finally, I noted that I can't close chrome:

```<code>> remDr$close()

Selenium message:Connection refused: connect

    Error:   Summary: UnknownError
         Detail: An unknown server-side error occurred while processing the command.
         class: java.net.ConnectException
         Further Details: run errorDetails method
</code>```

I don't know why I obtain this errors. I will grateful with your help.

答:
If you don't use rsDriver(), no RSelenium server is launched. I can navigate to the website and load the page with:

```<code>require(RSelenium)
rSel <- rsDriver()
remDr <- rSel$client

enlace<-"http://www.la14.com"
remDr$navigate(enlace)
rSel$server$stop()
</code>```

Title: RSelenium doesn't open web page

Body:
I am working with RSelenium to access a JSON web page. I already configure my machine to open Google Chrome but I have problems to navigate my web page. My code is the following:

> require(RSelenium)
Loading required package: RSelenium
> remDr <- remoteDriver(browserName = "chrome")
> remDr$open()
[1] "Connecting to remote server"
$applicationCacheEnabled
[1] FALSE

$rotatable
[1] FALSE

$mobileEmulationEnabled
[1] FALSE

$networkConnectionEnabled
[1] TRUE

$chrome
$chrome$userDataDir
[1] "C:\\Users\\fjchauxg\\AppData\\Local\\Temp\\scoped_dir6336_25181"

$takesHeapSnapshot
[1] TRUE

$databaseEnabled
[1] FALSE

$handlesAlerts
[1] TRUE

$hasTouchScreen
[1] TRUE

$version
[1] "58.0.3029.110"

$platform
[1] "XP"

$browserConnectionEnabled
[1] FALSE

$nativeEvents
[1] TRUE

$acceptSslCerts
[1] TRUE

$webdriver.remote.sessionid
[1] "f3bb1468-58e9-427d-82e1-c11c2beedcfe"

$locationContextEnabled
[1] TRUE

$webStorageEnabled
[1] TRUE

$browserName
[1] "chrome"

$takesScreenshot
[1] TRUE

$javascriptEnabled
[1] TRUE

$cssSelectorsEnabled
[1] TRUE

$id
[1] "f3bb1468-58e9-427d-82e1-c11c2beedcfe"

> enlace<-"http://www.la14.com"
> remDr$navigate(enlace)

Selenium message:unknown error: Runtime.executionContextCreated has invalid 'context': {"auxData":{"frameId":"7836.1","isDefault":true},"id":1,"name":"","origin":"://"}
  (Session info: chrome=58.0.3029.110)
  (Driver info: chromedriver=2.11.298604 (75ea2fdb5c87f133a8e1b8da16f6091fb7d5321e),platform=Windows NT 6.1 SP1 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 8 milliseconds
Build info: version: '3.4.0', revision: 'unknown', time: 'unknown'
System info: host: 'FJCHAUXG', ip: '172.16.120.129', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_131'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, chrome={userDataDir=C:\Users\fjchauxg\AppData\Local\Temp\scoped_dir6336_25181}, takesHeapSnapshot=true, databaseEnabled=false, handlesAlerts=true, version=58.0.3029.110, platform=XP, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
Session ID: cf2489a4c083409ed6072ed2f8b9eaf7

Error:   Summary: UnknownError
     Detail: An unknown server-side error occurred while processing the command.
     class: org.openqa.selenium.WebDriverException
     Further Details: run errorDetails method

In chrome, I obtain the following message:

It is something refered to extensions in Chrome. I click on cancel and run again:

> remDr$navigate(enlace)

Selenium message:java.net.SocketException: Connection reset
Build info: version: '3.4.0', revision: 'unknown', time: 'unknown'
System info: host: 'FJCHAUXG', ip: '172.16.120.129', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_131'
Driver info: driver.version: EventFiringWebDriver

Error:   Summary: UnknownError
     Detail: An unknown server-side error occurred while processing the command.
     class: org.openqa.selenium.WebDriverException
     Further Details: run errorDetails method

Finally, I noted that I can't close chrome:

> remDr$close()

Selenium message:Connection refused: connect

    Error:   Summary: UnknownError
         Detail: An unknown server-side error occurred while processing the command.
         class: java.net.ConnectException
         Further Details: run errorDetails method

I don't know why I obtain this errors. I will grateful with your help.

Body:
If you don't use rsDriver(), no RSelenium server is launched. I can navigate to the website and load the page with:

require(RSelenium)
rSel <- rsDriver()
remDr <- rSel$client

enlace<-"http://www.la14.com"
remDr$navigate(enlace)
rSel$server$stop()


问:
Core Data Document-Based Application with Global Persistent Store
I've got a document-based Core Data application which works as is. I would like to add support for a global persistent store to hold a library of items.

I've read most of the relevant docs, and understand that I should use configurations in the managed object models. I've defined two configurations: "DocumentConfiguration" and "LibraryConfiguration". The entities in the document configuration are only in the document configuration, and the entities in the library configuration are only in the library configuration -- i.e., no overlap.

The docs then say "You then use this model when you create a coordinator". But I don't actually create my own persistent store coordinator since I'm using the default NSPersistentDocument coordinator.

A few questions on how best to proceed and help clear up any misunderstandings I might have:

A. Would I obtain the NSPersistentStoreCoordinator in the NSPersistentDocument and then add a new persistent store to it along the lines of:

```<code>NSPersistentStoreCoordinator * coordinator = [[myDocument managedObjectContext] persistentStoreCoordinator];
[coordinator addPersistentStoreWithType:NSXMLStoreType
    configuration:@"LibraryConfiguration"
    URL:url
    options:nil
    error:&error];
</code>```

I'm thinking that this may be a problem because I haven't provided the other configuration definition ("DocumentConfiguration") in the NSPersistentDocument's persistent store coordinator as I'm using the default provided by NSPersistentDocument. I'm guessing it would probably use nil when the time came to save the document. And if so, would this be a problem? I.e., how would the coordinator know which persistent store to save an entity with a given configuration definition if the same configurations are not defined for all the persistent stores (in this case two)? Am I able to set the configuration (to "DocumentConfiguration") of the NSPersistentDocument's persistent store before it has been created/saved? From the NSPersistentDocument docs:

Saving a new document adds a store of the default type with the chosen URL and invokes save: on the context. For an existing document, a save just invokes save: on the context.

B. Would it be better to create my own NSPersistentStoreCoordinator and NSManagedObjectContext instances, adding the two persistent stores with configurations defined, and then make the NSPersistentDocument use these NSPersistentStoreCoordinator and NSManagedObjectContext instances, and free the old ones? If so, how would I specify the url for the NSPersistentDocument for the addPersistentStoreWithType:... method? It seems this URL is only known once the untitled document has been saved. (Testing this, there does not appear to be any temporary persistent store (via method persistentStores on the persistent store coordinator) until the document is saved for the first time).

C. Or would it be better to leave NSPersistentDocument alone, and create my own NSPersistentStoreCoordinator instance that I use exclusively for the persistent library store and managed library object model? The docs say that multiple instances of NSPersistentStoreCoordinator should be used in multithreaded Core Data applications, but I don't require multithreaded Core Data support. Is it desirable to have two instances of NSPersistentStoreCoordinator -- one for the library and one for documents (intuition says that this is not necessary and probably not the correct approach)?

Any suggestions?

答:
The solution I used that works well is based on C) above. I leave the NSPersistentDocument and it's persistent store coordinator alone, and instead create my own NSPersistentStoreCoordinator instance that I use exclusively for the persistent library store (global store).

I can set the configuration for the store to a custom value in case I want to have multiple stores associated with this persistent store coordinator later (e.g., "LibraryConfiguration"). Since the library store is managed by a persistent store coordinator different from the NSPersistentDocument's persistent store coordinator, I don't need to be concerned about specifying a configuration for the NSPersistentDocument's persistent stores.

Body:
I've got a document-based Core Data application which works as is. I would like to add support for a global persistent store to hold a library of items.

I've read most of the relevant docs, and understand that I should use configurations in the managed object models. I've defined two configurations: "DocumentConfiguration" and "LibraryConfiguration". The entities in the document configuration are only in the document configuration, and the entities in the library configuration are only in the library configuration -- i.e., no overlap.

The docs then say "You then use this model when you create a coordinator". But I don't actually create my own persistent store coordinator since I'm using the default NSPersistentDocument coordinator.

A few questions on how best to proceed and help clear up any misunderstandings I might have:

A. Would I obtain the NSPersistentStoreCoordinator in the NSPersistentDocument and then add a new persistent store to it along the lines of:

NSPersistentStoreCoordinator * coordinator = [[myDocument managedObjectContext] persistentStoreCoordinator];
[coordinator addPersistentStoreWithType:NSXMLStoreType
    configuration:@"LibraryConfiguration"
    URL:url
    options:nil
    error:&error];

I'm thinking that this may be a problem because I haven't provided the other configuration definition ("DocumentConfiguration") in the NSPersistentDocument's persistent store coordinator as I'm using the default provided by NSPersistentDocument. I'm guessing it would probably use nil when the time came to save the document. And if so, would this be a problem? I.e., how would the coordinator know which persistent store to save an entity with a given configuration definition if the same configurations are not defined for all the persistent stores (in this case two)? Am I able to set the configuration (to "DocumentConfiguration") of the NSPersistentDocument's persistent store before it has been created/saved? From the NSPersistentDocument docs:

Saving a new document adds a store of the default type with the chosen URL and invokes save: on the context. For an existing document, a save just invokes save: on the context.

B. Would it be better to create my own NSPersistentStoreCoordinator and NSManagedObjectContext instances, adding the two persistent stores with configurations defined, and then make the NSPersistentDocument use these NSPersistentStoreCoordinator and NSManagedObjectContext instances, and free the old ones? If so, how would I specify the url for the NSPersistentDocument for the addPersistentStoreWithType:... method? It seems this URL is only known once the untitled document has been saved. (Testing this, there does not appear to be any temporary persistent store (via method persistentStores on the persistent store coordinator) until the document is saved for the first time).

C. Or would it be better to leave NSPersistentDocument alone, and create my own NSPersistentStoreCoordinator instance that I use exclusively for the persistent library store and managed library object model? The docs say that multiple instances of NSPersistentStoreCoordinator should be used in multithreaded Core Data applications, but I don't require multithreaded Core Data support. Is it desirable to have two instances of NSPersistentStoreCoordinator -- one for the library and one for documents (intuition says that this is not necessary and probably not the correct approach)?

Any suggestions?


问:
how can I convert string into HTML. I want the actual href to show/display instead of the text
how can I convert string into HTML. I want the actual href to show/display instead of the text. </p>

```<code>    var zzz = "test";
    var value0 = 14251876;
    var value1 = "AAAA";

    var EmailSubject = 'Transcription Assigned   Due (' + zzz + ')';
    var EmailBody = 'Dear ' + zzz + ',\n\n' + 'A dictation for the following Service has been assigned to you;\n\n' + 'Service Name: ' + zzz + '\n\n' + 'Thank you,\n' + 'Assessments\n' + '(416) 111 - 2222';
    EmailBody = EmailBody + $($.parseHTML('<div><a href="/Apps/app_editevent.jsp?eventid=' + value1 + '" target="_blank">' + value0 + '</a></div>'));
    send_msg(false,'',20,0,'mailer@test.ca',1081636,'',EmailSubject,EmailBody);
</code>```

答:
You have to .append() it as HTML.

var zzz = "test";
var value0 = 14251876;
var value1 = "AAAA";
var EmailSubject = 'Transcription Assigned   Due (' + zzz + ')';

var mailText = 'Dear ' + zzz + ',\n\n' + 'A dictation for the following Service has been assigned to you;\n\n' + 'Service Name: ' + zzz + '\n\n' + 'Thank you,\n' + 'Assessments\n' + '(416) 111 - 2222';

var $mailBody = $('
', {
  text: $('
', {
    text: mailText
  }).html()
});

var $href = $('
').append($('', {
  href: '/Apps/app_editevent.jsp?eventid=' + value1 + '',
  target: '_blank',
  text: value0
})).appendTo($mailBody);

$('body').append($mailBody);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Body:
how can I convert string into HTML. I want the actual href to show/display instead of the text.

    var zzz = "test";
    var value0 = 14251876;
    var value1 = "AAAA";

    var EmailSubject = 'Transcription Assigned   Due (' + zzz + ')';
    var EmailBody = 'Dear ' + zzz + ',\n\n' + 'A dictation for the following Service has been assigned to you;\n\n' + 'Service Name: ' + zzz + '\n\n' + 'Thank you,\n' + 'Assessments\n' + '(416) 111 - 2222';
    EmailBody = EmailBody + $($.parseHTML('
' + value0 + '
'));
    send_msg(false,'',20,0,'mailer@test.ca',1081636,'',EmailSubject,EmailBody);

Body:
You have to .append() it as HTML.

var zzz = "test";
var value0 = 14251876;
var value1 = "AAAA";
var EmailSubject = 'Transcription Assigned   Due (' + zzz + ')';

var mailText = 'Dear ' + zzz + ',\n\n' + 'A dictation for the following Service has been assigned to you;\n\n' + 'Service Name: ' + zzz + '\n\n' + 'Thank you,\n' + 'Assessments\n' + '(416) 111 - 2222';

var $mailBody = $('<div>', {
  text: $('<p>', {
    text: mailText
  }).html()
});

var $href = $('<div>').append($('<a>', {
  href: '/Apps/app_editevent.jsp?eventid=' + value1 + '',
  target: '_blank',
  text: value0
})).appendTo($mailBody);

$('body').append($mailBody);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
Age vertification input box - calculate if over 18 years
I have an input box where you should put your year of birth in. If the number is below 1998 you should gain access, if it's over 1998 you should go to another page.

I know this could possible be a mixture of javascript and html, but I can't figure out how to make the code and hoped you guys could help me!

This is the action that should happen, if the user is born in 1998 or before:

```<code><div  id="btn-close-modal" class="close-modal-03">
   CLOSE MODAL
</div>
</code>```

Hope you can help me :-)

答:
A better way is to use ::: </p>

```<code>db=new Date("original time string from input field with type date here");
db1=new Date();
var d= db1.getFullYear()-db.getFullYear();
if (d>limit) {alert("decide what to do you are not upto limit");}
</code>```

Body:
I have an input box where you should put your year of birth in. If the number is below 1998 you should gain access, if it's over 1998 you should go to another page.

I know this could possible be a mixture of javascript and html, but I can't figure out how to make the code and hoped you guys could help me!

This is the action that should happen, if the user is born in 1998 or before:

   CLOSE MODAL

Hope you can help me :-)

Body:
A better way is to use :::

db=new Date("original time string from input field with type date here");
db1=new Date();
var d= db1.getFullYear()-db.getFullYear();
if (d>limit) {alert("decide what to do you are not upto limit");}


问:
Error in Go's slices exercise
I'm trying to solve the slices exercise. My current solution is

```<code>package main

import "golang.org/x/tour/pic"

func Pic(dx, dy int) [][]uint8 {
    picture := make([][]uint8, dy)

    x := dx

    for iy := 0; iy < dy; iy++ {
        picture[iy] = make([]uint8, dx)

        for ix := 0; ix < dx; ix++ {
            x = (x+dy)/2
            picture[iy][ix] = uint8(x)
        }
    }

    return picture
}

func main() {
    pic.Show(Pic(1,2))
}
</code>```

But I'm getting the following error

tmp/sandbox931798243/main.go:23: cannot use Pic(1, 2) (type [][]uint8)
  as type func(int, int) [][]uint8 in argument to pic.Show

What am I doing wrong? Might that be a bug with the sandbox?

答:
pic.Show takes a single argument of type func(int, int) [][]uint8 - you need to pass it a function. You're passing the result of executing a func(int, int) [][]uint8, i.e. a [][]uint8. What you want would be:

```<code>pic.Show(Pic)
</code>```

Passing in your function Pic itself, which meets the requirements.

Title: Error in Go's slices exercise

Body:
I'm trying to solve the slices exercise. My current solution is

package main

import "golang.org/x/tour/pic"

func Pic(dx, dy int) [][]uint8 {
    picture := make([][]uint8, dy)

    x := dx

    for iy := 0; iy < dy; iy++ {
        picture[iy] = make([]uint8, dx)

        for ix := 0; ix < dx; ix++ {
            x = (x+dy)/2
            picture[iy][ix] = uint8(x)
        }
    }

    return picture
}

func main() {
    pic.Show(Pic(1,2))
}

But I'm getting the following error

tmp/sandbox931798243/main.go:23: cannot use Pic(1, 2) (type [][]uint8)
  as type func(int, int) [][]uint8 in argument to pic.Show

What am I doing wrong? Might that be a bug with the sandbox?

Body:
pic.Show takes a single argument of type func(int, int) [][]uint8 - you need to pass it a function. You're passing the result of executing a func(int, int) [][]uint8, i.e. a [][]uint8. What you want would be:

pic.Show(Pic)

Passing in your function Pic itself, which meets the requirements.


问:
Path of the USB devices which are connected to the machine?
If I have some USB devices which are connected to my machine, how can I know which is the path to access each one of them?

Is there way to know it through the code?

答:
```<code>DriveInfo[] mydrives = DriveInfo.GetDrives();

foreach (DriveInfo mydrive in mydrives)
{
    Console.WriteLine("Drive: {0}", mydrive.Name);
    Console.WriteLine("Type: {0}", mydrive.DriveType);
}
</code>```

This code will loop through each drive, and you'll see that your USB drive(s) will appear.  The DriveType will display as Removable and not USB, just so you are aware.

More information on DriveType.

Body:
DriveInfo[] mydrives = DriveInfo.GetDrives();

foreach (DriveInfo mydrive in mydrives)
{
    Console.WriteLine("Drive: {0}", mydrive.Name);
    Console.WriteLine("Type: {0}", mydrive.DriveType);
}

This code will loop through each drive, and you'll see that your USB drive(s) will appear.  The DriveType will display as Removable and not USB, just so you are aware.

More information on DriveType.


问:
** (CompileError) test/integration/listing_authors.test.exs:9: BookcaseApi.Author.__struct__/1
I have a integration test I am working on, but right now it won't compile.

listing_authors.test.exs

```<code>defmodule ListingAuthorsIntegrationTest do
  use ExUnit.Case, async: true
  use Plug.Test
  alias BookcaseApi.Web.Router
  alias BookcaseApi.Author

  @opts Router.init([])
  test 'listing authors' do
    author = %Author{name: "Oscar Wilde"}
             |> Repo.insert!

    # Note: single quotes are for char lists.
    # Note: double quotes are for strings.
    conn = conn(:get, "/authors")
    response = Router.call(conn, @opts)

    assert response.status == 200
    assert response.resp_body == author
  end
end
</code>```

author.ex

```<code>defmodule BookcaseApi.Author do
  use BookcaseApi.Web, :model

  schema "name" do

    timestamps()
  end

  @doc """
  Builds a changeset based on the `struct` and `params`.
  """
  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [])
    |> validate_required([])
  end
end
</code>```

stacktrace.txt

```<code>λ mix test test/integration/listing_authors.test.exs                             0 < 18:39:12
** (CompileError) test/integration/listing_authors.test.exs:9: BookcaseApi.Author.__struct__/1 is undefined, cannot expand struct BookcaseApi.Author
    (stdlib) lists.erl:1354: :lists.mapfoldl/3
    test/integration/listing_authors.test.exs:8: (module)
(stdlib) erl_eval.erl:670: :erl_eval.do_apply/6
</code>```

Any help on how I can get the integration test to compile would be awesome.

Update June 4, 2017
This is a phoenix v1.3 rc2 project that was generated with the below command,

```<code>mix phx.new bookcase_api --no-html --no-brunch
</code>```

I then generated a model for the project with the below command,

```<code>mix phoenix.gen.json Author name
</code>```

答:
Dennis already pointed out that you've used two different generators for the app and the model, so that could definitely be the source of your problem. There's another issue with the model that was generated, too. It looks like you intended to generate an Author schema with a single name field, but it looks like you didn't pass it a name for the database table so it interpreted name as the table name. With the new generators, you also need to give it a context -- in this case you might want to use Authors, in case you want to add more modules related to your Authors api. So your generator command would be:

mix phx.gen.json Authors Author authors name:string

(:string can technically be left off, the generator assumes you want fields to be :string time unless told otherwise)

The correct generated structure would look like:

```<code>defmodule BookcaseApi.Authors.Author do
  use Ecto.Schema

  schema "authors" do
    field :name, :string
    timestamps
  end
end
</code>```

The Phoenix website's documentation hasn't been updated yet to cover the new generators, but the source files are well documented. Here are the docs for the new json generator (also accessible with mix help phx.gen.json): https://github.com/phoenixframework/phoenix/blob/master/lib/mix/tasks/phx.gen.json.ex

Body:
I have a integration test I am working on, but right now it won't compile.

listing_authors.test.exs

defmodule ListingAuthorsIntegrationTest do
  use ExUnit.Case, async: true
  use Plug.Test
  alias BookcaseApi.Web.Router
  alias BookcaseApi.Author

  @opts Router.init([])
  test 'listing authors' do
    author = %Author{name: "Oscar Wilde"}
             |> Repo.insert!

    # Note: single quotes are for char lists.
    # Note: double quotes are for strings.
    conn = conn(:get, "/authors")
    response = Router.call(conn, @opts)

    assert response.status == 200
    assert response.resp_body == author
  end
end

author.ex

defmodule BookcaseApi.Author do
  use BookcaseApi.Web, :model

  schema "name" do

    timestamps()
  end

  @doc """
  Builds a changeset based on the `struct` and `params`.
  """
  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [])
    |> validate_required([])
  end
end

stacktrace.txt

λ mix test test/integration/listing_authors.test.exs                             0 < 18:39:12
** (CompileError) test/integration/listing_authors.test.exs:9: BookcaseApi.Author.__struct__/1 is undefined, cannot expand struct BookcaseApi.Author
    (stdlib) lists.erl:1354: :lists.mapfoldl/3
    test/integration/listing_authors.test.exs:8: (module)
(stdlib) erl_eval.erl:670: :erl_eval.do_apply/6

Any help on how I can get the integration test to compile would be awesome.

Update June 4, 2017
This is a phoenix v1.3 rc2 project that was generated with the below command,

mix phx.new bookcase_api --no-html --no-brunch

I then generated a model for the project with the below command,

mix phoenix.gen.json Author name

Body:
Dennis already pointed out that you've used two different generators for the app and the model, so that could definitely be the source of your problem. There's another issue with the model that was generated, too. It looks like you intended to generate an Author schema with a single name field, but it looks like you didn't pass it a name for the database table so it interpreted name as the table name. With the new generators, you also need to give it a context -- in this case you might want to use Authors, in case you want to add more modules related to your Authors api. So your generator command would be:

mix phx.gen.json Authors Author authors name:string

(:string can technically be left off, the generator assumes you want fields to be :string time unless told otherwise)

The correct generated structure would look like:

defmodule BookcaseApi.Authors.Author do
  use Ecto.Schema

  schema "authors" do
    field :name, :string
    timestamps
  end
end

The Phoenix website's documentation hasn't been updated yet to cover the new generators, but the source files are well documented. Here are the docs for the new json generator (also accessible with mix help phx.gen.json): https://github.com/phoenixframework/phoenix/blob/master/lib/mix/tasks/phx.gen.json.ex


问:
Replace special charachter '´' in C
I have a string to parse and it maybe contains the symbol "& acute;" depends on user data. So i want to eliminate this symbole and replace it with '.
Example :

Before --> Won´t Get Fooled Again
After  --> Won't Get Fooled Again

This is my try but it dosen't work in any way ..

```<code>int main()
{

  char* permenant="Won´t Get Fooled Again";
  char* s=permenant;
  for ( ; *s && *s != '&'; s++) ;
  printf("found '&' character \n"); // ---> OK
  printf("s=%s \n",s);              // ---> OK
  if (*(s+1) == 'a' && *(s+2) == 'c' && *(s+3) == 'u' && *(s+4) == 't'  && *(s+5) == 'e'  && *(s+6) == ';') // ---> OK
  {
     *s='\'';   //---> NO also if *s='a'; segmentation fault !!
     while(*(s+7)!='\0')
     {
          *(s+1)=*(s+7);
          s++;
          printf("the next character is -> %c \n", *(s+7));
     }// ---> Segmentation fault also if i remove *s='\''

   }
  printf("permenant=%s \n",permenant);

return 0;

}
</code>```

答:
Personally, I'd break this down as follows:

First, don't attempt to modify the input string; instead, write the converted string to a different buffer;

Second, break your operations up into different functions - one to find the entity in the string, one to map the entity onto a replacement string, one to perform the replacement, etc;

Third, use a lookup table or something instead of trying to match individual characters.

Here's a pass off the top of my head - it undoubtedly has some ugly bugs, but it should give you a flavor of what I'm trying to do:

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

/**
 * Create a structure to map an entity name onto a replacement string...
 */
struct entity_lookup {
   char *entity_name;
   char *replacement;
};

/**
 * ... and use that structure to build the lookup table
 */
static const struct entity_lookup lookup_table[] =  {
  { "acute", "'" },
  { "amp", "&" },
  { "apos", "'"},
  { "lt", "<" },
  { "gt", ">" },
  { "nbsp", " " },
  { NULL, NULL }
};

/**
 * Scan the input string for the next entity, which begins with the
 * character '&' and ends with ';' - if we don't find the trailing
 * ';', then we treat the '&' as a literal character.  Returns the location
 * of the first character of the entity name in the string.
 */
char *getNextEntity( const char *str, char **start, size_t *len )
{
  *len = 0;
  *start = strchr( str, '&' );

  if ( *start )
  {
    *start = *start + 1; // we want the text *following* &
    const char *end = strchr( *start, ';' );
    if ( end )
    {
      *len = end - *start - 1;
    }
    else
    {
      *start = NULL;
      *len = 0;
    }
  }

  return *start;
 }

/**
 * Find the replacement string for the given entity name.  Since our lookup
 * table is so small, a linear search is just fine in this case.
 */
char *getEntityReplacement( const char *entity )
{
  const struct entity_lookup *entry = lookup_table;

  while ( entry->entity_name != NULL && strcmp( entity, entry->entity_name ) )
  {
    entry++;
  }

  return entry->replacement;
}

/**
 * Replace any and all entities in an input string.  This code tries
 * to avoid any buffer overflows, but it's not very pretty and I haven't
 * exercised it that well.  I'm sure I could come up with a more elegant
 * method, but I've spent enough time on this already.
 */
void replaceEntities( const char * restrict input, char * restrict output, size_t maxOutputLen )
{
  char *entityStart = NULL;
  size_t entityLen = 0;

  /**
   * Initially point to the beginning of the input string.
   */
  const char *current = input;

  /**
   * Initially write an empty string to the output buffer.
   */
  *output = 0;

  /**
   * Look for the next entity; if we find one, copy everything from
   * the current position in the input buffer up to (but not including)
   * the first character of the entity; then we copy the replacement
   * for the entity to the output buffer.
   */
  while ( getNextEntity( current, &entityStart, &entityLen ) )
  {
    if ( strlen( output ) + entityStart - current - 1 <  maxOutputLen - 1 )
    {
      /**
       * Copy everything from the current position to the start of the
       * entity to the output buffer; for example, copy "Won" to
       * the output.
       */
      strncat( output, current, entityStart - current - 1 );

      /**
       * Find the entity in the lookup table.
       */
      char entityText[20] = {0};
      strncpy( entityText, entityStart, entityLen + 1 );

      char *repl = getEntityReplacement( entityText );

      /**
       * If there's a match and there's room in the output buffer,
       * write the replacement text to the output buffer, e.g., "'"
       */
      if ( repl && strlen( output ) + strlen( repl ) < maxOutputLen - 1 )
        strcat( output, repl );
      else
      {
        output[maxOutputLen] = 0;
        return;
      }
      current = entityStart + entityLen + 2;
    }
    else
    {
      output[maxOutputLen] = 0;
      return;
    }
  }

  /**
   * If we don't find any more entities, write the remainder of the input
   * string to the output buffer, e.g., "t Get Fooled Again"
   */
  if ( strlen( output ) + strlen( current ) < maxOutputLen - 1 )
    strcat( output, current );
}

int main( int argc, char **argv )
{
  char output[128];

  replaceEntities( argv[1], output, sizeof output );

  printf( "Original: %s\n", argv[1] );
  printf( "Stripped: %s\n", output );

  return 0;
}
</code>```

As always, the proof is in the pudding - here are some example runs:

```<code>$ ./entities "Won´t Get Fooled Again"
Original: Won´t Get Fooled Again
Stripped: Won't Get Fooled Again

$ ./entities "Won´t Get Fooled Again"
Original: Won´t Get Fooled Again
Stripped: Won't Get Fooled Again

$ ./entities "Black & Blue"
Original: Black & Blue
Stripped: Black & Blue

$ ./entities "Black & Blue"
Original: Black & Blue
Stripped: Black & Blue

$ ./entities "#include <stdio.h>"
Original: #include <stdio.h>
Stripped: #include <stdio.h>
</code>```

This code is too fragile for production use, but again, it should give you some ideas.

Title: Replace special charachter '´' in C

Body:
I have a string to parse and it maybe contains the symbol "& acute;" depends on user data. So i want to eliminate this symbole and replace it with '.
Example :

Before --> Won´t Get Fooled Again
After  --> Won't Get Fooled Again

This is my try but it dosen't work in any way ..

int main()
{

  char* permenant="Won´t Get Fooled Again";
  char* s=permenant;
  for ( ; *s && *s != '&'; s++) ;
  printf("found '&' character \n"); // ---> OK
  printf("s=%s \n",s);              // ---> OK
  if (*(s+1) == 'a' && *(s+2) == 'c' && *(s+3) == 'u' && *(s+4) == 't'  && *(s+5) == 'e'  && *(s+6) == ';') // ---> OK
  {
     *s='\'';   //---> NO also if *s='a'; segmentation fault !!
     while(*(s+7)!='\0')
     {
          *(s+1)=*(s+7);
          s++;
          printf("the next character is -> %c \n", *(s+7));
     }// ---> Segmentation fault also if i remove *s='\''

   }
  printf("permenant=%s \n",permenant);

return 0;

}

Body:
Personally, I'd break this down as follows:

First, don't attempt to modify the input string; instead, write the converted string to a different buffer;

Second, break your operations up into different functions - one to find the entity in the string, one to map the entity onto a replacement string, one to perform the replacement, etc;

Third, use a lookup table or something instead of trying to match individual characters.

Here's a pass off the top of my head - it undoubtedly has some ugly bugs, but it should give you a flavor of what I'm trying to do:

#include <stdio.h>
#include <string.h>

/**
 * Create a structure to map an entity name onto a replacement string...
 */
struct entity_lookup {
   char *entity_name;
   char *replacement;
};

/**
 * ... and use that structure to build the lookup table
 */
static const struct entity_lookup lookup_table[] =  {
  { "acute", "'" },
  { "amp", "&" },
  { "apos", "'"},
  { "lt", "<" },
  { "gt", ">" },
  { "nbsp", " " },
  { NULL, NULL }
};

/**
 * Scan the input string for the next entity, which begins with the
 * character '&' and ends with ';' - if we don't find the trailing
 * ';', then we treat the '&' as a literal character.  Returns the location
 * of the first character of the entity name in the string.
 */
char *getNextEntity( const char *str, char **start, size_t *len )
{
  *len = 0;
  *start = strchr( str, '&' );

  if ( *start )
  {
    *start = *start + 1; // we want the text *following* &
    const char *end = strchr( *start, ';' );
    if ( end )
    {
      *len = end - *start - 1;
    }
    else
    {
      *start = NULL;
      *len = 0;
    }
  }

  return *start;
 }

/**
 * Find the replacement string for the given entity name.  Since our lookup
 * table is so small, a linear search is just fine in this case.
 */
char *getEntityReplacement( const char *entity )
{
  const struct entity_lookup *entry = lookup_table;

  while ( entry->entity_name != NULL && strcmp( entity, entry->entity_name ) )
  {
    entry++;
  }

  return entry->replacement;
}

/**
 * Replace any and all entities in an input string.  This code tries
 * to avoid any buffer overflows, but it's not very pretty and I haven't
 * exercised it that well.  I'm sure I could come up with a more elegant
 * method, but I've spent enough time on this already.
 */
void replaceEntities( const char * restrict input, char * restrict output, size_t maxOutputLen )
{
  char *entityStart = NULL;
  size_t entityLen = 0;

  /**
   * Initially point to the beginning of the input string.
   */
  const char *current = input;

  /**
   * Initially write an empty string to the output buffer.
   */
  *output = 0;

  /**
   * Look for the next entity; if we find one, copy everything from
   * the current position in the input buffer up to (but not including)
   * the first character of the entity; then we copy the replacement
   * for the entity to the output buffer.
   */
  while ( getNextEntity( current, &entityStart, &entityLen ) )
  {
    if ( strlen( output ) + entityStart - current - 1 <  maxOutputLen - 1 )
    {
      /**
       * Copy everything from the current position to the start of the
       * entity to the output buffer; for example, copy "Won" to
       * the output.
       */
      strncat( output, current, entityStart - current - 1 );

      /**
       * Find the entity in the lookup table.
       */
      char entityText[20] = {0};
      strncpy( entityText, entityStart, entityLen + 1 );

      char *repl = getEntityReplacement( entityText );

      /**
       * If there's a match and there's room in the output buffer,
       * write the replacement text to the output buffer, e.g., "'"
       */
      if ( repl && strlen( output ) + strlen( repl ) < maxOutputLen - 1 )
        strcat( output, repl );
      else
      {
        output[maxOutputLen] = 0;
        return;
      }
      current = entityStart + entityLen + 2;
    }
    else
    {
      output[maxOutputLen] = 0;
      return;
    }
  }

  /**
   * If we don't find any more entities, write the remainder of the input
   * string to the output buffer, e.g., "t Get Fooled Again"
   */
  if ( strlen( output ) + strlen( current ) < maxOutputLen - 1 )
    strcat( output, current );
}

int main( int argc, char **argv )
{
  char output[128];

  replaceEntities( argv[1], output, sizeof output );

  printf( "Original: %s\n", argv[1] );
  printf( "Stripped: %s\n", output );

  return 0;
}

As always, the proof is in the pudding - here are some example runs:

$ ./entities "Won&acute;t Get Fooled Again"
Original: Won&acute;t Get Fooled Again
Stripped: Won't Get Fooled Again

$ ./entities "Won&acute;t&nbsp;Get&nbsp;Fooled&nbsp;Again"
Original: Won&acute;t&nbsp;Get&nbsp;Fooled&nbsp;Again
Stripped: Won't Get Fooled Again

$ ./entities "Black &amp; Blue"
Original: Black &amp; Blue
Stripped: Black & Blue

$ ./entities "Black & Blue"
Original: Black & Blue
Stripped: Black & Blue

$ ./entities "#include &lt;stdio.h&gt;"
Original: #include &lt;stdio.h&gt;
Stripped: #include <stdio.h>

This code is too fragile for production use, but again, it should give you some ideas.


问:
Rails 5 InvalidAuthenticityToken, but token is present
I am getting ActionController::InvalidAuthenticityToken saving a simple resource..

CSRF meta tags are present:

```<code><meta name="csrf-token" content="Z4fDRsIqCp4cvpCw1Dp6kN7z0uPNF5otp611C80YhUg/oB+AcUy+dz2b5qKyoMMo48LdEvbF3dcBn2d0GqeR+g==" />
</code>```

And the form's token field:

```<code><input type="hidden" name="authenticity_token" value="bIMZ5cndd/CTgOwjC3quOp02WlvWdDmhdNQCyKb920HIZz2Y8vvNDlTa7d4PKaJ5pUY6QkHKYCqiHikc2rFsyQ==" />
</code>```

Sessions ID is not persisting between requests, but I understand that this behaviour is intended when CSRF errors occur.

The form's code:

```<code><%= form_for document do |f| %>
  <% if document.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(document.errors.count, "error") %> prohibited this document from being saved:</h2>

      <ul>
      <% document.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>
</code>```

Actions relevant in the controller:

```<code>  def new
    @document = Document.new
  end

  def create
    @document = Document.new(document_params)

    respond_to do |format|
      if @document.save
        format.html { redirect_to @document, notice: 'Document was successfully created.' }
        format.json { render :show, status: :created, location: @document }
      else
        format.html { render :new }
        format.json { render json: @document.errors, status: :unprocessable_entity }
      end
    end
  end
</code>```

Not sure how to even troubleshoot this, and for obvious reasons, I'm not willing to turn off CSRF protection.

Edit: I'm going through an nginx container as a proxy, maybe my config for that is incorrect? Here is that config:

```<code>upstream backend {
    server service:3000;
}

server {
    listen 80 default_server;

    error_page 500 502 503 504 /500.html;
    error_log /dev/stdout info;
    access_log /dev/stdout;

    location / {
        proxy_pass http://backend;
    }
}
</code>```

答:
For anyone else running into this behind an nginx proxy, this is resolved by adding proxy configuration to nginx as outlined here:

I was missing these:

```<code>proxy_set_header        X-Real_IP       $remote_addr;
proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header        X-NginX-Proxy   true;
proxy_set_header        Host            $http_host;
proxy_set_header        Upgrade         $http_upgrade;
proxy_pass_header       Set-Cookie;
</code>```

Body:
I am getting ActionController::InvalidAuthenticityToken saving a simple resource..

CSRF meta tags are present:

<meta name="csrf-token" content="Z4fDRsIqCp4cvpCw1Dp6kN7z0uPNF5otp611C80YhUg/oB+AcUy+dz2b5qKyoMMo48LdEvbF3dcBn2d0GqeR+g==" />

And the form's token field:

<input type="hidden" name="authenticity_token" value="bIMZ5cndd/CTgOwjC3quOp02WlvWdDmhdNQCyKb920HIZz2Y8vvNDlTa7d4PKaJ5pUY6QkHKYCqiHikc2rFsyQ==" />

Sessions ID is not persisting between requests, but I understand that this behaviour is intended when CSRF errors occur.

The form's code:

<%= form_for document do |f| %>
  <% if document.errors.any? %>

<%= pluralize(document.errors.count, "error") %> prohibited this document from being saved:

      <% document.errors.full_messages.each do |message| %>

<%= message %>

      <% end %>

  <% end %>

    <%= f.submit %>

<% end %>

Actions relevant in the controller:

  def new
    @document = Document.new
  end

  def create
    @document = Document.new(document_params)

    respond_to do |format|
      if @document.save
        format.html { redirect_to @document, notice: 'Document was successfully created.' }
        format.json { render :show, status: :created, location: @document }
      else
        format.html { render :new }
        format.json { render json: @document.errors, status: :unprocessable_entity }
      end
    end
  end

Not sure how to even troubleshoot this, and for obvious reasons, I'm not willing to turn off CSRF protection.

Edit: I'm going through an nginx container as a proxy, maybe my config for that is incorrect? Here is that config:

upstream backend {
    server service:3000;
}

server {
    listen 80 default_server;

    error_page 500 502 503 504 /500.html;
    error_log /dev/stdout info;
    access_log /dev/stdout;

    location / {
        proxy_pass http://backend;
    }
}

Body:
For anyone else running into this behind an nginx proxy, this is resolved by adding proxy configuration to nginx as outlined here:

I was missing these:

proxy_set_header        X-Real_IP       $remote_addr;
proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header        X-NginX-Proxy   true;
proxy_set_header        Host            $http_host;
proxy_set_header        Upgrade         $http_upgrade;
proxy_pass_header       Set-Cookie;


问:
BASH script to check for two mounted drives 'unary operator expected'
Trying to write a bash script that will check for two mounted drives then do something if both are connected. So far I've got:

```<code>if [ $(mount | grep -c /media/card) != 1 ]
 then
    echo "ERROR: SD card not mounted"
    sudo sh -c "echo timer > /sys/class/leds/led0/trigger"
    sudo sh -c "echo 2000 > /sys/class/leds/led0/delay_on"
else
    if [ $(mount | grep -c /media/backup) !=1 ]
    then
            echo "ERROR: Backup not mounted"
            sudo sh -c "echo timer > /sys/class/leds/led0/trigger"
            sudo sh -c "echo 2000 > /sys/class/leds/led0/delay_on"
    else
            echo "All Plugged in"
    fi
fi
</code>```

Running returns the error:

```<code>./backup2.sh: line 12: [: 0: unary operator expected
</code>```

Not sure why the first if statement works, but then the second doesn't, as they basically the same. Is there a cleaner way of checking for two mounted devices? Ideally outputting an error showing which one(s) aren't mounted.

答:
You need to put a space after the !=:

```<code>if [ $(mount | grep -c /media/backup) !=1 ]
</code>```

Like this:

```<code>if [ $(mount | grep -c /media/backup) != 1 ]
</code>```

Btw, what happens if you have more than 1 mounted drives matching /media/card or /media/backup?
The output will be misleading,
saying that "X is not mounted".

So it seems it would make more sense to replace the != 1 conditions with == 0.
But if you decide to do that,
then there's a better way to write the conditions,
using the exit codes of the pipelines directly.

```<code>if ! mount | grep /media/card >/dev/null
then
    echo "ERROR: SD card not mounted"
    sudo sh -c "echo timer > /sys/class/leds/led0/trigger"
    sudo sh -c "echo 2000 > /sys/class/leds/led0/delay_on"
elif ! mount | grep /media/backup >/dev/null
then
    echo "ERROR: Backup not mounted"
    sudo sh -c "echo timer > /sys/class/leds/led0/trigger"
    sudo sh -c "echo 2000 > /sys/class/leds/led0/delay_on"
else
    echo "All Plugged in"
fi
</code>```

Body:
Trying to write a bash script that will check for two mounted drives then do something if both are connected. So far I've got:

if [ $(mount | grep -c /media/card) != 1 ]
 then
    echo "ERROR: SD card not mounted"
    sudo sh -c "echo timer > /sys/class/leds/led0/trigger"
    sudo sh -c "echo 2000 > /sys/class/leds/led0/delay_on"
else
    if [ $(mount | grep -c /media/backup) !=1 ]
    then
            echo "ERROR: Backup not mounted"
            sudo sh -c "echo timer > /sys/class/leds/led0/trigger"
            sudo sh -c "echo 2000 > /sys/class/leds/led0/delay_on"
    else
            echo "All Plugged in"
    fi
fi

Running returns the error:

./backup2.sh: line 12: [: 0: unary operator expected

Not sure why the first if statement works, but then the second doesn't, as they basically the same. Is there a cleaner way of checking for two mounted devices? Ideally outputting an error showing which one(s) aren't mounted.

Body:
You need to put a space after the !=:

if [ $(mount | grep -c /media/backup) !=1 ]

Like this:

if [ $(mount | grep -c /media/backup) != 1 ]

Btw, what happens if you have more than 1 mounted drives matching /media/card or /media/backup?
The output will be misleading,
saying that "X is not mounted".

So it seems it would make more sense to replace the != 1 conditions with == 0.
But if you decide to do that,
then there's a better way to write the conditions,
using the exit codes of the pipelines directly.

if ! mount | grep /media/card >/dev/null
then
    echo "ERROR: SD card not mounted"
    sudo sh -c "echo timer > /sys/class/leds/led0/trigger"
    sudo sh -c "echo 2000 > /sys/class/leds/led0/delay_on"
elif ! mount | grep /media/backup >/dev/null
then
    echo "ERROR: Backup not mounted"
    sudo sh -c "echo timer > /sys/class/leds/led0/trigger"
    sudo sh -c "echo 2000 > /sys/class/leds/led0/delay_on"
else
    echo "All Plugged in"
fi


问:
Python using same date/time in multiple files
I'm currently generating three different xml files, and I would like to have the second and third file have the same date/time as the first file.
In the first file, I do

```<code>import datetime
time = datetime.datetime.utcnow().strftime('%y%m%d%H%M%S')
</code>```

This gives me the format I would like. I've tried multiple approaches such as storing it in a different variable and importing it to the second and third files, but it seems that it'll always keep the actual current time and not the time of the first file. I don't know if there's a solution to my problem using the datetime module but if anyone has any ideas that would be wonderful.

答:
Whenever you call that function, whether directly or through import it will always run again and give a new "now".

If the same program just uses that string for 3 times there shouldn't be a problem, but if you're running 3 different scripts you will get 3 different dates!

To avoid this, I would save the first generated string to a file:

```<code>with open('.tmpdate') as f:
    f.write(time)
</code>```

And read it in the next to files:

```<code>with open('.tmpdate') as f:
    time = f.read()
</code>```

And finally, just to clean up after yourself, you can delete that file after it was used for the 3rd time with os.remove('.tmpdate') (you need to import os before that, of course)

Body:
I'm currently generating three different xml files, and I would like to have the second and third file have the same date/time as the first file.
In the first file, I do

import datetime
time = datetime.datetime.utcnow().strftime('%y%m%d%H%M%S')

This gives me the format I would like. I've tried multiple approaches such as storing it in a different variable and importing it to the second and third files, but it seems that it'll always keep the actual current time and not the time of the first file. I don't know if there's a solution to my problem using the datetime module but if anyone has any ideas that would be wonderful.

Body:
Whenever you call that function, whether directly or through import it will always run again and give a new "now".

If the same program just uses that string for 3 times there shouldn't be a problem, but if you're running 3 different scripts you will get 3 different dates!

To avoid this, I would save the first generated string to a file:

with open('.tmpdate') as f:
    f.write(time)

And read it in the next to files:

with open('.tmpdate') as f:
    time = f.read()

And finally, just to clean up after yourself, you can delete that file after it was used for the 3rd time with os.remove('.tmpdate') (you need to import os before that, of course)


问:
Spark File not found . works fine in local mode but failed in cluster mode
Hi every one ,
                        I have simple spark application in which I have few spring context and rule xml file . all these files are part of the projects and located under resource folder (reource\db\rule\rule2.xml) and its working fine in spark local mode . when I ran the same application in yarn cluster mode , its complaining that the file rule2.xml not found and its part of Maven built jar. do I need to specify the file in a different format for cluster mode ? do I need to make any changes for the application to work in cluster mode ? any help would be appreciated

Here is the code in which I am reading the xml file

```<code> JaxbUtils.unmarshalRule(
            ByteStreams.toByteArray(
            Resources.getResource(String.format("db/rule/rule2.xml", id)).openStream()));

Here is the error log

/24 15:57:07 INFO storage.BlockManager: Registering executor with local external shuffle service.
15/09/24 15:57:07 INFO util.AkkaUtils: Connecting to HeartbeatReceiver: akka.tcp://sparkDriver@bdaolc011node08.sabre.com:40589/user/HeartbeatReceiver
15/09/24 15:57:09 INFO executor.CoarseGrainedExecutorBackend: Got assigned task 0
15/09/24 15:57:09 INFO executor.Executor: Running task 0.0 in stage 0.0 (TID 0)
15/09/24 15:57:09 INFO broadcast.TorrentBroadcast: Started reading broadcast variable 0
15/09/24 15:57:09 INFO storage.MemoryStore: ensureFreeSpace(3132) called with curMem=0, maxMem=555755765
15/09/24 15:57:09 INFO storage.MemoryStore: Block broadcast_0_piece0 stored as bytes in memory (estimated size 3.1 KB, free 530.0 MB)
15/09/24 15:57:09 INFO storage.BlockManagerMaster: Updated info of block broadcast_0_piece0
15/09/24 15:57:09 INFO broadcast.TorrentBroadcast: Reading broadcast variable 0 took 134 ms
15/09/24 15:57:09 INFO storage.MemoryStore: ensureFreeSpace(6144) called with curMem=3132, maxMem=555755765
15/09/24 15:57:09 INFO storage.MemoryStore: Block broadcast_0 stored as values in memory (estimated size 6.0 KB, free 530.0 MB)
15/09/24 15:57:12 INFO support.ClassPathXmlApplicationContext: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@3c6db742: startup date [Thu Sep 24 15:57:12 CDT 2015]; root of context hierarchy
15/09/24 15:57:12 INFO xml.XmlBeanDefinitionReader: Loading XML bean definitions from class path resource [spring/rules-engine-spring.xml]
15/09/24 15:57:13 INFO xml.XmlBeanDefinitionReader: Loading XML bean definitions from class path resource [spring/ere-spring.xml]
15/09/24 15:57:13 INFO support.DefaultListableBeanFactory: Overriding bean definition for bean 'nativeRuleBuilder': replacing [Generic bean: class [com.sabre.sp.ere.core.loader.DroolsNativeRuleBuilder]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in class path resource [spring/ere-spring.xml]] with [Generic bean: class [com.sabre.sp.ere.core.loader.DroolsNativeRuleBuilder]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in class path resource [spring/rules-engine-spring.xml]]
15/09/24 15:57:13 INFO support.DefaultListableBeanFactory: Overriding bean definition for bean 'rulesExecutor': replacing [Generic bean: class [com.sabre.sp.ere.core.executor.DroolsRulesExecutor]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in class path resource [spring/ere-spring.xml]] with [Generic bean: class [com.sabre.sp.ere.core.executor.DroolsRulesExecutor]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in class path resource [spring/rules-engine-spring.xml]]
15/09/24 15:57:13 INFO support.PropertySourcesPlaceholderConfigurer: Loading properties file from class path resource [spring/ere-test.properties]
15/09/24 15:57:13 WARN support.PropertySourcesPlaceholderConfigurer: Could not load properties from class path resource [spring/ere-test.properties]: class path resource [spring/ere-test.properties] cannot be opened because it does not exist
15/09/24 15:57:13 INFO support.PropertySourcesPlaceholderConfigurer: Loading properties file from class path resource [spring/ere-spring.properties]
15/09/24 15:57:13 INFO annotation.AutowiredAnnotationBeanPostProcessor: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
15/09/24 15:57:13 INFO jdbc.JDBCRDD: closed connection
java.lang.IllegalArgumentException: resource spring/rule2.xml not found.
at com.google.common.base.Preconditions.checkArgument(Preconditions.java:115)
at com.google.common.io.Resources.getResource(Resources.java:152)
at com.sabre.rules.AppRuleExecutor.rule(AppRuleExecutor.java:50)
at com.sabre.rules.AppRuleExecutor.executeRules(AppRuleExecutor.java:39)
at com.sabre.rules.RuleComponent.executeRules(RuleComponent.java:43)
at com.sabre.rules.SMAAlertImpl$1.call(SMAAlertImpl.java:60)
at com.sabre.rules.SMAAlertImpl$1.call(SMAAlertImpl.java:37)
at org.apache.spark.api.java.JavaRDDLike$$anonfun$fn$4$1.apply(JavaRDDLike.scala:143)
at org.apache.spark.api.java.JavaRDDLike$$anonfun$fn$4$1.apply(JavaRDDLike.scala:143)
at org.apache.spark.rdd.RDD$$anonfun$14.apply(RDD.scala:634)
at org.apache.spark.rdd.RDD$$anonfun$14.apply(RDD.scala:634)
at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:35)
at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:277)
at org.apache.spark.rdd.RDD.iterator(RDD.scala:244)
at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:61)
at org.apache.spark.scheduler.Task.run(Task.scala:64)
at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:203)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
</code>```

答:
Let's say you have your code inside main() as given below:

JaxbUtils.unmarshalRule(
              ByteStreams.toByteArray(
              Resources.getResource(String.format(args[0], id)).openStream()));

So, you need to invoke the code as below:

spark-submit --master yarn --deploy-mode cluster --files db/rule/rule2.xml mySample.jar rule2.xml

What it does? It tells yarn to deploy the code/jar in cluster mode and keep the file specified in "--files" on container. In cluster mode, container can be created in any one of the nodes in cluster. However, once it has been specified in "--files", you need to refer it by its name only rather than specifying fully qualified path.

Body:
Hi every one ,
                        I have simple spark application in which I have few spring context and rule xml file . all these files are part of the projects and located under resource folder (reource\db\rule\rule2.xml) and its working fine in spark local mode . when I ran the same application in yarn cluster mode , its complaining that the file rule2.xml not found and its part of Maven built jar. do I need to specify the file in a different format for cluster mode ? do I need to make any changes for the application to work in cluster mode ? any help would be appreciated

Here is the code in which I am reading the xml file

 JaxbUtils.unmarshalRule(
            ByteStreams.toByteArray(
            Resources.getResource(String.format("db/rule/rule2.xml", id)).openStream()));

Here is the error log

/24 15:57:07 INFO storage.BlockManager: Registering executor with local external shuffle service.
15/09/24 15:57:07 INFO util.AkkaUtils: Connecting to HeartbeatReceiver: akka.tcp://sparkDriver@bdaolc011node08.sabre.com:40589/user/HeartbeatReceiver
15/09/24 15:57:09 INFO executor.CoarseGrainedExecutorBackend: Got assigned task 0
15/09/24 15:57:09 INFO executor.Executor: Running task 0.0 in stage 0.0 (TID 0)
15/09/24 15:57:09 INFO broadcast.TorrentBroadcast: Started reading broadcast variable 0
15/09/24 15:57:09 INFO storage.MemoryStore: ensureFreeSpace(3132) called with curMem=0, maxMem=555755765
15/09/24 15:57:09 INFO storage.MemoryStore: Block broadcast_0_piece0 stored as bytes in memory (estimated size 3.1 KB, free 530.0 MB)
15/09/24 15:57:09 INFO storage.BlockManagerMaster: Updated info of block broadcast_0_piece0
15/09/24 15:57:09 INFO broadcast.TorrentBroadcast: Reading broadcast variable 0 took 134 ms
15/09/24 15:57:09 INFO storage.MemoryStore: ensureFreeSpace(6144) called with curMem=3132, maxMem=555755765
15/09/24 15:57:09 INFO storage.MemoryStore: Block broadcast_0 stored as values in memory (estimated size 6.0 KB, free 530.0 MB)
15/09/24 15:57:12 INFO support.ClassPathXmlApplicationContext: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@3c6db742: startup date [Thu Sep 24 15:57:12 CDT 2015]; root of context hierarchy
15/09/24 15:57:12 INFO xml.XmlBeanDefinitionReader: Loading XML bean definitions from class path resource [spring/rules-engine-spring.xml]
15/09/24 15:57:13 INFO xml.XmlBeanDefinitionReader: Loading XML bean definitions from class path resource [spring/ere-spring.xml]
15/09/24 15:57:13 INFO support.DefaultListableBeanFactory: Overriding bean definition for bean 'nativeRuleBuilder': replacing [Generic bean: class [com.sabre.sp.ere.core.loader.DroolsNativeRuleBuilder]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in class path resource [spring/ere-spring.xml]] with [Generic bean: class [com.sabre.sp.ere.core.loader.DroolsNativeRuleBuilder]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in class path resource [spring/rules-engine-spring.xml]]
15/09/24 15:57:13 INFO support.DefaultListableBeanFactory: Overriding bean definition for bean 'rulesExecutor': replacing [Generic bean: class [com.sabre.sp.ere.core.executor.DroolsRulesExecutor]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in class path resource [spring/ere-spring.xml]] with [Generic bean: class [com.sabre.sp.ere.core.executor.DroolsRulesExecutor]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in class path resource [spring/rules-engine-spring.xml]]
15/09/24 15:57:13 INFO support.PropertySourcesPlaceholderConfigurer: Loading properties file from class path resource [spring/ere-test.properties]
15/09/24 15:57:13 WARN support.PropertySourcesPlaceholderConfigurer: Could not load properties from class path resource [spring/ere-test.properties]: class path resource [spring/ere-test.properties] cannot be opened because it does not exist
15/09/24 15:57:13 INFO support.PropertySourcesPlaceholderConfigurer: Loading properties file from class path resource [spring/ere-spring.properties]
15/09/24 15:57:13 INFO annotation.AutowiredAnnotationBeanPostProcessor: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
15/09/24 15:57:13 INFO jdbc.JDBCRDD: closed connection
java.lang.IllegalArgumentException: resource spring/rule2.xml not found.
at com.google.common.base.Preconditions.checkArgument(Preconditions.java:115)
at com.google.common.io.Resources.getResource(Resources.java:152)
at com.sabre.rules.AppRuleExecutor.rule(AppRuleExecutor.java:50)
at com.sabre.rules.AppRuleExecutor.executeRules(AppRuleExecutor.java:39)
at com.sabre.rules.RuleComponent.executeRules(RuleComponent.java:43)
at com.sabre.rules.SMAAlertImpl$1.call(SMAAlertImpl.java:60)
at com.sabre.rules.SMAAlertImpl$1.call(SMAAlertImpl.java:37)
at org.apache.spark.api.java.JavaRDDLike$$anonfun$fn$4$1.apply(JavaRDDLike.scala:143)
at org.apache.spark.api.java.JavaRDDLike$$anonfun$fn$4$1.apply(JavaRDDLike.scala:143)
at org.apache.spark.rdd.RDD$$anonfun$14.apply(RDD.scala:634)
at org.apache.spark.rdd.RDD$$anonfun$14.apply(RDD.scala:634)
at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:35)
at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:277)
at org.apache.spark.rdd.RDD.iterator(RDD.scala:244)
at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:61)
at org.apache.spark.scheduler.Task.run(Task.scala:64)
at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:203)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)


问:
Can't merge two lists into a dictionary
I can't merge two lists into a dictionary.I tried the following :

Map two lists into a dictionary in Python

I tried all solutions and I still get an empty dictionary

```<code>from sklearn.feature_extraction import DictVectorizer
from itertools import izip
import itertools

text_file = open("/home/vesko_/evnt_classification/bag_of_words", "r")
text_fiel2 = open("/home/vesko_/evnt_classification/sdas", "r")
lines = text_file.read().split('\n')
words = text_fiel2.read().split('\n')

diction = dict(itertools.izip(words,lines))
new_dict = {k: v for k, v in zip(words, lines)}
print new_dict
</code>```

I get the following :

{'word': ''}
['word=']

The two lists are not empty.

I'm using python2.7

EDIT :

Output from the two lists (I'm only showing a few because it's a vector with 11k features)

```<code>//lines
['change', 'I/O', 'fcnet2', 'ifconfig',....
//words
['word', 'word', 'word', .....
</code>```

EDIT :

Now at least I have some output @DamianLattenero

```<code>{'word\n': 'XXAMSDB35:XXAMSDB35_NGCEAC_DAT_L_Drivei\n'}
['word\n=XXAMSDB35:XXAMSDB35_NGCEAC_DAT_L_Drivei\n']
</code>```

答:
I think the root of a lot of confusion is code in the example that is not relevant.

Try this:

```<code>text_file = open("/home/vesko_/evnt_classification/bag_of_words", "r")
text_fiel2 = open("/home/vesko_/evnt_classification/sdas", "r")
lines = text_file.read().split('\n')
words = text_fiel2.read().split('\n')

# to remove any extra newline or whitespace from what was read in
map(lambda line: line.rstrip(), lines)
map(lambda word: word.rstrip(), words)

new_dict = dict(zip(words,lines))
print new_dict
</code>```

Python builtin zip() returns an iterable of tuples from each of the arguments. Giving this iterable of tuples to the dict() object constructor creates a dictionary where each of the items in words is the key and items in lines is the corresponding value.

Also note that if the words file has more items than lines then there will either keys with empty values. If lines has items then only the last one will be added with an None key.

Title: Can't merge two lists into a dictionary

Body:
I can't merge two lists into a dictionary.I tried the following :

Map two lists into a dictionary in Python

I tried all solutions and I still get an empty dictionary

from sklearn.feature_extraction import DictVectorizer
from itertools import izip
import itertools

text_file = open("/home/vesko_/evnt_classification/bag_of_words", "r")
text_fiel2 = open("/home/vesko_/evnt_classification/sdas", "r")
lines = text_file.read().split('\n')
words = text_fiel2.read().split('\n')

diction = dict(itertools.izip(words,lines))
new_dict = {k: v for k, v in zip(words, lines)}
print new_dict

I get the following :

{'word': ''}
['word=']

The two lists are not empty.

I'm using python2.7

EDIT :

Output from the two lists (I'm only showing a few because it's a vector with 11k features)

//lines
['change', 'I/O', 'fcnet2', 'ifconfig',....
//words
['word', 'word', 'word', .....

EDIT :

Now at least I have some output @DamianLattenero

{'word\n': 'XXAMSDB35:XXAMSDB35_NGCEAC_DAT_L_Drivei\n'}
['word\n=XXAMSDB35:XXAMSDB35_NGCEAC_DAT_L_Drivei\n']

Body:
I think the root of a lot of confusion is code in the example that is not relevant.

Try this:

text_file = open("/home/vesko_/evnt_classification/bag_of_words", "r")
text_fiel2 = open("/home/vesko_/evnt_classification/sdas", "r")
lines = text_file.read().split('\n')
words = text_fiel2.read().split('\n')

# to remove any extra newline or whitespace from what was read in
map(lambda line: line.rstrip(), lines)
map(lambda word: word.rstrip(), words)

new_dict = dict(zip(words,lines))
print new_dict

Python builtin zip() returns an iterable of tuples from each of the arguments. Giving this iterable of tuples to the dict() object constructor creates a dictionary where each of the items in words is the key and items in lines is the corresponding value.

Also note that if the words file has more items than lines then there will either keys with empty values. If lines has items then only the last one will be added with an None key.


问:
How do you create hybrid Xcode projects for Mac & iPhone?
I'm working on a project which shall contain two targets. One for building a Framework to use in Mac development and another to create a static library to use in iPhone development.

In the common code it's no problem to #ifdef between the platforms, but I just can't get the targets and dependencies right.

The first question is, which base SDK to use?
For example if I use Mac 10.5 i can't include the UIKit framework (it is marked red and doesn't show the header files if i expand it). Even if the target that actually links against it builds for iPhone OS..

The other question is, how about the Foundation.framework, or stuff like Security.framework?  How to deal with them, as I can only include one of the versions (Mac or iPhone SDK)...

Anyone has an advice for me?
I'd like to have a clean project structure and definitely the same codebase for both targets... Are configurations the way to go?

Thanks!

答: Can't you use the PIMPL idiom? And/or have a common header for both but use different implementation file based on the target architecture or SDK?</p>

OwnerDisplayName: stigi

LastEditorDisplayName: stigi

OwnerDisplayName: Henrik Hartz