问:
When using multiple buffers with Flex, how do I avoid having tokens get split between buffers
Let's assume I have a simple grammar of positive integers and alphabetic strings separated by commas. I want to parse this grammar using Flex and Bison, and I want to use multiple input buffers with Flex, for whatever reasons (maybe data is arriving over the network or a serial line or whatever). The problem I'm seeing is that when a string or an integer (which are both variable length tokens) are split between the end of one buffer and the start of the next, the lexer reports two tokens when there should only be one.

In the example below, the chunks are  10, asdf and g,. If that was all in one buffer it would yield the tokens INT(10) COMMA STR(asdfg) COMMA. But with the 'g' in a different buffer from the 'asdf', the lexer actually produces INT(10) COMMA STR(asdf) STR(g) COMMA. It appears the logic upon reaching the end of the buffer is (1) check if the input matches a token, (2) refill the buffer. I feel it should be the other way around: (2) refill the buffer, (1) check if the input matches a token.

I want to make sure I'm not doing something silly with the way I'm changing the buffers.

stdout/stderr:

```<code>read_more_input: Setting up buffer containing: 10,
--accepting rule at line 48 ("10")
Starting parse
Entering state 0
Reading a token: Next token is token INT_TERM ()
Shifting token INT_TERM ()
Entering state 1
Return for a new token:
--accepting rule at line 50 (",")
Reading a token: Next token is token COMMA ()
Shifting token COMMA ()
Entering state 4
Reducing stack by rule 2 (line 67):
   $1 = token INT_TERM ()
   $2 = token COMMA ()
-> $$ = nterm int_non_term ()
Stack now 0
Entering state 3
Return for a new token:
--(end of buffer or a NUL)
--EOF (start condition 0)
read_more_input: Setting up buffer containing: asdf
--(end of buffer or a NUL)
--accepting rule at line 49 ("asdf")
Reading a token: Next token is token STR_TERM ()
Shifting token STR_TERM ()
Entering state 6
Return for a new token:
--(end of buffer or a NUL)
--EOF (start condition 0)
read_more_input: Setting up buffer containing: g,
--accepting rule at line 49 ("g")
Reading a token: Next token is token STR_TERM ()
syntax errorError: popping token STR_TERM ()
Stack now 0 3
Error: popping nterm int_non_term ()
Stack now 0
Cleanup: discarding lookahead token STR_TERM ()
Stack now 0
</code>```

Lex file:

```<code>%{
#include <stdbool.h>
#include "yacc.h"
bool read_more_input(yyscan_t scanner);
%}

%option reentrant bison-bridge

%%

[0-9]+     { yylval->int_value = atoi(yytext); return INT_TERM; }
[a-zA-Z]+  { yylval->str_value = strdup(yytext); return STR_TERM; }
,          { return COMMA;    }
<<EOF>>    {
             if (!read_more_input(yyscanner)) {
                yyterminate();
             }
           }
</code>```

Yacc file:

```<code>%{
// This appears to be a bug. This typedef breaks a dependency cycle between the headers.
// See https://stackoverflow.com/questions/44103798/cyclic-dependency-in-reentrant-flex-bison-headers-with-union-yystype
typedef void * yyscan_t;

#include <stdbool.h>
#include "yacc.h"
#include "lex.h"
%}

%define api.pure full
%lex-param {yyscan_t scanner}
%parse-param {yyscan_t scanner}
%define api.push-pull push

%union {
  int int_value;
  char * str_value;
}

%token <int_value> INT_TERM
%type  <int_value> int_non_term
%token <str_value> STR_TERM
%type  <str_value> str_non_term
%token COMMA

%%

complete : int_non_term str_non_term { printf(" === %d === %s === \n", $1, $2); }

int_non_term : INT_TERM COMMA { $$ = $1; }
str_non_term : STR_TERM COMMA { $$ = $1; }

%%

char * packets[]= {"10,", "asdf", "g,"};
int current_packet = 0;

bool read_more_input(yyscan_t scanner) {
  if (current_packet >= 3) {
    fprintf(stderr, "read_more_input: No more input\n");
    return false;
  }

  fprintf(stderr, "read_more_input: Setting up buffer containing: %s\n", packets[current_packet]);
  size_t buffer_size = strlen(packets[current_packet]) + 2;
  char * buffer = (char *) calloc(buffer_size, sizeof(char));
  memcpy(buffer, packets[current_packet], buffer_size - 2);

  yy_scan_buffer(buffer, buffer_size, scanner);
  current_packet++;
  return true;
}

int main(int argc, char** argv) {

  yyscan_t scanner;
  yylex_init(&scanner) ;

  read_more_input(scanner);

  yyset_debug(1, scanner);
  yydebug = 1;

  int status;
  yypstate *ps = yypstate_new ();

  YYSTYPE pushed_value;

  do {
    status = yypush_parse(ps, yylex(&pushed_value, scanner), &pushed_value, scanner);
  } while(status == YYPUSH_MORE);

  yypstate_delete (ps);
  yylex_destroy (scanner) ;
  return 0;
}
</code>```

答:
That is not the expected use case for multiple buffers. Multiple input buffers are generally used to handle things like #include or even macro expansion, where the included text definitely should respect token boundaries. (Consider an #included file which has an unterminated comment...)

If you want to paste together inputs from different sources in a way which allows tokens to flow across buffer boundaries, redefine the YY_INPUT macro to meet your needs.

YY_INPUT is the macro hook for customising input; it is given a buffer and a maximum length and it must copy the specified number of bytes (or fewer) into the buffer, and also indicate hoe many bytes were provided (0 bytes is taken as meaning end of input, at which point yywrap will be called.)

YY_INPUT is expanded inside yylex so it has access to the yylex arguments, which includes the lexer state. yywrap in a reentrant lexer is called with the scanner state as an argument. So you can use the two mechanisms together, if you want to.

Unfortunately, this does not allow "zero-copy" buffer switching. But flex is not optimised for in-memory input buffers in general: you can provide flex with a buffer using yyscan_buffer but the buffer must be terminated with two NUL bytes, and it will be modified during the scan, so the feature is rarely useful.

Here's a trivial example, which lets you set yylex up with a NULL-terminated argv-like array of strings, and proceeds to lex them all as a single input. (If you choose to use argv+1 to initialize this array, you'll notice that it runs tokens together from consecutive arguments.)

```<code>%{
#include <string.h>
#include <parser.tab.h>
#define YY_EXTRA_TYPE char**
/* FIXME:
 * This assumes that none of the string segments are empty
 * strings (or for the feature-not-a-bug interpretation,
 * it allows the list to be terminated by NULL or an empty string).
 */
#define YY_INPUT(buf,result,max_size) { \
  char* segment = *yyextra; \
  if (segment == NULL) result = 0; \
  else { \
    size_t avail = strnlen(segment, max_size); \
    memcpy(buf, segment, avail); \
    if (segment[avail]) *yyextra += avail; \
    else ++yyextra; \
    result = avail; \
  } \
}

%}

%option reentrant bison-bridge
%option noinput nounput nodefault noyywrap

%%

[[:space:]]+              ;
[0-9]+                    { yylval->number = strtol(yytext, 0, 10); return NUMBER; }
[[:alpha:]_][[:alnum:]_]* { yylval->string = strdup(yytext); return ID; }
.                         { return *yytext; }

%%

/* This function must be exported in some header */
void yylex_strings(char** argv, yyscan_t scanner) {
  yyset_extra(argv, scanner);
}
</code>```

Body:
Let's assume I have a simple grammar of positive integers and alphabetic strings separated by commas. I want to parse this grammar using Flex and Bison, and I want to use multiple input buffers with Flex, for whatever reasons (maybe data is arriving over the network or a serial line or whatever). The problem I'm seeing is that when a string or an integer (which are both variable length tokens) are split between the end of one buffer and the start of the next, the lexer reports two tokens when there should only be one.

In the example below, the chunks are  10, asdf and g,. If that was all in one buffer it would yield the tokens INT(10) COMMA STR(asdfg) COMMA. But with the 'g' in a different buffer from the 'asdf', the lexer actually produces INT(10) COMMA STR(asdf) STR(g) COMMA. It appears the logic upon reaching the end of the buffer is (1) check if the input matches a token, (2) refill the buffer. I feel it should be the other way around: (2) refill the buffer, (1) check if the input matches a token.

I want to make sure I'm not doing something silly with the way I'm changing the buffers.

stdout/stderr:

read_more_input: Setting up buffer containing: 10,
--accepting rule at line 48 ("10")
Starting parse
Entering state 0
Reading a token: Next token is token INT_TERM ()
Shifting token INT_TERM ()
Entering state 1
Return for a new token:
--accepting rule at line 50 (",")
Reading a token: Next token is token COMMA ()
Shifting token COMMA ()
Entering state 4
Reducing stack by rule 2 (line 67):
   $1 = token INT_TERM ()
   $2 = token COMMA ()
-> $$ = nterm int_non_term ()
Stack now 0
Entering state 3
Return for a new token:
--(end of buffer or a NUL)
--EOF (start condition 0)
read_more_input: Setting up buffer containing: asdf
--(end of buffer or a NUL)
--accepting rule at line 49 ("asdf")
Reading a token: Next token is token STR_TERM ()
Shifting token STR_TERM ()
Entering state 6
Return for a new token:
--(end of buffer or a NUL)
--EOF (start condition 0)
read_more_input: Setting up buffer containing: g,
--accepting rule at line 49 ("g")
Reading a token: Next token is token STR_TERM ()
syntax errorError: popping token STR_TERM ()
Stack now 0 3
Error: popping nterm int_non_term ()
Stack now 0
Cleanup: discarding lookahead token STR_TERM ()
Stack now 0

Lex file:

%{
#include <stdbool.h>
#include "yacc.h"
bool read_more_input(yyscan_t scanner);
%}

%option reentrant bison-bridge

%%

[0-9]+     { yylval->int_value = atoi(yytext); return INT_TERM; }
[a-zA-Z]+  { yylval->str_value = strdup(yytext); return STR_TERM; }
,          { return COMMA;    }
<<EOF>>    {
             if (!read_more_input(yyscanner)) {
                yyterminate();
             }
           }

Yacc file:

%{
// This appears to be a bug. This typedef breaks a dependency cycle between the headers.
// See https://stackoverflow.com/questions/44103798/cyclic-dependency-in-reentrant-flex-bison-headers-with-union-yystype
typedef void * yyscan_t;

#include <stdbool.h>
#include "yacc.h"
#include "lex.h"
%}

%define api.pure full
%lex-param {yyscan_t scanner}
%parse-param {yyscan_t scanner}
%define api.push-pull push

%union {
  int int_value;
  char * str_value;
}

%token <int_value> INT_TERM
%type  <int_value> int_non_term
%token <str_value> STR_TERM
%type  <str_value> str_non_term
%token COMMA

%%

complete : int_non_term str_non_term { printf(" === %d === %s === \n", $1, $2); }

int_non_term : INT_TERM COMMA { $$ = $1; }
str_non_term : STR_TERM COMMA { $$ = $1; }

%%

char * packets[]= {"10,", "asdf", "g,"};
int current_packet = 0;

