问:
Analyzing spikes in performance measurement
I have a set of  C++ functions which does some image processing related operation. Generally I see that the final output is delivered in 5-6ms time range. I am measuring the time taken using QueryPerformanceCounter Win32 API. But when running in a continuous loop with 100 images, I see that the performance spikes up to 20ms for some images. My question is how do I go about analyzing such issues. Basically I want to determine whether the spikes are caused due to some delay in this code or whether some other task started running inside the CPU because of which this operation took time. I have tried using GetThreadTimes API to see how much time my thread spent inside CPU but am unable to conclude based on those numbers. What is the standard way to go about troubleshooting these types of issues?

答:
That's a nasty thing you are trying to figure out, I wouldn'd even attempt to, since coming into concrete conlusions is hard.

In general, one should run a loop of many iterations (100 just seems too small I think), and then take the average time for an image to be processed.

That will rule out any unexpected exterior events that may have hurt performance of your program.

A typical way to check if "some other task started running inside the CPU" would be to run your program once and mark the images that produce that spike. Example, image 2, 4, 5, and 67 take too long to be processed. Run your program again some times, and mark again which images produce the spikes.

If the same images produce these spikes, then it's not something caused by another exterior task.


来源: stackexchange

问:
Integer Value Right Padding in SQL
Step1: I have a table called XYZ which contains following integer columns:

```<code> ID      A          B          C
 1    201507    20150810   20150311
 2    20150812  201509     201510
</code>```

I need to write a SQL query where if any values of A, B, and C is smaller than 8 digits then I need to consider it as 8 digits by adding zeros to the right of the value for step2 (I am not allowed to update the table.). For example:

```<code> ID      A            B          C
 1    20150700    20150810   20150311
 2    20150812    20150900   20151000
</code>```

How to add zeros to the right of the integer values through SQL query?

Step 2: I need to find for each record A<B, B<C or not. Please let me know how to write the query. I am using PostgreSQL. Thank you.

答:
You can use rpad() to add trailing zeros, then cast the result back to an integer:

```<code>select id,
       rpad(a::text, 8, '0')::int,
       rpad(b::text, 8, '0')::int,
       rpad(c::text, 8, '0')::int
from the_table;
</code>```

To avoid repeating the expressions, use a derived table:

```<code>select *
from (
  select id,
         rpad(a::text, 8, '0')::int as a,
         rpad(b::text, 8, '0')::int as b,
         rpad(c::text, 8, '0')::int as c
  from the_table
) t
where a < b or b < c --<< change that to the condition you want
</code>```

ContentLicense: CC BY-SA 3.0

Title: Integer Value Right Padding in SQL

Body:
Step1: I have a table called XYZ which contains following integer columns:

 ID      A          B          C
 1    201507    20150810   20150311
 2    20150812  201509     201510

I need to write a SQL query where if any values of A, B, and C is smaller than 8 digits then I need to consider it as 8 digits by adding zeros to the right of the value for step2 (I am not allowed to update the table.). For example:

 ID      A            B          C
 1    20150700    20150810   20150311
 2    20150812    20150900   20151000

How to add zeros to the right of the integer values through SQL query?

Step 2: I need to find for each record A<B, B<C or not. Please let me know how to write the query. I am using PostgreSQL. Thank you.

Body:
You can use rpad() to add trailing zeros, then cast the result back to an integer:

select id,
       rpad(a::text, 8, '0')::int,
       rpad(b::text, 8, '0')::int,
       rpad(c::text, 8, '0')::int
from the_table;

To avoid repeating the expressions, use a derived table:

select *
from (
  select id,
         rpad(a::text, 8, '0')::int as a,
         rpad(b::text, 8, '0')::int as b,
         rpad(c::text, 8, '0')::int as c
  from the_table
) t
where a < b or b < c --<< change that to the condition you want


问:
Cant access uploaded files (flv&images) in drupal
I have a custom upload field with a content type which allows to upload flv files. And I have jw player in my theme which plays it for me. Everything works fine in my localhost.
But after uploading it show Access Denied or File not found Error.

I checked the permission of files folder, it seems to be ok. Directly typing the link to the file also returns page not found.

What is the problem? What can be done?
I tried with absolute url using print $base_url and also tried with print $base_path both of which work really well in localhost.

Update: even the thumbnail of image_cache or any uploaded images are not accessible. This is kind of weird. I cant figure this out.

.htacess is same in localhost and server. But why only in server I cant access? I checked
the log and its show pagenotfound error for all attempts.

My .htaccess file :

```<code>> #
> # Apache/PHP/Drupal settings:
> #
> # Protect files and directories from prying eyes. <FilesMatch
> "\.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl|svn-base)$|^(code-style\.pl|Entries.*|Repository|Root|Tag|Template|all-wcprops|entries|format)$">
> Order allow,deny </FilesMatch>
> # Don't show directory listings for URLs which map to a directory. Options
> -Indexes
>
>
>
> # Make Drupal handle any 404 errors. ErrorDocument 404 /index.php
>
> # Force simple error message for requests for non-existent favicon.ico.
> <Files favicon.ico>   # There is no
> end quote below, for compatibility
> with Apache 1.3.   ErrorDocument 404
> "The requested file favicon.ico was
> not found. </Files>
>
> # Set the default handler. DirectoryIndex index.php
>
> # Override PHP settings. More in sites/default/settings.php
> # but the following cannot be changed at runtime.
>
> # PHP 4, Apache 1. <IfModule mod_php4.c>   php_value
> magic_quotes_gpc                0
> php_value register_globals
> 0   php_value session.auto_start
> 0   php_value mbstring.http_input
> pass   php_value mbstring.http_output
> pass   php_value
> mbstring.encoding_translation   0
> </IfModule>
>
> # PHP 4, Apache 2. <IfModule sapi_apache2.c>   php_value
> magic_quotes_gpc                0
> php_value register_globals
> 0   php_value session.auto_start
> 0   php_value mbstring.http_input
> pass   php_value mbstring.http_output
> pass   php_value
> mbstring.encoding_translation   0
> </IfModule>
>
> # PHP 5, Apache 1 and 2. <IfModule mod_php5.c>   php_value
> magic_quotes_gpc                0
> php_value register_globals
> 0   php_value session.auto_start
> 0   php_value mbstring.http_input
> pass   php_value mbstring.http_output
> pass   php_value
> mbstring.encoding_translation   0
> </IfModule>
>
> # Requires mod_expires to be enabled. <IfModule mod_expires.c>   # Enable
> expirations.   ExpiresActive On
>
>   # Cache all files for 2 weeks after
> access (A).   ExpiresDefault A1209600
>
>   <FilesMatch \.php$>
>     # Do not allow PHP scripts to be cached unless they explicitly send
> cache
>     # headers themselves. Otherwise all scripts would have to overwrite
> the
>     # headers set by mod_expires if they want another caching behavior.
> This may
>     # fail if an error occurs early in the bootstrap process, and it may
> cause
>     # problems if a non-Drupal PHP file is installed in a subdirectory.
>     ExpiresActive Off   </FilesMatch> </IfModule>
>
> # Various rewrite rules. <IfModule mod_rewrite.c>   RewriteEngine on
>
>   # If your site can be accessed both
> with and without the 'www.' prefix,
> you   # can use one of the following
> settings to redirect users to your
> preferred   # URL, either WITH or
> WITHOUT the 'www.' prefix. Choose ONLY
> one option:   #   # To redirect all
> users to access the site WITH the
> 'www.' prefix,   #
> (http://example.com/... will be
> redirected to
> http://www.example.com/...)   # adapt
> and uncomment the following:   #
> RewriteCond %{HTTP_HOST}
> ^example\.com$ [NC]   # RewriteRule
> ^(.*)$ http://www.example.com/$1
> [L,R=301]   #   # To redirect all
> users to access the site WITHOUT the
> 'www.' prefix,   #
> (http://www.example.com/... will be
> redirected to http://example.com/...)
> # uncomment and adapt the following:   # RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]   #
> RewriteRule ^(.*)$
> http://example.com/$1 [L,R=301]
>
>   # Modify the RewriteBase if you are
> using Drupal in a subdirectory or in a
> # VirtualDocumentRoot and the rewrite rules are not working properly.   #
> For example if your site is at
> http://example.com/drupal uncomment
> and   # modify the following line:   #
> RewriteBase /drupal   #   # If your
> site is running in a
> VirtualDocumentRoot at
> http://example.com/,   # uncomment the
> following line:   # RewriteBase /
>
>   # Rewrite URLs of the form 'x' to
> the form 'index.php?q=x'.
> RewriteCond %{REQUEST_FILENAME} !-f
> RewriteCond %{REQUEST_FILENAME} !-d
> RewriteCond %{REQUEST_URI}
> !=/favicon.ico   RewriteRule ^(.*)$
> index.php?q=$1 [L,QSA] </IfModule>
>
> # $Id: .htaccess,v 1.90.2.5 2010/02/02 07:25:22 dries Exp $
</code>```

.htacess in the file directory:

```<code>> SetHandler
> Drupal_Security_Do_Not_Remove_See_SA_2006_006
> Options None Options -FollowSymLinks
</code>```

答:
Check to make sure you uploaded the .htaccess file to Drupal's root directory.

Is your site running at the root of the domain or in a subdirectory? If it's in a subdirectory, you may need to set RewriteBase in the .htaccess file.

Check the Admin > Reports > Status reports page to see if there are any error messages.

Check the Admin > Reports > Recent log entries for any additional errors.

ContentLicense: CC BY-SA 2.5

Body:
I have a custom upload field with a content type which allows to upload flv files. And I have jw player in my theme which plays it for me. Everything works fine in my localhost.
But after uploading it show Access Denied or File not found Error.

I checked the permission of files folder, it seems to be ok. Directly typing the link to the file also returns page not found.

What is the problem? What can be done?
I tried with absolute url using print $base_url and also tried with print $base_path both of which work really well in localhost.

Update: even the thumbnail of image_cache or any uploaded images are not accessible. This is kind of weird. I cant figure this out.

.htacess is same in localhost and server. But why only in server I cant access? I checked
the log and its show pagenotfound error for all attempts.

My .htaccess file :

