问:
Redirect error 404 Angular 5

I am trying to handle 404 error when urls are wrong, http://localhost:8100/#/login. This is my login url and if I write something like http:.../loginasdasd i would like to automatically open my own NotFoundPage.

```<code>const appRoutes3: Routes = [
  {
    path: '',
    children: [
      {
         path: 'login',
         component: LoginPage
      },
      { path: 'login**', redirectTo: '/notfound' }
   ]
 },
 { path: 'notfound', component: NotFoundPage }
];

RouterModule.forRoot(
  appRoutes3,
  { enableTracing: true } // <-- debugging purposes only
)
,
IonicModule.forRoot(MyApp, {}, {
  links: [
    { component: HomePage, name: "Home", segment: "" },
    { component: LoginPage, name: "Login", segment: "login", defaultHistory: [HomePage] },
    { component: SubscribePage, name: "Signup", segment: "signup", defaultHistory: [HomePage] },
    { component: SubscribeExtendPage, name: "Signup", segment: "signup-extend", defaultHistory: [HomePage] },
    { component: MainPage, name: "Main", segment: "main", defaultHistory: [HomePage] },
    { component: WelcomePage, name: "Welcome", segment: "welcome" },
    { component: NotFoundPage, name: "notFound", segment: "login/**", defaultHistory: [HomePage] },
  ]
}
)
],
</code>```

I am an angular noob and I don't how to properly do it, the best info i've found is https://vsavkin.com/angular-router-understanding-redirects-2826177761fc in some other angular redirection posts.

Please some help or any clue would be grateful.
Thanks.

答:
As Angular tries to match the routes in the order you declared in your Routes array. You could do this:

```<code>const appRoutes3: Routes = [
  {
    path: '',
    children: [
      {
         path: 'login',
         component: LoginPage
      }
 },
 { path: '**', component: NotFoundPage }
];
</code>```

But if you really want a route /notfound, change the redirectTo: '/notfound' for redirectTo: 'notfound'.

Title: Redirect error 404 Angular 5

Body:
I am trying to handle 404 error when urls are wrong, http://localhost:8100/#/login. This is my login url and if I write something like http:.../loginasdasd i would like to automatically open my own NotFoundPage.

const appRoutes3: Routes = [
  {
    path: '',
    children: [
      {
         path: 'login',
         component: LoginPage
      },
      { path: 'login**', redirectTo: '/notfound' }
   ]
 },
 { path: 'notfound', component: NotFoundPage }
];

RouterModule.forRoot(
  appRoutes3,
  { enableTracing: true } // <-- debugging purposes only
)
,
IonicModule.forRoot(MyApp, {}, {
  links: [
    { component: HomePage, name: "Home", segment: "" },
    { component: LoginPage, name: "Login", segment: "login", defaultHistory: [HomePage] },
    { component: SubscribePage, name: "Signup", segment: "signup", defaultHistory: [HomePage] },
    { component: SubscribeExtendPage, name: "Signup", segment: "signup-extend", defaultHistory: [HomePage] },
    { component: MainPage, name: "Main", segment: "main", defaultHistory: [HomePage] },
    { component: WelcomePage, name: "Welcome", segment: "welcome" },
    { component: NotFoundPage, name: "notFound", segment: "login/**", defaultHistory: [HomePage] },
  ]
}
)
],

I am an angular noob and I don't how to properly do it, the best info i've found is https://vsavkin.com/angular-router-understanding-redirects-2826177761fc in some other angular redirection posts.

Please some help or any clue would be grateful.
Thanks.

Body:
As Angular tries to match the routes in the order you declared in your Routes array. You could do this:

const appRoutes3: Routes = [
  {
    path: '',
    children: [
      {
         path: 'login',
         component: LoginPage
      }
 },
 { path: '**', component: NotFoundPage }
];

But if you really want a route /notfound, change the redirectTo: '/notfound' for redirectTo: 'notfound'.


来源: stackexchange

问:
Batch file to make another batch file to execute
i am trying to make a batch file (lets say a.bat) which when run creates another batch file (lets say b.bat). Now, i am using b.bat to rename certain file.The code for renaming is,

```<code>@echo off
SETLOCAL ENABLEDELAYEDEXPANSION

SET "folder=path\to the\file"

::Action
CD /d "%folder%"
FOR %%F IN ("old filename") DO (
 MOVE "%%F" "new filename"
)
</code>```

The code in a.bat to write code in b.bat is,

```<code>@echo off

set VarOne=@echo off
set VarTwo=SETLOCAL ENABLEDELAYEDEXPANSION
set VarThree=::Action
set VarFour=CD /d "path\to the\file"
set VarFive=FOR %%F IN ("old filename") DO (
set VarSix= MOVE "%%F" "new filename"
set VarSeven=)

echo %VarOne% >> %Output%\test.bat
echo %VarTwo% >> %Output%\test.bat
echo %VarThree% >> %Output%\test.bat
echo %VarFour% >> %Output%\test.bat
echo %VarFive% >> %Output%\test.bat
echo %VarSix% >> %Output%\test.bat
echo %VarSeven% >> %Output%\test.bat
</code>```

Now the problem is that the when b.bat is generated it is like this,

```<code>@echo off
SETLOCAL ENABLEDELAYEDEXPANSION

SET "folder=path\to the\file"

::Action
CD /d ""
FOR %F IN ("old filename") DO (
 MOVE "%F" "new filename"
)
</code>```

The %folder% and a % from %%f is gone. So how would i get it right ? Help me please.

答:
What npocmaka and LS_dev said in the comments was correct. You have to double each % and use:

```<code>set VarFive=FOR %%%%F IN ("old filename") DO (
</code>```

I personally tested both of these and can confirm.

ContentLicense: CC BY-SA 3.0

Body:
i am trying to make a batch file (lets say a.bat) which when run creates another batch file (lets say b.bat). Now, i am using b.bat to rename certain file.The code for renaming is,

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION

SET "folder=path\to the\file"

::Action
CD /d "%folder%"
FOR %%F IN ("old filename") DO (
 MOVE "%%F" "new filename"
)

The code in a.bat to write code in b.bat is,

@echo off

set VarOne=@echo off
set VarTwo=SETLOCAL ENABLEDELAYEDEXPANSION
set VarThree=::Action
set VarFour=CD /d "path\to the\file"
set VarFive=FOR %%F IN ("old filename") DO (
set VarSix= MOVE "%%F" "new filename"
set VarSeven=)

echo %VarOne% >> %Output%\test.bat
echo %VarTwo% >> %Output%\test.bat
echo %VarThree% >> %Output%\test.bat
echo %VarFour% >> %Output%\test.bat
echo %VarFive% >> %Output%\test.bat
echo %VarSix% >> %Output%\test.bat
echo %VarSeven% >> %Output%\test.bat

Now the problem is that the when b.bat is generated it is like this,

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION

SET "folder=path\to the\file"

::Action
CD /d ""
FOR %F IN ("old filename") DO (
 MOVE "%F" "new filename"
)

The %folder% and a % from %%f is gone. So how would i get it right ? Help me please.

Body:
What npocmaka and LS_dev said in the comments was correct. You have to double each % and use:

set VarFive=FOR %%%%F IN ("old filename") DO (

I personally tested both of these and can confirm.


问:
Laravel Route based on query string
Currently in my routes.php file I've got the following:

```<code>Route::get('import', 'Controller@import');
</code>```

But as for the requests they'd be sent in the following way:

```<code>/import?flag=0&data={} //flag could be anything from 0-4 & data is json encoded info
/import?flag=5&data={}
/import?flag=6&data={}
</code>```

These are the only 3 requests that I'd have, I'm aware that Laravel supports where method on the route but only regular expressions but not on query parameters, is there a solution for this that I'm overlooking?

The expression method would be something like so:

```<code>Route::get('import?flag={id}&data={data}', 'Controller@importFlag0-4')->where('id', '<=', '4');
Route::get('import?flag={id}&data={data}', 'Controller@importFlag5')->where('id', '5');
Route::get('import?flag={id}&data={data}', 'Controller@importFlag6')->where('id', '6');
</code>```

答:
You can use only single way </p>

```<code>Route::any('import', 'Controller@import');

On controller write the following function.

public function import(Request $request)
    {
        $getData  = $request->all();
        $flag = $getData['flag'];
        $data = $getData['data'];

        $getModelData = ModelName::where('id',$flag);

    }
</code>```

Title: Laravel Route based on query string

Body:
Currently in my routes.php file I've got the following:

Route::get('import', 'Controller@import');

But as for the requests they'd be sent in the following way:

/import?flag=0&data={} //flag could be anything from 0-4 & data is json encoded info
/import?flag=5&data={}
/import?flag=6&data={}

These are the only 3 requests that I'd have, I'm aware that Laravel supports where method on the route but only regular expressions but not on query parameters, is there a solution for this that I'm overlooking?

The expression method would be something like so:

Route::get('import?flag={id}&data={data}', 'Controller@importFlag0-4')->where('id', '<=', '4');
Route::get('import?flag={id}&data={data}', 'Controller@importFlag5')->where('id', '5');
Route::get('import?flag={id}&data={data}', 'Controller@importFlag6')->where('id', '6');

Body:
You can use only single way

Route::any('import', 'Controller@import');

On controller write the following function.

public function import(Request $request)
    {
        $getData  = $request->all();
        $flag = $getData['flag'];
        $data = $getData['data'];

        $getModelData = ModelName::where('id',$flag);

    }


问:
How to dynamically append sections and use those to append other sections with JQuery?
Straight to the point. I have a problem with .append() function. I need to append a section, containing datetime-local and a button to another section, which is visible.

This new appended button must append another section, containing the same elements, but WITH DIFFERENT IDs. First part of the code is working, but second doesn’t and I can’t get why. I know my code is elegant like an elephant, but...

Your help is appreciated!

$(document).ready(function() {
  var max_fields = 2;
  var wrapper = $(".input_1");
  var add_button = $(".add_1");

  var x = 1;

  $(add_button).click(function(e) {
    e.preventDefault();
    if (x < max_fields) {
      x++;
      $(wrapper).append('
-.-.-
<input type="datetime-local">Remove
 <button class="add_2">return</button>
');
    }
  });

  $(wrapper).on("click", ".remove_1", function(e) {
    e.preventDefault();
    $(this).parent('section').remove();
    x--;
  })
});

//level 2
$(document).ready(function() {
  var max_fields_2 = 2;
  var wrapper_2 = $(".input_2");
  var add_button_2 = $(".add_2");

  var x = 1;

  $(add_button_2).click(function(e) {
    e.preventDefault();
    if (x < max_fields_2) {
      x++;
      $(wrapper_2).append('
-.-.-
<input type="datetime-local">Remove
 <button class="add_3">return 2</button>
');
    }
  });

  $(wrapper_2).on("click", ".remove_2", function(e) {
    e.preventDefault();
    $(this).parent('section').remove();
    x--;
  })
});```
<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>
<section class="input_1">
  <input type="datetime-local"><br/>
  <button class="add_1">return to icu</button>
</section></code>```

答:
You need to use delegates and find elements in event handler for dynamically added content, like it's for ".remove_1" in your code.

//level 2
$(document).ready(function() {
  var max_fields_2 = 2;
  var x = 1;

  $(document).on('click', '.add_2', function(e) {
    e.preventDefault();
    var wrapper_2 = $(".input_2");
    if (x < max_fields_2) {
      x++;
      $(wrapper_2).append('
-.-.-
<input type="datetime-local">Remove
 <button class="add_3">return 2</button>
');
      $(wrapper_2).on("click", ".remove_2", function(e) {
        e.preventDefault();
        $(this).parent('section').remove();
        x--;
      })
    }
  });
});```

Body:
Straight to the point. I have a problem with .append() function. I need to append a section, containing datetime-local and a button to another section, which is visible.

This new appended button must append another section, containing the same elements, but WITH DIFFERENT IDs. First part of the code is working, but second doesn’t and I can’t get why. I know my code is elegant like an elephant, but...

Your help is appreciated!

$(document).ready(function() {
  var max_fields = 2;
  var wrapper = $(".input_1");
  var add_button = $(".add_1");

  var x = 1;

  $(add_button).click(function(e) {
    e.preventDefault();
    if (x < max_fields) {
      x++;
      $(wrapper).append('
-.-.-
<input type="datetime-local">Remove
 <button class="add_2">return</button>
');
    }
  });

  $(wrapper).on("click", ".remove_1", function(e) {
    e.preventDefault();
    $(this).parent('section').remove();
    x--;
  })
});

//level 2
$(document).ready(function() {
  var max_fields_2 = 2;
  var wrapper_2 = $(".input_2");
  var add_button_2 = $(".add_2");

  var x = 1;

  $(add_button_2).click(function(e) {
    e.preventDefault();
    if (x < max_fields_2) {
      x++;
      $(wrapper_2).append('
-.-.-
<input type="datetime-local">Remove
 <button class="add_3">return 2</button>
');
    }
  });

  $(wrapper_2).on("click", ".remove_2", function(e) {
    e.preventDefault();
    $(this).parent('section').remove();
    x--;
  })
});

  <input type="datetime-local">

  <button class="add_1">return to icu</button>

Body:
You need to use delegates and find elements in event handler for dynamically added content, like it's for ".remove_1" in your code.

//level 2
$(document).ready(function() {
  var max_fields_2 = 2;
  var x = 1;

  $(document).on('click', '.add_2', function(e) {
    e.preventDefault();
    var wrapper_2 = $(".input_2");
    if (x < max_fields_2) {
      x++;
      $(wrapper_2).append('<section>-.-.-<br/><input type="datetime-local"><a href="#" class="remove_2">Remove</a><br /> <button class="add_3">return 2</button> </section>');
      $(wrapper_2).on("click", ".remove_2", function(e) {
        e.preventDefault();
        $(this).parent('section').remove();
        x--;
      })
    }
  });
});


问:
PHP: PEAR mail message error
I can send an email by the code in this (url:http://stackoverflow.com/questions/712392/send-email-using-gmail-smtp-server-from-php-page)

but the errors shown as following...

Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in /Users/abc/pear/share/pear/Mail/smtp.php on line 365

Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in /Users/abc/pear/share/pear/Net/SMTP.php on line 450

Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in /Users/abc/pear/share/pear/Net/SMTP.php on line 467

Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in /Users/abc/pear/share/pear/Net/SMTP.php on line 474

Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in /Users/abc/pear/share/pear/Net/SMTP.php on line 517

Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in /Users/abc/pear/share/pear/Net/SMTP.php on line 265

Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in /Users/abc/pear/share/pear/Net/SMTP.php on line 521

Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in /Users/abc/pear/share/pear/Mail/smtp.php on line 376

Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in /Users/abc/pear/share/pear/Net/SMTP.php on line 628

Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in /Users/abc/pear/share/pear/Net/SMTP.php on line 809

Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in /Users/abc/pear/share/pear/Net/SMTP.php on line 265

Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in /Users/abc/pear/share/pear/Net/SMTP.php on line 813

Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in /Users/abc/pear/share/pear/Net/SMTP.php on line 821

Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in /Users/abc/pear/share/pear/Net/SMTP.php on line 265

Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in /Users/abc/pear/share/pear/Net/SMTP.php on line 825

Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in /Users/abc/pear/share/pear/Net/SMTP.php on line 829

Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in /Users/abc/pear/share/pear/Net/SMTP.php on line 265

Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in /Users/abc/pear/share/pear/Net/SMTP.php on line 834

Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in /Users/abc/pear/share/pear/Net/SMTP.php on line 656

Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in /Users/abc/pear/share/pear/Mail/smtp.php on line 249

Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in /Users/abc/pear/share/pear/Mail/smtp.php on line 285

Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in /Users/abc/pear/share/pear/Net/SMTP.php on line 952

Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in /Users/abc/pear/share/pear/Net/SMTP.php on line 265

Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in /Users/abc/pear/share/pear/Net/SMTP.php on line 955

Strict Standards: Non-static method Mail_RFC822::parseAddressList() should not be called statically, assuming $this from incompatible context in /Users/abc/pear/share/pear/Mail.php on line 253

Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in /Users/abc/pear/share/pear/Net/SMTP.php on line 982

Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in /Users/abc/pear/share/pear/Net/SMTP.php on line 265

Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in /Users/abc/pear/share/pear/Net/SMTP.php on line 985

Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in /Users/abc/pear/share/pear/Net/SMTP.php on line 1063

Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in /Users/abc/pear/share/pear/Net/SMTP.php on line 265

Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in /Users/abc/pear/share/pear/Net/SMTP.php on line 1066

Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in /Users/abc/pear/share/pear/Net/SMTP.php on line 1126

Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in /Users/abc/pear/share/pear/Net/SMTP.php on line 265

Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in /Users/abc/pear/share/pear/Net/SMTP.php on line 1136

Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in /Users/abc/pear/share/pear/Net/SMTP.php on line 1141

Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in /Users/abc/pear/share/pear/Net/SMTP.php on line 491

Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in /Users/abc/pear/share/pear/Net/SMTP.php on line 265

Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in /Users/abc/pear/share/pear/Net/SMTP.php on line 494

Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in /Users/abc/pear/share/pear/Net/SMTP.php on line 497

Strict Standards: Non-static method PEAR::isError() should not be called statically in /Applications/MAMP/htdocs/p/testEmail.php on line 27

Message successfully sent!

in php.ini file, I also change error reporting level to

"error_reporting = E_ALL ^ E_STRICT"

Could anyone help me to solve this problem?

答: If you're on a cPanel server, go into your PEAR packages and make sure that you've updated your Net Server and SMTP packages.  You should install net_socket2 and net_smtp2 packages.  This solved my problem with this issue after upgrading to PHP 5.6.</p>

Title: PHP: PEAR mail message error


问:
Importing data from excelsheet file into the mysql database C#
I have the following lines of code:

```<code>     protected void btnUpload_Click(object sender, EventArgs e)
{

        MySqlTransaction transaction;

        string ex_id = "";

        string file_name = Path.GetFileName(FileUpload1.FileName);
        string Excel_path = Server.MapPath("~/Excel/" + file_name);
    DataTable dtExceldata = new DataTable();//just added
    FileUpload1.SaveAs(Excel_path);

        OleDbConnection my_con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Excel_path + ";Extended Properties=Excel 8.0;Persist Security Info=False");
    my_con.Open();
    OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", my_con);
        da.Fill(dtExceldata);
    if (dtExceldata.Rows.Count > 0)
    {
        //foreach (DataRow row in dtExceldata.Rows)
            for (int i = 0; i <= dtExceldata.Rows.Count - 1; i++)

        {

                string ex_dir = dtExceldata.Rows[i]["website_a"].ToString();
                //string ex_dir = row["website_a"].ToString();

                string ex_email = dtExceldata.Rows[i]["email_id"].ToString();
                // string ex_email = row["email_id"].ToString();

                string ex_email1 = dtExceldata.Rows[i]["email_id2"].ToString();
                //string ex_email1 = row["email_id2"].ToString();

                string ex_email2 = dtExceldata.Rows[i]["email_id3"].ToString();
                //string ex_email2 = row["email_id3"].ToString();

                string ex_company = dtExceldata.Rows[i]["company"].ToString();
                //string ex_company = row["company"].ToString();

                string ex_contact = dtExceldata.Rows[i]["contact_name"].ToString();
                //string ex_contact = row["contact_name"].ToString();

                string ex_proposal = dtExceldata.Rows[i]["proposal_status"].ToString();
                // string ex_proposal = row["proposal_status"].ToString();

                string ex_reason = dtExceldata.Rows[i]["reason"].ToString();
                //string ex_reason = row["reason"].ToString();

        int chk = 0;
            int type = 0;
            int dup = 0;
            int dir = 0;

            if (ddlwebsites.SelectedIndex != 0)
            {
                dir = Convert.ToInt32(ddlwebsites.SelectedValue);
                if (dir == 8)
                {
                    type = 1;
                }

            }

            foreach (ListItem lstAssign in ddlevents.Items)
            {
                if (lstAssign.Selected == true)
                {
                    chk = 1;
                }
            }

            if (type == 1 && chk == 0)
            {
                evyerror.Text = "Please Select the Event!!";
                return;

            }

            else
            {
                string querycomp = "", compID = "";
                querycomp = "Select * from barter_company where website like '%' '" + ex_dir + "' '%'";
                string connStr = ConfigurationManager.ConnectionStrings["BarterConnectionString"].ToString();
                connect = new MySqlConnection(connStr);
                connect.Open();
                transaction = connect.BeginTransaction();
                try
                {
                    ClassDtBaseConnect clsDtResult = new ClassDtBaseConnect();
                    DataTable dt = clsDtResult.GetDataTable(querycomp);
                    if (dt.Rows.Count > 0)
                    {
                        compID = dt.Rows[0]["comp_id"].ToString();
                        ViewState["comp_id"] = compID;
                        if (type == 1)
                        {
                            dup = checkforDuplicates(Convert.ToInt32(compID));
                            if (dup == 1)
                            {
                                //Confirm_MP.Show();
                                // ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "confirmation();", true);
                            }

                        }
                        //return;
                    }
                    else
                    {

                        string queryStr = "insert into barter_company (comp_name,website) values(?comp,?website)";
                        MySqlCommand cmd = new MySqlCommand(queryStr, connect, transaction);
                        cmd.Parameters.AddWithValue("?comp", ex_company);
                        cmd.Parameters.AddWithValue("?website", ex_dir);
                        cmd.ExecuteNonQuery();
                        cmd.CommandText = "Select LAST_INSERT_ID()";
                        compID = cmd.ExecuteScalar().ToString();
                        transaction.Commit();
                        connect.Close();

                    }
                }
                catch
                {
                    transaction.Rollback();
                }

                if (dup == 0)
                {
                    // create a connection string with your sql database
                    string connStr1 = ConfigurationManager.ConnectionStrings["BarterConnectionString"].ToString();
                    connect = new MySqlConnection(connStr1);
                    connect.Open();
                    DateTime date = new DateTime();
                    date = DateTime.ParseExact(txtsentdate.Text, "MM/dd/yyyy", null);
                    string SentDateString = date.ToString("yyyy/MM/dd");
                    //DateTime date = new DateTime();
                    //if (!string.IsNullOrEmpty(ex_date))
                    // {
                    //DateTime date = new DateTime();//added by chetan
                    //ex_date = ex_date.Split(' ')[0];//added by chetan
                    //date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", null);//added by chetan
                    //string SentDateString = date.ToString("yyyy/MM/dd");//added by chetan
                    //DateTime SentDate = Convert.ToDateTime(SentDateString).Date;//added by chetan
                    //// DateTime date = DateTime.Parse(ex_date);//added by chetan

                    // }
                    //date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture);//added by chetan
                    //date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", null);
                    // string SentDateString = date.ToString("yyyy/MM/dd");
                    transaction = connect.BeginTransaction();
                    try
                    {

                        string ex_uid = Session["session_barterUser_id"].ToString();

                        MySqlCommand cmd = new MySqlCommand("insert into barter_proposals(user_id, sent_date, website_a, email_id, email_id2, email_id3, company, contact_name, proposal_status, reason,type) values(?uid,?sentdate,?dir,?email,?email2,?email3,?comp,?cont_name,?pro_status,?reason,?type)", connect);

                        cmd.Parameters.AddWithValue("?uid", ex_uid);
                        cmd.Parameters.AddWithValue("?comp", compID);

                        cmd.Parameters.AddWithValue("?sentdate", SentDateString);
                        // command.Parameters.AddWithValue("?event", eventname);
                        cmd.Parameters.AddWithValue("?dir", dir);
                        // command.Parameters.AddWithValue("?bar_type", ddlbartertype.SelectedValue);
                        // command.Parameters.AddWithValue("?website_b", txtwebsite.Text);
                        //cmd.Parameters.AddWithValue("?comp", ex_company);
                        cmd.Parameters.AddWithValue("?cont_name", ex_contact);
                        cmd.Parameters.AddWithValue("?email", ex_email);
                        cmd.Parameters.AddWithValue("?email2", ex_email1);
                        cmd.Parameters.AddWithValue("?email3", ex_email2);
                        cmd.Parameters.AddWithValue("?pro_status", ex_proposal);
                        cmd.Parameters.AddWithValue("?reason", ex_reason);
                        cmd.Parameters.AddWithValue("?type", type);
                        // command.Parameters.AddWithValue("?type", type);

                        cmd.ExecuteNonQuery();
                        if (type == 1)
                        {

                            cmd.CommandText = "Select LAST_INSERT_ID()";
                            Int64 CurrentProId = Convert.ToInt64(cmd.ExecuteScalar());
                            int eventAssignID;
                            string QueryInqEventAssign = "insert into barter_propeventassign(prop_id,event_id) values(?pro_id,?event_id)";

                            foreach (ListItem lstAssign in ddlevents.Items)
                            {
                                if (lstAssign.Selected == true)
                                {
                                    cmd = new MySqlCommand(QueryInqEventAssign, connect, transaction);
                                    cmd.Parameters.AddWithValue("?pro_id", CurrentProId);
                                    eventAssignID = Convert.ToInt32(lstAssign.Value);
                                    cmd.Parameters.AddWithValue("?event_id", eventAssignID);
                                    cmd.ExecuteNonQuery();

                                }
                            }

                        }//end of if
                        transaction.Commit();
                        connect.Close();
                        Response.Write("<script type=\"text/javascript\">alert('Proposal Added Successfully!!!');</script>");
                    }//end of try
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        Response.Write("<script>alert('There is an Error Ocurred:" + Server.HtmlEncode(ex.Message) + "')</script>");
                    }
                    finally
                    {
                        connect.Close();

                    }

                }//ifdupzero
            }//else
        }//for//foreach
      }//while //if

   // dr.Close();//commented by chetan

    my_con.Close();
    if (System.IO.File.Exists(Excel_path))
    {
        System.IO.File.Delete(Excel_path);
    }

}
</code>```

suppose there are 2 entries in the excelsheet file.When trying to import,it is inserting those 2 rows entries into the database table.but the problem is that, the reader does not stop its execution.After reading 2 rows entry,it is reading 3rd row which is blank.i have used dr.close and it keeps on reading the rows entries which is blank.

答:
see this excel file

and the datatable in c#

this loop will repeat for only number of row in datatable then also i practically tried this and it only loop for number of row (e.g two times) but i found a bug that if you will enter two row then five blank row then some data it will give you blank value in data table check your excel file there may some blank value as shown in attechment
then also you can skip blank value by checking null value in row like this

```<code>for (int i = 0; i <= dtExceldata.Rows.Count - 1; i++)
            {
                if (!String.IsNullOrEmpty(Convert.ToString(dtExceldata.Rows[i]["fieldvalues"])))
                {
                    //assign value to variable
                    //like below
                    //string ex_uid = dtExceldata.Rows[i]["columnName"];
                    //then insert operation here
                }
            }
</code>```

Body:
I have the following lines of code:

     protected void btnUpload_Click(object sender, EventArgs e)
{

        MySqlTransaction transaction;

        string ex_id = "";

        string file_name = Path.GetFileName(FileUpload1.FileName);
        string Excel_path = Server.MapPath("~/Excel/" + file_name);
    DataTable dtExceldata = new DataTable();//just added
    FileUpload1.SaveAs(Excel_path);

        OleDbConnection my_con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Excel_path + ";Extended Properties=Excel 8.0;Persist Security Info=False");
    my_con.Open();
    OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", my_con);
        da.Fill(dtExceldata);
    if (dtExceldata.Rows.Count > 0)
    {
        //foreach (DataRow row in dtExceldata.Rows)
            for (int i = 0; i <= dtExceldata.Rows.Count - 1; i++)

        {

                string ex_dir = dtExceldata.Rows[i]["website_a"].ToString();
                //string ex_dir = row["website_a"].ToString();

                string ex_email = dtExceldata.Rows[i]["email_id"].ToString();
                // string ex_email = row["email_id"].ToString();

                string ex_email1 = dtExceldata.Rows[i]["email_id2"].ToString();
                //string ex_email1 = row["email_id2"].ToString();

                string ex_email2 = dtExceldata.Rows[i]["email_id3"].ToString();
                //string ex_email2 = row["email_id3"].ToString();

                string ex_company = dtExceldata.Rows[i]["company"].ToString();
                //string ex_company = row["company"].ToString();

                string ex_contact = dtExceldata.Rows[i]["contact_name"].ToString();
                //string ex_contact = row["contact_name"].ToString();

                string ex_proposal = dtExceldata.Rows[i]["proposal_status"].ToString();
                // string ex_proposal = row["proposal_status"].ToString();

                string ex_reason = dtExceldata.Rows[i]["reason"].ToString();
                //string ex_reason = row["reason"].ToString();

        int chk = 0;
            int type = 0;
            int dup = 0;
            int dir = 0;

            if (ddlwebsites.SelectedIndex != 0)
            {
                dir = Convert.ToInt32(ddlwebsites.SelectedValue);
                if (dir == 8)
                {
                    type = 1;
                }

            }

            foreach (ListItem lstAssign in ddlevents.Items)
            {
                if (lstAssign.Selected == true)
                {
                    chk = 1;
                }
            }

            if (type == 1 && chk == 0)
            {
                evyerror.Text = "Please Select the Event!!";
                return;

            }

            else
            {
                string querycomp = "", compID = "";
                querycomp = "Select * from barter_company where website like '%' '" + ex_dir + "' '%'";
                string connStr = ConfigurationManager.ConnectionStrings["BarterConnectionString"].ToString();
                connect = new MySqlConnection(connStr);
                connect.Open();
                transaction = connect.BeginTransaction();
                try
                {
                    ClassDtBaseConnect clsDtResult = new ClassDtBaseConnect();
                    DataTable dt = clsDtResult.GetDataTable(querycomp);
                    if (dt.Rows.Count > 0)
                    {
                        compID = dt.Rows[0]["comp_id"].ToString();
                        ViewState["comp_id"] = compID;
                        if (type == 1)
                        {
                            dup = checkforDuplicates(Convert.ToInt32(compID));
                            if (dup == 1)
                            {
                                //Confirm_MP.Show();
                                // ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "confirmation();", true);
                            }

                        }
                        //return;
                    }
                    else
                    {

                        string queryStr = "insert into barter_company (comp_name,website) values(?comp,?website)";
                        MySqlCommand cmd = new MySqlCommand(queryStr, connect, transaction);
                        cmd.Parameters.AddWithValue("?comp", ex_company);
                        cmd.Parameters.AddWithValue("?website", ex_dir);
                        cmd.ExecuteNonQuery();
                        cmd.CommandText = "Select LAST_INSERT_ID()";
                        compID = cmd.ExecuteScalar().ToString();
                        transaction.Commit();
                        connect.Close();

                    }
                }
                catch
                {
                    transaction.Rollback();
                }

                if (dup == 0)
                {
                    // create a connection string with your sql database
                    string connStr1 = ConfigurationManager.ConnectionStrings["BarterConnectionString"].ToString();
                    connect = new MySqlConnection(connStr1);
                    connect.Open();
                    DateTime date = new DateTime();
                    date = DateTime.ParseExact(txtsentdate.Text, "MM/dd/yyyy", null);
                    string SentDateString = date.ToString("yyyy/MM/dd");
                    //DateTime date = new DateTime();
                    //if (!string.IsNullOrEmpty(ex_date))
                    // {
                    //DateTime date = new DateTime();//added by chetan
                    //ex_date = ex_date.Split(' ')[0];//added by chetan
                    //date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", null);//added by chetan
                    //string SentDateString = date.ToString("yyyy/MM/dd");//added by chetan
                    //DateTime SentDate = Convert.ToDateTime(SentDateString).Date;//added by chetan
                    //// DateTime date = DateTime.Parse(ex_date);//added by chetan

                    // }
                    //date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture);//added by chetan
                    //date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", null);
                    // string SentDateString = date.ToString("yyyy/MM/dd");
                    transaction = connect.BeginTransaction();
                    try
                    {

                        string ex_uid = Session["session_barterUser_id"].ToString();

                        MySqlCommand cmd = new MySqlCommand("insert into barter_proposals(user_id, sent_date, website_a, email_id, email_id2, email_id3, company, contact_name, proposal_status, reason,type) values(?uid,?sentdate,?dir,?email,?email2,?email3,?comp,?cont_name,?pro_status,?reason,?type)", connect);

                        cmd.Parameters.AddWithValue("?uid", ex_uid);
                        cmd.Parameters.AddWithValue("?comp", compID);

                        cmd.Parameters.AddWithValue("?sentdate", SentDateString);
                        // command.Parameters.AddWithValue("?event", eventname);
                        cmd.Parameters.AddWithValue("?dir", dir);
                        // command.Parameters.AddWithValue("?bar_type", ddlbartertype.SelectedValue);
                        // command.Parameters.AddWithValue("?website_b", txtwebsite.Text);
                        //cmd.Parameters.AddWithValue("?comp", ex_company);
                        cmd.Parameters.AddWithValue("?cont_name", ex_contact);
                        cmd.Parameters.AddWithValue("?email", ex_email);
                        cmd.Parameters.AddWithValue("?email2", ex_email1);
                        cmd.Parameters.AddWithValue("?email3", ex_email2);
                        cmd.Parameters.AddWithValue("?pro_status", ex_proposal);
                        cmd.Parameters.AddWithValue("?reason", ex_reason);
                        cmd.Parameters.AddWithValue("?type", type);
                        // command.Parameters.AddWithValue("?type", type);

                        cmd.ExecuteNonQuery();
                        if (type == 1)
                        {

                            cmd.CommandText = "Select LAST_INSERT_ID()";
                            Int64 CurrentProId = Convert.ToInt64(cmd.ExecuteScalar());
                            int eventAssignID;
                            string QueryInqEventAssign = "insert into barter_propeventassign(prop_id,event_id) values(?pro_id,?event_id)";

                            foreach (ListItem lstAssign in ddlevents.Items)
                            {
                                if (lstAssign.Selected == true)
                                {
                                    cmd = new MySqlCommand(QueryInqEventAssign, connect, transaction);
                                    cmd.Parameters.AddWithValue("?pro_id", CurrentProId);
                                    eventAssignID = Convert.ToInt32(lstAssign.Value);
                                    cmd.Parameters.AddWithValue("?event_id", eventAssignID);
                                    cmd.ExecuteNonQuery();

                                }
                            }

                        }//end of if
                        transaction.Commit();
                        connect.Close();
                        Response.Write("");
                    }//end of try
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        Response.Write("");
                    }
                    finally
                    {
                        connect.Close();

                    }

                }//ifdupzero
            }//else
        }//for//foreach
      }//while //if

   // dr.Close();//commented by chetan

    my_con.Close();
    if (System.IO.File.Exists(Excel_path))
    {
        System.IO.File.Delete(Excel_path);
    }

}

suppose there are 2 entries in the excelsheet file.When trying to import,it is inserting those 2 rows entries into the database table.but the problem is that, the reader does not stop its execution.After reading 2 rows entry,it is reading 3rd row which is blank.i have used dr.close and it keeps on reading the rows entries which is blank.

Body:
see this excel file

and the datatable in c#

this loop will repeat for only number of row in datatable then also i practically tried this and it only loop for number of row (e.g two times) but i found a bug that if you will enter two row then five blank row then some data it will give you blank value in data table check your excel file there may some blank value as shown in attechment
then also you can skip blank value by checking null value in row like this

for (int i = 0; i <= dtExceldata.Rows.Count - 1; i++)
            {
                if (!String.IsNullOrEmpty(Convert.ToString(dtExceldata.Rows[i]["fieldvalues"])))
                {
                    //assign value to variable
                    //like below
                    //string ex_uid = dtExceldata.Rows[i]["columnName"];
                    //then insert operation here
                }
            }


问:
Apache 2.4 + FPM + Wordpress Multisite: URL Rewrite not working in admin
I just moved a Wordpress multi-site from a Apache 2.4 Prefork + mod_php to a new server with Apache 2.4 Event + php-fpm.

The site is working well on the frontend and it is a lot faster then before due to the CGI, but... the Wordpress administration panel is working just for the main site (and network administration).
The admin area for the second site is no more working, but the frontend is working great.

Examples

http://www.example.com/en/wp-admin/ => works

http://www.example.com/en/wp-admin/post-new.php => goes on error 404

I tried to debug the rewrites, but the unique log I have (also using Debug Level 8) is

```<code>[proxy_fcgi:error] [pid 13700:tid 140381047965440] [client X.X.X.X:54354] AH01071: Got error 'Primary script unknown\n', referer: http://www.example.com/en/wp-admin/
</code>```

Follwing my configurations.
Any help appreciated. Thank you.

Virtual Host

```<code><VirtualHost *:80>
ServerName www.example.com
DocumentRoot "/srv/www/example.com/public_html"
<IfModule mpm_event_module>
ProxyPassMatch ^/(.*\.php(/.*)?)$ fcgi://127.0.0.1:9000/srv/www/example.com/public_html/$1
</IfModule>
<Directory "/srv/www/example.com/public_html">
AllowOverride all
Require all granted
</Directory>
ErrorLog /srv/www/example.com/logs/error_log
TransferLog /srv/www/example.com/logs/access_log
</VirtualHost>
</code>```

.htaccess

```<code><Files "xmlrpc.php">
Order Allow,Deny
Deny from all
</Files>

# BEGIN WordPress
<IfModule mod_rewrite.c>
Options +FollowSymLinks

RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]

# uploaded ﬁles
RewriteRule ^([_0-9a-zA-Z-]+/)?ﬁles/(.+) wp-includes/ms-ﬁles.php?ﬁle=$2 [L]

# add a trailing slash to /wp-admin
RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(admin|content|includes).*) $2 [L]
RewriteRule ^([_0-9a-zA-Z-]+]/)?(.*\.php)$ $2 [L]
RewriteRule . index.php [L]
</IfModule>
# END WordPress
</code>```

答:
I add a different solution because @parpar's one, although it is working for me, it continues to throw proxy_fcgi errors:

```<code>[proxy_fcgi:error] Got error 'Primary script unknown\n'
</code>```

The solution consists in removing the ProxyPassMatch way to call PHP FPM and including a handler to manage PHP calls into the Directory environment:

```<code><Directory "/path/to/host/root">
   # rest of configuration...
   <FilesMatch \.php$>
      SetHandler "proxy:unix:/path/to/socket.sock|fcgi://localhost"
   </FilesMatch>
