问:
Laravel Spark redirect on registration
I am simply trying to redirect a user to a page when they register. I have accomplished this redirect when the user logs in by altering the following line in the LoginController in vendors/laravel/Spark/src/Http/Controllers/Auth

```<code>protected $redirectTo = '/Profile/';
</code>```

In attempting to do the same thing for the registration, I altered the same line in the RegisterController at the same address. However, that did not work.

I traced the code down to the RedirectsUsers trait which first looks for the redirectPath property and then for the redirectTo property. So it seems like this should work.

However, I get redirected to 'undefined' which would seem to indicate that the 'redirectTo' variable is either protected somewhere that it should not be or is simply missing. The variable is present in the authController for laravel.

答:
If you want to change the redirect after you have logged in or registered a new user add the following line to your booted() function in App/Providers/SparkServiceProvider.php</p>

```<code>Spark::afterLoginRedirectTo('example');
</code>```

Title: Laravel Spark redirect on registration

Body:
I am simply trying to redirect a user to a page when they register. I have accomplished this redirect when the user logs in by altering the following line in the LoginController in vendors/laravel/Spark/src/Http/Controllers/Auth

protected $redirectTo = '/Profile/';

In attempting to do the same thing for the registration, I altered the same line in the RegisterController at the same address. However, that did not work.

I traced the code down to the RedirectsUsers trait which first looks for the redirectPath property and then for the redirectTo property. So it seems like this should work.

However, I get redirected to 'undefined' which would seem to indicate that the 'redirectTo' variable is either protected somewhere that it should not be or is simply missing. The variable is present in the authController for laravel.

Body:
If you want to change the redirect after you have logged in or registered a new user add the following line to your booted() function in App/Providers/SparkServiceProvider.php

Spark::afterLoginRedirectTo('example');


来源: stackexchange

问:
Rewrite/hiding some URL in .htaccess
I'm trying to get right syntax for .htaccess without any result...

I've a URL structured as domain.com/app/public/pageName .

It's working fine but I would "hide" the 'app/public/' part in browsers, basically doing something like:

```<code>[real URL] domain.com/app/public/pageName -> domain.com/pageName [what users type and see in browsers]
</code>```

I think in that way it should be more readable and seo-friendly.

As I understood from docs (and maybe it's wrong because it's not working...) I should tell to Apache to map/redirect all URL like domain.com/pageName to domain.com/app/public/pageName , but only internally, in order to show the minimal URL in users' browsers.

Right now I have something like:

```<code>RewriteEngine on

#RewriteBase /app/public/

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^(.+)$ https://localhost/app/public/index.php?url=$1 [QSA,L]
</code>```

(I'm using full URL with https://... in order to get something that will be quick and easy to adapt when I upload all to my hosting, is it right?).

Problem is that RewriteRule actually change the URL, because it perform a redirect and URL rewrite it's not handle internally.

So, first of all: is it possible what I'm trying to do? If so, how can I handle the URL rewrite only internally?

Everything should be uploaded to a shared hosting, so I don't have other than .htaccess.
Anyway, I can consider to upgrade to a vps if there are not other possibilities...

Thanks!

==============

EDIT (should be more clear now)

tl;dr version:

I'm looking for a method that let users to type domain.com/pageName (and they will see that address in their browsers) and rewrite internally that URL in order to point to domain.com/app/public/pageName.

==============

More: after /app/public/ there can be an arbitrary number of elements, separated by / . All of these elements are appended at the end of the URL after index.php. At the end URL looks like:

```<code>  domain/app/public/index.php?url=lot/of/elements/here
</code>```

This is already working with the RewriteRule posted above, I would keep that too.
Thanks!

答:
This is working fine for me, Hope it will work for you as well.

Check .htaccess here

```<code>RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_URI} ^/app/public
RewriteRule ^app/public/(.*)$ /$1 [L,QSA]
</code>```

ContentLicense: CC BY-SA 3.0

Title: Rewrite/hiding some URL in .htaccess

Body:
I'm trying to get right syntax for .htaccess without any result...

I've a URL structured as domain.com/app/public/pageName .

It's working fine but I would "hide" the 'app/public/' part in browsers, basically doing something like:

[real URL] domain.com/app/public/pageName -> domain.com/pageName [what users type and see in browsers]

I think in that way it should be more readable and seo-friendly.

As I understood from docs (and maybe it's wrong because it's not working...) I should tell to Apache to map/redirect all URL like domain.com/pageName to domain.com/app/public/pageName , but only internally, in order to show the minimal URL in users' browsers.

Right now I have something like:

RewriteEngine on

#RewriteBase /app/public/

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^(.+)$ https://localhost/app/public/index.php?url=$1 [QSA,L]

(I'm using full URL with https://... in order to get something that will be quick and easy to adapt when I upload all to my hosting, is it right?).

Problem is that RewriteRule actually change the URL, because it perform a redirect and URL rewrite it's not handle internally.

So, first of all: is it possible what I'm trying to do? If so, how can I handle the URL rewrite only internally?

Everything should be uploaded to a shared hosting, so I don't have other than .htaccess.
Anyway, I can consider to upgrade to a vps if there are not other possibilities...

Thanks!

==============

EDIT (should be more clear now)

tl;dr version:

I'm looking for a method that let users to type domain.com/pageName (and they will see that address in their browsers) and rewrite internally that URL in order to point to domain.com/app/public/pageName.

==============

More: after /app/public/ there can be an arbitrary number of elements, separated by / . All of these elements are appended at the end of the URL after index.php. At the end URL looks like:

  domain/app/public/index.php?url=lot/of/elements/here

This is already working with the RewriteRule posted above, I would keep that too.
Thanks!

Body:
This is working fine for me, Hope it will work for you as well.

Check .htaccess here

RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_URI} ^/app/public
RewriteRule ^app/public/(.*)$ /$1 [L,QSA]


问:
add validation on email field on woocommerce checkout page
I want to fire validation to check entered email address is business email address or not immediately after lost focus from email field before submitting the form. I tried many filters

```<code>add_action('woocommerce_after_checkout_validation', 'rei_after_checkout_validation');

function rei_after_checkout_validation( $posted ) {

}
</code>```

but filter is fired after submitting the form.
Please help me to solve it.

答:
I have done validation using below woocommerce hook.add it in your active theme's functions.php file.

```<code>    add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );

    function custom_override_checkout_fields( $fields ) {
        ?>

    <script>

            jQuery('#billing_email').on('blur', function() {
                validationFunction();
            });

            function validationFunction() {

                if(document.getElementById("billing_email").value!='')
                {
                console.log(document.getElementById("billing_email").value);
                var re = /^([\w-\.]+@(?!gmail.com)(?!yahoo.com)(?!hotmail.com)(?!yahoo.co.in)(?!aol.com)(?!abc.com)(?!xyz.com)(?!pqr.com)(?!rediffmail.com)(?!live.com)(?!outlook.com)(?!me.com)(?!msn.com)(?!ymail.com)(?!att.net)(?!comcast.net)(?!facebook.com)(?!gmx.com)(?!googleemail.com)(?!hotmail.co.uk)(?!mac.com)(?!google.com)(?!mail.com)(?!sbcglobal.net)(?!verizon.net)(?!yahoo.co.uk)(?!email.com)(?!games.com)(?!gmx.net)(?!hush.com)(?!hushmail.com)(?!icloud.com)(?!inbox.com)(?!lavbit.com)(?!love.com)(?!hush.com)(?!pobox.com)(?!rocketmail.com)(?!safe-mail.net.com)(?!wow.com)(?!ygm.com)(?!email.com)(?!zoho.com)(?!fastmail.fm)(?!yandex.com)([\w-]+\.)+[\w-]{2,4})?$/;
                if(re.test(document.getElementById("billing_email").value)==false)
                {
                    jQuery('#error').remove();
                    jQuery('#billing_email_field label').addClass('wrongemail');
                    jQuery('#billing_email_field input.input-text').addClass('wrongemailborder');
                    jQuery('#billing_email_field').append('<span class="wrongemail" id="error" style="font-size: 14px;">Please Enter valid business email address.<span>');
                    jQuery('#billing_email_field label').removeClass('rightemail');
                    jQuery('#place_order').attr('disabled',true);
                }
                else
                {
                    jQuery('#billing_email_field label').addClass('rightemailborder');
                    jQuery('#billing_email_field input.input-text').removeClass('wrongemailborder');
                    jQuery('#error').remove();
                    jQuery('#billing_email_field label').removeClass('wrongemail');
                    jQuery('#place_order').attr('disabled',false);
                }
                }
            }

</script>

<?php
    }
     return $fields;
    }
</code>```

i bind the javascript blur event to email text field then check the email id enterd by user.

Body:
I want to fire validation to check entered email address is business email address or not immediately after lost focus from email field before submitting the form. I tried many filters

add_action('woocommerce_after_checkout_validation', 'rei_after_checkout_validation');

function rei_after_checkout_validation( $posted ) {

}

but filter is fired after submitting the form.
Please help me to solve it.

Body:
I have done validation using below woocommerce hook.add it in your active theme's functions.php file.

    add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );

    function custom_override_checkout_fields( $fields ) {
        ?>

    <script>

            jQuery('#billing_email').on('blur', function() {
                validationFunction();
            });

            function validationFunction() {

                if(document.getElementById("billing_email").value!='')
                {
                console.log(document.getElementById("billing_email").value);
                var re = /^([\w-\.]+@(?!gmail.com)(?!yahoo.com)(?!hotmail.com)(?!yahoo.co.in)(?!aol.com)(?!abc.com)(?!xyz.com)(?!pqr.com)(?!rediffmail.com)(?!live.com)(?!outlook.com)(?!me.com)(?!msn.com)(?!ymail.com)(?!att.net)(?!comcast.net)(?!facebook.com)(?!gmx.com)(?!googleemail.com)(?!hotmail.co.uk)(?!mac.com)(?!google.com)(?!mail.com)(?!sbcglobal.net)(?!verizon.net)(?!yahoo.co.uk)(?!email.com)(?!games.com)(?!gmx.net)(?!hush.com)(?!hushmail.com)(?!icloud.com)(?!inbox.com)(?!lavbit.com)(?!love.com)(?!hush.com)(?!pobox.com)(?!rocketmail.com)(?!safe-mail.net.com)(?!wow.com)(?!ygm.com)(?!email.com)(?!zoho.com)(?!fastmail.fm)(?!yandex.com)([\w-]+\.)+[\w-]{2,4})?$/;
                if(re.test(document.getElementById("billing_email").value)==false)
                {
                    jQuery('#error').remove();
                    jQuery('#billing_email_field label').addClass('wrongemail');
                    jQuery('#billing_email_field input.input-text').addClass('wrongemailborder');
                    jQuery('#billing_email_field').append('<span class="wrongemail" id="error" style="font-size: 14px;">Please Enter valid business email address.<span>');
                    jQuery('#billing_email_field label').removeClass('rightemail');
                    jQuery('#place_order').attr('disabled',true);
                }
                else
                {
                    jQuery('#billing_email_field label').addClass('rightemailborder');
                    jQuery('#billing_email_field input.input-text').removeClass('wrongemailborder');
                    jQuery('#error').remove();
                    jQuery('#billing_email_field label').removeClass('wrongemail');
                    jQuery('#place_order').attr('disabled',false);
                }
                }
            }

</script>

<?php
    }
     return $fields;
    }