bool read_more_input(yyscan_t scanner) {
  if (current_packet >= 3) {
    fprintf(stderr, "read_more_input: No more input\n");
    return false;
  }

  fprintf(stderr, "read_more_input: Setting up buffer containing: %s\n", packets[current_packet]);
  size_t buffer_size = strlen(packets[current_packet]) + 2;
  char * buffer = (char *) calloc(buffer_size, sizeof(char));
  memcpy(buffer, packets[current_packet], buffer_size - 2);

  yy_scan_buffer(buffer, buffer_size, scanner);
  current_packet++;
  return true;
}

int main(int argc, char** argv) {

  yyscan_t scanner;
  yylex_init(&scanner) ;

  read_more_input(scanner);

  yyset_debug(1, scanner);
  yydebug = 1;

  int status;
  yypstate *ps = yypstate_new ();

  YYSTYPE pushed_value;

  do {
    status = yypush_parse(ps, yylex(&pushed_value, scanner), &pushed_value, scanner);
  } while(status == YYPUSH_MORE);

  yypstate_delete (ps);
  yylex_destroy (scanner) ;
  return 0;
}

Body:
That is not the expected use case for multiple buffers. Multiple input buffers are generally used to handle things like #include or even macro expansion, where the included text definitely should respect token boundaries. (Consider an #included file which has an unterminated comment...)

If you want to paste together inputs from different sources in a way which allows tokens to flow across buffer boundaries, redefine the YY_INPUT macro to meet your needs.

YY_INPUT is the macro hook for customising input; it is given a buffer and a maximum length and it must copy the specified number of bytes (or fewer) into the buffer, and also indicate hoe many bytes were provided (0 bytes is taken as meaning end of input, at which point yywrap will be called.)

YY_INPUT is expanded inside yylex so it has access to the yylex arguments, which includes the lexer state. yywrap in a reentrant lexer is called with the scanner state as an argument. So you can use the two mechanisms together, if you want to.

Unfortunately, this does not allow "zero-copy" buffer switching. But flex is not optimised for in-memory input buffers in general: you can provide flex with a buffer using yyscan_buffer but the buffer must be terminated with two NUL bytes, and it will be modified during the scan, so the feature is rarely useful.

Here's a trivial example, which lets you set yylex up with a NULL-terminated argv-like array of strings, and proceeds to lex them all as a single input. (If you choose to use argv+1 to initialize this array, you'll notice that it runs tokens together from consecutive arguments.)

%{
#include <string.h>
#include <parser.tab.h>
#define YY_EXTRA_TYPE char**
/* FIXME:
 * This assumes that none of the string segments are empty
 * strings (or for the feature-not-a-bug interpretation,
 * it allows the list to be terminated by NULL or an empty string).
 */
#define YY_INPUT(buf,result,max_size) { \
  char* segment = *yyextra; \
  if (segment == NULL) result = 0; \
  else { \
    size_t avail = strnlen(segment, max_size); \
    memcpy(buf, segment, avail); \
    if (segment[avail]) *yyextra += avail; \
    else ++yyextra; \
    result = avail; \
  } \
}

%}

%option reentrant bison-bridge
%option noinput nounput nodefault noyywrap

%%

[[:space:]]+              ;
[0-9]+                    { yylval->number = strtol(yytext, 0, 10); return NUMBER; }
[[:alpha:]_][[:alnum:]_]* { yylval->string = strdup(yytext); return ID; }
.                         { return *yytext; }

%%

/* This function must be exported in some header */
void yylex_strings(char** argv, yyscan_t scanner) {
  yyset_extra(argv, scanner);
}


来源: stackexchange

问:
How to Generate nokogumbo Gem File
I recently added the sanitize sanitize gem, which appears to have a dependency on the nokogumbo gem, to a site I'm deploying on Heroku. Unfortunately, after installing sanitize, I began receiving the following error on the Heroku deployment:

```<code>/app/vendor/bundle/ruby/2.3.0/gems/activesupport-5.0.3/lib/active_support/dependencies.rb:293:in `require': /tmp/build_4dbcff4c3c5e0bb6bed481077377225e/vendor/bundle/ruby/2.3.0/gems/nokogiri-1.7.2/ext/nokogiri/nokogiri.so: cannot open shared object file: No such file or directory - /app/vendor/bundle/ruby/2.3.0/gems/nokogumbo-1.4.12/lib/nokogumboc.so (LoadError)
</code>```

There is no nokogumbo-1.4.12 directory, but everything is working fine locally. I've tried manually installing the gem, but I'm still receiving the same error. Any suggestions for a fix would be greatly appreciated!

答:
This seems to be an issue on the nokogumbo gem. https://github.com/rubys/nokogumbo/issues/25

"Downgrading to nokogumbo 1.4.11 fixes Heroku deployment so something is definitely up.
  The issue appears on both cedar-14 (Ubuntu 14 LTS) and heroku-16 (Ubuntu 16 LTS) stacks."

The suggestion on how to fix this until this issue has been resolved is to downgrade nokogumbo to 1.4.11.

```<code># Fix the version until https://github.com/rubys/nokogumbo/issues/25 gets fixed
gem 'nokogumbo', '= 1.4.11'
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to Generate nokogumbo Gem File

Body:
I recently added the sanitize sanitize gem, which appears to have a dependency on the nokogumbo gem, to a site I'm deploying on Heroku. Unfortunately, after installing sanitize, I began receiving the following error on the Heroku deployment:

/app/vendor/bundle/ruby/2.3.0/gems/activesupport-5.0.3/lib/active_support/dependencies.rb:293:in `require': /tmp/build_4dbcff4c3c5e0bb6bed481077377225e/vendor/bundle/ruby/2.3.0/gems/nokogiri-1.7.2/ext/nokogiri/nokogiri.so: cannot open shared object file: No such file or directory - /app/vendor/bundle/ruby/2.3.0/gems/nokogumbo-1.4.12/lib/nokogumboc.so (LoadError)

There is no nokogumbo-1.4.12 directory, but everything is working fine locally. I've tried manually installing the gem, but I'm still receiving the same error. Any suggestions for a fix would be greatly appreciated!

Body:
This seems to be an issue on the nokogumbo gem. https://github.com/rubys/nokogumbo/issues/25

"Downgrading to nokogumbo 1.4.11 fixes Heroku deployment so something is definitely up.
  The issue appears on both cedar-14 (Ubuntu 14 LTS) and heroku-16 (Ubuntu 16 LTS) stacks."

The suggestion on how to fix this until this issue has been resolved is to downgrade nokogumbo to 1.4.11.

# Fix the version until https://github.com/rubys/nokogumbo/issues/25 gets fixed
gem 'nokogumbo', '= 1.4.11'


问:
multiple datepicker in a page (php)
im trying to use two date picker in a page. it seems to worked fine but after  clicked on the submit button the date entered is not the same as the choosen date. both of the date inserted to the database is 01-01-1970.

how can i fix this?

```<code><div class="form-group">
    <label class="control-label col-sm-4">Date Issued</label>
    <div class="col-sm-5">
        <input class="form-control" type="text" id="dateIssuedpc" name="dateissued" required class="form-control" placeholder="Enter Date Issued"/>
    </div>
</div>

<div class="form-group">
    <label class="control-label col-sm-4">Date Expired</label>
    <div class="col-sm-5">
    <input class="form-control" type="text" id="dateExpiredpc" name="dateexpired" required class="form-control"  placeholder="Enter Date Expired" />
    </div>
</div>

<script>
$( function() {
$( "#dateIssuedpc").datepicker({
  dateFormat: "dd-mm-yy",
  changeMonth: true,
  changeYear: true
});
$( "#dateExpiredpc" ).datepicker({
  dateFormat: "dd-mm-yy",
  changeMonth: true,
  changeYear: true
  });
  } );
 </script>
</code>```

答:
if field data type in database is datetime then

```<code>$dateexpired = $_POST['dateexpired'];
$new_dateexpired = date("Y-m-d H:i:s",strtotime($dateexpired));
$dateissued = $_POST['dateissued'];
$new_dateissued = date("Y-m-d H:i:s",strtotime($dateissued));
</code>```

if field data type is date then

```<code>$dateexpired = $_POST['dateexpired'];
$new_dateexpired = date("Y-m-d",strtotime($dateexpired));
$dateissued = $_POST['dateissued'];
$new_dateissued = date("Y-m-d",strtotime($dateissued));
</code>```

Title: multiple datepicker in a page (php)

Body:
im trying to use two date picker in a page. it seems to worked fine but after  clicked on the submit button the date entered is not the same as the choosen date. both of the date inserted to the database is 01-01-1970.

how can i fix this?

    Date Issued

        <input class="form-control" type="text" id="dateIssuedpc" name="dateissued" required class="form-control" placeholder="Enter Date Issued"/>

    Date Expired

    <input class="form-control" type="text" id="dateExpiredpc" name="dateexpired" required class="form-control"  placeholder="Enter Date Expired" />

Body:
if field data type in database is datetime then

$dateexpired = $_POST['dateexpired'];
$new_dateexpired = date("Y-m-d H:i:s",strtotime($dateexpired));
$dateissued = $_POST['dateissued'];
$new_dateissued = date("Y-m-d H:i:s",strtotime($dateissued));

if field data type is date then

$dateexpired = $_POST['dateexpired'];
$new_dateexpired = date("Y-m-d",strtotime($dateexpired));
$dateissued = $_POST['dateissued'];
$new_dateissued = date("Y-m-d",strtotime($dateissued));


问:
Where is Xcode's "TOOLCHAINS" set?
I upgraded my project from Swift 2.2 to 2.3 (Xcode 7 to 8), and committed everything on one Mac.  When I pulled from git on my other Mac, and built, I get:

```<code>Warning: target specifies SWIFT_VERSION = '2.3', but it is overridden by TOOLCHAINS = 'com.apple.dt.toolchain.XcodeDefault'
</code>```

I can't find anything called "TOOLCHAINS" in any file.  What's this warning mean?

答: If you don't have "Toolchain" option under Xcode menu, you need to download and install a snapshot or release first.</p>

Title: Where is Xcode's "TOOLCHAINS" set?

Body:
I upgraded my project from Swift 2.2 to 2.3 (Xcode 7 to 8), and committed everything on one Mac.  When I pulled from git on my other Mac, and built, I get:

Warning: target specifies SWIFT_VERSION = '2.3', but it is overridden by TOOLCHAINS = 'com.apple.dt.toolchain.XcodeDefault'

I can't find anything called "TOOLCHAINS" in any file.  What's this warning mean?

ContentLicense: CC BY-SA 4.0


问:
how to run "sudo passwd username" noninteractively
In a shell script with sudo privileges, I'm trying to change another users password.

I tried sudo passwd username but didn't get anywhere.

答:
You need to use the chpasswd command. You can try something like this:

```<code>echo "username:password" | sudo chpasswd
</code>```

I used it many times. It worked for me.

Body:
You need to use the chpasswd command. You can try something like this:

echo "username:password" | sudo chpasswd

I used it many times. It worked for me.


问:
strstr() function in C programming
I am learning C from the book Head First C, and I tried one of the examples, and despite having the same code, my code won't run like the example in the book.
The code aims to use the strstr() function to find a string within another string, but after running my code, it only asks for my input, and displays "Program ended with exit code: 0"

Below is my code:

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

char tracks[][80] = {
    "I left my heart in Harvard Med School",
    "Newark, Newark - a wonderful town",
    "Dancing with a Dork",
    "From here to maternity",
    "The girl from Iwo Jima",
};

void find_track(char search_for[])
{
    int i;
    for (i=0; i<5; i++) {
        if(strstr(tracks[i],search_for))
            printf("Track %i: '%s'\n", i, tracks[i]);
    }
}

int main()
{
    char search_for[80];
    printf("Search for: ");
    fgets(search_for, 80, stdin);
    find_track(search_for);
    return 0;
}
</code>```