</Directory>
</code>```

Body:
I just moved a Wordpress multi-site from a Apache 2.4 Prefork + mod_php to a new server with Apache 2.4 Event + php-fpm.

The site is working well on the frontend and it is a lot faster then before due to the CGI, but... the Wordpress administration panel is working just for the main site (and network administration).
The admin area for the second site is no more working, but the frontend is working great.

Examples

http://www.example.com/en/wp-admin/ => works

http://www.example.com/en/wp-admin/post-new.php => goes on error 404

I tried to debug the rewrites, but the unique log I have (also using Debug Level 8) is

[proxy_fcgi:error] [pid 13700:tid 140381047965440] [client X.X.X.X:54354] AH01071: Got error 'Primary script unknown\n', referer: http://www.example.com/en/wp-admin/

Follwing my configurations.
Any help appreciated. Thank you.

Virtual Host

<VirtualHost *:80>
ServerName www.example.com
DocumentRoot "/srv/www/example.com/public_html"
<IfModule mpm_event_module>
ProxyPassMatch ^/(.*\.php(/.*)?)$ fcgi://127.0.0.1:9000/srv/www/example.com/public_html/$1
</IfModule>
<Directory "/srv/www/example.com/public_html">
AllowOverride all
Require all granted
</Directory>
ErrorLog /srv/www/example.com/logs/error_log
TransferLog /srv/www/example.com/logs/access_log
</VirtualHost>

.htaccess

<Files "xmlrpc.php">
Order Allow,Deny
Deny from all
</Files>

# BEGIN WordPress
<IfModule mod_rewrite.c>
Options +FollowSymLinks

RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]

# uploaded ﬁles
RewriteRule ^([_0-9a-zA-Z-]+/)?ﬁles/(.+) wp-includes/ms-ﬁles.php?ﬁle=$2 [L]

# add a trailing slash to /wp-admin
RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(admin|content|includes).*) $2 [L]
RewriteRule ^([_0-9a-zA-Z-]+]/)?(.*\.php)$ $2 [L]
RewriteRule . index.php [L]
</IfModule>
# END WordPress

Body:
I add a different solution because @parpar's one, although it is working for me, it continues to throw proxy_fcgi errors:

[proxy_fcgi:error] Got error 'Primary script unknown\n'

The solution consists in removing the ProxyPassMatch way to call PHP FPM and including a handler to manage PHP calls into the Directory environment:

<Directory "/path/to/host/root">
   # rest of configuration...
   <FilesMatch \.php$>
      SetHandler "proxy:unix:/path/to/socket.sock|fcgi://localhost"
   </FilesMatch>
</Directory>

ContentLicense: CC BY-SA 4.0


问:
Set Basemap meridians or parallels labels within plot or change color of text
I am making a map with Basemap in python and I'd like for the meridians/parallels to be either inside the plot or for the text (i.e. 0˚N) to be white. I want to do this so that I can set the figure against a black background but still read the axes.

This is what I have:

```<code># plot lines of longitudes
m.drawparallels(np.arange(-90.,120.,1),labels=[1,1,1,1])