i bind the javascript blur event to email text field then check the email id enterd by user.


问:
Open a series of terminal and run bash files
I have a lot of bash files which need to be executed in separated terminals. It is noted that it took 1 hour to run a bash file with 2 cores. I would like to write a python code that will open a series of terminals at a time and submit bash files automatically. I thought about FOR loop and Sub-process library but I cannot get what I want.

Could you please help me with this?

Thank you in advanced!

P/s: I am using Ubuntu 16.04, Python 2.7.

答:
You can use screen/tmux for such kind of things. Example for a tmux:

```<code>tmux new-session 'script1 param1' \; split-window 'script2 param2'
</code>```

Tmux will open two terminal in splitted window, and run your scripts in same time. If you need run more scripts, just add another \; split-window 'script param'.

If you need run it from bootup scripts or from cron, you can run it detached:

```<code>tmux new-session -s my-session 'script1 param1' \; split-window 'script2 param2' \; detach-client
</code>```

If you like to see what happend in detached tmux, you can attach to it again:

```<code>tmux att -t my-session
</code>```

Also you can put all commands to separated config file and run it. For example create file tmux-run-my-scripts.conf

```<code>new-session -s my-session 'script1 param1'
split-window 'script2 param2'
detach-client
</code>```

And run it:

```<code>tmux source-file /path/to/tmux-run-my-scripts.conf
</code>```

Body:
You can use screen/tmux for such kind of things. Example for a tmux:

tmux new-session 'script1 param1' \; split-window 'script2 param2'

Tmux will open two terminal in splitted window, and run your scripts in same time. If you need run more scripts, just add another \; split-window 'script param'.

If you need run it from bootup scripts or from cron, you can run it detached:

tmux new-session -s my-session 'script1 param1' \; split-window 'script2 param2' \; detach-client

If you like to see what happend in detached tmux, you can attach to it again:

tmux att -t my-session

Also you can put all commands to separated config file and run it. For example create file tmux-run-my-scripts.conf

new-session -s my-session 'script1 param1'
split-window 'script2 param2'
detach-client

And run it:

tmux source-file /path/to/tmux-run-my-scripts.conf


问:
How to do a JavaScript HTML 5 Canvas image "page flip" like you commonly see in Flash?
Has anyone tried recreating the page flip effect with images like you commonly see in Adobe Flash with JavaScript and HTML 5's canvas tag?

Are there any frameworks or JQuery plug-ins that do this type of effect?

The page flip in Flash allows you to grab a corner of the simulated book page and flip the page like you would flip a real book's page.

I really want to learn how to do this with JavaScript and HTML 5's canvas tag, but not sure where to start nor what formulas would be necessary.

Example page flip in flash

ContentLicense: CC BY-SA 2.5


问:
Scale mode,Scale width, Scale height in mfc
What is scale mode in VB wether we can do same logic in mfc . as scale mode is having different modes which are inches etc. how do do in mfc. what scale height ? and let me know how we can do it in mfc.</p>

```<code>This code is in vb :
    dScale = m_dScale 'sliScale.Value / 2
     liSTppX = Screen.TwipsPerPixelX
      liSTppY = Screen.TwipsPerPixelY

This code is in vb :
      picPreview.ScaleMode = vbInches //scale mode
      picPreview.ScaleHeight = picPreview.ScaleHeight * ldScale
      picPreview.ScaleWidth = picPreview.ScaleWidth * ldScale

how to do in mfc..
</code>```

答: If you are talking about dialogs and controls, the answer is simply no. VB creates its forms programmatically, while MFC uses dialog resources, and the coordinates and sizes are in "dialog units". Unfortunately it is affected by the font scale on each computer, which means that a dialog won't always be sized the same on every computer, even if all use the same resolution, eg 1920x1080. Refer to the Microsoft documentation for more details.</p>

Body:
What is scale mode in VB wether we can do same logic in mfc . as scale mode is having different modes which are inches etc. how do do in mfc. what scale height ? and let me know how we can do it in mfc.

This code is in vb :
    dScale = m_dScale 'sliScale.Value / 2
     liSTppX = Screen.TwipsPerPixelX
      liSTppY = Screen.TwipsPerPixelY

This code is in vb :
      picPreview.ScaleMode = vbInches //scale mode
      picPreview.ScaleHeight = picPreview.ScaleHeight * ldScale
      picPreview.ScaleWidth = picPreview.ScaleWidth * ldScale

how to do in mfc..


问:
Set aspnetcore_environment within build configuration
I have simple asp.net core project. I want to deploy it via TeamCity to IIS.
The problem is that I can't setup ASPNETCORE_ENVIRONMENT when publishing the project.
My goal is to use default behaviour to load appsettings files:

```<code>.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
</code>```

I use .csproj instead of project.json and Web.config's section related to configuration looks like:

```<code><PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'prod-zone-a|AnyCPU' ">
    <IntermediateOutputPath>obj\Debug\netcoreapp1.1</IntermediateOutputPath>
    <DebugSymbols>true</DebugSymbols>
    <Optimize>false</Optimize>
    <DefineConstants>TRACE;DEBUG;NETCOREAPP1_1</DefineConstants>
</PropertyGroup>
</code>```

Publish is executed like:

```<code>dotnet publish --configuration prod-zone-a --output <some-dir>
</code>```

Also it's necessary to have several site on IIS published with different configurations: prod-zone-a, prod-zone-b, etc (corresponded appsettings.{env.EnvironmentName}.json looks different too)

How can I implement such idea?
Or probably I should to throw this idea out and follow another way?

Update:

According to MS docs I've added separate build step to TeamCity (powershell command):

```<code>$Env:ASPNETCORE_ENVIRONMENT = "prod-zone-a"
</code>```

but it doesn't work.

答:
The only way I found (quite different to this question) is to use web.config transformations that way (another my question on SO)

The main reason is that it's necessary not just publish the project with necessary ASPNETCORE_ENVIRONMENT value, but this value is also needed in application runtime on IIS

Body:
I have simple asp.net core project. I want to deploy it via TeamCity to IIS.
The problem is that I can't setup ASPNETCORE_ENVIRONMENT when publishing the project.
My goal is to use default behaviour to load appsettings files:

.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

I use .csproj instead of project.json and Web.config's section related to configuration looks like:

<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'prod-zone-a|AnyCPU' ">
    <IntermediateOutputPath>obj\Debug\netcoreapp1.1</IntermediateOutputPath>
    <DebugSymbols>true</DebugSymbols>
    <Optimize>false</Optimize>
    <DefineConstants>TRACE;DEBUG;NETCOREAPP1_1</DefineConstants>
</PropertyGroup>

Publish is executed like:

dotnet publish --configuration prod-zone-a --output <some-dir>

Also it's necessary to have several site on IIS published with different configurations: prod-zone-a, prod-zone-b, etc (corresponded appsettings.{env.EnvironmentName}.json looks different too)

How can I implement such idea?
Or probably I should to throw this idea out and follow another way?

Update:

According to MS docs I've added separate build step to TeamCity (powershell command):

$Env:ASPNETCORE_ENVIRONMENT = "prod-zone-a"

but it doesn't work.


问:
Windows 10 pro will not accept group policy from 2012 r2 AD DC
I have a win 2012 r2 AD controller that windows 2012 r2 servers can join and group policy is correctly applied to.... however after joining a Windows 10 desktop the same group policy does not work. These systems can join the domain but will not apply the group policy. I get  an error code 1326 when looking through the report generated with GPRESULT /H GPReport.html. Any ideas what is going on?</p>

答:
Have you downloaded and installed the Windows 10 Group Policy Templates?

These are available here:

https://www.microsoft.com/en-us/download/details.aspx?id=48257

The guide to installing them is available here:

https://msdn.microsoft.com/en-us/library/bb530196.aspx

Also is your Windows 10 PC in the same Active Directory container the group Policy is applied to? If not it will need to be moved there for the policies to be applied.

The error code does seem to refer to issues logging in with the computer account, which could mean that there were problems with it joining the domian correctly. Have you tried removing the PC from the domain, deleting it from AD, and re-adding it?


问:
Issue exporting data from php to csv
I have a php file. This file is a copy of a feed file inside Opencart and its like this:

```<code>  <?php
    public function index() {
    $ids = $this->db->query("select * from t_product where quantity>0");
    foreach ($ids->rows as $id) {
    //Inside here i create php variables, each one includes information like description, url etc and at the end i place it here:
    $myrow  = $id . ',' . $model . ',' . $name . ',' . $product_url;
    }

    $this->response->addHeader('Content-type: text/csv');
    $this->response->setOutput($myrow);
    }
    ?>
</code>```

When i use the above code, then when i run the php file in browser, i get a php file downloaded that has all my data that i need. My question is how could i export this in csv format?

I tried code from: http://code.stephenmorley.org/php/creating-downloadable-csv-files/ with no success at all. Any ideas?

Also i somewhere read that i have to escape single quotes, double quotes and commas. How do i do this?

EDIT:

I also tried this:

```<code><?php
    public function index() {
    $ids = $this->db->query("select * from t_product where quantity>0");
    $fp = fopen('php://output', 'w');
 foreach ($ids->rows as $id) {
        //Inside here i create php variables, each one includes information like description, url etc and at the end i place it here:
        $myrow  = $id . ',' . $model . ',' . $name . ',' . $product_url;
        fputcsv($fp, $myrow);
        }
fclose($fp);
 $this->response->addHeader('Content-type: text/csv');
         $this->response->setOutput($fp);
}
?>
</code>```

with no success!

答:
I think you are not telling your browser to download file, to resolve this problem I just told browser in which file we are writing.</p>