The result after running the code is:

```<code>Search for: (my input)
Program ended with exit code: 0
</code>```

Help!

答:
search_for[strlen(search_for)-1] = 0;
 fgets(search_for, 80, stdin);

fgets() adds a newline

Title: strstr() function in C programming

Body:
I am learning C from the book Head First C, and I tried one of the examples, and despite having the same code, my code won't run like the example in the book.
The code aims to use the strstr() function to find a string within another string, but after running my code, it only asks for my input, and displays "Program ended with exit code: 0"

Below is my code:

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

char tracks[][80] = {
    "I left my heart in Harvard Med School",
    "Newark, Newark - a wonderful town",
    "Dancing with a Dork",
    "From here to maternity",
    "The girl from Iwo Jima",
};

void find_track(char search_for[])
{
    int i;
    for (i=0; i<5; i++) {
        if(strstr(tracks[i],search_for))
            printf("Track %i: '%s'\n", i, tracks[i]);
    }
}

int main()
{
    char search_for[80];
    printf("Search for: ");
    fgets(search_for, 80, stdin);
    find_track(search_for);
    return 0;
}

The result after running the code is:

Search for: (my input)
Program ended with exit code: 0

Help!


问:
Will conditionals that are always false be removed by compiler in C#
Say I have the following code snippet in c#

```<code>static const bool DO_PERFORMANCE_CODE = false;

if (DO_PERFORMANCE_CODE)
{
   // performance monitoring code goes here
}
</code>```

Will that code get removed by the compiler? This is the functionality I'd like. Basically I want to mimic the conditional compilation stuff in C#, but I want more configurations other than Release and Debug. If there is a better way of doing this, I'd be open to hearing it.

答:
You can define your own precompiler variables.</p>

```<code> #define temp

 #if temp
 // Do something
 #endif
</code>```

OwnerDisplayName: WindyCityEagle

ContentLicense: CC BY-SA 2.5

Body:
Say I have the following code snippet in c#

static const bool DO_PERFORMANCE_CODE = false;

if (DO_PERFORMANCE_CODE)
{
   // performance monitoring code goes here
}

Will that code get removed by the compiler? This is the functionality I'd like. Basically I want to mimic the conditional compilation stuff in C#, but I want more configurations other than Release and Debug. If there is a better way of doing this, I'd be open to hearing it.

LastEditorDisplayName: Dana

Body:
You can define your own precompiler variables.

 #define temp

 #if temp
 // Do something
 #endif

OwnerDisplayName: Aaron Smith


问:
Send Variable arguments for Java execution using Ant
I have a build.xml where I have a target as follows:

```<code><target name="run" depends="compile">
    <java fork="true" classname="${main-class}">
        <arg value="${arg0}" />
        <arg value="${arg1}" />
        <arg value="${arg2}" />
        <arg value="${arg3}" />
        <arg value="${arg4}" />
        <arg value="${arg5}" />
        <arg value="${arg6}" />
        <classpath>
            <path refid="classpath" />
            <path location="${jar.dir}/${ant.project.name}.jar" />
        </classpath>
    </java>
</target>
</code>```

However I pass the arguments as :- ant -Darg0=XY -Darg1=ZX -Darg2=Sh -Darg3=RPR -Darg4=g -Darg5=t -Darg6=TC main. If I need to pass more variables then I will need to add argument field to the java tag in the run target as  and so forth.

答:
In this case I know the number of variable arguments that can be passed to the jar file. So I keep creating  elements. So for the above I had figured that the number of cases in use so I defined them as:-

```<code><property name="arg0" value="..."/>
<property name="arg1" value="..."/>
<property name="arg2" value="..."/>
<property name="arg3" value="..."/>
...
</code>```

Then I refer to them as:

```<code><arg value="${arg0}" />
<arg value="${arg1}" />
<arg value="${arg2}" />
<arg value="${arg3}" />
...
</code>```

To change the values in arg variables use :

```<code>ant -Darg0=value1 -Darg3=value2 run
</code>```

Refer to the variable I appending -D to it.

Body:
I have a build.xml where I have a target as follows:

<target name="run" depends="compile">
    <java fork="true" classname="${main-class}">
        <arg value="${arg0}" />
        <arg value="${arg1}" />
        <arg value="${arg2}" />
        <arg value="${arg3}" />
        <arg value="${arg4}" />
        <arg value="${arg5}" />
        <arg value="${arg6}" />
        <classpath>
            <path refid="classpath" />
            <path location="${jar.dir}/${ant.project.name}.jar" />
        </classpath>
    </java>
</target>

However I pass the arguments as :- ant -Darg0=XY -Darg1=ZX -Darg2=Sh -Darg3=RPR -Darg4=g -Darg5=t -Darg6=TC main. If I need to pass more variables then I will need to add argument field to the java tag in the run target as  and so forth.

Body:
In this case I know the number of variable arguments that can be passed to the jar file. So I keep creating  elements. So for the above I had figured that the number of cases in use so I defined them as:-

<property name="arg0" value="..."/>
<property name="arg1" value="..."/>
<property name="arg2" value="..."/>
<property name="arg3" value="..."/>
...

Then I refer to them as:

<arg value="${arg0}" />
<arg value="${arg1}" />
<arg value="${arg2}" />
<arg value="${arg3}" />
...

To change the values in arg variables use :

ant -Darg0=value1 -Darg3=value2 run

Refer to the variable I appending -D to it.


问:
"Error: [$injector:unpr] Unknown provider:" when updating controller dependencies
I'm unable to get my project to run. It's fine until I...

Update my controller to include the "$ionicPlatform, $cordovaToast, $cordovaLocalNotification"

```<code>.controller('MenuController', ['$scope', 'menuFactory', 'dishes', 'favoriteFactory', 'baseURL', '$ionicListDelegate', '$ionicPlatform', '$cordovaToast',  '$cordovaLocalNotification',
function ($scope, menuFactory, dishes, favoriteFactory, baseURL, $ionicListDelegate, $ionicPlatform, $cordovaToast, $cordovaLocalNotification) {
</code>```

I attempt to run my project and get

Error: [$injector:unpr] Unknown provider: $cordovaLocalNotificationProvider <- $cordovaLocalNotification <- MenuController

Then Angular doc and other posts I've seen suggest that that $cordovaLocalNotification has been omitted or misspelled in the dependency injection for this controller, but I'm sure they're the same.

答:
make sure that you have included all the required JS files that is required to work $cordovaLocalNotification.</p>

```<code> <!-- ngCordova -->
<script src="lib/ngCordova/dist/ng-cordova.js"></script>

 var ctrls = angular.module('notiApp.controllers', ['ionic', 'ngCordova', 'ngCordova.plugins']);
</code>```

Body:
I'm unable to get my project to run. It's fine until I...

Update my controller to include the "$ionicPlatform, $cordovaToast, $cordovaLocalNotification"

.controller('MenuController', ['$scope', 'menuFactory', 'dishes', 'favoriteFactory', 'baseURL', '$ionicListDelegate', '$ionicPlatform', '$cordovaToast',  '$cordovaLocalNotification',
function ($scope, menuFactory, dishes, favoriteFactory, baseURL, $ionicListDelegate, $ionicPlatform, $cordovaToast, $cordovaLocalNotification) {

I attempt to run my project and get

Error: [$injector:unpr] Unknown provider: $cordovaLocalNotificationProvider <- $cordovaLocalNotification <- MenuController

Then Angular doc and other posts I've seen suggest that that $cordovaLocalNotification has been omitted or misspelled in the dependency injection for this controller, but I'm sure they're the same.

Body:
make sure that you have included all the required JS files that is required to work $cordovaLocalNotification.

 <!-- ngCordova -->
<script src="lib/ngCordova/dist/ng-cordova.js"></script>

 var ctrls = angular.module('notiApp.controllers', ['ionic', 'ngCordova', 'ngCordova.plugins']);


问:
Django Framework: Python function in views.py unable to find the json file
I am trying to write into a json file through a python function. The python function dumps the python data structure into a json file using json.dumps funtion.
The file gets created as well as the python data structure in form of json object is present in the json file but when javascript function present inside the python function tries to open and read the object it fails.
I get the following error: Not found file_name.json
I am pretty sure that the file is indeed present.

```<code>def func(request):

arr = [[]]
message = ''
arr[0].append('Hello')
arr[0].append('There')
arr.append([])
arr[1].append('Good')
arr[1].append('Morning')
arr[1].append('!')
message = message + '<html><head><script type="text/javascript" src="outputjson.js"></script><script>function Hello(){alert(hello[1]);}</script></head>'

with open('outputjson.js', 'w') as fo:
        jsonp_structure = "hello = "+json.dumps(arr)+" "
        fo.write(jsonp_structure)
message = message + '<body><h1>This is shit and you know it</h1><input value="Click Bro" type="button" onclick="Hello();"></input></body></html>'
return HttpResponse(message)
</code>```

I get the error stating: Not found: outputjson.js

Do I need to explicitly tell Django where to look for the file ?

答:
keep the js file in the static folder and try something like this

```<code>from django.contrib.staticfiles.templatetags.staticfiles import static

url = static('outputjson.js')
</code>```

and in

```<code>src="'+url+'"
</code>```

Body:
I am trying to write into a json file through a python function. The python function dumps the python data structure into a json file using json.dumps funtion.
The file gets created as well as the python data structure in form of json object is present in the json file but when javascript function present inside the python function tries to open and read the object it fails.
I get the following error: Not found file_name.json
I am pretty sure that the file is indeed present.

def func(request):

arr = [[]]
message = ''
arr[0].append('Hello')
arr[0].append('There')
arr.append([])
arr[1].append('Good')
arr[1].append('Morning')
arr[1].append('!')
message = message + ''

with open('outputjson.js', 'w') as fo:
        jsonp_structure = "hello = "+json.dumps(arr)+" "
        fo.write(jsonp_structure)
message = message + '
This is shit and you know it
<input value="Click Bro" type="button" onclick="Hello();"></input>'
return HttpResponse(message)

I get the error stating: Not found: outputjson.js

Do I need to explicitly tell Django where to look for the file ?

Body:
keep the js file in the static folder and try something like this

from django.contrib.staticfiles.templatetags.staticfiles import static

url = static('outputjson.js')

and in

src="'+url+'"


问:
Passing DataContext between windows in MVVM
On the main window onClick I have

```<code>AddNoticeAboutWrongCity addNoticeAboutWrongCity = new AddNoticeAboutWrongCity();
addNoticeAboutWrongCity.DataContext = ((VerificationViewModule)this.DataContext).WrongCityNotice;
addNoticeAboutWrongCity.ShowDialog();
</code>```

At popup window there a lot of textboxes and two buttons

Delete object:

this.DataContext = null;

And second option "Save edited notice" which is not usable , because every change of user affection datacontext on main window,and this is demand from design department :)

I don't know why first option(it's "implementation" doesn't work.

Second explanation:

On the ParentWindow I have list of Notices and I can click EditSelectedNotice.

On the EditNoticeWindow I can edit Notice or delete Notice.

Editinig works(After closing EditNoticeWindow  I see changed notice on the ParentWindow), but deleting doesn't (Notice is still in collection - on control and in this.DataContext)

My ViewModel:

```<code>class VerificationViewModule
    {
        public ObservableCollection<ReporterNotice> ReporterNotices { get; set; }

        public ReporterNotice OtherNotice
        {
            get
            {
                return ReporterNotices.Where(n => n.Type == ReporterNoticeType.Other).FirstOrDefault();
            }
        }
        public ReporterNotice DuplicateNotice
        {
            get
            {
                return ReporterNotices.Where(n => n.Type == ReporterNoticeType.Duplicate).FirstOrDefault();
            }
        }
        public ReporterNotice WrongCityNotice
        {
            get
            {
                return ReporterNotices.Where(n => n.Type == ReporterNoticeType.WrongCity).FirstOrDefault();
            }
            set { if(value==null)
            {
                ReporterNotices.Remove(ReporterNotices.Where(n => n.Type == ReporterNoticeType.WrongCity).First());
            }
            else
            {
                if (ReporterNotices.Where(n => n.Type == ReporterNoticeType.WrongCity).FirstOrDefault()==null)//there is always only max one instance of this type of notice
                {
                    ReporterNotices.Add(value);
                }
                else
                {
                    var c = ReporterNotices.Where(n => n.Type == ReporterNoticeType.WrongCity).First();
                    c = value;

                }
            }}
        }

         public VerificationViewModule()
        {
            ObservableCollection<ReporterNotice> loadedReporterNotices = new ObservableCollection<ReporterNotice>();
            loadedReporterNotices.Add(new ReporterNotice() { Content = "Dublic", Type = ReporterNoticeType.WrongCity });
            loadedReporterNotices.Add(new ReporterNotice() { Content = "Hilton", Type = ReporterNoticeType.Duplicate });
            loadedReporterNotices.Add(new ReporterNotice() { Content = "Another notice", Type = ReporterNoticeType.Other });
            ReporterNotices = loadedReporterNotices;
        }

    }
</code>```

答:
You're trying to destroy the DataContext. C# doesn't work that way. Setting an object reference to null doesn't delete the object, it only removes the reference to it. (When nothing references an object anymore it gets garbage collected, but you can't destroy an object directly).

DataContext = null only means that locally your DataContext doesn't point to any object any more. The main view model still has a reference however so nothing changes there. You'll have to ask the main view model to remove the notification from it's collection (probably through a callback method (Action) is best so you don't have to know about the parent view model).