# plot latitudes
m.drawmeridians(np.arange(-180.,180,1),labels=[1,0,0,1])
</code>```

and in case it helps here's the basemap instance and packages used:

```<code>m = Basemap(resolution=None, # c, l, i, h, f or None
        projection='merc',
        llcrnrlon=33.795774, llcrnrlat=-6.182035,
        urcrnrlon=34.6000037, urcrnrlat=6.236179,epsg=5520)

import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
</code>```

But it sets the labels outside the map and they're black.

答:
To change the ticks or the text colour, you need to use the additional parameters to drawmeridians/drawparallels. color changes the tick colour, textcolor changes the text colour. You can change more properties of the text by passing in additional text kwargs (see here). I have also grabbed the figure object and changed the background colour to show it working when black. Note the additional args to savefig if you want to save the figure with a different background colour.

```<code>import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap

m = Basemap(resolution='h', # c, l, i, h, f or None
        projection='merc',
        llcrnrlon=33.795774, llcrnrlat=-6.182035,
        urcrnrlon=34.6000037, urcrnrlat=6.236179,epsg=5520)

m.drawcoastlines()

# plot lines of longitudes
m.drawparallels(np.arange(-90.,120.,1),labels=[1,1,1,1], color='white', textcolor='white')

# plot latitudes
m.drawmeridians(np.arange(-180.,180,1),labels=[1,0,0,1], color='white', textcolor='white')