```<code>// output headers so that the file is downloaded rather than displayed
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename="demo.csv"');
// do not cache the file
header('Pragma: no-cache');
header('Expires: 0');

// create a file pointer connected to the output stream
$file = fopen('php://output', 'w');

// send the column headers
fputcsv($file, array('Column 1', 'Column 2', 'Column 3', 'Column 4', 'Column 5'));

// Sample data. This can be fetched from mysql too
$data = array(
array('Data 11', 'Data 12', 'Data 13', 'Data 14', 'Data 15'),
array('Data 21', 'Data 22', 'Data 23', 'Data 24', 'Data 25'),
array('Data 31', 'Data 32', 'Data 33', 'Data 34', 'Data 35'),
array('Data 41', 'Data 42', 'Data 43', 'Data 44', 'Data 45'),
array('Data 51', 'Data 52', 'Data 53', 'Data 54', 'Data 55'));

// output each row of the data
foreach ($data as $row)
{
 fputcsv($file, $row);
}

exit();
</code>```

Title: Issue exporting data from php to csv

Body:
I have a php file. This file is a copy of a feed file inside Opencart and its like this:

  <?php
    public function index() {
    $ids = $this->db->query("select * from t_product where quantity>0");
    foreach ($ids->rows as $id) {
    //Inside here i create php variables, each one includes information like description, url etc and at the end i place it here:
    $myrow  = $id . ',' . $model . ',' . $name . ',' . $product_url;
    }

    $this->response->addHeader('Content-type: text/csv');
    $this->response->setOutput($myrow);
    }
    ?>

When i use the above code, then when i run the php file in browser, i get a php file downloaded that has all my data that i need. My question is how could i export this in csv format?

I tried code from: http://code.stephenmorley.org/php/creating-downloadable-csv-files/ with no success at all. Any ideas?

Also i somewhere read that i have to escape single quotes, double quotes and commas. How do i do this?

EDIT:

I also tried this:

<?php
    public function index() {
    $ids = $this->db->query("select * from t_product where quantity>0");
    $fp = fopen('php://output', 'w');
 foreach ($ids->rows as $id) {
        //Inside here i create php variables, each one includes information like description, url etc and at the end i place it here:
        $myrow  = $id . ',' . $model . ',' . $name . ',' . $product_url;
        fputcsv($fp, $myrow);
        }
fclose($fp);
 $this->response->addHeader('Content-type: text/csv');
         $this->response->setOutput($fp);
}
?>

with no success!

Body:
I think you are not telling your browser to download file, to resolve this problem I just told browser in which file we are writing.

// output headers so that the file is downloaded rather than displayed
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename="demo.csv"');
// do not cache the file
header('Pragma: no-cache');
header('Expires: 0');

// create a file pointer connected to the output stream
$file = fopen('php://output', 'w');

// send the column headers
fputcsv($file, array('Column 1', 'Column 2', 'Column 3', 'Column 4', 'Column 5'));

// Sample data. This can be fetched from mysql too
$data = array(
array('Data 11', 'Data 12', 'Data 13', 'Data 14', 'Data 15'),
array('Data 21', 'Data 22', 'Data 23', 'Data 24', 'Data 25'),
array('Data 31', 'Data 32', 'Data 33', 'Data 34', 'Data 35'),
array('Data 41', 'Data 42', 'Data 43', 'Data 44', 'Data 45'),
array('Data 51', 'Data 52', 'Data 53', 'Data 54', 'Data 55'));

// output each row of the data
foreach ($data as $row)
{
 fputcsv($file, $row);
}

exit();


问:
how to save data after download image?
I am facing one problem i want to save data after downloading an image. My image has been successfully downloaded after that i want to maintain the history of downloads.Here is my Function:-

```<code>enter code here
public function UserImageDownlaod($userid=null,$imageid=null){
    $imagedata = DB::table('alt_images')->where('id',$imageid)->first();
    $imagedata = json_decode(json_encode($imagedata),true);
    $destination = 'images/ContributorImages'.'/';
    $pathToFile = $destination.$imagedata['img'];
    return response()->download($pathToFile);
    //Now i want to save the history of downloaded images
    $history= new DownloadHistory;
    $history->user_id = Auth::user()->id;
    $history->alt_image_id = $imageid;
    $history->save();
 }
</code>```

Now you can see after this return response()->download($pathToFile) line i want to save the history data. I want when User click on OK button then data will saved on history table. Can anyone help me.

答:
The popup you showed us is from the browser. At the point, you see this popup, the browser might already started to download the file in the background. As this is part of your browser and you dont have any callback about pressing ok/cancel, there is no direct way to determine, what the user did.

A simple workaround would be, to show the user an alert box in javascript and ask, if he really wants to download the file.

```<code><a href="{{ action(...) }}" onclick="confirm('are you sure?')">Download</a>
</code>```

Title: how to save data after download image?

Body:
I am facing one problem i want to save data after downloading an image. My image has been successfully downloaded after that i want to maintain the history of downloads.Here is my Function:-

enter code here
public function UserImageDownlaod($userid=null,$imageid=null){
    $imagedata = DB::table('alt_images')->where('id',$imageid)->first();
    $imagedata = json_decode(json_encode($imagedata),true);
    $destination = 'images/ContributorImages'.'/';
    $pathToFile = $destination.$imagedata['img'];
    return response()->download($pathToFile);
    //Now i want to save the history of downloaded images
    $history= new DownloadHistory;
    $history->user_id = Auth::user()->id;
    $history->alt_image_id = $imageid;
    $history->save();
 }

Now you can see after this return response()->download($pathToFile) line i want to save the history data. I want when User click on OK button then data will saved on history table. Can anyone help me.

Body:
The popup you showed us is from the browser. At the point, you see this popup, the browser might already started to download the file in the background. As this is part of your browser and you dont have any callback about pressing ok/cancel, there is no direct way to determine, what the user did.

A simple workaround would be, to show the user an alert box in javascript and ask, if he really wants to download the file.

<a href="{{ action(...) }}" onclick="confirm('are you sure?')">Download</a>


问:
Binary Semaphore not working if release() comes before acquire()
I am writing a test code where i found if we put release() before acquire() then Binary Semaphore functionality is broken.

I checked and found more then one thread passes acquire() and increase the count to N where N is number of threads and thus contradicting binary semaphore.

```<code>import java.util.concurrent.Semaphore;

/**
 * Consider an ATM cubicle with 1 ATM, Semaphore can make sure only 1 person
 * can access simultaneously.
 *
 * Here if relese() comes before then this binary semaphore is not working.
 */
public class SemaphoreTest {

    // max 4 people
    static Semaphore semaphore = new Semaphore(1);

    public static void main(String[] args) {

        System.out.println("Total available Semaphore permits : " + semaphore.availablePermits());

        MyATMThread t1 = new MyATMThread("A",semaphore);
        t1.start();

        MyATMThread t2 = new MyATMThread("B",semaphore);
        t2.start();

        MyATMThread t3 = new MyATMThread("C",semaphore);
        t3.start();

        MyATMThread t4 = new MyATMThread("D",semaphore);
        t4.start();

        MyATMThread t5 = new MyATMThread("E",semaphore);
        t5.start();

        MyATMThread t6 = new MyATMThread("F",semaphore);
        t6.start();

    }
}

class MyATMThread extends Thread {

    String name = "";
    Semaphore semaphore = null;

    MyATMThread(String name,Semaphore s) {
        this.name = name;
        this.semaphore=s;
    }

    public void run() {

        try {

            System.out.println(name + " : acquiring lock...");
            System.out.println(name + " : available Semaphore permits now: " + semaphore.availablePermits());
            semaphore.release();
            semaphore.acquire();
            System.out.println(name + " : got the permit!");

            try {

                for (int i = 1; i <= 5; i++) {

                    System.out.println(name + " : is performing operation " + i + ", available Semaphore permits : "
                            + semaphore.availablePermits());

                    // sleep 1 second
                    Thread.sleep(1000);

                }

            } finally {

                // calling release() after a successful acquire()
                System.out.println(name + " : releasing lock...");
                semaphore.release();
                System.out.println(name + " : available Semaphore permits now: " + semaphore.availablePermits());

            }

        } catch (InterruptedException e) {

            e.printStackTrace();

        }

    }

}
</code>```

Can some one explain this behavior ?

答: You can think of release() as "creating" another permit if that thread had not previously acquired a permit from that Semaphore.

Body:
I am writing a test code where i found if we put release() before acquire() then Binary Semaphore functionality is broken.

I checked and found more then one thread passes acquire() and increase the count to N where N is number of threads and thus contradicting binary semaphore.

import java.util.concurrent.Semaphore;

/**
 * Consider an ATM cubicle with 1 ATM, Semaphore can make sure only 1 person
 * can access simultaneously.
 *
 * Here if relese() comes before then this binary semaphore is not working.
 */
public class SemaphoreTest {

    // max 4 people
    static Semaphore semaphore = new Semaphore(1);

    public static void main(String[] args) {

        System.out.println("Total available Semaphore permits : " + semaphore.availablePermits());

        MyATMThread t1 = new MyATMThread("A",semaphore);
        t1.start();

        MyATMThread t2 = new MyATMThread("B",semaphore);
        t2.start();

        MyATMThread t3 = new MyATMThread("C",semaphore);
        t3.start();

        MyATMThread t4 = new MyATMThread("D",semaphore);
        t4.start();

        MyATMThread t5 = new MyATMThread("E",semaphore);
        t5.start();

        MyATMThread t6 = new MyATMThread("F",semaphore);
        t6.start();

    }
}

class MyATMThread extends Thread {

    String name = "";
    Semaphore semaphore = null;

    MyATMThread(String name,Semaphore s) {
        this.name = name;
        this.semaphore=s;
    }

    public void run() {

        try {

            System.out.println(name + " : acquiring lock...");
            System.out.println(name + " : available Semaphore permits now: " + semaphore.availablePermits());
            semaphore.release();
            semaphore.acquire();
            System.out.println(name + " : got the permit!");

            try {

                for (int i = 1; i <= 5; i++) {

                    System.out.println(name + " : is performing operation " + i + ", available Semaphore permits : "
                            + semaphore.availablePermits());

                    // sleep 1 second
                    Thread.sleep(1000);

                }

            } finally {

                // calling release() after a successful acquire()
                System.out.println(name + " : releasing lock...");
                semaphore.release();
                System.out.println(name + " : available Semaphore permits now: " + semaphore.availablePermits());

            }

        } catch (InterruptedException e) {

            e.printStackTrace();

        }

    }

}