> #
> # Apache/PHP/Drupal settings:
> #
> # Protect files and directories from prying eyes. <FilesMatch
> "\.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl|svn-base)$|^(code-style\.pl|Entries.*|Repository|Root|Tag|Template|all-wcprops|entries|format)$">
> Order allow,deny </FilesMatch>
> # Don't show directory listings for URLs which map to a directory. Options
> -Indexes
>
>
>
> # Make Drupal handle any 404 errors. ErrorDocument 404 /index.php
>
> # Force simple error message for requests for non-existent favicon.ico.
> <Files favicon.ico>   # There is no
> end quote below, for compatibility
> with Apache 1.3.   ErrorDocument 404
> "The requested file favicon.ico was
> not found. </Files>
>
> # Set the default handler. DirectoryIndex index.php
>
> # Override PHP settings. More in sites/default/settings.php
> # but the following cannot be changed at runtime.
>
> # PHP 4, Apache 1. <IfModule mod_php4.c>   php_value
> magic_quotes_gpc                0
> php_value register_globals
> 0   php_value session.auto_start
> 0   php_value mbstring.http_input
> pass   php_value mbstring.http_output
> pass   php_value
> mbstring.encoding_translation   0
> </IfModule>
>
> # PHP 4, Apache 2. <IfModule sapi_apache2.c>   php_value
> magic_quotes_gpc                0
> php_value register_globals
> 0   php_value session.auto_start
> 0   php_value mbstring.http_input
> pass   php_value mbstring.http_output
> pass   php_value
> mbstring.encoding_translation   0
> </IfModule>
>
> # PHP 5, Apache 1 and 2. <IfModule mod_php5.c>   php_value
> magic_quotes_gpc                0
> php_value register_globals
> 0   php_value session.auto_start
> 0   php_value mbstring.http_input
> pass   php_value mbstring.http_output
> pass   php_value
> mbstring.encoding_translation   0
> </IfModule>
>
> # Requires mod_expires to be enabled. <IfModule mod_expires.c>   # Enable
> expirations.   ExpiresActive On
>
>   # Cache all files for 2 weeks after
> access (A).   ExpiresDefault A1209600
>
>   <FilesMatch \.php$>
>     # Do not allow PHP scripts to be cached unless they explicitly send
> cache
>     # headers themselves. Otherwise all scripts would have to overwrite
> the
>     # headers set by mod_expires if they want another caching behavior.
> This may
>     # fail if an error occurs early in the bootstrap process, and it may
> cause
>     # problems if a non-Drupal PHP file is installed in a subdirectory.
>     ExpiresActive Off   </FilesMatch> </IfModule>
>
> # Various rewrite rules. <IfModule mod_rewrite.c>   RewriteEngine on
>
>   # If your site can be accessed both
> with and without the 'www.' prefix,
> you   # can use one of the following
> settings to redirect users to your
> preferred   # URL, either WITH or
> WITHOUT the 'www.' prefix. Choose ONLY
> one option:   #   # To redirect all
> users to access the site WITH the
> 'www.' prefix,   #
> (http://example.com/... will be
> redirected to
> http://www.example.com/...)   # adapt
> and uncomment the following:   #
> RewriteCond %{HTTP_HOST}
> ^example\.com$ [NC]   # RewriteRule
> ^(.*)$ http://www.example.com/$1
> [L,R=301]   #   # To redirect all
> users to access the site WITHOUT the
> 'www.' prefix,   #
> (http://www.example.com/... will be
> redirected to http://example.com/...)
> # uncomment and adapt the following:   # RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]   #
> RewriteRule ^(.*)$
> http://example.com/$1 [L,R=301]
>
>   # Modify the RewriteBase if you are
> using Drupal in a subdirectory or in a
> # VirtualDocumentRoot and the rewrite rules are not working properly.   #
> For example if your site is at
> http://example.com/drupal uncomment
> and   # modify the following line:   #
> RewriteBase /drupal   #   # If your
> site is running in a
> VirtualDocumentRoot at
> http://example.com/,   # uncomment the
> following line:   # RewriteBase /
>
>   # Rewrite URLs of the form 'x' to
> the form 'index.php?q=x'.
> RewriteCond %{REQUEST_FILENAME} !-f
> RewriteCond %{REQUEST_FILENAME} !-d
> RewriteCond %{REQUEST_URI}
> !=/favicon.ico   RewriteRule ^(.*)$
> index.php?q=$1 [L,QSA] </IfModule>
>
> # $Id: .htaccess,v 1.90.2.5 2010/02/02 07:25:22 dries Exp $

.htacess in the file directory:

> SetHandler
> Drupal_Security_Do_Not_Remove_See_SA_2006_006
> Options None Options -FollowSymLinks


问:
Making C code plot a graph automatically
I have written a program which writes a list of data to a '.dat' file with the intention of then plotting it separately using gnuplot.  Is there a way of making my code plot it automatically?  My output is of the form:

```<code>x-coord    analytic    approximation
x-coord    analytic    approximation
x-coord    analytic    approximation
x-coord    analytic    approximation
x-coord    analytic    approximation
 ....
</code>```

Ideally, when I run the code the graph would also be printed with an x-label, y-label and title (which could be changed from my C code).  Many thanks.

答:
I've adapted the accepted answer to plot a float array while avoiding the use of a temporary file. In it, float* data_ is the array and size_t size_ its size. Hopefully it is helpful for someone!

Cheers,

Andres

```<code>void plot(const char* name="FloatSignal"){
  // open persistent gnuplot window
  FILE* gnuplot_pipe = popen ("gnuplot -persistent", "w");
  // basic settings
  fprintf(gnuplot_pipe, "set title '%s'\n", name);
  // fill it with data
  fprintf(gnuplot_pipe, "plot '-'\n");
  for(size_t i=0; i<size_; ++i){
    fprintf(gnuplot_pipe, "%zu %f\n", i, data_[i]);
  }
  fprintf(gnuplot_pipe, "e\n");
  // refresh can probably be omitted
  fprintf(gnuplot_pipe, "refresh\n");
}
</code>```

Body:
I have written a program which writes a list of data to a '.dat' file with the intention of then plotting it separately using gnuplot.  Is there a way of making my code plot it automatically?  My output is of the form:

x-coord    analytic    approximation
x-coord    analytic    approximation
x-coord    analytic    approximation
x-coord    analytic    approximation
x-coord    analytic    approximation
 ....

Ideally, when I run the code the graph would also be printed with an x-label, y-label and title (which could be changed from my C code).  Many thanks.

Body:
I've adapted the accepted answer to plot a float array while avoiding the use of a temporary file. In it, float* data_ is the array and size_t size_ its size. Hopefully it is helpful for someone!

Cheers,

Andres

void plot(const char* name="FloatSignal"){
  // open persistent gnuplot window
  FILE* gnuplot_pipe = popen ("gnuplot -persistent", "w");
  // basic settings
  fprintf(gnuplot_pipe, "set title '%s'\n", name);
  // fill it with data
  fprintf(gnuplot_pipe, "plot '-'\n");
  for(size_t i=0; i<size_; ++i){
    fprintf(gnuplot_pipe, "%zu %f\n", i, data_[i]);
  }
  fprintf(gnuplot_pipe, "e\n");
  // refresh can probably be omitted
  fprintf(gnuplot_pipe, "refresh\n");
}


问:
Java Taking Multiple Line Input
How do I go about taking input that is multiple lines, such as

```<code>4 2 9
1 4 2
9 8 5
</code>```

and placing it into an array of that is big enough to hold each line with no empty positions, or an arraylist. I've tried many ways to do this and cannot find a solution.
For example, if the user copied and pasted the above snippet as input, I want an array or arraylist to hold

```<code>["4 2 9", "1 4 2", "9 8 5"]
</code>```

答:
try this:</p>

```<code>List<String> list = new ArrayList<String>();
 while((str = in.readLine()) != null){
 list.add(str);
}
</code>```

Title: Java Taking Multiple Line Input

Body:
How do I go about taking input that is multiple lines, such as

4 2 9
1 4 2
9 8 5

and placing it into an array of that is big enough to hold each line with no empty positions, or an arraylist. I've tried many ways to do this and cannot find a solution.
For example, if the user copied and pasted the above snippet as input, I want an array or arraylist to hold

["4 2 9", "1 4 2", "9 8 5"]

Body:
try this:

List<String> list = new ArrayList<String>();
 while((str = in.readLine()) != null){
 list.add(str);
}


问:
How to run a foreground scheduled task in ASP.NET MVC?
I've this code in my ASP.NET MVC application to share a value across the application.

```<code>public static class Global
{
    public static string Token { get; private set; };

    public static void LoadFromFile()
    {
        // loads Token value from a settings file
    }
}
</code>```

What I want to do is to run LoadFromFile method once a day to update the Token value.

I can't use a separate background task like in HangFire, since I want to update the value for current running application.

How can I do it? thanks.

Update:
Mates who think this is a duplicate, please read the question. I want to update the shared value in current running application. changing it in in a separate  background task won't change it for current application.

答:
To help SO wandering polices rest a while, I got the answer.

I can run a scheduled background task to access an endpoint in my site, and from there update the static Token value.

Body:
I've this code in my ASP.NET MVC application to share a value across the application.

public static class Global
{
    public static string Token { get; private set; };

    public static void LoadFromFile()
    {
        // loads Token value from a settings file
    }
}

What I want to do is to run LoadFromFile method once a day to update the Token value.

I can't use a separate background task like in HangFire, since I want to update the value for current running application.

How can I do it? thanks.

Update:
Mates who think this is a duplicate, please read the question. I want to update the shared value in current running application. changing it in in a separate  background task won't change it for current application.


问:
Pelican: join Tags with comma
I create a static website by Pelican, and currently in the theme the keywords is created from tag, like:

```<code>{% for tag in articles.tags %}
<meta name="keywords" content="{{ tag }}"/>
{% endfor %}
</code>```

In this case, there will be multiple lines.
What I want is one line with the tag joining by ',', just like: <meta name="keywords" content="word1,word2,word3"/>.

Thanks.

答:
As i understand it right, Pelican uses Jinja template engine.

So this will do:

```<code><meta name="keywords" content="{{ articles.tags|join(',') }}"/>
</code>```

Documentation for this build-in filter: join()

Title: Pelican: join Tags with comma

Body:
I create a static website by Pelican, and currently in the theme the keywords is created from tag, like:

{% for tag in articles.tags %}
<meta name="keywords" content="{{ tag }}"/>
{% endfor %}

In this case, there will be multiple lines.
What I want is one line with the tag joining by ',', just like: <meta name="keywords" content="word1,word2,word3"/>.

Thanks.

Body:
As i understand it right, Pelican uses Jinja template engine.

So this will do:

<meta name="keywords" content="{{ articles.tags|join(',') }}"/>

Documentation for this build-in filter: join()


问:
Data from a Column, only if another Column has the correct requirements, to go into Sheet 2
I have a basic knowledge of excel, but I need more than basic to achieve what I'm trying to do. Here is what I'm trying to do.

Sheet 1 has 3 Columns - A) Price, B) Month, & C) Category