fig = plt.gcf()
fig.set_facecolor('black')
fig.savefig("white ticks.png", facecolor=fig.get_facecolor(), edgecolor='none')

plt.show()
</code>```

Body:
I am making a map with Basemap in python and I'd like for the meridians/parallels to be either inside the plot or for the text (i.e. 0˚N) to be white. I want to do this so that I can set the figure against a black background but still read the axes.

This is what I have:

# plot lines of longitudes
m.drawparallels(np.arange(-90.,120.,1),labels=[1,1,1,1])

# plot latitudes
m.drawmeridians(np.arange(-180.,180,1),labels=[1,0,0,1])

and in case it helps here's the basemap instance and packages used:

m = Basemap(resolution=None, # c, l, i, h, f or None
        projection='merc',
        llcrnrlon=33.795774, llcrnrlat=-6.182035,
        urcrnrlon=34.6000037, urcrnrlat=6.236179,epsg=5520)

import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap

But it sets the labels outside the map and they're black.

Body:
To change the ticks or the text colour, you need to use the additional parameters to drawmeridians/drawparallels. color changes the tick colour, textcolor changes the text colour. You can change more properties of the text by passing in additional text kwargs (see here). I have also grabbed the figure object and changed the background colour to show it working when black. Note the additional args to savefig if you want to save the figure with a different background colour.

import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap

m = Basemap(resolution='h', # c, l, i, h, f or None
        projection='merc',
        llcrnrlon=33.795774, llcrnrlat=-6.182035,
        urcrnrlon=34.6000037, urcrnrlat=6.236179,epsg=5520)

m.drawcoastlines()

# plot lines of longitudes
m.drawparallels(np.arange(-90.,120.,1),labels=[1,1,1,1], color='white', textcolor='white')

# plot latitudes
m.drawmeridians(np.arange(-180.,180,1),labels=[1,0,0,1], color='white', textcolor='white')

fig = plt.gcf()
fig.set_facecolor('black')
fig.savefig("white ticks.png", facecolor=fig.get_facecolor(), edgecolor='none')

plt.show()


问:
Postgresql does not update last updated row by trigger
I created a trigger. When I update a row the trigger before doesn't work. Later, when I update a row second time the trigger is working. Why doesn't work before? </p>

```<code>CREATE TRIGGER trg_update_em_z_module_mod_codes
  before UPDATE
ON emlakmuayene.em_z_module
FOR EACH ROW
  EXECUTE PROCEDURE emlakmuayene.update_em_z_module_mod_codes();

CREATE OR REPLACE FUNCTION emlakmuayene.update_em_z_module_mod_codes()
  RETURNS trigger AS
$BODY$
    BEGIN
        if (TG_OP = 'UPDATE') then
        if new.mod_codes_ids is not null  then
        new.mod_codes=
        (
        SELECT translate(array_Agg(pages)::Text,'{}','') as mod_codes
        FROM emlakmuayene.em_z_module  t1
        join emlakmuayene.em_z_order_pages_view  t2
        on t2.id_seq_x = any ( ('{'||t1.mod_codes_ids||'}')::bigint[]) where t1.id_Seq_X=new.id_seq_x  group by t1.id_Seq_X );
        end if ;
        end if;
    RETURN new;
    END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
</code>```

答:
After added my trigger IF pg_trigger_depth() <> 1 THEN RETURN NEW;
and change my
            update sql update  emlakmuayene.em_z_module t1
            set  mod_codes = t2.mod_codes  ,reg=1
            from    (
            SELECT t1.id_Seq_x ,translate(array_Agg(pages)::Text,'{}','') as mod_codes
            FROM emlakmuayene.em_z_module  t1
            join emlakmuayene.em_z_order_pages_view  t2
            on t2.id_seq_x = any ( ('{'||t1.mod_codes_ids||'}')::bigint[])
            where t1.id_seq_x=new.id_seq_x
            group by t1.id_Seq_X
                ) t2
            where  t1.id_seq_x=T2.id_seq_x; is working

then my trigger
CREATE OR REPLACE FUNCTION emlakmuayene.update_em_z_module_mod_codes()
  RETURNS trigger AS
$BODY$
        BEGIN

            IF pg_trigger_depth() <> 1 THEN
                RETURN NEW;
                END IF;
            update  emlakmuayene.em_z_module t1 set  mod_codes = t2.mod_codes  ,reg=1
            from    (
            SELECT t1.id_Seq_x ,translate(array_Agg(pages)::Text,'{}','') as mod_codes
            FROM emlakmuayene.em_z_module  t1
            join emlakmuayene.em_z_order_pages_view  t2
            on t2.id_seq_x = any ( ('{'||t1.mod_codes_ids||'}')::bigint[])
            where t1.id_seq_x=new.id_seq_x
            group by t1.id_Seq_X
                ) t2
            where  t1.id_seq_x=T2.id_seq_x;
            return new;
        END;

    $BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION emlakmuayene.update_em_z_module_mod_codes()
  OWNER TO tuvimer_ortak

Body:
I created a trigger. When I update a row the trigger before doesn't work. Later, when I update a row second time the trigger is working. Why doesn't work before?

CREATE TRIGGER trg_update_em_z_module_mod_codes
  before UPDATE
ON emlakmuayene.em_z_module
FOR EACH ROW
  EXECUTE PROCEDURE emlakmuayene.update_em_z_module_mod_codes();

CREATE OR REPLACE FUNCTION emlakmuayene.update_em_z_module_mod_codes()
  RETURNS trigger AS
$BODY$
    BEGIN
        if (TG_OP = 'UPDATE') then
        if new.mod_codes_ids is not null  then
        new.mod_codes=
        (
        SELECT translate(array_Agg(pages)::Text,'{}','') as mod_codes
        FROM emlakmuayene.em_z_module  t1
        join emlakmuayene.em_z_order_pages_view  t2
        on t2.id_seq_x = any ( ('{'||t1.mod_codes_ids||'}')::bigint[]) where t1.id_Seq_X=new.id_seq_x  group by t1.id_Seq_X );
        end if ;
        end if;
    RETURN new;
    END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;


问:
How to find @username for tunneling SSH to the VMs behind Azure Databricks
I can able to view Spark Cluster Master & Worker nodes hostname but I couldn't find username to log in on SSH

For Example(In terminal):
ssh username@hostname_or_Ip

答:
As per my knowledge, you cannot SSH on Azure Databricks.

Note: Azure Databricks integrated with Azure Active Directory – So, Azure Databricks users are only regular AAD users.

Azure Active Directory users can be used directly in Azure Databricks
for al user-based access control (Clusters, jobs, Notebooks etc.).

Azure Databricks has delegated user authentication to AAD enabling

single-sign on (SSO) and unified authentication.

Notebooks and their outputs, are stored in the Databricks account.

However, AAD based access control ensures that only authorized users
can access them.

For more details, refer “Azure Databricks Preview Documentation”.


问:
Is it possible to 'bin' values by date to get a total per 2 weeks in ggplot2 and R?
I have a dataframe which is a history of runs.  Some fo the variables include a date (in POSIXct) and a value for that run (here = size).  I want to produce various graphs showing a line based on the total fo the size column for a particular date range.  Ideally I'd like to use the same dataset and change from totals per week, 2 weeks, month quarter.

Here's an example dataset;

```<code>require(ggplot2)
set.seed(666)

seq(Sys.time()-(365*24*60*60), Sys.time(), by="day")

foo<-data.frame(Date=sample(seq(today-(365*24*60*60), today, by="day"),50, replace=FALSE),
        value=rnorm(50, mean=100, sd=25),
        type=sample(c("Red", "Blue", "Green"), 50, replace=TRUE))
</code>```

I can create this plot which shows individual values;

```<code>ggplot(data=foo, aes(x=Date, y=value, colour=type))+stat_summary(fun.y=sum, geom="line")
</code>```

Or I can do this to show a sum per Month;

```<code>ggplot(data=foo, aes(x=format(Date, "%m %y"), y=value, colour=type))+stat_summary(fun.y=sum, geom="line", aes(group=type))
</code>```

However it gets more complicated to do sums per quarter / 2 weeks etc.  Ideally I'd like something like the stat_bin and stat_summary combined so I could specify a binwidth (or have ggplot make a best guess based on the range)

Am I missing something obvious, or is this just not possible ?

答:
It's pretty easy with plyr and lubridate to do all the calculations yourself:</p>

```<code>library(plyr)
library(lubridate)

foo <- data.frame(
  date = sample(today() + days(1:365), 50, replace = FALSE),
  value = rnorm(50, mean = 100, sd = 25),
  type = sample(c("Red", "Blue", "Green"), 50, replace = TRUE))

foo$date2 <- floor_date(foo$date2, "week")
foosum <- ddply(foo, c("date2", "type"), summarise,
  n = length(value),
  mean = mean(value))

ggplot(foosum, aes(date2, mean, colour = type)) +
  geom_point(aes(size = n)) +
  geom_line()
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a dataframe which is a history of runs.  Some fo the variables include a date (in POSIXct) and a value for that run (here = size).  I want to produce various graphs showing a line based on the total fo the size column for a particular date range.  Ideally I'd like to use the same dataset and change from totals per week, 2 weeks, month quarter.

Here's an example dataset;

require(ggplot2)
set.seed(666)

seq(Sys.time()-(365*24*60*60), Sys.time(), by="day")

foo<-data.frame(Date=sample(seq(today-(365*24*60*60), today, by="day"),50, replace=FALSE),
        value=rnorm(50, mean=100, sd=25),
        type=sample(c("Red", "Blue", "Green"), 50, replace=TRUE))

I can create this plot which shows individual values;

ggplot(data=foo, aes(x=Date, y=value, colour=type))+stat_summary(fun.y=sum, geom="line")

Or I can do this to show a sum per Month;