Can some one explain this behavior ?


问:
Export huge database (40GB)
I have database that is big 42GB (and I need all tables), Two tables have more than 10gb.

When i do :

```<code>mysqldump -h host -u username -ppassword dbname > export.sql
</code>```

Server in most cases crash, or I get message after some duration "MySQL server has gone away".

I use docker with nginx, ubuntu 16.04, php...

答:
To dump the database and gzip it at the same time, use the following. This will prompt you for your password.</p>

```<code>mysqldump -u [USERNAME] -p [DBNAME] | gzip > [/path_to_file/DBNAME].sql.gz
</code>```

Title: Export huge database (40GB)

Body:
I have database that is big 42GB (and I need all tables), Two tables have more than 10gb.

When i do :

mysqldump -h host -u username -ppassword dbname > export.sql

Server in most cases crash, or I get message after some duration "MySQL server has gone away".

I use docker with nginx, ubuntu 16.04, php...

Body:
To dump the database and gzip it at the same time, use the following. This will prompt you for your password.

mysqldump -u [USERNAME] -p [DBNAME] | gzip > [/path_to_file/DBNAME].sql.gz


问:
Create Own Column Property in SQL
i want to create my one own property for every column.

ex. every column has description property but i require one more property for me.

i want required for auto code generate from that property.

what is best way for that?

答: Extended properties are exactly what you're looking for. They can be specified for any database object (including columns) and retrieved using system functions/procedures.</p>

Title: Create Own Column Property in SQL


问:
Python file reading and writing is not working
I am making a game for Python and in it there is code to write to a file the answer for when I am running it myself to prevent myself having to actually play the game.
I have already coded for writing and reading a file which works fine, but for the cheat .txt file, printing its contents returns only [].

Here's a shortened example of what is happening.

```<code>file = open("E:\\ICT and Computer Science\\Python\\GCSE\\cheat.txt", "a+")
text = file.readlines()
print(text)
[]
file.close()

file = open("E:\\ICT and Computer Science\\Python\\GCSE\\cheat.txt", "r+")
text = file.readlines()
print(text)
['xcfghujiosdfnonoooooowhello']
</code>```