```<code>             Rows - Unlimited
</code>```

Sheet 2 has 13 Columns - A) Creditor, B) Jan, C) Feb, D) Mar ....

```<code>             Rows - Unlimited
</code>```

What I need is first of all is "Sheet 1, Column B (Month)" to go under the correct Column on "Sheet 2". Second, I want anything in "Sheet 1, Column A" to go into "Sheet 2, under the correct Month Column" only if the "Sheet 1, Column C" has the correct Category #.

I have try a lot of different types of formulas & functions that I can think of, but nothing will work.  As I said before, I have a very very very basic knowledge of excel.  Any help will be very greatly appreciated.

答:
This can be done using a Pivot Table.

Use the data in sheet 1 as its source, use the category for the rows, the month for the columns, and the sum of the prices for the content.

Initially you might get some (sub)totals you didn't ask for, but you can change that using the context menu.

Body:
I have a basic knowledge of excel, but I need more than basic to achieve what I'm trying to do. Here is what I'm trying to do.

Sheet 1 has 3 Columns - A) Price, B) Month, & C) Category

             Rows - Unlimited

Sheet 2 has 13 Columns - A) Creditor, B) Jan, C) Feb, D) Mar ....

             Rows - Unlimited

What I need is first of all is "Sheet 1, Column B (Month)" to go under the correct Column on "Sheet 2". Second, I want anything in "Sheet 1, Column A" to go into "Sheet 2, under the correct Month Column" only if the "Sheet 1, Column C" has the correct Category #.

I have try a lot of different types of formulas & functions that I can think of, but nothing will work.  As I said before, I have a very very very basic knowledge of excel.  Any help will be very greatly appreciated.


问:
How to handle empty URL parameter in react router dom (4.xx)
I have route defined as below :

```<code><Route path='/result/:searchTerm' component={Result}/>
</code>```

It works fine. For example localhost:3000/result/cat page works. But when the user decided to remove the :searchTerm from the URL and opens just localhost:3000/result/ it shows empty page. No errors or anything. Just empty page. It is not even hitting my component {Result} too.

So my doubt is how to handle this scenario.? Say I want to redirect the user who tries to open /result/ without :searchTerms to my index page.? How to do that.?

答:
Switch is a component used to render routes exclusively. So, in general, at the end of children inside Switch, you can provide a default route (in your case the index page) for any path that you don't explicitly specify in other routes.

Eg:

```<code>        <Switch>
          <Route exact path='/'
            component={()=>(<Redirect to='/index'/>)}/>
          <Route exact path='/index' component={Index}/>
          <Route path='/result/:searchTerm' component={Result}/>
          .
          .
          // default route, gets rendered if none of the above match:
          <Route component={NotFound404}/>
        </Switch>
</code>```

Body:
I have route defined as below :

<Route path='/result/:searchTerm' component={Result}/>

It works fine. For example localhost:3000/result/cat page works. But when the user decided to remove the :searchTerm from the URL and opens just localhost:3000/result/ it shows empty page. No errors or anything. Just empty page. It is not even hitting my component {Result} too.

So my doubt is how to handle this scenario.? Say I want to redirect the user who tries to open /result/ without :searchTerms to my index page.? How to do that.?

Body:
Switch is a component used to render routes exclusively. So, in general, at the end of children inside Switch, you can provide a default route (in your case the index page) for any path that you don't explicitly specify in other routes.

Eg:

        <Switch>
          <Route exact path='/'
            component={()=>(<Redirect to='/index'/>)}/>
          <Route exact path='/index' component={Index}/>
          <Route path='/result/:searchTerm' component={Result}/>
          .
          .
          // default route, gets rendered if none of the above match:
          <Route component={NotFound404}/>
        </Switch>


问:
Javascript - Check numeric range overlapping in array
I have an array of time ranges with start & end values.

```<code>var timeRanges = [{
    start: 120,
    end: 140
},{
    start: 180,
    end: 220
},{
    start: 250,
    end: 300
}]
</code>```

Need to check whether the selected range overlap the time range or not. And also the selected range should be in between the timeRange intervals. (Ex: 140-180, 220-250)

```<code>var selected = {
    start: 150,
    end: 170
}
</code>```

答:
Assuming that your time ranges are sorted, this solution will work. Otherwise, you need to implement time range sorting as well.</p>

```<code>function isValidRange(timeRanges, selectedRange) {
var isValid = true;
var minStart = timeRanges[0].start;
var maxEnd = timeRanges[timeRanges.length - 1].end;

if(selectedRange.start < selectedRange.end && selectedRange.start > minStart && selectedRange.end < maxEnd) {
    for(var i=0; i<timeRanges.length; i++) {
        if((selectedRange.start >= timeRanges[i].start && selectedRange.start <= timeRanges[i].end)
        || (selectedRange.end >= timeRanges[i].start && selectedRange.end <= timeRanges[i].end)) {
            isValid = false;
            break;
        }
        else if(i != timeRanges.length - 1) {
            if(selectedRange.start > timeRanges[i].end && selectedRange.start < timeRanges[i+1].start) {
                if(selectedRange.end < timeRanges[i+1].start) {
                    break;
                }
                else {
                    isValid = false;
                    break;
                }
            }
        }
    }
}
else {
    isValid = false;
}
return isValid;
}

var timeRanges = [{
    start: 120,
    end: 140
},{
    start: 180,
    end: 220
},{
    start: 250,
    end: 300
}];

var selected = {
    start: 141,
    end: 222
};

alert(isValidRange(timeRanges, selected));
</code>```

Body:
I have an array of time ranges with start & end values.

var timeRanges = [{
    start: 120,
    end: 140
},{
    start: 180,
    end: 220
},{
    start: 250,
    end: 300
}]

Need to check whether the selected range overlap the time range or not. And also the selected range should be in between the timeRange intervals. (Ex: 140-180, 220-250)

var selected = {
    start: 150,
    end: 170
}

Body:
Assuming that your time ranges are sorted, this solution will work. Otherwise, you need to implement time range sorting as well.

function isValidRange(timeRanges, selectedRange) {
var isValid = true;
var minStart = timeRanges[0].start;
var maxEnd = timeRanges[timeRanges.length - 1].end;

if(selectedRange.start < selectedRange.end && selectedRange.start > minStart && selectedRange.end < maxEnd) {
    for(var i=0; i<timeRanges.length; i++) {
        if((selectedRange.start >= timeRanges[i].start && selectedRange.start <= timeRanges[i].end)
        || (selectedRange.end >= timeRanges[i].start && selectedRange.end <= timeRanges[i].end)) {
            isValid = false;
            break;
        }
        else if(i != timeRanges.length - 1) {
            if(selectedRange.start > timeRanges[i].end && selectedRange.start < timeRanges[i+1].start) {
                if(selectedRange.end < timeRanges[i+1].start) {
                    break;
                }
                else {
                    isValid = false;
                    break;
                }
            }
        }
    }
}
else {
    isValid = false;
}
return isValid;
}

var timeRanges = [{
    start: 120,
    end: 140
},{
    start: 180,
    end: 220
},{
    start: 250,
    end: 300
}];

var selected = {
    start: 141,
    end: 222
};

alert(isValidRange(timeRanges, selected));


问:
All possible permutations in factor variable when ties exist in R
I have a data frame with rows sorted by values of variable x. If there are ties in values of x (like values 50 and 60 in the example below), I need all possible permutations of values in variable group. How can I achieve this in R? Is there a specialized function?

Initial data:

```<code>x  group
45     A
50     A
50     A
50     B
52     A
60     A
60     B
70     B
88     B
</code>```

Desired result:

```<code>x  group group2 group3 group4 group5 group6
45     A      A      A      A      A      A
50     A      A      B      A      A      B
50     A      B      A      A      B      A
50     B      A      A      B      A      A
52     A      A      A      A      A      A
60     A      A      A      B      B      B
60     B      B      B      A      A      A
70     B      B      B      B      B      B
88     B      B      B      B      B      B
</code>```

答:
Just another (cleaner) solution. The idea is to compute all the permutations for each tie and calculate the number of copies needed for combining.</p>

```<code>df <- structure(list(x = c(45L, 50L, 50L, 50L, 52L, 60L, 60L, 70L,
88L), group = structure(c(1L, 1L, 1L, 2L, 1L, 1L, 2L, 2L, 2L), .Label = c("A",
"B"), class = "factor")), .Names = c("x", "group"), class = "data.frame", row.names = c(NA,
-9L))

library(tidyverse)
library(iterpc)

ux <- unique(df$x)
m <- length(ux)
members <- ux %>% map(~ filter(df, x == .)) %>%
    map(~ getall(iterpc(table(as.character(.$group)), ordered = TRUE)))
nrs <- members %>% map_int(nrow)
members <- members %>%
    imap(~.x[rep(seq_len(nrow(.x)), prod(tail(nrs, m-.y)) , each = prod(head(nrs, .y-1))), , drop=FALSE])
data.frame(x = df$x, t(do.call(cbind, members)))
#>    x X1 X2 X3 X4 X5 X6
#> 1 45  A  A  A  A  A  A
#> 2 50  A  A  B  A  A  B
#> 3 50  A  B  A  A  B  A
#> 4 50  B  A  A  B  A  A
#> 5 52  A  A  A  A  A  A
#> 6 60  A  A  A  B  B  B
#> 7 60  B  B  B  A  A  A
#> 8 70  B  B  B  B  B  B
#> 9 88  B  B  B  B  B  B
</code>```

Body:
I have a data frame with rows sorted by values of variable x. If there are ties in values of x (like values 50 and 60 in the example below), I need all possible permutations of values in variable group. How can I achieve this in R? Is there a specialized function?

Initial data:

x  group
45     A
50     A
50     A
50     B
52     A
60     A
60     B
70     B
88     B

Desired result:

x  group group2 group3 group4 group5 group6
45     A      A      A      A      A      A
50     A      A      B      A      A      B
50     A      B      A      A      B      A
50     B      A      A      B      A      A
52     A      A      A      A      A      A
60     A      A      A      B      B      B
60     B      B      B      A      A      A
70     B      B      B      B      B      B
88     B      B      B      B      B      B

Body:
Just another (cleaner) solution. The idea is to compute all the permutations for each tie and calculate the number of copies needed for combining.