Body:
On the main window onClick I have

AddNoticeAboutWrongCity addNoticeAboutWrongCity = new AddNoticeAboutWrongCity();
addNoticeAboutWrongCity.DataContext = ((VerificationViewModule)this.DataContext).WrongCityNotice;
addNoticeAboutWrongCity.ShowDialog();

At popup window there a lot of textboxes and two buttons

Delete object:

this.DataContext = null;

And second option "Save edited notice" which is not usable , because every change of user affection datacontext on main window,and this is demand from design department :)

I don't know why first option(it's "implementation" doesn't work.

Second explanation:

On the ParentWindow I have list of Notices and I can click EditSelectedNotice.

On the EditNoticeWindow I can edit Notice or delete Notice.

Editinig works(After closing EditNoticeWindow  I see changed notice on the ParentWindow), but deleting doesn't (Notice is still in collection - on control and in this.DataContext)

My ViewModel:

class VerificationViewModule
    {
        public ObservableCollection<ReporterNotice> ReporterNotices { get; set; }

        public ReporterNotice OtherNotice
        {
            get
            {
                return ReporterNotices.Where(n => n.Type == ReporterNoticeType.Other).FirstOrDefault();
            }
        }
        public ReporterNotice DuplicateNotice
        {
            get
            {
                return ReporterNotices.Where(n => n.Type == ReporterNoticeType.Duplicate).FirstOrDefault();
            }
        }
        public ReporterNotice WrongCityNotice
        {
            get
            {
                return ReporterNotices.Where(n => n.Type == ReporterNoticeType.WrongCity).FirstOrDefault();
            }
            set { if(value==null)
            {
                ReporterNotices.Remove(ReporterNotices.Where(n => n.Type == ReporterNoticeType.WrongCity).First());
            }
            else
            {
                if (ReporterNotices.Where(n => n.Type == ReporterNoticeType.WrongCity).FirstOrDefault()==null)//there is always only max one instance of this type of notice
                {
                    ReporterNotices.Add(value);
                }
                else
                {
                    var c = ReporterNotices.Where(n => n.Type == ReporterNoticeType.WrongCity).First();
                    c = value;

                }
            }}
        }

         public VerificationViewModule()
        {
            ObservableCollection<ReporterNotice> loadedReporterNotices = new ObservableCollection<ReporterNotice>();
            loadedReporterNotices.Add(new ReporterNotice() { Content = "Dublic", Type = ReporterNoticeType.WrongCity });
            loadedReporterNotices.Add(new ReporterNotice() { Content = "Hilton", Type = ReporterNoticeType.Duplicate });
            loadedReporterNotices.Add(new ReporterNotice() { Content = "Another notice", Type = ReporterNoticeType.Other });
            ReporterNotices = loadedReporterNotices;
        }

    }


问:
Jmeter- how to extract start and end dates from System Calendar and then pass it to variable
I need to dynamically extract start and end dates of System Calendar control.
Example: On clicking System Calendar, Start date is May 29th and End date is June 9th.
Is it possible to extract this dynamically and then pass the same to variables in the Jmeter script, please let me know</p>

答:
If the values are present in the HTTP response - it is possible to extract them using one of JMeter's Post Processors, depending on the nature of the response data you can use:

Regular Expression Extractor - for any text-based response

CSS/JQuery Extractor - for HTML

XPath Extractor - for XML, XHTML and HTML

JSON Extractor - for JSON

Also be aware that you can use __time() function to get the current time in different formats and scripting for time manipulation (i.e. add 10 business days to given date)


问:
CFURLCopyResourcePropertyForKey failed because passed URL no scheme
I have a program that saves a file to the iCloud and this has worked great for iOS7, but now I get this error with iOS8 and cannot seem to find the answer on how to fix it. Anyone else had this problem? Any ideas would be greatly appreciated.

The Error:
CFURLCopyResourcePropertyForKey failed because it was passed this URL which has no scheme: /var/mobile/Containers/Data/Application/ASFHDDE3-B1BB-41D7-A47C-DCC328362W21/Documents/mypictostore.png

The Line of Code Throws Error:
[fileManager setUbiquitous:YES itemAtURL:backupUrl destinationURL:[[ubiq URLByAppendingPathComponent:@"Documents" isDirectory:true] URLByAppendingPathComponent:backupName] error:&theError];

URLS:
destinationURL: file:///private/var/mobile/Library/Mobile%20Documents/ABC23455~MY-Program/
backupUrl: /var/mobile/Containers/Data/Application/ASDFGEEW-B1BB—6FR6-A47C-DCCF21876D36/Documents/mypic.png

Thank you,
Jon

答:
look, I find this,The url is The location to write the data into. we should tell the system a file path.

var filePath = "file://(fileURLpath)"

var url:URL = URL.init(fileURLWithPath: fileURLpath)

Data


问:
Asp.Net Web API Error: The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'
Simplest example of this, I get a collection and try to output it via Web API:

```<code>// GET api/items
public IEnumerable<Item> Get()
{
    return MyContext.Items.ToList();
}
</code>```

And I get the error:

Object of type

'System.Data.Objects.ObjectQuery`1[Dcip.Ams.BO.EquipmentWarranty]'
  cannot be converted to type

'System.Data.Entity.DbSet`1[Dcip.Ams.BO.EquipmentWarranty]'

This is a pretty common error to do with the new proxies, and I know that I can fix it by setting:

```<code>MyContext.Configuration.ProxyCreationEnabled = false;
</code>```

But that defeats the purpose of a lot of what I am trying to do.  Is there a better way?

答:
Add the following code in Application_Start function of Global.asax.cs:

```<code>GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings
    .ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
GlobalConfiguration.Configuration.Formatters
    .Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
</code>```

This instruct the API to serialize every response into JSON and remove XML responses.

Body:
Simplest example of this, I get a collection and try to output it via Web API:

// GET api/items
public IEnumerable<Item> Get()
{
    return MyContext.Items.ToList();
}

And I get the error:

Object of type

'System.Data.Objects.ObjectQuery`1[Dcip.Ams.BO.EquipmentWarranty]'
  cannot be converted to type

'System.Data.Entity.DbSet`1[Dcip.Ams.BO.EquipmentWarranty]'

This is a pretty common error to do with the new proxies, and I know that I can fix it by setting:

MyContext.Configuration.ProxyCreationEnabled = false;

But that defeats the purpose of a lot of what I am trying to do.  Is there a better way?

Body:
Add the following code in Application_Start function of Global.asax.cs:

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings
    .ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
GlobalConfiguration.Configuration.Formatters
    .Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);

This instruct the API to serialize every response into JSON and remove XML responses.


问:
Coding a Scatter plot with smooth lines in VBA
I am trying to code for a Scatter Plot using smooth lines with VBA.
I am trying to take data off of a worksheet and create a scatter plot with lines and no markers in the same workbook different sheet using VBA.

This is part snapshot of my worksheet

The values below 247 and between 263 to 455 in column A will have corresponding -1.75 in column B.

The x values are in range A1:A401

y-values are in range B1:B401

Also I want to have title to my graph and X and Y axis labelled. I am having trouble figuring how to get the y-values to plot with the x-values instead of excel making two seperate lines on the chart.

This is graph I need

This is the code I have used

```<code>Set xData = ThisWorkbook.Worksheets(2).Range("A1:A" & LastRow_this)
Set yData = ThisWorkbook.Worksheets(2).Range("B1:B" & LastRow_this)

Set GraphRange = Union(xData, yData)

'Create a chart
  Set cht = ThisWorkbook.Worksheets(1).Shapes.AddChart2

'Give chart some data
  cht.Chart.SetSourceData Source:=GraphRange

'Determine the chart type
  cht.Chart.ChartType = xlXYScatterLines
</code>```

This is what it gives me in Excel.

How can I get the desired result ?

Also what can I do if the range is dynamic ?

答:
With a scatter chart you don't want to use "GraphRange" for the whole chart. Depending on the data and the phase of the moon, Excel will try to plot the X and the Y data as individual series, which is not what you want.

Instead, edit or insert each series separately and set the range for the X and the Y values. Also you need xlXYScatterSmoothNoMarkers as the chart type.

Try using the macro recorder to select the range, add a scatter chart with smoothed lines. Then inspect the code. This will give you valuable pointers about the changes you need to make to your code.

Body:
I am trying to code for a Scatter Plot using smooth lines with VBA.
I am trying to take data off of a worksheet and create a scatter plot with lines and no markers in the same workbook different sheet using VBA.

This is part snapshot of my worksheet