It appears now on a network machine that the a+ does not work, but r+. I fully understand the functionality of each mode, but can anyone suggest why it cannot read (or write, which returns the argument's length) when in a+ mode?

Note a+ is the required mode as it needs to be appended to the file.

Edit: as I am typing file.write(), the small box assisting you apply arguments reads 'See source or doc'.

答:
in case of a+ both reading and writing  you can have two functions seaparately
for reading before file.readlines() you should have file.seek(0) for positioning of file descriptor at start of file

code :

```<code>file = open("E:\\ICT and Computer Science\\Python\\GCSE\\cheat.txt", "a+")
file.seek(0)
text = file.readlines()
print(text)
file.close()
</code>```

it will work perfectly

Body:
I am making a game for Python and in it there is code to write to a file the answer for when I am running it myself to prevent myself having to actually play the game.
I have already coded for writing and reading a file which works fine, but for the cheat .txt file, printing its contents returns only [].

Here's a shortened example of what is happening.

file = open("E:\\ICT and Computer Science\\Python\\GCSE\\cheat.txt", "a+")
text = file.readlines()
print(text)
[]
file.close()

file = open("E:\\ICT and Computer Science\\Python\\GCSE\\cheat.txt", "r+")
text = file.readlines()
print(text)
['xcfghujiosdfnonoooooowhello']

It appears now on a network machine that the a+ does not work, but r+. I fully understand the functionality of each mode, but can anyone suggest why it cannot read (or write, which returns the argument's length) when in a+ mode?

Note a+ is the required mode as it needs to be appended to the file.

Edit: as I am typing file.write(), the small box assisting you apply arguments reads 'See source or doc'.

Body:
in case of a+ both reading and writing  you can have two functions seaparately
for reading before file.readlines() you should have file.seek(0) for positioning of file descriptor at start of file

code :

file = open("E:\\ICT and Computer Science\\Python\\GCSE\\cheat.txt", "a+")
file.seek(0)
text = file.readlines()
print(text)
file.close()

it will work perfectly


问:
How to "communicate" between components in Angular?
How to exchange data between components in Angular?

For instance, communicating between parent and child components or between siblings.

答:
Using a service:

```<code>import { Injectable } from '@angular/core';
import { Subject }    from 'rxjs/Subject';

@Injectable()
export class AppState {
  public _subject = new Subject<object>();
  public event = this._subject.asObservable();

  public publish(data: any) {
    this._subject.next(data);
  }
}
</code>```

and you can publish event-like messages like this:

```<code>export class AppComponent {
  constructor(
    public appState: AppState
  ) {
    appState.publish({data: 'some data'});
  }
}
</code>```

and you can subscribe to these events:

```<code>export class HomeComponent {
  constructor(
    public appState: AppState
  ) {
    appState.event.subscribe((data) => {
      console.log(data); // {data: 'some data'}
    });
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Using a service:

import { Injectable } from '@angular/core';
import { Subject }    from 'rxjs/Subject';

@Injectable()
export class AppState {
  public _subject = new Subject<object>();
  public event = this._subject.asObservable();

  public publish(data: any) {
    this._subject.next(data);
  }
}

and you can publish event-like messages like this:

export class AppComponent {
  constructor(
    public appState: AppState
  ) {
    appState.publish({data: 'some data'});
  }
}

and you can subscribe to these events:

export class HomeComponent {
  constructor(
    public appState: AppState
  ) {
    appState.event.subscribe((data) => {
      console.log(data); // {data: 'some data'}
    });
  }
}


问:
Android app no longer usable after declaring browsable category
While developing a very simple application I stumbled upon this strange behaviour when declaring the following lines to my AndroidManifest.xml:

```<code><category android:name="android.intent.category.BROWSABLE" />

            <data android:scheme="com.example.appname"
            android:host="myHost" />
</code>```

Basically people can install the APK but the app disappears from the menu and can't be started anymore. Via Settings > Applications you can see that the app is installed.

So I've created a basic testcase, just a webview app with only one activity which loads the webview. Published it to the app store, as expected no problems. Pushed an update with the intent category, and same problem arrises. I can update to this newer version, but the app is removed from the home/app screen so it can't be launched.

Complete Manifestfile:

```<code><?xml version="1.0" encoding="utf-8"?>
      <manifest package="com.example.appname"
      xmlns:android="http://schemas.android.com/apk/res/android">

<uses-permission android:name="android.permission.INTERNET"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>

            <category android:name="android.intent.category.BROWSABLE" />

            <data android:scheme="com.example.appname"
            android:host="myHost" />

        </intent-filter>
    </activity>
</application>
</code>```

The app runs fine when installed in emulator, or via ADB on device. The browsable declaration works fine.

答:
You can declare different intent-filter for different actions.

```<code><activity
    android:name=".MainActivity"
    android:label="@string/app_name">

    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>

    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="http" android:host="www.example.com" android:pathPrefix="/prefix" />
    </intent-filter>

</activity>
</code>```

Body:
While developing a very simple application I stumbled upon this strange behaviour when declaring the following lines to my AndroidManifest.xml:

<category android:name="android.intent.category.BROWSABLE" />

            <data android:scheme="com.example.appname"
            android:host="myHost" />

Basically people can install the APK but the app disappears from the menu and can't be started anymore. Via Settings > Applications you can see that the app is installed.

So I've created a basic testcase, just a webview app with only one activity which loads the webview. Published it to the app store, as expected no problems. Pushed an update with the intent category, and same problem arrises. I can update to this newer version, but the app is removed from the home/app screen so it can't be launched.

Complete Manifestfile:

<?xml version="1.0" encoding="utf-8"?>
      <manifest package="com.example.appname"
      xmlns:android="http://schemas.android.com/apk/res/android">

<uses-permission android:name="android.permission.INTERNET"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>

            <category android:name="android.intent.category.BROWSABLE" />

            <data android:scheme="com.example.appname"
            android:host="myHost" />

        </intent-filter>
    </activity>
</application>

The app runs fine when installed in emulator, or via ADB on device. The browsable declaration works fine.

Body:
You can declare different intent-filter for different actions.

<activity
    android:name=".MainActivity"
    android:label="@string/app_name">

    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>

    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="http" android:host="www.example.com" android:pathPrefix="/prefix" />
    </intent-filter>

</activity>


问:
File Upload for asp.net in c#
I have been working on an image/file uploader that stores an image to a virtual directory with MapPath or to a database. I have been using if statements for the button click event to check the file and attempt to save but I have not been successful.</p>

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

    if (FileUpload1.HasFile)
    {

        string extension = Path.GetExtension(FileUpload1.FileName);

        if (extension == ".jpg" || extension == ".gif" || extension == ".png" || extension == ".bmp")
        {

            FileUpload1.SaveAs(Server.MapPath("../photos/" + FileUpload1.FileName));

            string imagePath = "/photos/" + FileUpload1.FileName;
</code>```

答:
please try this</p>

```<code>FileUpload1.SaveAs(Server.MapPath(@"~\photos\" + FileUpload1.FileName));
</code>```

Title: File Upload for asp.net in c#

Body:
I have been working on an image/file uploader that stores an image to a virtual directory with MapPath or to a database. I have been using if statements for the button click event to check the file and attempt to save but I have not been successful.

protected void Button1_Click(object sender, EventArgs e)
{

    if (FileUpload1.HasFile)
    {

        string extension = Path.GetExtension(FileUpload1.FileName);

        if (extension == ".jpg" || extension == ".gif" || extension == ".png" || extension == ".bmp")
        {

            FileUpload1.SaveAs(Server.MapPath("../photos/" + FileUpload1.FileName));

            string imagePath = "/photos/" + FileUpload1.FileName;

Body:
please try this

FileUpload1.SaveAs(Server.MapPath(@"~\photos\" + FileUpload1.FileName));


问:
Transform array by cutting in half but extend elements
I want to transform an existing array to display it. Therefore I cut the array in half but add the content of the cut element to the remained elements.

```<code># source structure
s = [[1, 'blue'],
     [2, 'red'],
     [3, 'yellow'],
     [4, 'green'],
     [5, 'orange'],
     [6, 'black']]

# result structure
format_array(s)
# [[1, 'blue', 4, 'green'],
#  [2, 'red', 5, 'orange'],
#  [3, 'yellow', 6, 'black']]
</code>```

How would you achieve it?

答:
Step1: Divide array into two using each_slice method of array. each_slice documentation

Step2: Use array.zip method to map self with corresponding elements of array. zip documentation

Step3: Use flatten to flatten the array. Flatten documentation

```<code>s  => [[1, "blue"], [2, "red"], [3, "yellow"], [4, "green"], [5, "orange"], [6, "black"]]

s1,s2 = s.each_slice((s.length)/2).to_a

==> [[[1, "blue"], [2, "red"], [3, "yellow"]], [[4, "green"], [5, "orange"], [6, "black"]]]

s1.zip(s2).map(&:flatten)

=> [[1, "blue", 4, "green"], [2, "red", 5, "orange"], [3, "yellow", 6, "black"]]
</code>```

Body:
I want to transform an existing array to display it. Therefore I cut the array in half but add the content of the cut element to the remained elements.

# source structure
s = [[1, 'blue'],
     [2, 'red'],
     [3, 'yellow'],
     [4, 'green'],
     [5, 'orange'],
     [6, 'black']]

# result structure
format_array(s)
# [[1, 'blue', 4, 'green'],
#  [2, 'red', 5, 'orange'],
#  [3, 'yellow', 6, 'black']]

How would you achieve it?

Body:
Step1: Divide array into two using each_slice method of array. each_slice documentation

Step2: Use array.zip method to map self with corresponding elements of array. zip documentation

Step3: Use flatten to flatten the array. Flatten documentation

s  => [[1, "blue"], [2, "red"], [3, "yellow"], [4, "green"], [5, "orange"], [6, "black"]]

s1,s2 = s.each_slice((s.length)/2).to_a

==> [[[1, "blue"], [2, "red"], [3, "yellow"]], [[4, "green"], [5, "orange"], [6, "black"]]]

s1.zip(s2).map(&:flatten)

=> [[1, "blue", 4, "green"], [2, "red", 5, "orange"], [3, "yellow", 6, "black"]]


问:
c# call a method with paramaters as a string variable
Hi i want to call a method:

```<code>public string MyMethod($MyVariable)
{
}
</code>```

Where the variable $MyVariable contains all arguments for the function i.e.:

```<code>$MyVariable = "argument1,argument2,argumentn"
</code>```

Is this possible, do i Need Special Syntax?

答:
I can't tell if you want to pass one string containing all parameters, or multiple parameters.

Single parameter

```<code>public void Main()
{
    MyMethod("argument1, argument2, ...");
}

public string MyMethod(string parameters)
{
    Console.Write(parameters);

    return "whatever your string was";
}
</code>```

Output:

argument1, argument2, ...

Multiple parameters

```<code>public void Main()
{
    MyMethod("argument1", "argument2", "...");
}

public string MyMethod(params string[] parameters)
{
    foreach (var parameter in parameters)
    {
        Console.Write(parameter);
    }

    return "whatever your string was";
}
</code>```

Output:

argument1

  argument2

  ...

Body:
Hi i want to call a method:

public string MyMethod($MyVariable)
{
}

Where the variable $MyVariable contains all arguments for the function i.e.:

$MyVariable = "argument1,argument2,argumentn"

Is this possible, do i Need Special Syntax?

Body:
I can't tell if you want to pass one string containing all parameters, or multiple parameters.

Single parameter

public void Main()
{
    MyMethod("argument1, argument2, ...");
}

public string MyMethod(string parameters)
{
    Console.Write(parameters);

    return "whatever your string was";
}

Output:

argument1, argument2, ...

Multiple parameters

public void Main()
{
    MyMethod("argument1", "argument2", "...");
}

public string MyMethod(params string[] parameters)
{
    foreach (var parameter in parameters)
    {
        Console.Write(parameter);
    }

    return "whatever your string was";
}

Output:

argument1

  argument2

  ...


问:
Java EE 8 - MVC 1.0 release date
When I can expect realising full or nearly full version of MVC 1.0.
I'm interesting to continue developing my web app in this technology as I don't like to do my own MVC with Servlets/JSP or use WebForms-like JSF/Facelets. I'm interesting in rather very basic features of MVC 1.0 as I will try to use more HTML5/javascript/angular.js or something like that to create front-end.
I think about developing front-end from half of this year and it may be with beta of MVC 1.0 and production will be at the end of year? when MVC 1.0 will be implemented.
When JBoss will launch their implementation of MVC 1.0 compatible with Wildfly as I'm developing on this and it isn't as easy to switch to glassfish/ozark as I previously thought. </p>

答:
It won't be released as part of Java EE 8 anymore.

Since October 2016 it has been abandoned and at February 2017 the whole spec is transferred to an individual, Ivar Grimstad. See also a.o. this article:

Oracle Transfers Ownership of MVC to the Community

By John K. Waters 02/08/2017

Oracle Corp. is transferring full ownership of the Model-View-Controller (MVC) specification to the Java community, the company announced. Once the transfer is completed, long-time contributor Ivar Grimstad will serve as a purely community spec lead for JSR 371, the MVC 1.0 standard.

The previous MVC spec leads, Oracle's Santiago Pericasgeertsen, and Manfred Riem, announced the initiation of a Transfer Ballot to the Expert Group of the Java Community Process (JCP) on Jan. 17. That ballot closed on January 31st, and the Executive Committee of the JCP approved the transfer. The community will now be responsible for moving the MVC 1.0 spec forward on its own.

[...]

In other words, Ivar Grimstad will now continue developing MVC as a separate library/framework.

Title: Java EE 8 - MVC 1.0 release date


问:
React-native component, adding child as component.button
I want to create a component with the name of 'MyComponent' and also want to add the child elements as < myComponent.Button />. </p>

```<code><MyComponent selected={this.state.activeTab} onSelected={this.onTabSelect}>
   <MyComponent.Button name='child1' text='text1' />
   <MyComponent.Button name='child2' text='text2'/>
   <MyComponent.Button name='child3' text='text3'/>
</myComponent>
</code>```

<p>How to structure component in react-native, so that i can call the component as mentioned above? </p>

答:
I am taking an example from PickerIOS and PickerIOS.Item.

Create your MyComponent component which will render this.props.children like so:

```<code>class MyComponent extends Component {
  render() {
    return this.props.children;
  }
}
</code>```

Then you can create your Button like so

```<code>MyComponent.Button = class extends Component {
  render() {
    return <Button title="Hello" onPress={() => {}} />;
  }
};
</code>```

And then you can declare your components like so

```<code><MyComponent>
  <MyComponent.Button />
</MyComponent>
</code>```

I have taken off some of your props for the purposes of this demonstration.

Body:
I want to create a component with the name of 'MyComponent' and also want to add the child elements as < myComponent.Button />.

<MyComponent selected={this.state.activeTab} onSelected={this.onTabSelect}>
   <MyComponent.Button name='child1' text='text1' />
   <MyComponent.Button name='child2' text='text2'/>
   <MyComponent.Button name='child3' text='text3'/>
</myComponent>

How to structure component in react-native, so that i can call the component as mentioned above?

Body:
I am taking an example from PickerIOS and PickerIOS.Item.

Create your MyComponent component which will render this.props.children like so:

class MyComponent extends Component {
  render() {
    return this.props.children;
  }
}

Then you can create your Button like so

MyComponent.Button = class extends Component {
  render() {
    return <Button title="Hello" onPress={() => {}} />;
  }
};

And then you can declare your components like so

<MyComponent>
  <MyComponent.Button />
</MyComponent>

I have taken off some of your props for the purposes of this demonstration.


问:
jquery onchange event for radio button now instantaneous
I am trying to make an ID active only when a certain type of radio button is selected.  Below is my jQuery code:

```<code>$(document).ready(function() {
   $('#Type').attr('disabled', 'disabled');
   $('input[@name=action]').change(function() {
     if ($("input[@name=action]:checked").val() == 'SomeKind')
        $('#Type').removeAttr('disabled');
     else
        $('#Type').attr('disabled', 'disabled');
    });
});
</code>```

This works as intended but with one flaw.  When I click on the radio button SomeKind it does not make Type active instantaneously, instead I have to click again (anywhere on the page) for Type to be active.

I am on IE7

答:
IE7 has some odd issues with change events and radio buttons, the change event doesn't fire until there's a blur as well. I ran into similar issues once and, after much gnashing off teeth, found this:

http://norman.walsh.name/2009/03/24/jQueryIE

You can use Chinmayee's .click approach (but check and double check that everything works properly when you use the keyboard rather than the mouse) or you can add a click handler to all your radio buttons that blurs and refocuses:

```<code>$(':radio').click(function() {
    try {
        this.blur();
        this.focus();
    }
    catch (e) {}
});
</code>```

You only want this disgusting kludge for IE7 so you'd probably want to wrap it in a conditional comment (a kludge within a kludge). I'm pretty sure IE8's radio buttons have the same problem.

Body:
I am trying to make an ID active only when a certain type of radio button is selected.  Below is my jQuery code:

$(document).ready(function() {
   $('#Type').attr('disabled', 'disabled');
   $('input[@name=action]').change(function() {
     if ($("input[@name=action]:checked").val() == 'SomeKind')
        $('#Type').removeAttr('disabled');
     else
        $('#Type').attr('disabled', 'disabled');
    });
});

This works as intended but with one flaw.  When I click on the radio button SomeKind it does not make Type active instantaneously, instead I have to click again (anywhere on the page) for Type to be active.

I am on IE7

Body:
IE7 has some odd issues with change events and radio buttons, the change event doesn't fire until there's a blur as well. I ran into similar issues once and, after much gnashing off teeth, found this:

http://norman.walsh.name/2009/03/24/jQueryIE

You can use Chinmayee's .click approach (but check and double check that everything works properly when you use the keyboard rather than the mouse) or you can add a click handler to all your radio buttons that blurs and refocuses:

$(':radio').click(function() {
    try {
        this.blur();
        this.focus();
    }
    catch (e) {}
});

You only want this disgusting kludge for IE7 so you'd probably want to wrap it in a conditional comment (a kludge within a kludge). I'm pretty sure IE8's radio buttons have the same problem.


问:
Customise tabs of native base
I need to customise tabs (change their background color ) from native base in my react native application, like shown in the image

I've already tried this  style={{  backgroundColor: '#C0C0C0' }} but i keep getting the default theme.

答:
You can apply, your own style to native base tabs like below.</p>

```<code><Tabs tabBarUnderlineStyle={{borderBottomWidth:2}}>
    <Tab heading="Popular" tabStyle={{backgroundColor: 'red'}} textStyle={{color: '#fff'}} activeTabStyle={{backgroundColor: 'red'}} activeTextStyle={{color: '#fff', fontWeight: 'normal'}}>
        // tab content
    </Tab>
    <Tab heading="Popular" tabStyle={{backgroundColor: 'red'}} textStyle={{color: '#fff'}} activeTabStyle={{backgroundColor: 'red'}} activeTextStyle={{color: '#fff', fontWeight: 'normal'}}>
        // tab content
    </Tab>
</Tabs>
</code>```

Title: Customise tabs of native base

Body:
You can apply, your own style to native base tabs like below.

<Tabs tabBarUnderlineStyle={{borderBottomWidth:2}}>
    <Tab heading="Popular" tabStyle={{backgroundColor: 'red'}} textStyle={{color: '#fff'}} activeTabStyle={{backgroundColor: 'red'}} activeTextStyle={{color: '#fff', fontWeight: 'normal'}}>
        // tab content
    </Tab>
    <Tab heading="Popular" tabStyle={{backgroundColor: 'red'}} textStyle={{color: '#fff'}} activeTabStyle={{backgroundColor: 'red'}} activeTextStyle={{color: '#fff', fontWeight: 'normal'}}>
        // tab content
    </Tab>
</Tabs>


问:
Why need synchronizedMap() if there is ConcurrentHashMap?
I read an article about thread safe maps and got a question. Collections.synchronizedMap() proxies underlying map with adding synchronized blocks on each method. On the other hand ConcurrentHashMap doesn't lock the whole map on read/write operations. Which means all operations in multi thread system are faster.

So what are the benefits of using synchronizedMap() nowadays? I see the only:

it's available since java 1.2 (vs java 1.5 for ConcurrentHashMap)

can store nullable values (if underlying map can do it)

Are there any other situations when synchronizedMap() is better?

答:
I can translate this with help of an anology of a Mutex vs. a Semaphore.

Just like any Mutex, synchronizedMap would allow only one thread at a time to access the backing map. This ensures that no other thread would be able to read/write entries from the map.

And for a ConcurrentHashMap, just like Semaphores we decide a concurrency level i.e. how many threads at one time can actually go and peek entries in your Map.

A research on when to use a Mutex and when to use a Semaphore could help you further clear your doubt.


问:
Find last cell value in array
I'm looking for a vba code to find the last value in an array in a column. It's also possible with the function LOOKUP(C1; A:B) but I would like to do it with VBA. I've already tried to use the function:
x = Application.Worksheetfunction.Lookup(Range("C1"), Range("A:B"))
But it didn't work. The data looks something like this:

A  :  B

1  :  10

1  :  12

2  :  20

2  :  25

2  :  30

3  :  35

3  :  40

4   : 45

4  :  50

4  :    55

So for 1 it has to return 12, for 2 -> 30, for 3 -> 40 and for 4 -> 55.

答:
edited after OP's further request

I guess you may be after this:

```<code>With Range("C1")
    If IsError(Application.Match(.Value, Range("A:A"), 0)) Then
        MsgBox "Sorry, no match for " & .Value & " in column A"
    Else
        Range("H7").Value = Application.VLookup(.Value, Range("A:B"), 2)
    End If
End With
</code>```

Title: Find last cell value in array

Body:
edited after OP's further request

I guess you may be after this:

With Range("C1")
    If IsError(Application.Match(.Value, Range("A:A"), 0)) Then
        MsgBox "Sorry, no match for " & .Value & " in column A"
    Else
        Range("H7").Value = Application.VLookup(.Value, Range("A:B"), 2)
    End If
End With


问:
Serious Bug:Sublime Text break file when remaining harddisk space isn't enought!!! How can I recover it？
When remaining harddisk space wasn't enough,I tried to close a txt，Sublime Text told me that it can't be save.It's no problem,I only update a little sentence, so I don't care if it's saved.Then I closed it.But the next time,I open the txt, it is empty.I lost all the data.(╯‵□′)╯︵┻━┻

I have used this file to note various things for months.It is broken now! How can I recover it？ (There were 200+ lines text in it yesterday T~T...)

OS: MacOS Sierra

SublimeText: Build 3126

The left is broken file, the right is another file(not be broken)

答:
(If you're using Windows):

Find the file on the drive, right-click, and check for "previous versions" of the file. There should be some there, and if one of them opens, you should be fine. And then, maybe make sure that a working drive always have available space...

If on OSX:

You can read it here: support.apple.com/kb/PH18862?locale=en_US
(Basically, open the file in TextEdit (usually just double click in Finder), go to the File or Archive-tab, and chose "revert file" - then you should see other versions).

No guarantees, though


问:
Prevent my Windows App to cause Windows Runtime Broker to run out of Memory
When my Windows 10 app runs, it causes a process called Runtime Broker to execute, which takes up a lot of Memory space.

I know my app isn't "Memory-hungry" and it hardly takes 80 MB of RAM to execute. But from the time it starts, the Memory used by Runtime Broker keeps in increasing until the PC gets stuck.

Upon killing that process, the app is force closed by Windows.

I would have posted my source code here, if only I knew which part of the code is causing this to happen.

What are the possible technical reasons for this problem to happen, and what are the possible fixes in my code to prevent this?

Is there something wrong with my code, or is it some API that I am calling?

答: You can easily delete RuntimeBroker.exe and any other file. I deleted RuntimeBroker.exe and Livecomm.exe by booting a live Linux Dvd and after loading go and mount the c: drive then simply navigate to the file and delete it. Done!</p>


问:
Import Excel file with different attributes from a different class in Ruby on Rails
I want to import excel with different attributes from different class. I have two models Student and Guardian.The problem is when I import File as Student it must get inserted in Student table and when I Import Guardian File it should get inserted in Guardian table. But for now I am not getting how the controller will get that the file selected is file of Student or Guardian. Now when when i write Guardian.import(params[:file]) the file gets inserted in guardian table and when I do Student.import(params[:file]) the file gets inserted in Student table.

controller

```<code>def import
    Guardian.import(params[:file])
    redirect_to import_reports_path, notice: "Students imported."
end
</code>```

model

```<code>def self.import(file)
  spreadsheet = open_spreadsheet(file)
  header = spreadsheet.row(1)
  (2..spreadsheet.last_row).each do |i|
    row = Hash[[header, spreadsheet.row(i)].transpose]
    row = clean_for row, COLUMNS_TO_STRING
    record = Student.find_by(:batch_id =>        row["batch_id"],:class_roll_no => row["class_roll_no"],:phone1 =>   row["phone1"],:phone2 => row["phone2"]) || new
    guardian = Guardian.find_by(:student_id => row["student_id"]) || new
    record.attributes = row.to_hash.slice(*row.to_hash.keys)
    guardian.attributes = row.to_hash.slice(*row.to_hash.keys)
    record.save!
    guardian.save!
  end
 end

def self.clean_for row_as_hash, string_columns_array
  row_as_hash.each do |key, value|
    if string_columns_array.include?key
      row_as_hash[key] = value.to_i.to_s
    end
  end
end

def self.open_spreadsheet(file)
  case File.extname(file.original_filename)
  when ".csv" then Roo::CSV.new(file.path)
  when ".xls" then Roo::Excel.new(file.path)
  when ".xlsx" then Roo::Excelx.new(file.path)
  else raise "Unknown file type: #{file.original_filename}"
end
end
</code>```

view

```<code><h1>IMPORT</h1>
<div class = "well">
<p>

<%= form_tag import_reports_path do %>
    <%= file_field_tag :file%>
   <br>
  <%= submit_tag "Import",class: "btn btn-primary" %>
<% end %>
</p>
</div>
</code>```

答:
I wanted to import excel with different attributes from different class.
Here i found a good way to solve this problem.
As I wanted to maintain a report of student and guardian excel data.
My mistake was I didn't check the report name i.e Student,Guardian There was a mistake in controller

Here is solution to my question:

report_controller.rb

```<code>class ReportsController < ApplicationController
before_action :load_report, only: [:import, :import_form], unless: -> { params[:id].nil? }
def import_form
end

def import
 importer = @report.name == 'Guardian' ? Guardian : Student
 importer.import(params[:file])
 redirect_to import_form_report_path, notice: "#{importer}s imported."
end

private

def load_report
 @report = Report.find_by_id(params[:id])
end
end
</code>```

Change Routes

routes.rb

```<code> member do
      get :import_form
      post :import
    end
</code>```

view

```<code><%= form_tag import_report_path(@report), method: :post, multipart: true do %>
</code>```

link

```<code><td><%= link_to 'IMPORT' , import_form_report_path(report)%></td>
</code>```

The code in student.rb and guardian.rb will remain same as above.

Body:
I want to import excel with different attributes from different class. I have two models Student and Guardian.The problem is when I import File as Student it must get inserted in Student table and when I Import Guardian File it should get inserted in Guardian table. But for now I am not getting how the controller will get that the file selected is file of Student or Guardian. Now when when i write Guardian.import(params[:file]) the file gets inserted in guardian table and when I do Student.import(params[:file]) the file gets inserted in Student table.

controller

def import
    Guardian.import(params[:file])
    redirect_to import_reports_path, notice: "Students imported."
end

model

def self.import(file)
  spreadsheet = open_spreadsheet(file)
  header = spreadsheet.row(1)
  (2..spreadsheet.last_row).each do |i|
    row = Hash[[header, spreadsheet.row(i)].transpose]
    row = clean_for row, COLUMNS_TO_STRING
    record = Student.find_by(:batch_id =>        row["batch_id"],:class_roll_no => row["class_roll_no"],:phone1 =>   row["phone1"],:phone2 => row["phone2"]) || new
    guardian = Guardian.find_by(:student_id => row["student_id"]) || new
    record.attributes = row.to_hash.slice(*row.to_hash.keys)
    guardian.attributes = row.to_hash.slice(*row.to_hash.keys)
    record.save!
    guardian.save!
  end
 end

def self.clean_for row_as_hash, string_columns_array
  row_as_hash.each do |key, value|
    if string_columns_array.include?key
      row_as_hash[key] = value.to_i.to_s
    end
  end
end

def self.open_spreadsheet(file)
  case File.extname(file.original_filename)
  when ".csv" then Roo::CSV.new(file.path)
  when ".xls" then Roo::Excel.new(file.path)
  when ".xlsx" then Roo::Excelx.new(file.path)
  else raise "Unknown file type: #{file.original_filename}"
end
end

view

IMPORT

<%= form_tag import_reports_path do %>
    <%= file_field_tag :file%>

  <%= submit_tag "Import",class: "btn btn-primary" %>
<% end %>

Body:
I wanted to import excel with different attributes from different class.
Here i found a good way to solve this problem.
As I wanted to maintain a report of student and guardian excel data.
My mistake was I didn't check the report name i.e Student,Guardian There was a mistake in controller

Here is solution to my question:

report_controller.rb

class ReportsController < ApplicationController
before_action :load_report, only: [:import, :import_form], unless: -> { params[:id].nil? }
def import_form
end

def import
 importer = @report.name == 'Guardian' ? Guardian : Student
 importer.import(params[:file])
 redirect_to import_form_report_path, notice: "#{importer}s imported."
end

private

def load_report
 @report = Report.find_by_id(params[:id])
end
end

Change Routes

routes.rb

 member do
      get :import_form
      post :import
    end

view

<%= form_tag import_report_path(@report), method: :post, multipart: true do %>

link

<td><%= link_to 'IMPORT' , import_form_report_path(report)%></td>

The code in student.rb and guardian.rb will remain same as above.


问:
Drupal 7 views - how to combine a contextual filter with a regular filter (with OR)?
Ok, so I have a "playlist" content type, with a node reference field and a boolean field called "always display this playlist".

I have a "playlists" view with a contextual filter based on the node reference. So, when I go to "/playlists/35", it shows all the playlists that reference node 35.

All good so far.

One extra requirement is that the view needs to also display all the playlist that have the "always_display_playlist" field set to 1 (that's the boolean field).

So basically the view needs to display playlists that match the contextual filter OR that have the boolean field set to 1.

So far I have failed rather miserably in making that work. The contextual filter works great, but of course it will only display playlists that have the node reference matching the argument. How can I combine the contextual filter with another regular filter, but with "or"?

Thanks a lot for any clue or idea!

答:
Option 1

Consider the Views Contextual Filters OR module, which only has a dev version today. Excerpt from its project page:

... provides a views plugin which modify query to support OR conditions for contextual filters.

Option 2

Otherwise the Views EVI (Exposed Value Injector) module, which only has a beta version today. Excerpt from its project page:

This module solves the fundamental and longstanding problem (#357082: Pull filter value from an argument? & Itangalos Sandbox) of views argument filters (=contextual filters): they are far less potent than regular filters.

It does this by allowing to wire argument tokens to exposed filters and optionally hide them. It also allows new use cases, think: use one exposed widget for two filters.

Credits (for Option 2): Hubert


问:
MyBatis Parameter index out of range
I'm trying to write this query into MyBatis

```<code>    (select * from table1 where field1 like '%"name":"appname"%' limit 1)
    union all
    (select * from table2 where field1 like '%"name":"appname"%' limit 1)
    limit 1
</code>```

So I created this annotation:

```<code>@Select({
    "(select * from table1 where field1 like '%\"name\":\"#{name,jdbcType=VARCHAR}\"%' limit 1)",
    "union all",
    "(select * from table2 where field1 like '%\"name\":\"#{name,jdbcType=VARCHAR}\"%' limit 1)",
    "limit 1"
})
@Results({
    @Result(column="ID", property="id", jdbcType=JdbcType.INTEGER, id=true)
})
Object hasName(@Param("name")String name);
</code>```

But when I run it I'm getting this exception:

Could not set parameters for mapping: ParameterMapping{property='name', mode=IN, javaType=class java.lang.String, jdbcType=VARCHAR, numericScale=null, resultMapId='null', jdbcTypeName='null', expression='null'}. Cause: org.apache.ibatis.type.TypeException: Error setting non null for parameter #1 with JdbcType VARCHAR . Try setting a different JdbcType for this parameter or a different configuration property. Cause: java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).

Can I map the annotation like that or am I missing something? I dont want to use XML for this.

答:
Not exactly your case, but you can get the same error message if you have commented out a line in your query, and that line included parameters, like:</p>
```<code>-- AND (neId=#{neId}))
</code>```

Title: MyBatis Parameter index out of range

Body:
I'm trying to write this query into MyBatis

    (select * from table1 where field1 like '%"name":"appname"%' limit 1)
    union all
    (select * from table2 where field1 like '%"name":"appname"%' limit 1)
    limit 1

So I created this annotation:

@Select({
    "(select * from table1 where field1 like '%\"name\":\"#{name,jdbcType=VARCHAR}\"%' limit 1)",
    "union all",
    "(select * from table2 where field1 like '%\"name\":\"#{name,jdbcType=VARCHAR}\"%' limit 1)",
    "limit 1"
})
@Results({
    @Result(column="ID", property="id", jdbcType=JdbcType.INTEGER, id=true)
})
Object hasName(@Param("name")String name);

But when I run it I'm getting this exception:

Could not set parameters for mapping: ParameterMapping{property='name', mode=IN, javaType=class java.lang.String, jdbcType=VARCHAR, numericScale=null, resultMapId='null', jdbcTypeName='null', expression='null'}. Cause: org.apache.ibatis.type.TypeException: Error setting non null for parameter #1 with JdbcType VARCHAR . Try setting a different JdbcType for this parameter or a different configuration property. Cause: java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).

Can I map the annotation like that or am I missing something? I dont want to use XML for this.

Body:
Not exactly your case, but you can get the same error message if you have commented out a line in your query, and that line included parameters, like:

-- AND (neId=#{neId}))


问:
C# adding random values "string" to a column in database
I have been adding random values to my database using the following Statement in visual studio and it works just fine for two values.

```<code>  Random rd;
  TextBox_Language.Text = rd.Next(2) == 0 ? "EN" : "FR";
</code>```

Now I need to have more than just two strings and I have tried the bellow Code, but that doesn't work. Any one got a hint on how to get around with it?

```<code> TextBox_Language.Text = rd.Next(3) == 0 ? "EN" : "FR" : "DE"; // doesn't work
</code>```

答:
You can use a temporary variable and then cascade the ? : operator.

```<code>int temp = rd.Next(3);
TextBox_Language.Text = temp == 0 ? "EN" : temp == 1 ? "FR" : "DE";
</code>```

Body:
I have been adding random values to my database using the following Statement in visual studio and it works just fine for two values.

  Random rd;
  TextBox_Language.Text = rd.Next(2) == 0 ? "EN" : "FR";

Now I need to have more than just two strings and I have tried the bellow Code, but that doesn't work. Any one got a hint on how to get around with it?

 TextBox_Language.Text = rd.Next(3) == 0 ? "EN" : "FR" : "DE"; // doesn't work

Body:
You can use a temporary variable and then cascade the ? : operator.

int temp = rd.Next(3);
TextBox_Language.Text = temp == 0 ? "EN" : temp == 1 ? "FR" : "DE";


问:
Accessing Table without primary Key -Spring data jpa
I am using spring data jpa and I have to port an existing application to Spring boot.

I am encountered with the database table which does not have the primary key column. How can I write the entity without @Id annotation.

If am trying, I am getting error :

```<code>Caused by: org.hibernate.AnnotationException: No identifier specified for entity: com.example.domain.Employee
    at org.hibernate.cfg.InheritanceState.getElementsToProcess(InheritanceState.java:243) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:775) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.cfg.Configuration$MetadataSourceQueue.processAnnotatedClassesQueue(Configuration.java:3845) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.cfg.Configuration$MetadataSourceQueue.processMetadata(Configuration.java:3799) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1412) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1846) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:857) ~[hibernate-entitymanager-4.3.11.Final.jar:4.3.11.Final]
    ... 29 common frames omitted
</code>```

Is there any way to use this without modifying the existing database?

答:
Even if the underlying table does not have an explicit primary key specified, I am sure there is at least one column that is defined as unique (or has a unique index specified for it).

You can add the @Id annotation to the entity field relevant to that column and  that will the sufficient for the persistence provider. You probably would not want to specify any generator of course.

If you happen to have a few unique columns which could form a sort of natural key then you can specify a composite key using the @EmbeddedId strategy or the @IdClass strategy in your entity.

Body:
I am using spring data jpa and I have to port an existing application to Spring boot.

I am encountered with the database table which does not have the primary key column. How can I write the entity without @Id annotation.

If am trying, I am getting error :

Caused by: org.hibernate.AnnotationException: No identifier specified for entity: com.example.domain.Employee
    at org.hibernate.cfg.InheritanceState.getElementsToProcess(InheritanceState.java:243) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:775) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.cfg.Configuration$MetadataSourceQueue.processAnnotatedClassesQueue(Configuration.java:3845) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.cfg.Configuration$MetadataSourceQueue.processMetadata(Configuration.java:3799) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1412) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1846) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:857) ~[hibernate-entitymanager-4.3.11.Final.jar:4.3.11.Final]
    ... 29 common frames omitted

Is there any way to use this without modifying the existing database?


问:
Is the input of `tf.image.resize_images` must have static shape?
I run the code below, it raises an ValueError: 'images' contains no shape. Therefore I have to add the line behind # to set the static shape, but img_raw may have different shapes and this line makes the tf.image.resize_images out of effect.
I just want to turn images with different shapes to [227,227,3]. How should I do that?

```<code>def tf_read(file_queue):
    reader = tf.WholeFileReader()
    file_name, content = reader.read(file_queue)
    img_raw = tf.image.decode_image(content,3)
    # img_raw.set_shape([227,227,3])
    img_resized = tf.image.resize_images(img_raw,[227,227])
    img_shape = tf.shape(img_resized)
    return file_name, img_resized,img_shape
</code>```

答:
No, tf.image.resize_images can handle dynamic shape

```<code>file_queue = tf.train.string_input_producer(['./dog1.jpg'])
# shape of dog1.jpg is (720, 720)

reader = tf.WholeFileReader()
file_name, content = reader.read(file_queue)
img_raw = tf.image.decode_jpeg(content, 3) # size (?, ?, 3)  <= dynamic h and w
# img_raw.set_shape([227,227,3])
img_resized = tf.image.resize_images(img_raw, [227, 227])
img_shape = tf.shape(img_resized)

with tf.Session() as sess:
    print img_shape.eval() #[227, 227, 3]
</code>```

BTW, I am using tf v0.12, and there is no function called tf.image.decode_image, but I don't think it is important

Body:
I run the code below, it raises an ValueError: 'images' contains no shape. Therefore I have to add the line behind # to set the static shape, but img_raw may have different shapes and this line makes the tf.image.resize_images out of effect.
I just want to turn images with different shapes to [227,227,3]. How should I do that?

def tf_read(file_queue):
    reader = tf.WholeFileReader()
    file_name, content = reader.read(file_queue)
    img_raw = tf.image.decode_image(content,3)
    # img_raw.set_shape([227,227,3])
    img_resized = tf.image.resize_images(img_raw,[227,227])
    img_shape = tf.shape(img_resized)
    return file_name, img_resized,img_shape

Body:
No, tf.image.resize_images can handle dynamic shape

file_queue = tf.train.string_input_producer(['./dog1.jpg'])
# shape of dog1.jpg is (720, 720)

reader = tf.WholeFileReader()
file_name, content = reader.read(file_queue)
img_raw = tf.image.decode_jpeg(content, 3) # size (?, ?, 3)  <= dynamic h and w
# img_raw.set_shape([227,227,3])
img_resized = tf.image.resize_images(img_raw, [227, 227])
img_shape = tf.shape(img_resized)

with tf.Session() as sess:
    print img_shape.eval() #[227, 227, 3]

BTW, I am using tf v0.12, and there is no function called tf.image.decode_image, but I don't think it is important


问:
What is the best way to avoid getting "Emacs Pinky"?
I just started using GNU Emacs as my text editor and I am concerned about getting afflicted with "Emacs Pinky" by having to constantly press the control key with my pinky finger as is required when using Emacs. How can I avoid potentially getting this type of repetitive strain injury?</p>

答:
For the love of God - use another text editor! If it's something that requires a foot pedal to work with it normally, then... well... frankly, I'm speechless. There is a multitude of powerful contemporary text editors out there that don't require you to memorize volumes of arcane keystrokes or buy fancy hardware.

You know, I can understand and accept a lot of things, but a foot pedal for a simple text editor is really where I draw the line.

OwnerDisplayName: Ray Vega

OwnerDisplayName: Vilx-


问:
Get EOFException while reading serialized object in Java
I have two methods, one that serialize the Object, and it works ok:

```<code>public void record()throws RecordingException
    {
        ObjectOutputStream outputStream = null;
        try
        {
            outputStream = new ObjectOutputStream(new FileOutputStream("src/data/employee.dat"));
            outputStream.writeObject(this);
        } catch (FileNotFoundException ex)
        {
            ex.printStackTrace();
            throw new RecordingException(ex);
        } catch (IOException ex)
        {
            ex.printStackTrace();
            throw new RecordingException(ex);
        }finally
        {
            try
            {
                if (outputStream != null) outputStream.close();
            } catch (IOException ex){}
        }
    }
</code>```

The problem here when deserializing the object, I get EOFException!:

```<code>public final User loadObject(UserType usertype) throws InvalidLoadObjectException
    {
        ObjectInputStream istream = null;
        String path = null;
        if (usertype == UserType.EMPLOYEE)
        {
            path = "data/employee.dat";
        }else if (usertype == UserType.CUSTOMER)
        {
            path = "data/customer.dat";
        }else
            throw new InvalidLoadObjectException("Object is not a sub class of User");

        try
        {
            istream = new ObjectInputStream(ObjectLoader.class.getClassLoader().getResourceAsStream(path));

            User u = loadObject(istream);
            istream.close();
            return u;
        }catch (EOFException ex)
        {
            System.out.println(ex.getMessage());
            return null;
        }catch(Exception ex)
        {
            ex.printStackTrace();
            throw new InvalidLoadObjectException(ex);
        }
    }

private User loadObject(ObjectInputStream stream) throws InvalidLoadObjectException
    {
        try
        {
            return (User) stream.readObject();
        } catch (IOException ex)
        {
            ex.printStackTrace();
            throw new InvalidLoadObjectException(ex);
        } catch (ClassNotFoundException ex)
        {
            ex.printStackTrace();
            throw new InvalidLoadObjectException(ex);
        }
    }
</code>```

答: Try outputStream.flush() before closing your stream in serialization object.

Body:
I have two methods, one that serialize the Object, and it works ok:

public void record()throws RecordingException
    {
        ObjectOutputStream outputStream = null;
        try
        {
            outputStream = new ObjectOutputStream(new FileOutputStream("src/data/employee.dat"));
            outputStream.writeObject(this);
        } catch (FileNotFoundException ex)
        {
            ex.printStackTrace();
            throw new RecordingException(ex);
        } catch (IOException ex)
        {
            ex.printStackTrace();
            throw new RecordingException(ex);
        }finally
        {
            try
            {
                if (outputStream != null) outputStream.close();
            } catch (IOException ex){}
        }
    }

The problem here when deserializing the object, I get EOFException!:

public final User loadObject(UserType usertype) throws InvalidLoadObjectException
    {
        ObjectInputStream istream = null;
        String path = null;
        if (usertype == UserType.EMPLOYEE)
        {
            path = "data/employee.dat";
        }else if (usertype == UserType.CUSTOMER)
        {
            path = "data/customer.dat";
        }else
            throw new InvalidLoadObjectException("Object is not a sub class of User");

        try
        {
            istream = new ObjectInputStream(ObjectLoader.class.getClassLoader().getResourceAsStream(path));

            User u = loadObject(istream);
            istream.close();
            return u;
        }catch (EOFException ex)
        {
            System.out.println(ex.getMessage());
            return null;
        }catch(Exception ex)
        {
            ex.printStackTrace();
            throw new InvalidLoadObjectException(ex);
        }
    }

private User loadObject(ObjectInputStream stream) throws InvalidLoadObjectException
    {
        try
        {
            return (User) stream.readObject();
        } catch (IOException ex)
        {
            ex.printStackTrace();
            throw new InvalidLoadObjectException(ex);
        } catch (ClassNotFoundException ex)
        {
            ex.printStackTrace();
            throw new InvalidLoadObjectException(ex);
        }
    }


问:
How do I change the distance between text and underline in TimePicker?
There is currently 12 pixels between the text and underline for timepicker and I want to set it to 7 pixels.

```<code><materialDesign:TimePicker  SelectedTime="{Binding LabCase.AptTime}" />
</code>```

In resource dictionary I have made these changes to style:

```<code><Style TargetType="materialDesign:TimePicker" BasedOn="{StaticResource {x:Type materialDesign:TimePicker}}">
     <Setter Property="HorizontalAlignment" Value="Left" />
     <Setter Property="MinWidth" Value="200" />
     <Setter Property="materialDesign:HintAssist.Hint" Value="" />
     <Setter Property="Margin" Value="0,-3,0,0" />
</Style>
</code>```

Padding didn't work

```<code><Setter Property="Padding" Value="0,7,0,0"/>
</code>```

https://github.com/ButchersBoy/MaterialDesignInXamlToolkit/blob/master/MaterialDesignThemes.Wpf/Themes/MaterialDesignTheme.TimePicker.xaml

It seems like margin is the problem but I can't see to override it when I can override everything else

答:
Add height in you app.xaml and verify it. It worked for me. You can increase or decrease height to set text at your desired position.</p>

```<code>      <Style TargetType="materialDesign:TimePicker" BasedOn="{StaticResource {x:Type materialDesign:TimePicker}}">
            <Setter Property="HorizontalAlignment" Value="Left" />
            <Setter Property="MinWidth" Value="200" />
            <Setter Property="materialDesign:HintAssist.Hint" Value="" />
            <Setter Property="Margin" Value="0,-3,0,0" />
            <Setter Property="Height" Value="22" />
        </Style>
</code>```

Body:
There is currently 12 pixels between the text and underline for timepicker and I want to set it to 7 pixels.

<materialDesign:TimePicker  SelectedTime="{Binding LabCase.AptTime}" />

In resource dictionary I have made these changes to style:

Padding didn't work

<Setter Property="Padding" Value="0,7,0,0"/>

https://github.com/ButchersBoy/MaterialDesignInXamlToolkit/blob/master/MaterialDesignThemes.Wpf/Themes/MaterialDesignTheme.TimePicker.xaml

It seems like margin is the problem but I can't see to override it when I can override everything else

Body:
Add height in you app.xaml and verify it. It worked for me. You can increase or decrease height to set text at your desired position.

      <Style TargetType="materialDesign:TimePicker" BasedOn="{StaticResource {x:Type materialDesign:TimePicker}}">
            <Setter Property="HorizontalAlignment" Value="Left" />
            <Setter Property="MinWidth" Value="200" />
            <Setter Property="materialDesign:HintAssist.Hint" Value="" />
            <Setter Property="Margin" Value="0,-3,0,0" />
            <Setter Property="Height" Value="22" />
        </Style>


问:
convert month name to month number when date is not given
From my UI Iam getting string like 'March 2017' and I want first date of this month in c#.net.how can I achieve this?In jquery calendar only months are visible.so only Iam getting 'March 2017'

I have tried this-

```<code>string pattern = "MM-dd-yy";
DateTime parsedDate;

DateTime.TryParseExact(txtDate.Text.Trim(), pattern, null, DateTimeStyles.None, out parsedDate);
</code>```

答:
You should use proper format string. MMMM represents long month name (just like "March" or "April"). yyyy represents full (4-digit) year. Returned date will be first day of the given month, just like you need:

```<code>DateTime parsedDate = DateTime.ParseExact(txtDate.Text.Trim(), "MMMM yyyy", CultureInfo.InvariantCulture);
// or CultureInfo.CurrentCulture, depending on requirements.
</code>```

Or with TryParseExact:

```<code>DateTime parsedDate;
if (DateTime.TryParseExact(txtDate.Text.Trim(), "MMMM yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate)) {
    // do stuff
}
</code>```

If month names are always in english (like "March") - use CultureInfo.InvariantCulture. Otherwise - use appropriate culture.

Body:
From my UI Iam getting string like 'March 2017' and I want first date of this month in c#.net.how can I achieve this?In jquery calendar only months are visible.so only Iam getting 'March 2017'

I have tried this-

string pattern = "MM-dd-yy";
DateTime parsedDate;

DateTime.TryParseExact(txtDate.Text.Trim(), pattern, null, DateTimeStyles.None, out parsedDate);

Body:
You should use proper format string. MMMM represents long month name (just like "March" or "April"). yyyy represents full (4-digit) year. Returned date will be first day of the given month, just like you need:

DateTime parsedDate = DateTime.ParseExact(txtDate.Text.Trim(), "MMMM yyyy", CultureInfo.InvariantCulture);
// or CultureInfo.CurrentCulture, depending on requirements.

Or with TryParseExact:

DateTime parsedDate;
if (DateTime.TryParseExact(txtDate.Text.Trim(), "MMMM yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate)) {
    // do stuff
}

If month names are always in english (like "March") - use CultureInfo.InvariantCulture. Otherwise - use appropriate culture.