df <- structure(list(x = c(45L, 50L, 50L, 50L, 52L, 60L, 60L, 70L,
88L), group = structure(c(1L, 1L, 1L, 2L, 1L, 1L, 2L, 2L, 2L), .Label = c("A",
"B"), class = "factor")), .Names = c("x", "group"), class = "data.frame", row.names = c(NA,
-9L))

library(tidyverse)
library(iterpc)

ux <- unique(df$x)
m <- length(ux)
members <- ux %>% map(~ filter(df, x == .)) %>%
    map(~ getall(iterpc(table(as.character(.$group)), ordered = TRUE)))
nrs <- members %>% map_int(nrow)
members <- members %>%
    imap(~.x[rep(seq_len(nrow(.x)), prod(tail(nrs, m-.y)) , each = prod(head(nrs, .y-1))), , drop=FALSE])
data.frame(x = df$x, t(do.call(cbind, members)))
#>    x X1 X2 X3 X4 X5 X6
#> 1 45  A  A  A  A  A  A
#> 2 50  A  A  B  A  A  B
#> 3 50  A  B  A  A  B  A
#> 4 50  B  A  A  B  A  A
#> 5 52  A  A  A  A  A  A
#> 6 60  A  A  A  B  B  B
#> 7 60  B  B  B  A  A  A
#> 8 70  B  B  B  B  B  B
#> 9 88  B  B  B  B  B  B


问:
ASP.Net JSON configuration file transforms with arrays
I have a base configuration file eg.

appsettings.json

```<code>{
    "Values": {
        "Test": ["one", "two"]
    }
}
</code>```

and

appsettings.dev.json

```<code>{
    "Values": {
        "Test": ["three"]
    }
}
</code>```

and after transforming, the array would be

```<code>["three", "two"]
</code>```

How do I make sure the transformed array is shrunk to a smaller number of elements rather than each element changing individually?

答:
@Matt in my opinion it's just an unnecessary logic. Flow 'KISS'.

appsettings.json should contain only common settings. If your production mode or development mode must have some same values in one key, just duplicate their. Like appsettings.Development.json

```<code>"Values": {
        "Test": ["one", "two"]
    }
</code>```

and appsettings.Production.json

```<code>"Values": {
        "Test": ["one", "two","three"]
    }
</code>```

And if you need same values for both modes you should put it in appsettings.json.

```<code>"SomeValues": {
        "Test": ["1", "2","3"]
    }
</code>```

In final settings you will have for production

```<code>"SomeValues": {
        "Test": ["1", "2","3"]
    },
"Values": {
        "Test": ["one", "two","three"]
    }
</code>```

and for development

```<code>"SomeValues": {
        "Test": ["1", "2","3"]
    },
"Values": {
        "Test": ["one", "two"]
    }
</code>```

anyway If previous  answer solve your problem it's ok, it's just my opinion. Thanks)

Body:
I have a base configuration file eg.

appsettings.json

{
    "Values": {
        "Test": ["one", "two"]
    }
}

and

appsettings.dev.json

{
    "Values": {
        "Test": ["three"]
    }
}

and after transforming, the array would be

["three", "two"]

How do I make sure the transformed array is shrunk to a smaller number of elements rather than each element changing individually?

Body:
@Matt in my opinion it's just an unnecessary logic. Flow 'KISS'.

appsettings.json should contain only common settings. If your production mode or development mode must have some same values in one key, just duplicate their. Like appsettings.Development.json

"Values": {
        "Test": ["one", "two"]
    }

and appsettings.Production.json

"Values": {
        "Test": ["one", "two","three"]
    }

And if you need same values for both modes you should put it in appsettings.json.

"SomeValues": {
        "Test": ["1", "2","3"]
    }

In final settings you will have for production

"SomeValues": {
        "Test": ["1", "2","3"]
    },
"Values": {
        "Test": ["one", "two","three"]
    }

and for development

"SomeValues": {
        "Test": ["1", "2","3"]
    },
"Values": {
        "Test": ["one", "two"]
    }

anyway If previous  answer solve your problem it's ok, it's just my opinion. Thanks)


问:
Object Normalization
In the same line as Database Normalization - is there an approach to object normalization, not design pattern, but the same mathematical like approach to normalizing object creation.  For example: first normal form: no repeating fields....
here's some links to DB Normalization:

http://en.wikipedia.org/wiki/Database_normalization
  http://databases.about.com/od/specificproducts/a/normalization.htm

Would this make object creation and self-documentation better?

Here's a link to a book about class normalization (guess we're really talking about classes)
http://www.agiledata.org/essays/classNormalization.html

答:
Object oriented design is rational but it does not have the same mathematically well-defined basis as the Relational Model. There is nothing exactly equivalent to the well-defined normal forms of database design. </p>

<p>Whether this is a strength or a weakness of Object oriented design is a matter of interpretation. </p>

OwnerDisplayName: meade

Title: Object Normalization

LastEditorDisplayName: meade

Body:
Object oriented design is rational but it does not have the same mathematically well-defined basis as the Relational Model. There is nothing exactly equivalent to the well-defined normal forms of database design.

Whether this is a strength or a weakness of Object oriented design is a matter of interpretation.

OwnerDisplayName: Joe Solbrig


问:
How to visualize a project structure in MATLAB?
I've come into ownership of several thousand lines of Matlab code, some as >900 line functions and a few directories full of function_name.m files.  It's hard to figure out what everything is doing (or relating to) or figure out the dependencies.  What would you suggest to visualize the functions structure, such as what functions are called from which, and in what sequence?

答:
some suggestions on Matlab coding convention:

use addpath to avert file cluttering and assist in functions taxnomony

break up section_ for functional scripts or set for conditional runs, this can also help in plug-in/ out modules and re-use or code referencing.

use a config file to turn on and off the options

have an overview of the architectural set up of the constructs, as well as the modus operandi

keep a status/ readme file ( treat yourself as a new-user, how would you assist in making it assimilable as part of a new-user's own module or part of the solutions seamlessly? if you come back to the code 3 months later feeling lost or unable to trace - something is wrong.) My suggestion: keep a journal to refine your thoughts on maintaining artful projects. Keep perfecting your art!

for equations, use latex for documentations (and keep it in a nearby folder titled eg. documents, ensure they are easily accessible and traceable - if you have to use 'search' over your drive, something is wrong with the project management)

break up codes into short modules for localization and shorter codes, with less scrolling, the codes will be easier to trace.

use meaningful variables and function names (java style seems nice, eg. 'backedupDataForVerification'), do not stint to shorten the words, you will suffer later

in designing, re-think if you should use function, scripting, or OO (object oriented)

do not haste on premature optimatization, for speed matlab is not the best choice. If you really must, keep a none optimized version for side-to-side readibility comparison, troubleshooting and debug will not be less of a curse.

Always, always, always comment your codes. Never use the excuse of having no time, you'll waste more time later.

for differentiation, consider setting a new node for code modifications, eg. set a tree to differentiate the versions.

use a separate folder for inputs/ outputs, images, intermediate results, etc.

use timestamp to trace your versions

share your codes with someone else, if they find it difficult to maintain, use or modify, rethink on how to refine your builds.


问:
DropShadowEffect WPF
I am new to WPF/XAML coding. I am trying to add a drop shadow effect to a Rectangle shape. The XAML for the rectangle is:

CODE 1

```<code><Rectangle HorizontalAlignment="Left" Height="552" Margin="2,10,0,0"
             VerticalAlignment="Top" Width="427" StrokeThickness="4"
             Fill="#FF484A4D" Grid.Column="1"/>
</code>```

The code for DropShadowEffect is:

CODE 2

```<code><Rectangle.Effect>
    <DropShadowEffect x:name="Dshadow" BlurRadius="10" ShadowDepth="0" Color="Black"/>
</Rectangle.Effect>
</code>```

The problem is, I can't combine/use these two codes together. When I arrange CODE 2 after CODE 1, it doesn't work. How should I fix/arrange these codes?

答:
The Rectangle.Effect has to be declared inside the Rectangle component tag.

<Rectangle>
    <Rectangle.Effect>
        <DropShadowEffect BlurRadius="10" ShadowDepth="0" Color="Black"/>
    </Rectangle.Effect>
</Rectangle>
```
<p>Alternatively, you can declare a <strong>Style</strong> tag in your XAML which can be reused for the components again and again. Below is an example of a style sheet, which will automatically add the effect to all Rectangles in the XAML.</p>
```<Window.Resources>

    </Style>
</Window.Resources>
```

Title: DropShadowEffect WPF

Body:
I am new to WPF/XAML coding. I am trying to add a drop shadow effect to a Rectangle shape. The XAML for the rectangle is:

CODE 1

<Rectangle HorizontalAlignment="Left" Height="552" Margin="2,10,0,0"
             VerticalAlignment="Top" Width="427" StrokeThickness="4"
             Fill="#FF484A4D" Grid.Column="1"/>

The code for DropShadowEffect is:

CODE 2

<Rectangle.Effect>
    <DropShadowEffect x:name="Dshadow" BlurRadius="10" ShadowDepth="0" Color="Black"/>
</Rectangle.Effect>

The problem is, I can't combine/use these two codes together. When I arrange CODE 2 after CODE 1, it doesn't work. How should I fix/arrange these codes?

Body:
The Rectangle.Effect has to be declared inside the Rectangle component tag.

<Rectangle>
    <Rectangle.Effect>
        <DropShadowEffect BlurRadius="10" ShadowDepth="0" Color="Black"/>
    </Rectangle.Effect>
</Rectangle>

Alternatively, you can declare a Style tag in your XAML which can be reused for the components again and again. Below is an example of a style sheet, which will automatically add the effect to all Rectangles in the XAML.

<Window.Resources>
   <Style TargetType="{x:Type Rectangle}">
        <Setter Property="Effect">
            <Setter.Value>
                <DropShadowEffect x:Name="shadowEffectButton" Color="Black" ShadowDepth="0" BlurRadius="5"/>
            </Setter.Value>
        </Setter>

       <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">

                <Trigger.EnterActions>
                    <BeginStoryboard>
                        <Storyboard>
                            <DoubleAnimation Storyboard.TargetProperty="Effect.ShadowDepth" From="0" To="3" Duration="0:0:0.5"/>
                        </Storyboard>
                    </BeginStoryboard>
                </Trigger.EnterActions>

                <Trigger.ExitActions>
                    <BeginStoryboard>
                        <Storyboard>
                            <DoubleAnimation Storyboard.TargetProperty="Effect.ShadowDepth" From="3" To="0" Duration="0:0:0.5"/>
                        </Storyboard>
                    </BeginStoryboard>
                </Trigger.ExitActions>

            </Trigger>
        </Style.Triggers>
    </Style>
</Window.Resources>

ContentLicense: CC BY-SA 4.0


答:
You can use Scanner to read the input from console.

Try something like this:

```<code>public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    List<String> list = new ArrayList<String>();

    while(scan.hasNextLine()) {
        String str = scan.nextLine();
        System.out.println(str);
        list.add(str);
    }

    System.out.println(java.util.Arrays.toString(list.toArray()));

    scan.close();
}
</code>```

Title: Java Taking Multiple Line Input

Body:
How do I go about taking input that is multiple lines, such as

4 2 9
1 4 2
9 8 5

and placing it into an array of that is big enough to hold each line with no empty positions, or an arraylist. I've tried many ways to do this and cannot find a solution.
For example, if the user copied and pasted the above snippet as input, I want an array or arraylist to hold

["4 2 9", "1 4 2", "9 8 5"]

Body:
You can use Scanner to read the input from console.

Try something like this:

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    List<String> list = new ArrayList<String>();

    while(scan.hasNextLine()) {
        String str = scan.nextLine();
        System.out.println(str);
        list.add(str);
    }

    System.out.println(java.util.Arrays.toString(list.toArray()));

    scan.close();
}


问:
 element adding a random space after word
I'm using Angular4 and I'm noticing this really weird issue where one of my span elements adds an extra space to the end of a word like this:

The only CSS properties being set are font-family, -webkit-font-smoothing, line-height and box-sizing.

I tried changing the word-spacing and white-space properties but that did not work either. I've never encountered this issue before so any advice would be helpful

答: Try adding in your css : padding-right: 0px; display: inline-block;

Title: <span> element adding a random space after word


问:
Textfields component number validation React js
I have 3 Textfields, what I want to do is just to accept number so if someone put text and click continue the application should display an error saying that just numbers are allowed.

The following code displays an error message if the Textfield is empty and thats ok but the other validation to check if the user inputs text or numbers is pending and I'm stucked.

```<code>import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import Divider from 'material-ui/Divider';