The values below 247 and between 263 to 455 in column A will have corresponding -1.75 in column B.

The x values are in range A1:A401

y-values are in range B1:B401

Also I want to have title to my graph and X and Y axis labelled. I am having trouble figuring how to get the y-values to plot with the x-values instead of excel making two seperate lines on the chart.

This is graph I need

This is the code I have used

Set xData = ThisWorkbook.Worksheets(2).Range("A1:A" & LastRow_this)
Set yData = ThisWorkbook.Worksheets(2).Range("B1:B" & LastRow_this)

Set GraphRange = Union(xData, yData)

'Create a chart
  Set cht = ThisWorkbook.Worksheets(1).Shapes.AddChart2

'Give chart some data
  cht.Chart.SetSourceData Source:=GraphRange

'Determine the chart type
  cht.Chart.ChartType = xlXYScatterLines

This is what it gives me in Excel.

How can I get the desired result ?

Also what can I do if the range is dynamic ?


问:
Transform a string to Vector3
I have this string in a MySQL database:

"-1035.43, -2728.861, 13.75664"

How can i transform it to a Vector3 to use it in this function:

```<code>Vector3 newpos = new Vector3(getChar[15]);
API.setEntityPosition(player, newpos);
</code>```

getChar is the database list, and the 15 is the value.

答:
Split the string and extract the coordinates:

```<code>float[] newPosCoordinates = getChar[15].Split(new string[] { ", " }, StringSplitOptions.None).Select(x => float.Parse(x)).ToArray();
Vector3 newpos = new Vector3(newPosCoordinates[0], newPosCoordinates[1], newPosCoordinates[2]);
</code>```

Title: Transform a string to Vector3

Body:
I have this string in a MySQL database:

"-1035.43, -2728.861, 13.75664"

How can i transform it to a Vector3 to use it in this function:

Vector3 newpos = new Vector3(getChar[15]);
API.setEntityPosition(player, newpos);

getChar is the database list, and the 15 is the value.

Body:
Split the string and extract the coordinates:

float[] newPosCoordinates = getChar[15].Split(new string[] { ", " }, StringSplitOptions.None).Select(x => float.Parse(x)).ToArray();
Vector3 newpos = new Vector3(newPosCoordinates[0], newPosCoordinates[1], newPosCoordinates[2]);


问:
Visual Studio 2017 not loading AjaxMin MSBuild Task from specified path
I'm attempting update an existing application so that it will load in Visual Studio 2017 (Enterprise - V15.2 (26430.12)) from Visual Studio 2015 (Enterprise) and having issues with the AjaxMin build task.

In Visual Studio 2015, the AjaxMin build task is found in C:\Program Files (x86)\MSBuild\Microsoft\MicrosoftAjax.  Visual Studio 2017 looks for it in C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Microsoft.  Given that all developers on the team may not have VS2017 Enterprise and we've had issues in the past with developers installing the wrong version, I'd like to have it use the AjaxMin NuGet package referenced in the solution.

There are 3 projects in the solution that use the AjaxMin task.  I've updated all of them to have the following import:

```<code><?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="12.0">
...
<Import Project="$(MSBuildProjectDirectory)\..\..\..\packages\AjaxMin.5.14.5506.26202\tools\net40\AjaxMin.targets" />
<Target Name="BeforeBuild">
  <ItemGroup>
    <JS Include="..." Exclude="..." />
  </ItemGroup>
  <ItemGroup>
    <CSS Include="..." Exclude="..." />
  </ItemGroup>
  <AjaxMin Switches="..." JsSourceFiles="@(JS)" JsCombinedFileName="..." CssSourceFiles="@(CSS)" CssCombinedFileName="..." />
</Target>
...
</Project>
</code>```

However, when the build happens, I receive an error saying it can't find the AjaxMin task in the default build extensions directory:

The "AjaxMin" task could not be loaded from the assembly C:\Program
  Files (x86)\Microsoft Visual
  Studio\2017\Enterprise\MSBuild\Microsoft\MicrosoftAjax\AjaxMinTask.dll.
  Could not load file or assembly 'file:///C:\Program Files
  (x86)\Microsoft Visual
  Studio\2017\Enterprise\MSBuild\Microsoft\MicrosoftAjax\AjaxMinTask.dll'
  or one of its dependencies. The system cannot find the file specified.
  Confirm that the  declaration is correct, that the assembly
  and all its dependencies are available, and that the task contains a
  public class that implements Microsoft.Build.Framework.ITask.

I've used the MSBuild Message Task to output the path and verified that it is correct by navigating to it from the command prompt.  I also tried using the UsingTask with no luck there.

Why is Visual Studio not looking for the AjaxMin DLL in the location I specified?

Update:
I moved the import tag for AjaxMin to the top (right under the project tag) and it works now.  I don't understand why.

答:
I moved the import tag for AjaxMin to the top (right under the project tag) and it works now. I don't understand why.

If I understand your question correctly, that is because you have two reference sources for the AjaxMinTask.dll, one is the default assembly source:C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Microsoft\MicrosoftAjax, another is the import reference, you will notice that the AjaxMinTask.dll is used in the AjaxMin.targets:

```<code><Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

<UsingTask AssemblyFile="AjaxMinTask.dll" TaskName="AjaxMin" />
<UsingTask AssemblyFile="AjaxMinTask.dll" TaskName="AjaxMinBundleTask" />
<UsingTask AssemblyFile="AjaxMinTask.dll" TaskName="AjaxMinManifestTask" />
<UsingTask AssemblyFile="AjaxMinTask.dll" TaskName="AjaxMinManifestCleanTask" />

 ...
</Project>
</code>```

So when set the import reference behind your task, MSBuild will use the default assembly source (under the VS2017 installation directory), when you set the import reference before you task, the AjaxMin.targets will rewrite the path of reference source.

Body:
I'm attempting update an existing application so that it will load in Visual Studio 2017 (Enterprise - V15.2 (26430.12)) from Visual Studio 2015 (Enterprise) and having issues with the AjaxMin build task.

In Visual Studio 2015, the AjaxMin build task is found in C:\Program Files (x86)\MSBuild\Microsoft\MicrosoftAjax.  Visual Studio 2017 looks for it in C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Microsoft.  Given that all developers on the team may not have VS2017 Enterprise and we've had issues in the past with developers installing the wrong version, I'd like to have it use the AjaxMin NuGet package referenced in the solution.

There are 3 projects in the solution that use the AjaxMin task.  I've updated all of them to have the following import:

<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="12.0">
...
<Import Project="$(MSBuildProjectDirectory)\..\..\..\packages\AjaxMin.5.14.5506.26202\tools\net40\AjaxMin.targets" />
<Target Name="BeforeBuild">
  <ItemGroup>
    <JS Include="..." Exclude="..." />
  </ItemGroup>
  <ItemGroup>
    <CSS Include="..." Exclude="..." />
  </ItemGroup>
  <AjaxMin Switches="..." JsSourceFiles="@(JS)" JsCombinedFileName="..." CssSourceFiles="@(CSS)" CssCombinedFileName="..." />
</Target>
...
</Project>

However, when the build happens, I receive an error saying it can't find the AjaxMin task in the default build extensions directory:

The "AjaxMin" task could not be loaded from the assembly C:\Program
  Files (x86)\Microsoft Visual
  Studio\2017\Enterprise\MSBuild\Microsoft\MicrosoftAjax\AjaxMinTask.dll.
  Could not load file or assembly 'file:///C:\Program Files
  (x86)\Microsoft Visual
  Studio\2017\Enterprise\MSBuild\Microsoft\MicrosoftAjax\AjaxMinTask.dll'
  or one of its dependencies. The system cannot find the file specified.
  Confirm that the  declaration is correct, that the assembly
  and all its dependencies are available, and that the task contains a
  public class that implements Microsoft.Build.Framework.ITask.

I've used the MSBuild Message Task to output the path and verified that it is correct by navigating to it from the command prompt.  I also tried using the UsingTask with no luck there.

Why is Visual Studio not looking for the AjaxMin DLL in the location I specified?

Update:
I moved the import tag for AjaxMin to the top (right under the project tag) and it works now.  I don't understand why.

Body:
I moved the import tag for AjaxMin to the top (right under the project tag) and it works now. I don't understand why.

If I understand your question correctly, that is because you have two reference sources for the AjaxMinTask.dll, one is the default assembly source:C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Microsoft\MicrosoftAjax, another is the import reference, you will notice that the AjaxMinTask.dll is used in the AjaxMin.targets:

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

<UsingTask AssemblyFile="AjaxMinTask.dll" TaskName="AjaxMin" />
<UsingTask AssemblyFile="AjaxMinTask.dll" TaskName="AjaxMinBundleTask" />
<UsingTask AssemblyFile="AjaxMinTask.dll" TaskName="AjaxMinManifestTask" />
<UsingTask AssemblyFile="AjaxMinTask.dll" TaskName="AjaxMinManifestCleanTask" />

 ...
</Project>

So when set the import reference behind your task, MSBuild will use the default assembly source (under the VS2017 installation directory), when you set the import reference before you task, the AjaxMin.targets will rewrite the path of reference source.


答:
That code is wrong; fgets reads a full line, leaving the newline character in the target buffer (unless you provided exactly 79 characters). For that reason, find_track will look for a string with a terminating newline, which of course cannot be found.

A possible fix can be to remove the last character from the input string, just after the fgets.

```<code>if(*search_for) search_for[strlen(search_for) -1] = 0;
</code>```

or to use a different input function, which does not read the newline.

Title: strstr() function in C programming

Body:
I am learning C from the book Head First C, and I tried one of the examples, and despite having the same code, my code won't run like the example in the book.
The code aims to use the strstr() function to find a string within another string, but after running my code, it only asks for my input, and displays "Program ended with exit code: 0"

Below is my code:

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

char tracks[][80] = {
    "I left my heart in Harvard Med School",
    "Newark, Newark - a wonderful town",
    "Dancing with a Dork",
    "From here to maternity",
    "The girl from Iwo Jima",
};

void find_track(char search_for[])
{
    int i;
    for (i=0; i<5; i++) {
        if(strstr(tracks[i],search_for))
            printf("Track %i: '%s'\n", i, tracks[i]);
    }
}

int main()
{
    char search_for[80];
    printf("Search for: ");
    fgets(search_for, 80, stdin);
    find_track(search_for);
    return 0;
}

The result after running the code is:

Search for: (my input)
Program ended with exit code: 0

Help!

Body:
That code is wrong; fgets reads a full line, leaving the newline character in the target buffer (unless you provided exactly 79 characters). For that reason, find_track will look for a string with a terminating newline, which of course cannot be found.

A possible fix can be to remove the last character from the input string, just after the fgets.

if(*search_for) search_for[strlen(search_for) -1] = 0;

or to use a different input function, which does not read the newline.


问:
Exec function in c is not running
This is not running on my Mac for some reasons that I can't figure out. the output I am getting is only from the main.c
the output is

```<code>Parent PID 4066
Child PID 4067
Process 4067 exited with status 5
</code>```

I need the main.c to execute counter.c and pass the argument 5 which I will then have to use it inside the for a loop, but I can't get exec to run at all no matter what path I put.

//main.c