ggplot(data=foo, aes(x=format(Date, "%m %y"), y=value, colour=type))+stat_summary(fun.y=sum, geom="line", aes(group=type))

However it gets more complicated to do sums per quarter / 2 weeks etc.  Ideally I'd like something like the stat_bin and stat_summary combined so I could specify a binwidth (or have ggplot make a best guess based on the range)

Am I missing something obvious, or is this just not possible ?

Body:
It's pretty easy with plyr and lubridate to do all the calculations yourself:

library(plyr)
library(lubridate)

foo <- data.frame(
  date = sample(today() + days(1:365), 50, replace = FALSE),
  value = rnorm(50, mean = 100, sd = 25),
  type = sample(c("Red", "Blue", "Green"), 50, replace = TRUE))

foo$date2 <- floor_date(foo$date2, "week")
foosum <- ddply(foo, c("date2", "type"), summarise,
  n = length(value),
  mean = mean(value))

ggplot(foosum, aes(date2, mean, colour = type)) +
  geom_point(aes(size = n)) +
  geom_line()


问:
Zip Code Demographics in R
I could get at my goals "the long way" but am hoping to stay completely within R.  I am looking to append Census demographic data by zip code to records in my database.  I know that R has a few Census-based packages, but, unless I am missing something, these data do not seem to exist at the zip code level, nor is it intuitive to merge onto an existing data frame.

In short, is it possible to do this within R, or is my best approach to grab the data elsewhere and read it into R?

Any help will be greatly appreciated!

Title: Zip Code Demographics in R