import cr from '../styles/general.css';

export default class Example extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      buy_: '',
      and_: '',
      save_: '',

    };
    this.handleChange = this.handleChange.bind(this);

  }

  handleChange(event, index, value) {
    this.setState({value});
  }

  clear() {
    console.info('Click on clear');
    this.setState({
      buy_: '',
      and_: '',
      save_: ''
    });
  }

  validate() {
    let isError = false;
    const errors = {
      descriptionError: ''
    };

    if (this.state.buy_.length < 1 || this.state.buy_ === null) {
      isError = true;
      errors.buy_error = 'Field requiered';
    }
    if (this.state.and_.length < 1 || this.state.and_ === null) {
      isError = true;
      errors.and_error = 'Field requiered';
    }
    if (this.state.save_.length < 1 || this.state.save_ === null) {
      isError = true;
      errors.save_error = 'Field requiered';
    }

    this.setState({
      ...this.state,
      ...errors
    });

    return isError;
  }

  onSubmit(e){
    e.preventDefault();
    // this.props.onSubmit(this.state);
    console.log('click onSubmit')
    const err = this.validate();
    if (!err) {
      // clear form
      this.setState({
        buy_error: '',
        and_error: '',
        save_error: ''
      });
      this.props.onChange({
        buy_: '',
        and_: '',
        save_: ''
      });
    }
  }

  render() {

    return (
      <div className={cr.container}>
        <div className ={cr.boton}>
          <Divider/>
          <br/>
        </div>

        <div className={cr.rows}>
          <div>
            <TextField
              onChange={(e) => {this.setState({buy_: e.target.value})}}
              value={this.state.buy_}
              errorText={this.state.buy_error}
              floatingLabelText="Buy"
            />
          </div>
          <div>
            <TextField
              onChange={(e) => {this.setState({and_: e.target.value})}}
              value={this.state.and_}
              errorText={this.state.and_error}
              floatingLabelText="And"
            />
          </div>
          <div>
            <TextField
              onChange={(e) => {this.setState({save_: e.target.value})}}
              value={this.state.save_}
              errorText={this.state.save_error}
              floatingLabelText="Save"
            />
          </div>
        </div>

        <div className={cr.botonSet}>
          <div className={cr.botonMargin}>
            <RaisedButton
              label="Continue"
              onClick={e => this.onSubmit(e)}/>
          </div>
          <div>
            <RaisedButton
              label="Clear"
              secondary ={true}
              onClick={this.clear = this.clear.bind(this)}
            />
          </div>
        </div>
      </div>
    );
  }
}
</code>```

Can someone help me on this please.

Thanks in advance.

答:
Try adding this code in your validate function.

You can use regex to validate your fields for text or numbers like :

```<code>  import * as RegExp from './RegExpression';

  validate() {
    let isError = false;
    const errors = {
      descriptionError: ''
    };

    if (this.state.buy_ && !RegExp.NAME.test(this.state.buy_)) {
      // validation check if input is name
      isError = true;
      errors.buy_error = 'Invalid name';
    }
    if (this.state.and_ && !RegExp.NUMBER.test(this.state.and_)) {
      // validation check if input is number
      isError = true;
      errors.and_error = 'Invalid Number';
    }

    this.setState({
      ...this.state,
      ...errors
    });

    return isError;
  }