```<code>int main(int argc, char *argv[]) {

    pid_t childOrZero = fork();

    if (childOrZero < 0){
        perror("Error happened while trying to fork\n");
        exit(-1);
    }

    if (childOrZero == 0){
        printf("Child PID %d\n", (int)getpid());
        execl("./counter", "5", NULL);
        exit(5);
    }

    // THis must be parent
    printf("Parent PID %d\n", (int)getpid());
    int status = 0;
    pid_t childpid = wait(&status);
    int childReturnedValue = WEXITSTATUS(status);
    printf("Process %d exited with status %d\n", (int)childOrZero, childReturnedValue);

    return 0;
}
</code>```

counter.c

```<code>#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main (int argc, char *argv[]){
    for (int i = 0; i<5; i++){
        printf("Process: %d  %d\n", (int)getpid(),i);
        //sleep(3);
    }
}
</code>```

答:
Read documentation of execl for MacOSX and the POSIX specification of execl

It can fail (and that is the only case when it is returning). So code:

```<code>if (childOrZero == 0){
    printf("Child PID %d\n", (int)getpid());
    execl("./counter", "5", NULL);
    perror("execl counter");
    exit(5);
}
</code>```

Title: Exec function in c is not running

Body:
This is not running on my Mac for some reasons that I can't figure out. the output I am getting is only from the main.c
the output is

Parent PID 4066
Child PID 4067
Process 4067 exited with status 5

I need the main.c to execute counter.c and pass the argument 5 which I will then have to use it inside the for a loop, but I can't get exec to run at all no matter what path I put.

//main.c

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

    pid_t childOrZero = fork();

    if (childOrZero < 0){
        perror("Error happened while trying to fork\n");
        exit(-1);
    }

    if (childOrZero == 0){
        printf("Child PID %d\n", (int)getpid());
        execl("./counter", "5", NULL);
        exit(5);
    }

    // THis must be parent
    printf("Parent PID %d\n", (int)getpid());
    int status = 0;
    pid_t childpid = wait(&status);
    int childReturnedValue = WEXITSTATUS(status);
    printf("Process %d exited with status %d\n", (int)childOrZero, childReturnedValue);

    return 0;
}

counter.c

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main (int argc, char *argv[]){
    for (int i = 0; i<5; i++){
        printf("Process: %d  %d\n", (int)getpid(),i);
        //sleep(3);
    }
}

Body:
Read documentation of execl for MacOSX and the POSIX specification of execl

It can fail (and that is the only case when it is returning). So code:

if (childOrZero == 0){
    printf("Child PID %d\n", (int)getpid());
    execl("./counter", "5", NULL);
    perror("execl counter");
    exit(5);
}


问:
RETURN values in PHP
I have 2 functions in PHP and i want to return a value to one function to another. this is my functions

```<code> public function save_payment_log_data($icasl_number, $exam_session) {

$paylog_av = $this->payment_log_exists($icasl_number, $exam_session);

}

function payment_log_exists($icasl_no, $exam_session) {
        $this->db->where('icasl_no', $icasl_no);
        $this->db->where('exam_session', $exam_session);
        $query = $this->db->get('exm_paymentlog');
        if ($query->num_rows() > 0) {
            $pl = $query->row();
            $pay_id = $pl->paylog_id;
            return $pay_id;
        } else {
            return false;
        }
    }
</code>```

I want to return $pay_id to the save_payment_log_data() function but in here $pay_id didn't return to that function. I think it's return from the function payment_log_exists()
so how can I return $pay_id to the  save_payment_log_data() function

答:
See this example it's working fine:

```<code>function save_payment_log_data() {

$paylog_av = payment_log_exists();

# print the return value
echo $paylog_av;

}

function payment_log_exists() {
        return "Hello";
    }

save_payment_log_data();
</code>```

You can try to remove public and this form save_payment_log_data(),
and call the save_payment_log_data() function where you want.

Title: RETURN values in PHP

Body:
I have 2 functions in PHP and i want to return a value to one function to another. this is my functions

 public function save_payment_log_data($icasl_number, $exam_session) {

$paylog_av = $this->payment_log_exists($icasl_number, $exam_session);

}

function payment_log_exists($icasl_no, $exam_session) {
        $this->db->where('icasl_no', $icasl_no);
        $this->db->where('exam_session', $exam_session);
        $query = $this->db->get('exm_paymentlog');
        if ($query->num_rows() > 0) {
            $pl = $query->row();
            $pay_id = $pl->paylog_id;
            return $pay_id;
        } else {
            return false;
        }
    }

I want to return $pay_id to the save_payment_log_data() function but in here $pay_id didn't return to that function. I think it's return from the function payment_log_exists()
so how can I return $pay_id to the  save_payment_log_data() function

Body:
See this example it's working fine:

function save_payment_log_data() {

$paylog_av = payment_log_exists();

# print the return value
echo $paylog_av;

}

function payment_log_exists() {
        return "Hello";
    }

save_payment_log_data();

You can try to remove public and this form save_payment_log_data(),
and call the save_payment_log_data() function where you want.


问:
Submit form after successful ajax call using jQuery in asp.net mvc 5
I have a form in an Asp.net MVC 5 project which has a Submit button. When the Submit button is clicked, I want to do the following:

Perform client=side validation using jQuery on various fields (required fields have been filled, email format is valid, etc...). That part is working fine.

Make an Ajax call that will perform some server side validation by calling an action from the controller and return a JSON response. The response contains a Success property and Errors property which contains a list of errors.

The Success property will return true if no error are found and the Errors property will be null. If errors are found the Success property is returns false and the Errors property contains a list of relevant errors.

I'm calling '\ApplicationForm\Validate' action from my ApplicationForm controller and this part is working fine.

When no errors are found in part 2, I want my form to be submitted as normal and call the '\ApplicationForm\Index' action so that my data can then be added to my database. I cannot get this part to work!!

The Submit button is defined as follows:

```<code><div class="form-group">
  <div>
    <input type="button" id="btnApply" value="Apply" class="btn btn-primary" />
  </div>
</div>
</code>```

My JavaScript code is defined as follows:

```<code>$('#AppllicationForm').submit(function () {
    if (!$(this).attr('validated')) {
        if ($(this).valid()) {
            $.ajax({
                type: "POST",
                data: $(this).serialize(),
                url: "/ApplicationForm/ValidateForm",
                dataType: 'json',
                success: function (response) {
                    $('validationSummary').show();
                    if (response != null && response.success) {
                        console.log('No Validation errors detected');
                        $('#ApplicationForm').attr('validated', true);
                        $('#ApplicationForm').attr('action', '/ApplicationForm/Index')
                            .submit();
                        return true;
                    }
                    else if (response != null && !response.success) {
                        console.log('Validation errors detected');
                        var errors = response['errors'];
                        displayValidationErrors(errors);
                        window.scrollTo(0, 0);
                    }
                    return false;
                },
                error: function (response) {
                    $('validationSummary').hide();
                    console.log(response);
                    return false;
                }
            });
        }
    }
    return false;
});
</code>```

The above is using a regular button but I've also tried to define its type as Submit but to no avail.

I know similar questions have been posted in the past but I cannot find one that has actually helped me out to find a resolution to my problem, so please bear with me and do not mark this question as a duplicate unless there is an actual question/answer with an actual resolution to my problem. Much appreciated!

The closest scenario I found to what I'm trying to achieve is can be found from this article on SO: Submit a form from inside an ajax success function that checks the values

I've been trying so many different things at this stage but nothing is working out. I either don't get the Index action to be called after the ValidateForm action, or either one or the other action is called or the only Index action is called or my model gets messed up, and the list goes on.

I'm clearly not doing this correctly or missing something but I'm at a complete stand still for now. I'm hoping that it will be something silly that I've missed and hopefully someone will clarify this for me.

Any help would be greatly appreciated.

答:
Please check below solution :

```<code>  $('#btnApply').on('click', function (event) {
        if ($('form').valid()) {
            event.preventDefault();
            $.ajax({
                type: "POST",
                data: $(this).serialize(),
                url: "/ApplicationForm/ValidateForm",
                dataType: 'json',
                success: function (response) {
                    $('validationSummary').show();
                    if (response != null && response.success) {
                        console.log('No Validation errors detected');
                        $('#ApplicationForm').attr('validated', true);
                        $('form').submit(); // Here form will be submmited to Index action.
                        return true;
                    }
                    else if (response != null && !response.success) {
                        console.log('Validation errors detected');
                        var errors = response['errors'];
                        displayValidationErrors(errors);
                        window.scrollTo(0, 0);
                    }
                    return false;
                },
                error: function (response) {
                    $('validationSummary').hide();
                    console.log(response);
                    return false;
                }
            });
    });
</code>```

And decorate your ValidateForm method with [HttpPost] attribute.

Body:
I have a form in an Asp.net MVC 5 project which has a Submit button. When the Submit button is clicked, I want to do the following:

Perform client=side validation using jQuery on various fields (required fields have been filled, email format is valid, etc...). That part is working fine.

Make an Ajax call that will perform some server side validation by calling an action from the controller and return a JSON response. The response contains a Success property and Errors property which contains a list of errors.

The Success property will return true if no error are found and the Errors property will be null. If errors are found the Success property is returns false and the Errors property contains a list of relevant errors.

I'm calling '\ApplicationForm\Validate' action from my ApplicationForm controller and this part is working fine.

When no errors are found in part 2, I want my form to be submitted as normal and call the '\ApplicationForm\Index' action so that my data can then be added to my database. I cannot get this part to work!!

The Submit button is defined as follows:

    <input type="button" id="btnApply" value="Apply" class="btn btn-primary" />

My JavaScript code is defined as follows:

$('#AppllicationForm').submit(function () {
    if (!$(this).attr('validated')) {
        if ($(this).valid()) {
            $.ajax({
                type: "POST",
                data: $(this).serialize(),
                url: "/ApplicationForm/ValidateForm",
                dataType: 'json',
                success: function (response) {
                    $('validationSummary').show();
                    if (response != null && response.success) {
                        console.log('No Validation errors detected');
                        $('#ApplicationForm').attr('validated', true);
                        $('#ApplicationForm').attr('action', '/ApplicationForm/Index')
                            .submit();
                        return true;
                    }
                    else if (response != null && !response.success) {
                        console.log('Validation errors detected');
                        var errors = response['errors'];
                        displayValidationErrors(errors);
                        window.scrollTo(0, 0);
                    }
                    return false;
                },
                error: function (response) {
                    $('validationSummary').hide();
                    console.log(response);
                    return false;
                }
            });
        }
    }
    return false;
});

The above is using a regular button but I've also tried to define its type as Submit but to no avail.

I know similar questions have been posted in the past but I cannot find one that has actually helped me out to find a resolution to my problem, so please bear with me and do not mark this question as a duplicate unless there is an actual question/answer with an actual resolution to my problem. Much appreciated!

The closest scenario I found to what I'm trying to achieve is can be found from this article on SO: Submit a form from inside an ajax success function that checks the values

I've been trying so many different things at this stage but nothing is working out. I either don't get the Index action to be called after the ValidateForm action, or either one or the other action is called or the only Index action is called or my model gets messed up, and the list goes on.

I'm clearly not doing this correctly or missing something but I'm at a complete stand still for now. I'm hoping that it will be something silly that I've missed and hopefully someone will clarify this for me.