Body:
I just wrote a R package called totalcensus (https://github.com/GL-Li/totalcensus), with which you can extract any data in decennial census and ACS survey easily.

For this old question if you still care, you can get total population (by default) and population of other races from national data of decennial census 2010 or 2015 ACS 5-year survey.

From 2015 ACS 5-year survey. Download national data with download_census("acs5year", 2015, "US") and then:

zip_acs5 <- read_acs5year(
    year = 2015,
    states = "US",
    geo_headers = "ZCTA5",
    table_contents = c(
        "white = B02001_002",
        "black = B02001_003",
        "asian = B02001_005"
    ),
    summary_level = "860"
)

#               GEOID        lon      lat ZCTA5 state population white black asian GEOCOMP SUMLEV        NAME
#     1: 86000US01001  -72.62827 42.06233 01001    NA      17438 16014   230   639     all    860 ZCTA5 01001
#     2: 86000US01002  -72.45851 42.36398 01002    NA      29780 23333  1399  3853     all    860 ZCTA5 01002
#     3: 86000US01003  -72.52411 42.38994 01003    NA      11241  8967   699  1266     all    860 ZCTA5 01003
#     4: 86000US01005  -72.10660 42.41885 01005    NA       5201  5062    40    81     all    860 ZCTA5 01005
#     5: 86000US01007  -72.40047 42.27901 01007    NA      14838 14086   104   330     all    860 ZCTA5 01007
# ---
# 32985: 86000US99923 -130.04103 56.00232 99923    NA         13    13     0     0     all    860 ZCTA5 99923
# 32986: 86000US99925 -132.94593 55.55020 99925    NA        826   368     7     0     all    860 ZCTA5 99925
# 32987: 86000US99926 -131.47074 55.13807 99926    NA       1711   141     0     2     all    860 ZCTA5 99926
# 32988: 86000US99927 -133.45792 56.23906 99927    NA        123   114     0     0     all    860 ZCTA5 99927
# 32989: 86000US99929 -131.60683 56.41383 99929    NA       2365  1643     5    60     all    860 ZCTA5 99929

From Census 2010. Download national data with download_census("decennial", 2010, "US") and then:

zip_2010 <- read_decennial(
    year = 2010,
    states = "US",
    table_contents = c(
        "white = P0030002",
        "black = P0030003",
        "asian = P0030005"
    ),
    geo_headers = "ZCTA5",
    summary_level = "860"
)

#               lon      lat ZCTA5 state population white black asian GEOCOMP SUMLEV
#     1:  -66.74996 18.18056 00601    NA      18570 17285   572     5     all    860
#     2:  -67.17613 18.36227 00602    NA      41520 35980  2210    22     all    860
#     3:  -67.11989 18.45518 00603    NA      54689 45348  4141    85     all    860
#     4:  -66.93291 18.15835 00606    NA       6615  5883   314     3     all    860
#     5:  -67.12587 18.29096 00610    NA      29016 23796  2083    37     all    860
# ---
# 33116: -130.04103 56.00232 99923    NA         87    79     0     0     all    860
# 33117: -132.94593 55.55020 99925    NA        819   350     2     4     all    860
# 33118: -131.47074 55.13807 99926    NA       1460   145     6     2     all    860
# 33119: -133.45792 56.23906 99927    NA         94    74     0     0     all    860
# 33120: -131.60683 56.41383 99929    NA       2338  1691     3    33     all    860


问:
How to import a text file on AWS S3 into pandas without writing to disk
I have a text file saved on S3 which is a tab delimited table. I want to load it into pandas but cannot save it first because I am running on a heroku server. Here is what I have so far.

```<code>import io
import boto3
import os
import pandas as pd

os.environ["AWS_ACCESS_KEY_ID"] = "xxxxxxxx"
os.environ["AWS_SECRET_ACCESS_KEY"] = "xxxxxxxx"

s3_client = boto3.client('s3')
response = s3_client.get_object(Bucket="my_bucket",Key="filename.txt")
file = response["Body"]

pd.read_csv(file, header=14, delimiter="\t", low_memory=False)
</code>```

the error is

```<code>OSError: Expected file path name or file-like object, got <class 'bytes'> type
</code>```

How do I convert the response body into a format pandas will accept?

```<code>pd.read_csv(io.StringIO(file), header=14, delimiter="\t", low_memory=False)

returns

TypeError: initial_value must be str or None, not StreamingBody

pd.read_csv(io.BytesIO(file), header=14, delimiter="\t", low_memory=False)

returns

TypeError: 'StreamingBody' does not support the buffer interface
</code>```

UPDATE - Using the following worked

```<code>file = response["Body"].read()
</code>```

and

```<code>pd.read_csv(io.BytesIO(file), header=14, delimiter="\t", low_memory=False)
</code>```

答:
With s3fs it can be done as follow:</p>

```<code>import s3fs
import pandas as pd
fs = s3fs.S3FileSystem(anon=False)

# CSV
with fs.open('mybucket/path/to/object/foo.pkl') as f:
    df = pd.read_csv(f)

# Pickle
with fs.open('mybucket/path/to/object/foo.pkl') as f:
    df = pd.read_pickle(f)
</code>```

Body:
I have a text file saved on S3 which is a tab delimited table. I want to load it into pandas but cannot save it first because I am running on a heroku server. Here is what I have so far.

import io
import boto3
import os
import pandas as pd

os.environ["AWS_ACCESS_KEY_ID"] = "xxxxxxxx"
os.environ["AWS_SECRET_ACCESS_KEY"] = "xxxxxxxx"

s3_client = boto3.client('s3')
response = s3_client.get_object(Bucket="my_bucket",Key="filename.txt")
file = response["Body"]

pd.read_csv(file, header=14, delimiter="\t", low_memory=False)

the error is

OSError: Expected file path name or file-like object, got <class 'bytes'> type

How do I convert the response body into a format pandas will accept?

pd.read_csv(io.StringIO(file), header=14, delimiter="\t", low_memory=False)

returns

TypeError: initial_value must be str or None, not StreamingBody

pd.read_csv(io.BytesIO(file), header=14, delimiter="\t", low_memory=False)

returns

TypeError: 'StreamingBody' does not support the buffer interface

UPDATE - Using the following worked

file = response["Body"].read()

and

pd.read_csv(io.BytesIO(file), header=14, delimiter="\t", low_memory=False)

Body:
With s3fs it can be done as follow:

import s3fs
import pandas as pd
fs = s3fs.S3FileSystem(anon=False)

# CSV
with fs.open('mybucket/path/to/object/foo.pkl') as f:
    df = pd.read_csv(f)

# Pickle
with fs.open('mybucket/path/to/object/foo.pkl') as f:
    df = pd.read_pickle(f)


问:
Creating a page for every product in a website
I'm designing a website for shopping.

When I click a product from the products page, I want to get a page only containing information about that one product but do I have to create a new page separately for every product on the products page?

I only know some javascript and jquery. I don't know PHP.

答: No,you don't have create page for each product.You just need to create a template where in you will be grabing the corresponding product information.Based on the product and its belonging category ,you have to generate a route with id.The data should be JSON format for better accessibility.</p>


问:
RDLC External Image works in ASP.NET but not in WPF
I have lots of RDLC reports in an ASP.NET app, many generated dynamically (manual manipulation of .rdlc XML file).

Many have external images (EnableExternalImages=true, full https://... url of image passed to report as a parameter).

Reports and images work fine in ASP.NET app (via ReportViewer control).

I am now building a WPF app that uses the same code to generate PDF files from the .rdlc reports.

For the most part the reports work just fine in both ASP.NET and WPF. Both use LocalReport.Render("PDF") to generate a PDF file. The only exception is where external images are used - the report does not seem to be able to render external images in WPF. If I replace the external image with an embedded image it works fine. The URL is definitely correct in the WPF app (works if pasted into browser).

I have tried http and https, and "run as administrator" - same results. The actual error message is typically unhelpful and just seems to be a generic "something wrong" message ("The subreport 'Subreport1' could not be found at the specified location Custom1. Please verify that the subreport has Page 1").

Any ideas?

答:
Doh! As usual the problem was my own stupid mistake, made worse by unhelpful error messages.

LocalReport.Render("PDF", ..., out warnings) has a version that includes an output parameter for Warnings which in this case gave me a precise reason for the malfunction: EnableExternalImages was NOT set as I thought (test all your ASSumptions!) (why don't they show this message in the report instead of the useless generic message, would have saved me a lot of time!).

EnableExternalImages turned out to be set in aspx markup, and not in the RDLC generator code, thus it worked in ASP.NET but not in WPF. I now set it in the code and it works in both apps as expected.

I have read many posts about external images not working in PDF - they definitely work just fine in PDF (and Word), at least with Microsfot.ReportViewer2015.Runtime v12.0.2.2402. What often does not work however is displaying the images in IE in the online (in-browser) preview of the report - half the time they show and half the time they do not show, but they always show in the PDF.


问:
Update position of All places in react-native-sortable-listview
I am using react-native-sortable-listview in react-native for sorting same places.

```<code> constructor() {
   this.state = {
     makers: [
       { kolkata: 'Hawrah Birdge' },
      { Delhi: 'Lal Kila' },
      { Agra: 'Taj Mahal' },
      { Mumbai: 'India Gate' },
     ],
     allObj: {},
     order: []
   };
 }
 componentDidMount() {
   const newAllObj = this.getAllObjFromMaker(this.state.makers);
   const newOrder = this.getOrderFromMaker(newAllObj);
   this.setState({ allObj: newAllObj, order: newOrder });
 }
 getAllObjFromMaker(makers) {
    const allObj = makers.reduce((result, d) => {
    result[`${d.coordinate.latitude}_${d.coordinate.longitude}`] = d;
    return result;
   }, {});
  return allObj;
 }
getOrderFromMaker(allObj) {
  const order = Object.keys(allObj);
  return order;
}
 renderOneDraggableMilestone(milestone) {
  const i = this.state.makers.indexOf(milestone);
  return (
     <TouchableOpacity {...this.props.sortHandlers}>
        <Text>{i + 1}</Text>
        <Text>{milestone.address}</Text>
     </TouchableOpacity>
    );
  }
  arrangedMilestoneList(e) {
    const arr = this.state.makers;
    arr.splice(e.to, 0, arr.splice(e.from, 1)[0]);
    const newAllObj = this.getAllObjFromMaker(arr);
    const newOrder = this.getOrderFromMaker(newAllObj);
    this.setState({ makers: arr, allObj: newAllObj, order: newOrder
     });
   }
 render() {
   return (
     <SortableListView
      data={this.state.allObj}
      order={this.state.order}
      activeOpacity={0.5}
      onRowMoved={e => {
        this.arrangedMilestoneList(e);
        this.forceUpdate();
      }}
      renderRow={(row) => this.renderOneDraggableMilestone(row)}
    />
   );
 }
</code>```

I want to arrange places and also their position in this.state.makers as I am doing using i in renderOneDraggableMilestone. On renderRow only draggable place are render so only their position is updated. And renderRow is last to excute so forceUpdate is also not working.

How to rerender after executing renderRow. So all position could be updated.

答:
Ok I have find a way to re-render as follow.

```<code>   <SortableListView
  key={this.state.count}
  data={this.state.allObj}
  order={this.state.order}
  activeOpacity={0.5}
  onRowMoved={e => {
    this.setState({ count: this.state.count + 1 });
    this.props.arrangedMilestoneList(e);
    console.log('onRowMoved is called');
  }}
  onMoveEnd={() => console.log('onMoveEnd is fired')}
  renderRow={(row, s1, i) => this.renderOneDraggableMilestone(row, s1, i)}
/>
</code>```

What I am doing is I added a key attribute to SortableListView and update this key on each onRowMoved action. And because of this it causes re-render.

Body:
I am using react-native-sortable-listview in react-native for sorting same places.

 constructor() {
   this.state = {
     makers: [
       { kolkata: 'Hawrah Birdge' },
      { Delhi: 'Lal Kila' },
      { Agra: 'Taj Mahal' },
      { Mumbai: 'India Gate' },
     ],
     allObj: {},
     order: []
   };
 }
 componentDidMount() {
   const newAllObj = this.getAllObjFromMaker(this.state.makers);
   const newOrder = this.getOrderFromMaker(newAllObj);
   this.setState({ allObj: newAllObj, order: newOrder });
 }
 getAllObjFromMaker(makers) {
    const allObj = makers.reduce((result, d) => {
    result[`${d.coordinate.latitude}_${d.coordinate.longitude}`] = d;
    return result;
   }, {});
  return allObj;
 }
getOrderFromMaker(allObj) {
  const order = Object.keys(allObj);
  return order;
}
 renderOneDraggableMilestone(milestone) {
  const i = this.state.makers.indexOf(milestone);
  return (
     <TouchableOpacity {...this.props.sortHandlers}>
        <Text>{i + 1}</Text>
        <Text>{milestone.address}</Text>
     </TouchableOpacity>
    );
  }
  arrangedMilestoneList(e) {
    const arr = this.state.makers;
    arr.splice(e.to, 0, arr.splice(e.from, 1)[0]);
    const newAllObj = this.getAllObjFromMaker(arr);
    const newOrder = this.getOrderFromMaker(newAllObj);
    this.setState({ makers: arr, allObj: newAllObj, order: newOrder
     });
   }
 render() {
   return (
     <SortableListView
      data={this.state.allObj}
      order={this.state.order}
      activeOpacity={0.5}
      onRowMoved={e => {
        this.arrangedMilestoneList(e);
        this.forceUpdate();
      }}
      renderRow={(row) => this.renderOneDraggableMilestone(row)}
    />
   );
 }

I want to arrange places and also their position in this.state.makers as I am doing using i in renderOneDraggableMilestone. On renderRow only draggable place are render so only their position is updated. And renderRow is last to excute so forceUpdate is also not working.

How to rerender after executing renderRow. So all position could be updated.

Body:
Ok I have find a way to re-render as follow.

   <SortableListView
  key={this.state.count}
  data={this.state.allObj}
  order={this.state.order}
  activeOpacity={0.5}
  onRowMoved={e => {
    this.setState({ count: this.state.count + 1 });
    this.props.arrangedMilestoneList(e);
    console.log('onRowMoved is called');
  }}
  onMoveEnd={() => console.log('onMoveEnd is fired')}
  renderRow={(row, s1, i) => this.renderOneDraggableMilestone(row, s1, i)}
/>

What I am doing is I added a key attribute to SortableListView and update this key on each onRowMoved action. And because of this it causes re-render.


问:
ORA-22816 while updating Joined View with Instead of trigger
I read a lot about it but didn't found any help on that.

My Situation:
I've two database tables which belongs together. This tables I want to query with EntityFramework. Because Table B contains for EntityFramework the discriminator (for choosing the correct class for Table A) I've created a View which Joins Table A and Table B.

This join is quite simple. But: I want also to store data with that View. The issue is, that EntityFramework also wants to store the discriminator. But this isn't possible because it would update/insert into two tables.

So I've tried to create an "Instead of" trigger to just update/insert Table A (because Table B doesn't matter and will never be updated).

When I created the trigger - everything fine. If I insert something with an SQL Statement - everything is fine. But: If I'm inserting directly in the View (using Oracle SQL Developer) it throws the Exception as below:

ORA-22816 (unsupported feature with RETURNING clause).

If I do the same with EntityFramework I get the same error. Can someone help me?

Below my Code:

Table A and Table B:

```<code>CREATE Table "TableA"
(
 "ID" Number NOT NULL,
 "OTHER_VALUESA" varchar2(255),
 "TableB_ID" number not null,
 CONSTRAINT PK_TableA PRIMARY KEY (ID)
);

CREATE Table "TableB"
(
 "ID" Number NOT NULL,
 "NAME" varchar2(255),
 "DISCRIMINATOR" varchar2(255),
 CONSTRAINT PK_TableB PRIMARY KEY (ID)
);
</code>```

The Joined View:

```<code>Create or Replace View "JoinTableAandB"
(
  "ID",
  "OTHER_VALUESA",
  "TableB_ID",
  "DISCRIMINATOR"
) AS
select tableA.ID, tableA.OTHER_VALUESA, tableA.TableB_ID, tableB.DISCRIMINATOR
from TABLEA tableA
inner join TABLEB tableB on tableA.TableB_ID = tableB.ID;
</code>```

And finally the Trigger:

```<code>create or replace TRIGGER "JoinTableAandB_TRG"
INSTEAD OF INSERT ON "JoinTableAandB"
FOR EACH ROW
BEGIN
insert into TABLEA(OTHER_VALUESA, TABLEB_ID)
values (:NEW.OTHER_VALUESA, :NEW.TABLEB_ID);
END;
</code>```

I've also tried it (to verify if the insert is correct just to enter "NULL" into the trigger instead of insert. But got the same error message.

Does anybody know how to solve this? Or does anybody have a good alternative (better Idea)?

Thanks!

Note: I've also defined a sequence for TableA's ID so that it will be generated automatically.

// Edit:
I found a possible Solution for MS SQL:

https://stackoverflow.com/a/26897952/3598980

But I don't know how to translate this to Oracle... How can I return something from a trigger?

答:
Note: I've also defined a sequence for TableA's ID so that it will be generated automatically.

In EF StoreGenerated keys in Oracle are incompatible with INSTEAD OF triggers.  EF uses a RETURNING clause to output the store generated keys, which doesn't work with INSTEAD OF triggers.

Body:
I read a lot about it but didn't found any help on that.

My Situation:
I've two database tables which belongs together. This tables I want to query with EntityFramework. Because Table B contains for EntityFramework the discriminator (for choosing the correct class for Table A) I've created a View which Joins Table A and Table B.

This join is quite simple. But: I want also to store data with that View. The issue is, that EntityFramework also wants to store the discriminator. But this isn't possible because it would update/insert into two tables.

So I've tried to create an "Instead of" trigger to just update/insert Table A (because Table B doesn't matter and will never be updated).

When I created the trigger - everything fine. If I insert something with an SQL Statement - everything is fine. But: If I'm inserting directly in the View (using Oracle SQL Developer) it throws the Exception as below:

ORA-22816 (unsupported feature with RETURNING clause).

If I do the same with EntityFramework I get the same error. Can someone help me?

Below my Code:

Table A and Table B:

CREATE Table "TableA"
(
 "ID" Number NOT NULL,
 "OTHER_VALUESA" varchar2(255),
 "TableB_ID" number not null,
 CONSTRAINT PK_TableA PRIMARY KEY (ID)
);

CREATE Table "TableB"
(
 "ID" Number NOT NULL,
 "NAME" varchar2(255),
 "DISCRIMINATOR" varchar2(255),
 CONSTRAINT PK_TableB PRIMARY KEY (ID)
);

The Joined View:

Create or Replace View "JoinTableAandB"
(
  "ID",
  "OTHER_VALUESA",
  "TableB_ID",
  "DISCRIMINATOR"
) AS
select tableA.ID, tableA.OTHER_VALUESA, tableA.TableB_ID, tableB.DISCRIMINATOR
from TABLEA tableA
inner join TABLEB tableB on tableA.TableB_ID = tableB.ID;

And finally the Trigger:

create or replace TRIGGER "JoinTableAandB_TRG"
INSTEAD OF INSERT ON "JoinTableAandB"
FOR EACH ROW
BEGIN
insert into TABLEA(OTHER_VALUESA, TABLEB_ID)
values (:NEW.OTHER_VALUESA, :NEW.TABLEB_ID);
END;

I've also tried it (to verify if the insert is correct just to enter "NULL" into the trigger instead of insert. But got the same error message.

Does anybody know how to solve this? Or does anybody have a good alternative (better Idea)?

Thanks!

Note: I've also defined a sequence for TableA's ID so that it will be generated automatically.

// Edit:
I found a possible Solution for MS SQL:

https://stackoverflow.com/a/26897952/3598980

But I don't know how to translate this to Oracle... How can I return something from a trigger?


问:
GSUTIL file upload percentage on web console from a child process
I am developing a simple web app to upload stuff to google bucket. I am using child_process.exec method to fire the upload command, the command is as follows,

```<code>child = exec(command, function (error,
stdout, stderr) {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
});
</code>```

command = /Users/nachiketjoshi/google-cloud-sdk/bin/bootstrapping/gsutil.py cp -r /Users/nachiketjoshi/Desktop/shell-upload-sample gs://bucket-name

The problem I am facing is that the console output in the web app shows the entire status after the file is uploaded.

I want to see the output just like the command line utility shows while uploading that is with a status bar and percentage and everything.

Currently, with above child_process I can see something as follows on the web app console.

```<code>[2 files][ 10.0 MiB/ 30.0 MiB]  664.3 KiB/s
\
\ [2 files][ 10.5 MiB/ 30.0 MiB]  585.3 KiB/s
|
| [2 files][ 11.0 MiB/ 30.0 MiB]  525.7 KiB/s
/
/ [2 files][ 11.6 MiB/ 30.0 MiB]  476.7 KiB/s

[2 files][ 12.1 MiB/ 30.0 MiB]  439.3 KiB/s
\
|
| [2 files][ 12.8 MiB/ 30.0 MiB]  511.6 KiB/s
/
/ [2 files][ 13.9 MiB/ 30.0 MiB]  595.3 KiB/s

[2 files][ 14.7 MiB/ 30.0 MiB]  660.8 KiB/s
\
\ [2 files][ 15.2 MiB/ 30.0 MiB]  538.9 KiB/s
|
/
/ [2 files][ 15.7 MiB/ 30.0 MiB]  424.6 KiB/s

[2 files][ 16.2 MiB/ 30.0 MiB]  339.7 KiB/s
\
\ [2 files][ 16.7 MiB/ 30.0 MiB]  408.2 KiB/s
|
/
/ [2 files][ 17.2 MiB/ 30.0 MiB]  427.0 KiB/s

\
\ [2 files][ 18.0 MiB/ 30.0 MiB]  415.3 KiB/s
|
/
/ [2 files][ 18.5 MiB/ 30.0 MiB]  394.7 KiB/s

\
\ [2 files][ 19.0 MiB/ 30.0 MiB]  403.4 KiB/s
|
| [2 files][ 19.5 MiB/ 30.0 MiB]  371.9 KiB/s
/
/ [2 files][ 20.3 MiB/ 30.0 MiB]  433.6 KiB/s

Operation completed over 3 objects/30.0 MiB.
</code>```

What exactly does above output mean?

What changes should I make so that I can see the proper 'live output' on my web console?

答: I am not sure you can do what you want using gsutil (I don't think you can capture the output), however this answer (using the cloud storage API instead of gsutil) may be what you are looking for.</p>

Body:
I am developing a simple web app to upload stuff to google bucket. I am using child_process.exec method to fire the upload command, the command is as follows,

child = exec(command, function (error,
stdout, stderr) {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
});

command = /Users/nachiketjoshi/google-cloud-sdk/bin/bootstrapping/gsutil.py cp -r /Users/nachiketjoshi/Desktop/shell-upload-sample gs://bucket-name

The problem I am facing is that the console output in the web app shows the entire status after the file is uploaded.

I want to see the output just like the command line utility shows while uploading that is with a status bar and percentage and everything.

Currently, with above child_process I can see something as follows on the web app console.

[2 files][ 10.0 MiB/ 30.0 MiB]  664.3 KiB/s
\
\ [2 files][ 10.5 MiB/ 30.0 MiB]  585.3 KiB/s
|
| [2 files][ 11.0 MiB/ 30.0 MiB]  525.7 KiB/s
/
/ [2 files][ 11.6 MiB/ 30.0 MiB]  476.7 KiB/s

[2 files][ 12.1 MiB/ 30.0 MiB]  439.3 KiB/s
\
|
| [2 files][ 12.8 MiB/ 30.0 MiB]  511.6 KiB/s
/
/ [2 files][ 13.9 MiB/ 30.0 MiB]  595.3 KiB/s

[2 files][ 14.7 MiB/ 30.0 MiB]  660.8 KiB/s
\
\ [2 files][ 15.2 MiB/ 30.0 MiB]  538.9 KiB/s
|
/
/ [2 files][ 15.7 MiB/ 30.0 MiB]  424.6 KiB/s

[2 files][ 16.2 MiB/ 30.0 MiB]  339.7 KiB/s
\
\ [2 files][ 16.7 MiB/ 30.0 MiB]  408.2 KiB/s
|
/
/ [2 files][ 17.2 MiB/ 30.0 MiB]  427.0 KiB/s

\
\ [2 files][ 18.0 MiB/ 30.0 MiB]  415.3 KiB/s
|
/
/ [2 files][ 18.5 MiB/ 30.0 MiB]  394.7 KiB/s

\
\ [2 files][ 19.0 MiB/ 30.0 MiB]  403.4 KiB/s
|
| [2 files][ 19.5 MiB/ 30.0 MiB]  371.9 KiB/s
/
/ [2 files][ 20.3 MiB/ 30.0 MiB]  433.6 KiB/s

Operation completed over 3 objects/30.0 MiB.

What exactly does above output mean?

What changes should I make so that I can see the proper 'live output' on my web console?


问:
Ctrl+V does not work in IntelliJ
A while ago, Ctrl+V stopped working in Intellij IDEA. Neither the shortcut nor Edit > Paste works. It's really weird, since "Paste Simple" still works fine, so does Ctrl+C and Ctrl+X.

I've seen a lot of suggestions to solve this problem, but most of them are somehow related to the Vim Emulator for IntelliJ, which I don't use. I tried to play around with the Keymap, but could not get it to work.

I'm using Intellij 2017.2.5 on Windows 10. Maybe I screwed it up myself somehow, but I wish to fix it, because it's really painful to work without Ctrl+V.

答:
You can try alternatives:

Ctrl + Shift + V for Windows or Linux

or

You might try Ctrl+INS for copy and Shift+INS for paste and
  see if they work. They are the traditional cut and paste and have been
  around a lot longer than Ctrl+c/Ctrl+v

Title: Ctrl+V does not work in IntelliJ


问:
Are private setters in C++/CX properties a thing?
Is it possible to create/design in a way to privately set a property but only expose the ability to get the properties to the consumers?

I've tackled a multiple inheritance property by making the base class wrapper a member of the concrete classes wrapper. I'd rather not allow someone to write over the base classes instance in the set of it's own property. But I can't seem to exclude set and set the base property and I can't make the set private.

Any ideas?

Code:

```<code>ConcreteClassWrapper(); // here I want to setup base class, i.e. give it a pointer to the actual C++ model I'm working with.

property BaseClassWrapper^ BaseClass
{
    BaseClassWrapper^ get() { return baseClass; }

    // I want to avoid giving my consumers the ability to set this property.
    void set(BaseClassWrapper^ value) { baseClass= value; }
}

private:
    BaseClassWrapper^ baseClass; // Having a base class wrapper makes it easier on code writing.. i.e. I don't need to implement interfaces. I just want to use my C++ code in C# Microsoft GOD!!!
</code>```

EDIT:

I'm an idiot, I can access the private member...

答:
This is just one answer... Still want to know why private setters arent' a thing

I just have to access my private member of my ConcreteClassWrapper and set the base class there. Then I can remove the set in the BaseClassWrapper property.

Body:
Is it possible to create/design in a way to privately set a property but only expose the ability to get the properties to the consumers?

I've tackled a multiple inheritance property by making the base class wrapper a member of the concrete classes wrapper. I'd rather not allow someone to write over the base classes instance in the set of it's own property. But I can't seem to exclude set and set the base property and I can't make the set private.

Any ideas?

Code:

ConcreteClassWrapper(); // here I want to setup base class, i.e. give it a pointer to the actual C++ model I'm working with.

property BaseClassWrapper^ BaseClass
{
    BaseClassWrapper^ get() { return baseClass; }

    // I want to avoid giving my consumers the ability to set this property.
    void set(BaseClassWrapper^ value) { baseClass= value; }
}

private:
    BaseClassWrapper^ baseClass; // Having a base class wrapper makes it easier on code writing.. i.e. I don't need to implement interfaces. I just want to use my C++ code in C# Microsoft GOD!!!

EDIT:

I'm an idiot, I can access the private member...


问:
Z.EntityFramework.Plus.QueryCache.EF6 Requires QueryDeferred Library?
When trying to use the QueryCache library to do some L2 caching of a few entities, I am receiving a compiler error on .FromCache() indicating the QueryDeferred library is required. Documentation indicates QueryCache can be used as stand-alone.

```<code>using Z.EntityFramework.Plus;

namespace LookupValuesMap.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            LookupValueContext ctx = new LookupValueContext();
            var companies = ctx.Companies.FromCache().ToList();  <-- error
</code>```

Here is the error:

```<code>Error   CS0012  The type 'QueryDeferred<>' is defined in an assembly that is not referenced. You must add a reference to assembly 'Z.EntityFramework.Plus.QueryDeferred.EF6, Version=1.6.8.0, Culture=neutral, PublicKeyToken=59b66d028979105b'.
</code>```

Thank you in advance!

J Kent

答:
Disclaimer: I'm the owner of the project Entity Framework Plus

Due to how the library has been built, some "standalone" features like this one may have the Z.EntityFramework.Plus.QueryDeferred.EF6 requirement.

You can download the version from: NuGet

We will eventually fix it for no longer having to have this dependence.

Body:
When trying to use the QueryCache library to do some L2 caching of a few entities, I am receiving a compiler error on .FromCache() indicating the QueryDeferred library is required. Documentation indicates QueryCache can be used as stand-alone.

using Z.EntityFramework.Plus;

namespace LookupValuesMap.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            LookupValueContext ctx = new LookupValueContext();
            var companies = ctx.Companies.FromCache().ToList();  <-- error

Here is the error:

Error   CS0012  The type 'QueryDeferred<>' is defined in an assembly that is not referenced. You must add a reference to assembly 'Z.EntityFramework.Plus.QueryDeferred.EF6, Version=1.6.8.0, Culture=neutral, PublicKeyToken=59b66d028979105b'.

Thank you in advance!

J Kent