</code>```

In RegexExpression file add these validations like this :

```<code> export const NAME = /^[a-z ,.'-()"-]+$/i;
 export const NUMBER = /^[0-9]*$/ ;
</code>```

Body:
I have 3 Textfields, what I want to do is just to accept number so if someone put text and click continue the application should display an error saying that just numbers are allowed.

The following code displays an error message if the Textfield is empty and thats ok but the other validation to check if the user inputs text or numbers is pending and I'm stucked.

import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import Divider from 'material-ui/Divider';

import cr from '../styles/general.css';

export default class Example extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      buy_: '',
      and_: '',
      save_: '',

    };
    this.handleChange = this.handleChange.bind(this);

  }

  handleChange(event, index, value) {
    this.setState({value});
  }

  clear() {
    console.info('Click on clear');
    this.setState({
      buy_: '',
      and_: '',
      save_: ''
    });
  }

  validate() {
    let isError = false;
    const errors = {
      descriptionError: ''
    };

    if (this.state.buy_.length < 1 || this.state.buy_ === null) {
      isError = true;
      errors.buy_error = 'Field requiered';
    }
    if (this.state.and_.length < 1 || this.state.and_ === null) {
      isError = true;
      errors.and_error = 'Field requiered';
    }
    if (this.state.save_.length < 1 || this.state.save_ === null) {
      isError = true;
      errors.save_error = 'Field requiered';
    }

    this.setState({
      ...this.state,
      ...errors
    });

    return isError;
  }

  onSubmit(e){
    e.preventDefault();
    // this.props.onSubmit(this.state);
    console.log('click onSubmit')
    const err = this.validate();
    if (!err) {
      // clear form
      this.setState({
        buy_error: '',
        and_error: '',
        save_error: ''
      });
      this.props.onChange({
        buy_: '',
        and_: '',
        save_: ''
      });
    }
  }

  render() {

    return (

          <Divider/>

            <TextField
              onChange={(e) => {this.setState({buy_: e.target.value})}}
              value={this.state.buy_}
              errorText={this.state.buy_error}
              floatingLabelText="Buy"
            />

            <TextField
              onChange={(e) => {this.setState({and_: e.target.value})}}
              value={this.state.and_}
              errorText={this.state.and_error}
              floatingLabelText="And"
            />

            <TextField
              onChange={(e) => {this.setState({save_: e.target.value})}}
              value={this.state.save_}
              errorText={this.state.save_error}
              floatingLabelText="Save"
            />

            <RaisedButton
              label="Continue"
              onClick={e => this.onSubmit(e)}/>

            <RaisedButton
              label="Clear"
              secondary ={true}
              onClick={this.clear = this.clear.bind(this)}
            />

    );
  }
}

Can someone help me on this please.

Thanks in advance.

Body:
Try adding this code in your validate function.

You can use regex to validate your fields for text or numbers like :

  import * as RegExp from './RegExpression';

  validate() {
    let isError = false;
    const errors = {
      descriptionError: ''
    };

    if (this.state.buy_ && !RegExp.NAME.test(this.state.buy_)) {
      // validation check if input is name
      isError = true;
      errors.buy_error = 'Invalid name';
    }
    if (this.state.and_ && !RegExp.NUMBER.test(this.state.and_)) {
      // validation check if input is number
      isError = true;
      errors.and_error = 'Invalid Number';
    }

    this.setState({
      ...this.state,
      ...errors
    });

    return isError;
  }

In RegexExpression file add these validations like this :

 export const NAME = /^[a-z ,.'-()"-]+$/i;
 export const NUMBER = /^[0-9]*$/ ;


问:
How can I dynamically create a new .java file from a Java program?
I want to create a one .java from the Java program.  When I run the program, automatically one Java file will created in my project, and also create some run time (dynamic) variable in that file.  How can I do this?

I know for this I have to use a Reflection API like Class and Method, but what are the methods in Class and Method to do this?

答:
Java is a strongly typed language( As opposed to a weakly typed language). Simply put you need to have a Class (prototype) to create a instance of object. What you are trying to do is not natural in java (or any strongly typed language).

If you have to have this functionality in java, you need to use groovy. Groovy is a dynamic language that can run in Java JVM. You need to check Expandos in groovy.(ofcourse it still will not create a .java file).


问:
Control-drag in Xcode gives outlets, but no action for UIButton. Why?
In my app I'm building, I've got a Navigation Controller with a View Controller connected as a subview (is that the right word?). I added a UIButton and tried to Control-drag it into my view controller class file, but it's only giving me Outlet and Outlet collection as my options, not Action.

Screenshot of what I'm seeing

It's a pretty simple app, and I've tried removing my Pods as a fix, but so far no luck.

I've also tried manually writing the function and trying to connect it back to the button, but to no avail. Dragging back to the button in the workspace doesn't work, and the function isn't firing when I test the app. Here's the code I tried:

```<code>@IBAction func tapSaveButton(_ sender: UIButton) {}
</code>```

It's probably something simple, so what am I missing here?

EDIT: Also, here's how I'm set up. I have a Navigation Controller with a UINavigationItem that shows a sub ViewController. The button in question is in the sub ViewController and I setup a new swift file to handle that ViewController's class. I'm trying to connect that button into that class file, and that's where it's not working.

Screenshot of my storyboard

Here's my ViewController class's code:

```<code>import Foundation
import UIKit
import KeychainSwift

class SettingsViewController : UIViewController {

    let keychain = KeychainSwift()

    @IBOutlet weak var APIKeyField: UITextField!
    @IBOutlet weak var WebSocketIPField: UITextField!
    @IBOutlet weak var SettingsSaveButton: UIButton!

    override func viewDidAppear(_ animated: Bool)  {
        super.viewDidAppear(animated)

        /* My other code, not related */
    }

    @IBAction func tapSaveButton(_ sender: UIButton) {

        // My button actions here.

    }

}
</code>```

答: It's also happen with me, when i added localization in my project, from that time which storyboard was added in localization, that storyboard buttons are not showing any action option, only showing outlet options.</p>

Body:
In my app I'm building, I've got a Navigation Controller with a View Controller connected as a subview (is that the right word?). I added a UIButton and tried to Control-drag it into my view controller class file, but it's only giving me Outlet and Outlet collection as my options, not Action.

Screenshot of what I'm seeing

It's a pretty simple app, and I've tried removing my Pods as a fix, but so far no luck.

I've also tried manually writing the function and trying to connect it back to the button, but to no avail. Dragging back to the button in the workspace doesn't work, and the function isn't firing when I test the app. Here's the code I tried:

@IBAction func tapSaveButton(_ sender: UIButton) {}

It's probably something simple, so what am I missing here?

EDIT: Also, here's how I'm set up. I have a Navigation Controller with a UINavigationItem that shows a sub ViewController. The button in question is in the sub ViewController and I setup a new swift file to handle that ViewController's class. I'm trying to connect that button into that class file, and that's where it's not working.

Screenshot of my storyboard

Here's my ViewController class's code:

import Foundation
import UIKit
import KeychainSwift

class SettingsViewController : UIViewController {

    let keychain = KeychainSwift()

    @IBOutlet weak var APIKeyField: UITextField!
    @IBOutlet weak var WebSocketIPField: UITextField!
    @IBOutlet weak var SettingsSaveButton: UIButton!

    override func viewDidAppear(_ animated: Bool)  {
        super.viewDidAppear(animated)

        /* My other code, not related */
    }

    @IBAction func tapSaveButton(_ sender: UIButton) {

        // My button actions here.

    }

}


问:
Not able to parse variable other than string using Moya in swift
I am working on an iOS project in Swift. I used Moya framework for API handling and parsing. It works perfectly. But when I try to parse varibles other than string it shows me en error:

"Missing argument for parameter 'transformation' in call"

Here is my mapper class

```<code>import Mapper

class MyMapperClaa:Mappable {
    var dateVariable: NSDate?

    required init(map: Mapper) throws{
        try dateVariable = map.from("date")
    }
}
</code>```

答:
Created an extension for Date and its worked for me

```<code>extension Date:Convertible
{
    public static func fromMap(_ value: Any) throws -> Date {
        guard let rawDate = value as? String else {
            throw MapperError.convertibleError(value: value, type: Date.self)
        }
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"

        if let date = dateFormatter.date(from: rawDate)  {
            return date
        } else {
            throw MapperError.convertibleError(value: value, type: Date.self)
        }

    }
</code>```

}

Body:
I am working on an iOS project in Swift. I used Moya framework for API handling and parsing. It works perfectly. But when I try to parse varibles other than string it shows me en error:

"Missing argument for parameter 'transformation' in call"

Here is my mapper class

import Mapper

class MyMapperClaa:Mappable {
    var dateVariable: NSDate?

    required init(map: Mapper) throws{
        try dateVariable = map.from("date")
    }
}

Body:
Created an extension for Date and its worked for me

extension Date:Convertible
{
    public static func fromMap(_ value: Any) throws -> Date {
        guard let rawDate = value as? String else {
            throw MapperError.convertibleError(value: value, type: Date.self)
        }
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"

        if let date = dateFormatter.date(from: rawDate)  {
            return date
        } else {
            throw MapperError.convertibleError(value: value, type: Date.self)
        }

    }

}


问:
Adding a matplotlib legend
How can one create a legend for a line graph in Matplotlib's PyPlot without creating any extra variables?

Please consider the graphing script below:

```<code>if __name__ == '__main__':
    PyPlot.plot(total_lengths, sort_times_bubble, 'b-',
                total_lengths, sort_times_ins, 'r-',
                total_lengths, sort_times_merge_r, 'g+',
                total_lengths, sort_times_merge_i, 'p-', )
    PyPlot.title("Combined Statistics")
    PyPlot.xlabel("Length of list (number)")
    PyPlot.ylabel("Time taken (seconds)")
    PyPlot.show()
</code>```

As you can see, this is a very basic use of matplotlib's PyPlot. This ideally generates a graph like the one below:

Nothing special, I know. However, it is unclear what data is being plotted where (I'm trying to plot the data of some sorting algorithms, length against time taken, and I'd like to make sure people know which line is which). Thus, I need a legend, however, taking a look at the following example below(from the official site):

```<code>ax = subplot(1,1,1)
p1, = ax.plot([1,2,3], label="line 1")
p2, = ax.plot([3,2,1], label="line 2")
p3, = ax.plot([2,3,1], label="line 3")

handles, labels = ax.get_legend_handles_labels()

# reverse the order
ax.legend(handles[::-1], labels[::-1])

# or sort them by labels
import operator
hl = sorted(zip(handles, labels),
            key=operator.itemgetter(1))
handles2, labels2 = zip(*hl)

ax.legend(handles2, labels2)
</code>```

You will see that I need to create an extra variable ax. How can I add a legend to my graph without having to create this extra variable and retaining the simplicity of my current script?

答:
Here's an example to help you out ...

```<code>fig = plt.figure(figsize=(10,5))
ax = fig.add_subplot(111)
ax.set_title('ADR vs Rating (CS:GO)')
ax.scatter(x=data[:,0],y=data[:,1],label='Data')
plt.plot(data[:,0], m*data[:,0] + b,color='red',label='Our Fitting
Line')
ax.set_xlabel('ADR')
ax.set_ylabel('Rating')
ax.legend(loc='best')
plt.show()
</code>```

Title: Adding a matplotlib legend

Body:
How can one create a legend for a line graph in Matplotlib's PyPlot without creating any extra variables?

Please consider the graphing script below:

if __name__ == '__main__':
    PyPlot.plot(total_lengths, sort_times_bubble, 'b-',
                total_lengths, sort_times_ins, 'r-',
                total_lengths, sort_times_merge_r, 'g+',
                total_lengths, sort_times_merge_i, 'p-', )
    PyPlot.title("Combined Statistics")
    PyPlot.xlabel("Length of list (number)")
    PyPlot.ylabel("Time taken (seconds)")
    PyPlot.show()

As you can see, this is a very basic use of matplotlib's PyPlot. This ideally generates a graph like the one below:

Nothing special, I know. However, it is unclear what data is being plotted where (I'm trying to plot the data of some sorting algorithms, length against time taken, and I'd like to make sure people know which line is which). Thus, I need a legend, however, taking a look at the following example below(from the official site):

ax = subplot(1,1,1)
p1, = ax.plot([1,2,3], label="line 1")
p2, = ax.plot([3,2,1], label="line 2")
p3, = ax.plot([2,3,1], label="line 3")

handles, labels = ax.get_legend_handles_labels()

# reverse the order
ax.legend(handles[::-1], labels[::-1])

# or sort them by labels
import operator
hl = sorted(zip(handles, labels),
            key=operator.itemgetter(1))
handles2, labels2 = zip(*hl)

ax.legend(handles2, labels2)

You will see that I need to create an extra variable ax. How can I add a legend to my graph without having to create this extra variable and retaining the simplicity of my current script?

Body:
Here's an example to help you out ...

fig = plt.figure(figsize=(10,5))
ax = fig.add_subplot(111)
ax.set_title('ADR vs Rating (CS:GO)')
ax.scatter(x=data[:,0],y=data[:,1],label='Data')
plt.plot(data[:,0], m*data[:,0] + b,color='red',label='Our Fitting
Line')
ax.set_xlabel('ADR')
ax.set_ylabel('Rating')
ax.legend(loc='best')
plt.show()


问:
PHP set value to php variable if variable store in database table
This is my Code

```<code>table_query
id query
1  SELECT * FROM TABLE WHERE date = "$loc_date"

 <?php
$q1 = 'SELECT query FROM table_query WHERE 1 LIMIT 1';
$result = execute q1;
$query = $result['query'];
    $loc_date = '2017-12-06';
    $loc_query = $query; //This query fetch from table. Not directly write on file
    execute query here
    ?>
</code>```

But I don't get any result after executing query.

答:
Put "" into the where condition.

```<code>$loc_query = 'SELECT * FROM TABLE WHERE date = "'.$loc_date.'"';
</code>```

Then execute the query. It should give your result.

Body:
This is my Code

table_query
id query
1  SELECT * FROM TABLE WHERE date = "$loc_date"

 <?php
$q1 = 'SELECT query FROM table_query WHERE 1 LIMIT 1';
$result = execute q1;
$query = $result['query'];
    $loc_date = '2017-12-06';
    $loc_query = $query; //This query fetch from table. Not directly write on file
    execute query here
    ?>

But I don't get any result after executing query.

Body:
Put "" into the where condition.

$loc_query = 'SELECT * FROM TABLE WHERE date = "'.$loc_date.'"';

Then execute the query. It should give your result.


问:
Why is there a type mismatch when unioning a collection of Datasets
I'm trying to get the union of an ArrayBuffer[Dataset[_]].

So I wrote the the following code:

```<code>var buffer: ArrayBuffer[Dataset[_]] = ArrayBuffer.empty[Dataset[_]]

var size:Long = 0
...

if size < 1000 {
  buffer.append(df)
  size = size + df.count()
} else {
  val unionedDataset = buffer.reduce(_ union _)
}
</code>```

I get the following error:

```<code>type mismatch;
[error]  found   : org.apache.spark.sql.Dataset[_$2(in value $anonfun)] where type _$2(in value $anonfun)
[error]  required: org.apache.spark.sql.Dataset[_$2(in variable buffer)]
[error]           val unionedDataset = buffer.reduce(_ union _)
[error]                                                      ^
</code>```

Shouldn't the type of the second argument in the anonymous function be the same type of the object at the index that was referenced?

答:
ArrayBuffer[Dataset[_]] can contain e.g. a Dataset[String] and a Dataset[Int] at the same time, and union isn't defined for them.

If you had ArrayBuffer[Dataset[T]] forSome { type T }, you could write buffer.reduce(_ union _) but then buffer.append(df) won't work: df must have type Dataset[T] but you don't know what T is.

Body:
I'm trying to get the union of an ArrayBuffer[Dataset[_]].

So I wrote the the following code:

var buffer: ArrayBuffer[Dataset[_]] = ArrayBuffer.empty[Dataset[_]]

var size:Long = 0
...

if size < 1000 {
  buffer.append(df)
  size = size + df.count()
} else {
  val unionedDataset = buffer.reduce(_ union _)
}

I get the following error:

type mismatch;
[error]  found   : org.apache.spark.sql.Dataset[_$2(in value $anonfun)] where type _$2(in value $anonfun)
[error]  required: org.apache.spark.sql.Dataset[_$2(in variable buffer)]
[error]           val unionedDataset = buffer.reduce(_ union _)
[error]                                                      ^

Shouldn't the type of the second argument in the anonymous function be the same type of the object at the index that was referenced?


问:
Angular4 is not refreshing the page after code change
When i changed the code in Angular4 then page is not refreshing. i have to again start the server using

```<code>ng serve --open
</code>```

Every time i change I have to restart the server.

Please guide me!

Is there any other option to avoid this?

答:
As mentioned in a similar answer here, try deleting your node_modules folder and running npm install again. This should upgrade a bad npm dependency.

I would recommend deleting cache as well, follow below steps:

Delete node_modules folder.

npm cache clean.

npm install.

Since you are using a relatively older version of CLI, it would be better to update that as well!

Body:
When i changed the code in Angular4 then page is not refreshing. i have to again start the server using

ng serve --open

Every time i change I have to restart the server.

Please guide me!

Is there any other option to avoid this?


答:
Need to add the single or double quote in $loc_date string

for example

```<code>$loc_query = 'SELECT * FROM TABLE WHERE date = "'.$loc_date.'"';
</code>```

OR

$loc_query = "SELECT * FROM TABLE WHERE date = '".$loc_date."'";

Title: PHP set value to php variable if variable store in database table

Body:
Need to add the single or double quote in $loc_date string

for example

$loc_query = 'SELECT * FROM TABLE WHERE date = "'.$loc_date.'"';

OR

$loc_query = "SELECT * FROM TABLE WHERE date = '".$loc_date."'";


问:
Retrieving data from XML file into variables
I have an XML file that has got the following structure:

```<code><root>
    <body>
        <e1>
            <en>
                <tag1>testt1</tag1>
                <tag2 user="anonym">testt2</tag2>
                <tag3>testt3</tag3>
                <tag4>testt4</tag4>
                <tag5>
                    <t51>tttt</t51>
                    <t52>ttt</t52>
                    <t53>ttt</t53>
                </tag5>
            </en>
            <r1>1</r1>
            <r2>
                <tr1>0</tr1>
            </r2>
        </e1>
        <r1>
        </r1>
        <r2>
        </r2>
    </body>
    <info>
    </info>
</root>
</code>```

I need to get the data from <e1> element into certain variables for further usage. For this purpose, I am doing the following:

```<code>foreach (XElement elem in xmlDoc.Descendants("body").Descendants("e1"))
{
    tag1 = elem.Element("en").Element("tag1").Value;
    tag2 = elem.Element("en").Element("tag2").Value;
    tag2a = elem.Element("en").Element("tag2").Attribute("user").Value;
    tag3 = elem.Element("en").Element("tag3").Value;
    tag4 = elem.Element("en").Element("tag4").Value;
    t51 = elem.Element("en").Element("tag5").Element("t51").Value;
    t52 = elem.Element("en").Element("tag5").Element("t52").Value;
    t53 = elem.Element("en").Element("tag5").Element("t53").Value;
    r1 = elem.Element("r1").Value;
    tr1 = elem.Element("r2").Element("tr1").Value;
}
</code>```

It is working properly, but I think, it's kinda looks not the best way. I am new to XDocuments and working with XML in C#. Was curious, if there is any more optimal way to do this?

答:
I found way to do it very easily ,below is my code ,

In my code I am reading value of you xml string which is given by you in question, and after reading storing it into dictionary object.

```<code>   static Dictionary<string, string> ele = new Dictionary<string, string>();
    private static void ReadAllElements(XElement node)
    {
        if (node.HasElements)
        {
            foreach (var element in node.Elements())
                ReadAllElements(element);
        }
        else
        {
            ele[node.Name.ToString()] = node.Value;
            if (node.HasAttributes)
            {
                foreach (var att in node.Attributes())
                    ele[node.Name.ToString() + att.Name.ToString()] = att.Value;
            }
            return;
        }
    }

    public static void Main()
    {
        FileStream fs = new FileStream("XMLFile1.xml", FileMode.Open);
        XDocument xDoc = XDocument.Load(fs);
        var rows=(from row in xDoc.Descendants("e1").Elements()
                     select row).ToList();
        foreach (XElement node in rows)
            ReadAllElements(node);
        foreach (var keypair in ele)
            Console.WriteLine($"{keypair.Key} : {keypair.Value}");
        Console.ReadLine();
 }
</code>```

Output will be

```<code>tag1 : testt1
tag2 : testt2
tag2user : anonym
tag3 : testt3
tag4 : testt4
t51 : tttt
t52 : ttt
t53 : ttt
r1 : 1
tr1 : 0
</code>```

I suggest you make use of XML(de)Serialization instead of doing this, that is much clearner way to do it and you dont have to do this much long code and remember things.

For doing XML(de)Serialization you need as class simimlar to your structure of xml. So to get similar structure you make use of visual studio : Visual Studio Generate Class From JSON or XML

```<code>  XmlSerializer serializer = new
    XmlSerializer(typeof(ClassName you create));
    FileStream fs = new FileStream(filename, FileMode.Open);
    XmlReader reader = XmlReader.Create(fs);
    ClassName i;
    i = (ClassName)serializer.Deserialize(reader);
</code>```

Body:
I have an XML file that has got the following structure:

<root>

        <e1>
            <en>
                <tag1>testt1</tag1>
                <tag2 user="anonym">testt2</tag2>
                <tag3>testt3</tag3>
                <tag4>testt4</tag4>
                <tag5>
                    <t51>tttt</t51>
                    <t52>ttt</t52>
                    <t53>ttt</t53>
                </tag5>
            </en>
            <r1>1</r1>
            <r2>
                <tr1>0</tr1>
            </r2>
        </e1>
        <r1>
        </r1>
        <r2>
        </r2>

    <info>
    </info>
</root>

I need to get the data from <e1> element into certain variables for further usage. For this purpose, I am doing the following:

foreach (XElement elem in xmlDoc.Descendants("body").Descendants("e1"))
{
    tag1 = elem.Element("en").Element("tag1").Value;
    tag2 = elem.Element("en").Element("tag2").Value;
    tag2a = elem.Element("en").Element("tag2").Attribute("user").Value;
    tag3 = elem.Element("en").Element("tag3").Value;
    tag4 = elem.Element("en").Element("tag4").Value;
    t51 = elem.Element("en").Element("tag5").Element("t51").Value;
    t52 = elem.Element("en").Element("tag5").Element("t52").Value;
    t53 = elem.Element("en").Element("tag5").Element("t53").Value;
    r1 = elem.Element("r1").Value;
    tr1 = elem.Element("r2").Element("tr1").Value;
}

It is working properly, but I think, it's kinda looks not the best way. I am new to XDocuments and working with XML in C#. Was curious, if there is any more optimal way to do this?

Body:
I found way to do it very easily ,below is my code ,

In my code I am reading value of you xml string which is given by you in question, and after reading storing it into dictionary object.

   static Dictionary<string, string> ele = new Dictionary<string, string>();
    private static void ReadAllElements(XElement node)
    {
        if (node.HasElements)
        {
            foreach (var element in node.Elements())
                ReadAllElements(element);
        }
        else
        {
            ele[node.Name.ToString()] = node.Value;
            if (node.HasAttributes)
            {
                foreach (var att in node.Attributes())
                    ele[node.Name.ToString() + att.Name.ToString()] = att.Value;
            }
            return;
        }
    }

    public static void Main()
    {
        FileStream fs = new FileStream("XMLFile1.xml", FileMode.Open);
        XDocument xDoc = XDocument.Load(fs);
        var rows=(from row in xDoc.Descendants("e1").Elements()
                     select row).ToList();
        foreach (XElement node in rows)
            ReadAllElements(node);
        foreach (var keypair in ele)
            Console.WriteLine($"{keypair.Key} : {keypair.Value}");
        Console.ReadLine();
 }

Output will be

tag1 : testt1
tag2 : testt2
tag2user : anonym
tag3 : testt3
tag4 : testt4
t51 : tttt
t52 : ttt
t53 : ttt
r1 : 1
tr1 : 0

I suggest you make use of XML(de)Serialization instead of doing this, that is much clearner way to do it and you dont have to do this much long code and remember things.

For doing XML(de)Serialization you need as class simimlar to your structure of xml. So to get similar structure you make use of visual studio : Visual Studio Generate Class From JSON or XML

  XmlSerializer serializer = new
    XmlSerializer(typeof(ClassName you create));
    FileStream fs = new FileStream(filename, FileMode.Open);
    XmlReader reader = XmlReader.Create(fs);
    ClassName i;
    i = (ClassName)serializer.Deserialize(reader);


问:
how to call a method from one controller to another controller in Objective-C

Hello everyone, I am a beginner in Mac OS Developer. I have a problem when calling a method in a controller named Controller1.

Here is my code for Controller1:

Controller1.h

```<code>#import <Cocoa/Cocoa.h>

@interface Controller1 : NSViewController

- (void)LoadViewActiveCall;

@end
</code>```

Controller1.m

```<code>#import "Controller1.h"
@implementation Controller1

- (void)showCallViewController:(NSViewController*)target_viewcontroller2{
    NSLog(@"Run method showCallViewController");
    NSLog(@"Parameter targe view controller 2 : %@",target_viewcontroller2);
    if(current_controller2!=nil){
        [current_controller2.view removeFromSuperview];
        [current_controller2 removeFromParentViewController];
    }
    [self addChildViewController:target_viewcontroller2];
    target_viewcontroller2.view.frame=container_Call.frame;
    [container_Call addSubview:target_viewcontroller2.view];
    current_controller2=target_viewcontroller2;
}

- (void)LoadViewActiveCall {
    [self showCallViewController:vCall];
    NSLog(@"keluar active call berhasil");
}

@end
</code>```

I want call LoadViewActiveCall method on button IBAction of Controller2

Controller2.h

```<code>#import <Cocoa/Cocoa.h>
#import "Controller1.h"

@interface Controller2 : NSViewController

- (IBAction)audioCall:(id)sender;

@end
</code>```

Controller2.m

```<code>#import "Controller1.h"
#import "Controller2.h"

@implementation Controller2

- (IBAction)audioCall:(id)sender {
    Controller1 *co1 = [[Controller1 alloc] init];
    [co1 LoadViewActiveCall];
}

@end
</code>```

My problem is when I press audioCall button, but LoadViewActiveCall method is not being called.

I am sorry for my bad english

答:
The way you are calling a function from another view controller is correct only.

Please check whether you have connected the button action correctly to the function

```<code>- (IBAction)audioCall:(id)sender
</code>```

pleas echeck it and reply. It is perfectly working for singleview application for ios using UIViewcontroller

Body:
Hello everyone, I am a beginner in Mac OS Developer. I have a problem when calling a method in a controller named Controller1.

Here is my code for Controller1:

Controller1.h

#import <Cocoa/Cocoa.h>

@interface Controller1 : NSViewController

- (void)LoadViewActiveCall;

@end

Controller1.m

#import "Controller1.h"
@implementation Controller1

- (void)showCallViewController:(NSViewController*)target_viewcontroller2{
    NSLog(@"Run method showCallViewController");
    NSLog(@"Parameter targe view controller 2 : %@",target_viewcontroller2);
    if(current_controller2!=nil){
        [current_controller2.view removeFromSuperview];
        [current_controller2 removeFromParentViewController];
    }
    [self addChildViewController:target_viewcontroller2];
    target_viewcontroller2.view.frame=container_Call.frame;
    [container_Call addSubview:target_viewcontroller2.view];
    current_controller2=target_viewcontroller2;
}

- (void)LoadViewActiveCall {
    [self showCallViewController:vCall];
    NSLog(@"keluar active call berhasil");
}

@end

I want call LoadViewActiveCall method on button IBAction of Controller2

Controller2.h

#import <Cocoa/Cocoa.h>
#import "Controller1.h"

@interface Controller2 : NSViewController

- (IBAction)audioCall:(id)sender;

@end

Controller2.m

#import "Controller1.h"
#import "Controller2.h"

@implementation Controller2

- (IBAction)audioCall:(id)sender {
    Controller1 *co1 = [[Controller1 alloc] init];
    [co1 LoadViewActiveCall];
}

@end

My problem is when I press audioCall button, but LoadViewActiveCall method is not being called.

I am sorry for my bad english

Body:
The way you are calling a function from another view controller is correct only.

Please check whether you have connected the button action correctly to the function

- (IBAction)audioCall:(id)sender

pleas echeck it and reply. It is perfectly working for singleview application for ios using UIViewcontroller


问:
How to set cronjob with non-root user?
Error :   crontab: must be suid to work properly

I want to set cronjob in docker container with non-root user. Is it possible to set a cron without using sudo and without installing cron?
I am using alpine docker container.

答:
Yes you can run its own, cron in specific user without sudo, As each user will be having the crontab file no need to install it explicitly.
to run crontab of any user, use -u option , please note  that user must be privileged to use -u

```<code> $ crontab -u <username> -e
</code>```

Title: How to set cronjob with non-root user?

Body:
Yes you can run its own, cron in specific user without sudo, As each user will be having the crontab file no need to install it explicitly.
to run crontab of any user, use -u option , please note  that user must be privileged to use -u

 $ crontab -u <username> -e


答:
try

ng serve --open --watch

if this does not work try cache clean and npm install

If you are using Ubuntu Try reseting the number of watches this might solve the problem

echo 65536 | sudo tee -a /proc/sys/fs/inotify/max_user_watches

Title: Angular4 is not refreshing the page after code change


问:
Calling ClickOnce App From Task Scheduler
I have a windows application that I deployed to a file share via ClickOnce (VS 2012).  It's configured as an online application (not installed on the client).  I can run this application via the client by just pointing to the file share and double-clicking the file.  What I'm having a problem doing is running this as a scheduled task on the client (client is actually a server, Windows Server 2008).  If however, I create a batch file that calls the ClickOnce app, task scheduler can successfully call the batch file.  But I'd rather not have to deal with the extra step of creating that batch file.

The error I get from Task Scheduler is this:
Task Scheduler failed to launch action "\pathToClickOnceApp" in instance "{d5cc956f-c09e-41dc-a04d-a4276f38704e}" of task "\TaskName". Additional Data: Error Value: 2147942403.

答:
Here's a sample code to create the Task that can call a clickonce app:</p>

```<code>  using (TaskService ts = new TaskService())
            {
                // Create a new task definition and assign properties
                TaskDefinition td = ts.NewTask();
                td.RegistrationInfo.Description = "runs clickonce app every 10 minutes";

                var trigger = new TimeTrigger();
                trigger.Repetition.Interval = TimeSpan.FromMinutes(10);
                // Create a trigger that will fire the task at this time every other day

                td.Triggers.Add(trigger);

                // Create an action that will launch the clickonce app
                td.Actions.Add(new ExecAction("rundll32.exe", @"dfshim.dll,ShOpenVerbApplication your_clickonce_app_url/clickonce_appname.application", null));

                // Register the task in the root folder
                ts.RootFolder.RegisterTaskDefinition(@"ClickOnce app", td);

            }
</code>```

Body:
Here's a sample code to create the Task that can call a clickonce app:

  using (TaskService ts = new TaskService())
            {
                // Create a new task definition and assign properties
                TaskDefinition td = ts.NewTask();
                td.RegistrationInfo.Description = "runs clickonce app every 10 minutes";

                var trigger = new TimeTrigger();
                trigger.Repetition.Interval = TimeSpan.FromMinutes(10);
                // Create a trigger that will fire the task at this time every other day

                td.Triggers.Add(trigger);

                // Create an action that will launch the clickonce app
                td.Actions.Add(new ExecAction("rundll32.exe", @"dfshim.dll,ShOpenVerbApplication your_clickonce_app_url/clickonce_appname.application", null));

                // Register the task in the root folder
                ts.RootFolder.RegisterTaskDefinition(@"ClickOnce app", td);

            }


问:
Compiling C floating point arithmetic on OSX for Shewchuk's Triangle program
This question suggests that the best way to triangulate a polygon with holes is to use Shewchuk's Triangle library, but I'm having trouble getting it to compile on my mac OSX. It is a very popular program that has been around for a while, and therefore should be relatively easy to compile, I'm just inexperienced with C.

This is the error I'm getting:

```<code>$ make
cc -O -DLINUX -I/usr/X11R6/include -L/usr/X11R6/lib -o ./triangle ./triangle.c -lm
Undefined symbols:
  "__FPU_SETCW", referenced from:
   _exactinit in ccrEJvxc.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
make: *** [triangle] Error 1
</code>```

I'm trying to comment out certain flags (i.e. #define LINUX, etc.) but I get a different set of errors for each combination.

Could someone walk me through step-by-step how to compile (and possibly call) this program on a mac?

答:
I don't believe that's a standard function and in any case I believe the Mac .. whose use of the Intel architecture post-dates SSE .. never had a reason to support 387-style FPU ops.

So your code is Linux-specific. You can either remove the linux specific code or implement do-nothing versions of its entry points.

I wouldn't do this myself, but you might get away with:

```<code>$ cat > /usr/include/fpu_control.h

#define _FPU_SETCW(cw) // nothing
#define _FPU_GETCW(cw) // nothing
</code>```

Don't worry about the null implementations. You don't need to tweak the FPU exception and rounding modes.

Body:
This question suggests that the best way to triangulate a polygon with holes is to use Shewchuk's Triangle library, but I'm having trouble getting it to compile on my mac OSX. It is a very popular program that has been around for a while, and therefore should be relatively easy to compile, I'm just inexperienced with C.

This is the error I'm getting:

$ make
cc -O -DLINUX -I/usr/X11R6/include -L/usr/X11R6/lib -o ./triangle ./triangle.c -lm
Undefined symbols:
  "__FPU_SETCW", referenced from:
   _exactinit in ccrEJvxc.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
make: *** [triangle] Error 1

I'm trying to comment out certain flags (i.e. #define LINUX, etc.) but I get a different set of errors for each combination.

Could someone walk me through step-by-step how to compile (and possibly call) this program on a mac?

Body:
I don't believe that's a standard function and in any case I believe the Mac .. whose use of the Intel architecture post-dates SSE .. never had a reason to support 387-style FPU ops.

So your code is Linux-specific. You can either remove the linux specific code or implement do-nothing versions of its entry points.

I wouldn't do this myself, but you might get away with:

$ cat > /usr/include/fpu_control.h

#define _FPU_SETCW(cw) // nothing
#define _FPU_GETCW(cw) // nothing

Don't worry about the null implementations. You don't need to tweak the FPU exception and rounding modes.


问:
Django Rest Framework: How to pass extra argument to django serializer?
I have a variable named email in view.

I want to access this in ManageSerializer.

How can I pass this argument in serializer and get there?

views.py

```<code>email = 'xyz@gmail.com'
interviewData = Manage.objects.
    filter(catcher_id = userCheck['id'], acceptation = '1').
    filter(invitation_date__gte = dateToday)[:5];
serializer = ManageSerializers(interviewData, many = True)
</code>```

答:
Maybe pass it as kwargs:

```<code> ManageSerializers(interviewData, many = True, email= email)
</code>```

You can access this in the init of the Serializer, using something like:kwargs.pop('email')

OR

You can pass the context to the Serializer like this.

```<code> ManageSerializers(interviewData, many = True, context={'email': email})
</code>```

and you can access the context in Serializer like self.context['email']

Body:
I have a variable named email in view.

I want to access this in ManageSerializer.

How can I pass this argument in serializer and get there?

views.py

email = 'xyz@gmail.com'
interviewData = Manage.objects.
    filter(catcher_id = userCheck['id'], acceptation = '1').
    filter(invitation_date__gte = dateToday)[:5];
serializer = ManageSerializers(interviewData, many = True)

Body:
Maybe pass it as kwargs:

 ManageSerializers(interviewData, many = True, email= email)

You can access this in the init of the Serializer, using something like:kwargs.pop('email')

OR

You can pass the context to the Serializer like this.

 ManageSerializers(interviewData, many = True, context={'email': email})

and you can access the context in Serializer like self.context['email']