Any help would be greatly appreciated.

Body:
Please check below solution :

  $('#btnApply').on('click', function (event) {
        if ($('form').valid()) {
            event.preventDefault();
            $.ajax({
                type: "POST",
                data: $(this).serialize(),
                url: "/ApplicationForm/ValidateForm",
                dataType: 'json',
                success: function (response) {
                    $('validationSummary').show();
                    if (response != null && response.success) {
                        console.log('No Validation errors detected');
                        $('#ApplicationForm').attr('validated', true);
                        $('form').submit(); // Here form will be submmited to Index action.
                        return true;
                    }
                    else if (response != null && !response.success) {
                        console.log('Validation errors detected');
                        var errors = response['errors'];
                        displayValidationErrors(errors);
                        window.scrollTo(0, 0);
                    }
                    return false;
                },
                error: function (response) {
                    $('validationSummary').hide();
                    console.log(response);
                    return false;
                }
            });
    });

And decorate your ValidateForm method with [HttpPost] attribute.


问:
Visual Studio Code powershell terminal display is broken
I am using VisualStudioCode with powershell, and the line breaks as shown below.

Do you have any idea why?

VisualStudioCode Version:

My settings file:

```<code>{
    "editor.fontFamily": "D2Coding",
    "editor.fontSize": 14,
    "editor.wordWrap": "on",
    "editor.mouseWheelZoom": true,
    "window.reopenFolders": "none",
    "workbench.colorTheme": "Visual Studio Dark",
    "workbench.welcome.enabled": false,
    "window.zoomLevel": 0,
    "editor.cursorStyle": "line-thin",
    "terminal.integrated.shell.windows": "C:\\Windows\\SysWOW64\\WindowsPowerShell\\v1.0\\powershell.exe"
}
</code>```

答:
You should not be using the "SysWOW64" path for your powershell.exe console.

Update your terminal setting to this:

```<code>"terminal.integrated.shell.windows": "C:\\Windows\\sysnative\\WindowsPowerShell\\v1.0\\powershell.exe"
</code>```

If you are running Windows 10 you can remove it all together as VS Code will default to PowerShell as the terminal for Windows.

Body:
I am using VisualStudioCode with powershell, and the line breaks as shown below.

Do you have any idea why?

VisualStudioCode Version:

My settings file:

{
    "editor.fontFamily": "D2Coding",
    "editor.fontSize": 14,
    "editor.wordWrap": "on",
    "editor.mouseWheelZoom": true,
    "window.reopenFolders": "none",
    "workbench.colorTheme": "Visual Studio Dark",
    "workbench.welcome.enabled": false,
    "window.zoomLevel": 0,
    "editor.cursorStyle": "line-thin",
    "terminal.integrated.shell.windows": "C:\\Windows\\SysWOW64\\WindowsPowerShell\\v1.0\\powershell.exe"
}

Body:
You should not be using the "SysWOW64" path for your powershell.exe console.

Update your terminal setting to this:

"terminal.integrated.shell.windows": "C:\\Windows\\sysnative\\WindowsPowerShell\\v1.0\\powershell.exe"

If you are running Windows 10 you can remove it all together as VS Code will default to PowerShell as the terminal for Windows.


问:
Scala type mismatch [scala]
I have the following function

```<code>def weight(Actors:RDD[(String,Int)],name:String,count:Int):Float={
    val count1=Actors.lookup(name)
    val i_count=if (!count1.isEmpty) count1(0) else 0
    val edge=if (i_count!=0) (count.toFloat/i_count.toFloat) else 0.0
}
</code>```

and I get the following error

```<code> <console>:229: error: type mismatch;
 found   : Unit
 required: Float
       }
</code>```

Is it caused by divide 0 error?
How to solve that problem?

答:
This error means your are return Unit for weight method, but
def weight(Actors:RDD[(String,Int)],name:String,count:Int):Float  is expecting return Float value of this method, so this compile error is throwed.

Solution:

@Ramesh Maharjan has provided a way to fix this. but also you can try pattern match in Scala, like:

```<code>i_count match {
  case 0 => 0.0F
  case _=> count.toFloat/i_count.toFloat
}
</code>```

Title: Scala type mismatch [scala]

Body:
I have the following function

def weight(Actors:RDD[(String,Int)],name:String,count:Int):Float={
    val count1=Actors.lookup(name)
    val i_count=if (!count1.isEmpty) count1(0) else 0
    val edge=if (i_count!=0) (count.toFloat/i_count.toFloat) else 0.0
}

and I get the following error

 <console>:229: error: type mismatch;
 found   : Unit
 required: Float
       }

Is it caused by divide 0 error?
How to solve that problem?

Body:
This error means your are return Unit for weight method, but
def weight(Actors:RDD[(String,Int)],name:String,count:Int):Float  is expecting return Float value of this method, so this compile error is throwed.

Solution:

@Ramesh Maharjan has provided a way to fix this. but also you can try pattern match in Scala, like:

i_count match {
  case 0 => 0.0F
  case _=> count.toFloat/i_count.toFloat
}


问:
Android button open link in background?
I am looking to build a button in my android app that when the user clicks on the button, it'll load a URL in the background without the user seeing the page it loaded.
(the url sets off something in my api, if someone loads the url it triggers my api to do x thing, thats why I need it.)

I looked around and could not find anything useful already.
Thanks for any help.

答:
Without providing any progress bar or loader in Async task the users doesn't recognize that the page is loading.
Why the user need to click that button(i.e. you may make user to click that button for some other action right?)

Title: Android button open link in background?


问:
Removing from superview with gestureRecognizer
I create a blurEffectView as such:

```<code>var blurEffectView: UIVisualEffectView{
    let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light)
    let blurEffectView = UIVisualEffectView(effect: blurEffect)
    blurEffectView.frame = self.view.bounds
    blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    return blurEffectView
}
</code>```

And then a tapGestureRecognizer to add to the effect view.

```<code>let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.dismissBlurView))
            self.blurEffectView.addGestureRecognizer(tapGestureRecognizer)
            self.mapView.addSubview(self.blurEffectView)
</code>```

And here is the function to dismiss it:

```<code>func dismissBlurView(){
    blurEffectView.removeFromSuperview()
}
</code>```

I am obviously missing something here, as dismissBlurView is not called when I tap on the blur view.

答:
Try to use this code because it's working for me. I,ve changed block declaration and set the frame size outside of block in viewDidLoad.

```<code>var blurEffectView: UIVisualEffectView = {
        let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light)
        let blurEffectView = UIVisualEffectView(effect: blurEffect)
        blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        return blurEffectView
   }()
</code>```

// Set UIVisualEffectView frame in viewDidLoad

```<code>self.blurEffectView.frame = self.view.bounds

        self.blurEffectView.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(self.dismissBlurView(gesture:))))
        self.view.addSubview(self.blurEffectView)

func dismissBlurView(gesture: UITapGestureRecognizer){
        blurEffectView.removeFromSuperview()
    }
</code>```

Body:
I create a blurEffectView as such:

var blurEffectView: UIVisualEffectView{
    let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light)
    let blurEffectView = UIVisualEffectView(effect: blurEffect)
    blurEffectView.frame = self.view.bounds
    blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    return blurEffectView
}

And then a tapGestureRecognizer to add to the effect view.

let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.dismissBlurView))
            self.blurEffectView.addGestureRecognizer(tapGestureRecognizer)
            self.mapView.addSubview(self.blurEffectView)

And here is the function to dismiss it:

func dismissBlurView(){
    blurEffectView.removeFromSuperview()
}

I am obviously missing something here, as dismissBlurView is not called when I tap on the blur view.

Body:
Try to use this code because it's working for me. I,ve changed block declaration and set the frame size outside of block in viewDidLoad.

var blurEffectView: UIVisualEffectView = {
        let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light)
        let blurEffectView = UIVisualEffectView(effect: blurEffect)
        blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        return blurEffectView
   }()

// Set UIVisualEffectView frame in viewDidLoad

self.blurEffectView.frame = self.view.bounds

        self.blurEffectView.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(self.dismissBlurView(gesture:))))
        self.view.addSubview(self.blurEffectView)

func dismissBlurView(gesture: UITapGestureRecognizer){
        blurEffectView.removeFromSuperview()
    }


问:
About transaction in Realm database
This is my Realm object:

```<code>class AchievementDate : Object {

    dynamic var date: Date = Date()
    dynamic var apple: Int = Int(0)

    func save() {
        do {
            let realm = try Realm()
            try realm.write {
                realm.add(self)
            }
        } catch let error as NSError {
            fatalError(error.localizedDescription)
        }
    }
}
</code>```

I change apple's value in View controller's viewDidLoad() method, as you can see:

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    achievementDate.apple = 2
    achievementDate.save()
}
</code>```

then I update the apple's value when user clicks the pause button on the screen like this:

```<code>@IBAction func pausedButtonTapped(_ sender: UIButton) {
    achievementDate.apple += 1
    achievementDate.save()
}
</code>```

Xcode runs it successfully but when I click the pause button, the app crashes. In the console it says:

*** Terminating app due to uncaught exception 'RLMException', reason: 'Attempting to modify object outside of a write transaction - call
  beginWriteTransaction on an RLMRealm instance first.'

I am quite confused about this, btw, what does transaction mean in general? Thanks a lot.

答:
First, you need to define a Primary Key if you want to update the model:

```<code>class AchievementDate: Object {
    dynamic var id = 0
    dynamic var date:Date = Date()
    dynamic var apple:Int = Int(0)

    override static func primaryKey() -> String? {
        return "id"
    }
}
</code>```

Then update the model like:

```<code>static func save(achievementDate:AchievementDate) {
    let realm = try! Realm()
    try! realm.write {
        realm.add(achievementDate, update: true)
    }
}
</code>```

Alternatively, if you don't want primary Key, and the model is already retrieved from Realm, you could update the model like this:

```<code>let realm = try! Realm()
try! realm.write {
    achievementDate.apple = 2
}
</code>```

Title: About transaction in Realm database

Body:
This is my Realm object:

class AchievementDate : Object {

    dynamic var date: Date = Date()
    dynamic var apple: Int = Int(0)

    func save() {
        do {
            let realm = try Realm()
            try realm.write {
                realm.add(self)
            }
        } catch let error as NSError {
            fatalError(error.localizedDescription)
        }
    }
}

I change apple's value in View controller's viewDidLoad() method, as you can see:

override func viewDidLoad() {
    super.viewDidLoad()
    achievementDate.apple = 2
    achievementDate.save()
}

then I update the apple's value when user clicks the pause button on the screen like this:

@IBAction func pausedButtonTapped(_ sender: UIButton) {
    achievementDate.apple += 1
    achievementDate.save()
}

Xcode runs it successfully but when I click the pause button, the app crashes. In the console it says:

*** Terminating app due to uncaught exception 'RLMException', reason: 'Attempting to modify object outside of a write transaction - call
  beginWriteTransaction on an RLMRealm instance first.'

I am quite confused about this, btw, what does transaction mean in general? Thanks a lot.

Body:
First, you need to define a Primary Key if you want to update the model:

class AchievementDate: Object {
    dynamic var id = 0
    dynamic var date:Date = Date()
    dynamic var apple:Int = Int(0)

    override static func primaryKey() -> String? {
        return "id"
    }
}

Then update the model like:

static func save(achievementDate:AchievementDate) {
    let realm = try! Realm()
    try! realm.write {
        realm.add(achievementDate, update: true)
    }
}

Alternatively, if you don't want primary Key, and the model is already retrieved from Realm, you could update the model like this:

let realm = try! Realm()
try! realm.write {
    achievementDate.apple = 2
}


问:
File Reading Problems With Python
I am trying to read a file, (password list), I get the following error:

```<code>Traceback (most recent call last):
  File "C:\Users\ayden\Documents\2.1 Hacks\Python\PowerUp\FTPCracker.py", line 25, in <module>
    passwords = file.read()
  File "C:\Users\ayden\AppData\Local\Programs\Python\Python35-32\lib\encodings\cp1252.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x8f in position 1911885: character maps to <undefined>
</code>```

Is it too big or is there some weird unallowed character?

答:
Check the encoding of the file and then specify the same while opening it.

For eg if it's UTF8 encoded, then do:

```<code>file = open(filename, encoding="utf8")
</code>```

Title: File Reading Problems With Python

Body:
I am trying to read a file, (password list), I get the following error:

Traceback (most recent call last):
  File "C:\Users\ayden\Documents\2.1 Hacks\Python\PowerUp\FTPCracker.py", line 25, in <module>
    passwords = file.read()
  File "C:\Users\ayden\AppData\Local\Programs\Python\Python35-32\lib\encodings\cp1252.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x8f in position 1911885: character maps to <undefined>

Is it too big or is there some weird unallowed character?

Body:
Check the encoding of the file and then specify the same while opening it.

For eg if it's UTF8 encoded, then do:

file = open(filename, encoding="utf8")


问:
C# - Call the same javascript function inside a loop
Good day!

I am trying to achieve to change the color in the calendar cell of EXT Calendar for each holiday (holiday dates are from the database). But it only changes the first holiday which is the first line in the database.

My client side code :

```<code>        var applyCss = function (param1) {
        var css = "#CalendarPanel1-month-day-" + param1 + " {background-color: pink;}";

        Ext.net.ResourceMgr.registerCssClass("someCssClassId", css);
    };
</code>```

My server side code:

```<code>DataTable holiday = Attendance.getInstance().getHolidays();

            for (var i = 0; i < holiday.Rows.Count; i++)
            {
                var hd = holiday.Rows[i]["holiday_date"].ToString();
                Page.ClientScript.RegisterClientScriptBlock(GetType(), "myScript", "applyCss(" + hd + ")", true);

            }
</code>```

Appreciate any recommendations / suggestions / solutions. Thanks!

答:
My suggestion would be instead of looping through the cells and RegisterClientScriptBlock function in server side you can get all the cells in one 'string array' and pass that to the client side function as a parameter via RegisterClientScriptBlock function.

Your client side function's parameter should be of string array type and you can loop through the array in the client side which will fetch you the result.

Body:
Good day!

I am trying to achieve to change the color in the calendar cell of EXT Calendar for each holiday (holiday dates are from the database). But it only changes the first holiday which is the first line in the database.

My client side code :

        var applyCss = function (param1) {
        var css = "#CalendarPanel1-month-day-" + param1 + " {background-color: pink;}";

        Ext.net.ResourceMgr.registerCssClass("someCssClassId", css);
    };

My server side code:

DataTable holiday = Attendance.getInstance().getHolidays();

            for (var i = 0; i < holiday.Rows.Count; i++)
            {
                var hd = holiday.Rows[i]["holiday_date"].ToString();
                Page.ClientScript.RegisterClientScriptBlock(GetType(), "myScript", "applyCss(" + hd + ")", true);

            }

Appreciate any recommendations / suggestions / solutions. Thanks!


问:
Alert script goes wrong
I am using below alert script in VB.net

```<code>Response.Write("<script language=""javascript"">alert('please select the data first!');</script>")
</code>```

But after executing the code my menu table enhanced like enter image description here Menu before executing the code enter image description here
something wrong with the code that causes such abnormal change.

The menu asp.net code is as below:

```<code><table align ="right"  width="400" border="1" class="table" style="border: thin outset #000000; background-image: url('Images/Red.png'); color: #FFFFFF;">
    <tr>
        <td>
            <asp:Button ID="btnConvert" runat="server" AutoPostBack="true" Text="Convert to Pipeline" ValidationGroup="ChangeStatus"  />
        </td>
        <td class="auto-style8">
            <a href="CreateRecords.aspx" style="color: #FFFFFF">||Home</a>
            <div class="item-container">
            </div>
        </td>
        <td class="auto-style8">
            <a href="Reports.aspx" style="color: #FFFFFF">||Reports</a>
            <div class="item-container">
            </div>
        </td>
    </tr>
</table>
</code>```

答:
```<code>ScriptManager.RegisterStartupScript(Page, GetType(Page), "somekey", "alert('please select the data first!');", True)
</code>```

Title: Alert script goes wrong

Body:
I am using below alert script in VB.net

Response.Write("")

But after executing the code my menu table enhanced like enter image description here Menu before executing the code enter image description here
something wrong with the code that causes such abnormal change.

The menu asp.net code is as below:

            <asp:Button ID="btnConvert" runat="server" AutoPostBack="true" Text="Convert to Pipeline" ValidationGroup="ChangeStatus"  />

            ||Home

            ||Reports


答:
No, it's not related to division-by-zero.  Defining a val as the last line in your function will be treated as returning type Unit.  Changing it to the following will fulfill the Float return type you declared for the function:

```<code>if (i_count != 0) (count.toFloat / i_count.toFloat) else 0.toFloat
</code>```

Title: Scala type mismatch [scala]

Body:
No, it's not related to division-by-zero.  Defining a val as the last line in your function will be treated as returning type Unit.  Changing it to the following will fulfill the Float return type you declared for the function:

if (i_count != 0) (count.toFloat / i_count.toFloat) else 0.toFloat


问:
How to change the name and value of default ID field of an entity in jhipster
During Entity creation in jhipster, ID field gets created automatically, with auto-increment feature.

As per my requirement, i want the ID field name as TK_ID, instead of ID. And also, value of the ID field starts with 1 and gets incremented automatically. In my case , i want the value to be started with TK001, and should be auto incremented.

During Entity creation , i want these changes to happen. Is there any way to do this is jhipster application ?

Requirement: Instead of field name- ID, want as TK_ID..... And Value of ID field should start with TK001, instead of 1.

Note: I am using mysql for DB and Gateway application

答:
You're entering the world of Hibernate/JPA generators. If you look at the Jhipster entity generator you'll see that the ID is a @GeneratedValue that uses the Identity generation type, not the Increment type that you say.

There are many different types of ID generators that are explained over on this SO answer.

I would avoid changing the ID attribute itself (the one that is automatically generated by JHipster) to a different name or generation type as it could have a few unintended consequences, and there could be other JHipster dependencies. Simply too messy to edit and manage.

A better way is to create another attribute with the name TK_ID and create your own @GenericGenerator that takes the ID attribute and adds the prefix you want. e.g. if a new record will have the ID field value of 3, take it and add the prefix TK00.

Have a look at this SO answer for a code example.

Alternatively, you could transform any of your queries to TK_ID and point it to ID instead, and transform the result back to the format you want. That way you're not adding an extra attribute and changing the way the entity is created.


问:
Can't form a chain between two views/widgets in Android Studio
When I'm using the layout editor in Android Studio and I try to make a chain (bidirectional constraint) between a EditText View and a Button View using the constraint anchors, it doesn't make the chain.

It only makes a constraint if I try to constrain one View to the other.

I am trying to chain the right side of the EditText to the left side of the Button.

This is what my Layout Editor looks like:

答:
i think android studio ui editor need more improvement for creating chain currently i am using Android Studio Preview 3.0 Canary 3

Sometime from editor it works perfectly but sometime it not, when linking not happen from ui editor we need to add constraint manually as per requirement Vertical or horizontal chain following are constraints

```<code>layout_constraintTop_toTopOf
layout_constraintTop_toBottomOf
layout_constraintBottom_toTopOf
layout_constraintBottom_toBottomOf
layout_constraintBaseline_toBaselineOf
layout_constraintStart_toEndOf
layout_constraintStart_toStartOf
layout_constraintEnd_toStartOf
layout_constraintEnd_toEndOf
</code>```

and also we declare chain style manually in XML as follow

layout_constraintHorizontal_chainStyle or layout_constraintVertical_chainStyle

CHAIN_SPREAD -- the elements will be spread out (default style)

Weighted chain -- in CHAIN_SPREAD mode, if some widgets are set to MATCH_CONSTRAINT, they will split the available space

CHAIN_SPREAD_INSIDE -- similar, but the endpoints of the chain will not be spread out

CHAIN_PACKED -- the elements of the chain will be packed together. The horizontal or vertical bias attribute of the child will then affect the positioning of the packed elements

hope android studio editor will improve this

Body:
i think android studio ui editor need more improvement for creating chain currently i am using Android Studio Preview 3.0 Canary 3

Sometime from editor it works perfectly but sometime it not, when linking not happen from ui editor we need to add constraint manually as per requirement Vertical or horizontal chain following are constraints

layout_constraintTop_toTopOf
layout_constraintTop_toBottomOf
layout_constraintBottom_toTopOf
layout_constraintBottom_toBottomOf
layout_constraintBaseline_toBaselineOf
layout_constraintStart_toEndOf
layout_constraintStart_toStartOf
layout_constraintEnd_toStartOf
layout_constraintEnd_toEndOf

and also we declare chain style manually in XML as follow

layout_constraintHorizontal_chainStyle or layout_constraintVertical_chainStyle

CHAIN_SPREAD -- the elements will be spread out (default style)

Weighted chain -- in CHAIN_SPREAD mode, if some widgets are set to MATCH_CONSTRAINT, they will split the available space

CHAIN_SPREAD_INSIDE -- similar, but the endpoints of the chain will not be spread out

CHAIN_PACKED -- the elements of the chain will be packed together. The horizontal or vertical bias attribute of the child will then affect the positioning of the packed elements

hope android studio editor will improve this


问:
How to make a Dynamic Line Graph in PHP - Mysql
I want to make a dynamic line graph in php with mysql data. Please verify my Attached Image

How to get this type of graph ?

答:
Use this tutorial to plot graphs using Google visualisation.

https://developers.google.com/chart/interactive/docs/php_example

If you want to make it dynamic, you have to use AJAX to call a function in PHP which updates the graph every x seconds. To do that, update the function the following way

```<code>setInterval(function(){
$.ajax({url: "getData.php",
      dataType: "json",
      async: false

    }, dataType: "json"});
}, 1000);
</code>```

This will repeat the call every 1 second. As the setIntervals second parameter is in Milliseconds.

Body:
Use this tutorial to plot graphs using Google visualisation.

https://developers.google.com/chart/interactive/docs/php_example

If you want to make it dynamic, you have to use AJAX to call a function in PHP which updates the graph every x seconds. To do that, update the function the following way

setInterval(function(){
$.ajax({url: "getData.php",
      dataType: "json",
      async: false

    }, dataType: "json"});
}, 1000);

This will repeat the call every 1 second. As the setIntervals second parameter is in Milliseconds.