问:
ORA-06511: PL/SQL: cursor already open
I am Closing and opening the cursor outside the loop but still its showing error .ORA-06511: PL/SQL: cursor already open. Can anyone check it out.    </p>

```<code>/* SQL*Plus prompt variable re-initialize */
    BEGIN
    ------------------------my codes------------------
    OPEN UPD;
    OPEN SEL;
    ------------------------end of my codes------------
    DBMS_OUTPUT.put_line('u2 starts at time: ' || company.sys_ts_fcn);

    /* Nested block to process UPD; cursor execution failure raises an exception
       and after exception processing, the loop body resumes for next i counter     value
       In nested block, add 1 to the d and f columns in each row of table A  */

    ------------------------my codes------------------
    --ACCEPT c_retry_count  PROMPT 'Please enter counter value: '

    ------------------------end of my codes-----------

    FOR i IN 1 .. c_retry_count LOOP        -- Update cursor retry loop
      BEGIN
           u2_try_num := i;  -- Set cursor retry counter to  next loop iteration     number
              DBMS_OUTPUT.PUT_LINE('Executing table A update in nested block');
              FOR x_rec in UPD LOOP
    ------------------------my codes------------------

              FETCH UPD INTO x_rec;

              UPDATE A SET D = x_rec.D + 1 , F = x_rec.F + 1 ;

              EXIT WHEN UPD%NOTFOUND;

    ------------------------end of my codes------------
      --      WHERE current of UPD;
              END LOOP;

              -- Commit UPD's changes to A rows
              COMMIT;
              a_updated := TRUE;

    ------------------------my codes------------------
        EXIT;

    IF a_updated = FALSE THEN

    RAISE rowsAreLocked ;

    END IF;
    ------------------------end of my codes-----------

      EXCEPTION
    /*      Returned SQL code and error message values only visible in handlers
            Example: If "ORA-00054: resource busy and acquire with NOWAIT specified" occurs
                    during PL/SQL code execution, above is posted when no handler is
                    defined; otherwise, the above msg is NOT posted, and the EXCEPTION
                     handler is entered so that the event can be dealt with;
                    When this exception section is done, control transfers to the enclosing block
       (which resumes the cursor retry loop) */
      WHEN rowsAreLocked THEN
            BEGIN
    ------------------------my codes------------------
         DBMS_OUTPUT.put_line (SQLCODE);
         DBMS_OUTPUT.put_line (SQLERRM);
         DBMS_OUTPUT.put_line ('error block one');
         dbms_lock.sleep( 5 );
    ------------------------end of my codes-----------
         END;
      WHEN OTHERS THEN
            -- Third argument TRUE means: keep error msgs returned from all stack levels
            raise_application_error(-20001, 'WHEN OTHERS exception occurred', TRUE);
           DBMS_OUTPUT.put_line ('error block 2');
      END;     -- Inner block

    END LOOP;     -- A update retry loop
    ------------------------my codes------------------
    CLOSE UPD;
    ------------------------end of my codes------------
</code>```

答:
At the top you open UPD explicitly with

```<code>OPEN UPD;
</code>```

Then later you have this:

```<code>FOR x_rec in UPD LOOP
</code>```

A Cursor FOR loop implicitly opens the cursor.

Title: ORA-06511: PL/SQL: cursor already open

Body:
I am Closing and opening the cursor outside the loop but still its showing error .ORA-06511: PL/SQL: cursor already open. Can anyone check it out.

/* SQL*Plus prompt variable re-initialize */
    BEGIN
    ------------------------my codes------------------
    OPEN UPD;
    OPEN SEL;
    ------------------------end of my codes------------
    DBMS_OUTPUT.put_line('u2 starts at time: ' || company.sys_ts_fcn);

    /* Nested block to process UPD; cursor execution failure raises an exception
       and after exception processing, the loop body resumes for next i counter     value
       In nested block, add 1 to the d and f columns in each row of table A  */

    ------------------------my codes------------------
    --ACCEPT c_retry_count  PROMPT 'Please enter counter value: '

    ------------------------end of my codes-----------

    FOR i IN 1 .. c_retry_count LOOP        -- Update cursor retry loop
      BEGIN
           u2_try_num := i;  -- Set cursor retry counter to  next loop iteration     number
              DBMS_OUTPUT.PUT_LINE('Executing table A update in nested block');
              FOR x_rec in UPD LOOP
    ------------------------my codes------------------

              FETCH UPD INTO x_rec;

              UPDATE A SET D = x_rec.D + 1 , F = x_rec.F + 1 ;

              EXIT WHEN UPD%NOTFOUND;

    ------------------------end of my codes------------
      --      WHERE current of UPD;
              END LOOP;

              -- Commit UPD's changes to A rows
              COMMIT;
              a_updated := TRUE;

    ------------------------my codes------------------
        EXIT;

    IF a_updated = FALSE THEN

    RAISE rowsAreLocked ;

    END IF;
    ------------------------end of my codes-----------

      EXCEPTION
    /*      Returned SQL code and error message values only visible in handlers
            Example: If "ORA-00054: resource busy and acquire with NOWAIT specified" occurs
                    during PL/SQL code execution, above is posted when no handler is
                    defined; otherwise, the above msg is NOT posted, and the EXCEPTION
                     handler is entered so that the event can be dealt with;
                    When this exception section is done, control transfers to the enclosing block
       (which resumes the cursor retry loop) */
      WHEN rowsAreLocked THEN
            BEGIN
    ------------------------my codes------------------
         DBMS_OUTPUT.put_line (SQLCODE);
         DBMS_OUTPUT.put_line (SQLERRM);
         DBMS_OUTPUT.put_line ('error block one');
         dbms_lock.sleep( 5 );
    ------------------------end of my codes-----------
         END;
      WHEN OTHERS THEN
            -- Third argument TRUE means: keep error msgs returned from all stack levels
            raise_application_error(-20001, 'WHEN OTHERS exception occurred', TRUE);
           DBMS_OUTPUT.put_line ('error block 2');
      END;     -- Inner block

    END LOOP;     -- A update retry loop
    ------------------------my codes------------------
    CLOSE UPD;
    ------------------------end of my codes------------

Body:
At the top you open UPD explicitly with

OPEN UPD;

Then later you have this:

FOR x_rec in UPD LOOP

A Cursor FOR loop implicitly opens the cursor.


来源: stackexchange

问:
Group items in multidimensional array by same value at index
I have a multi-dimensional array like this:

```<code>var arr = [ [x,x,1] , [x,x,2] , [x,x,2] , [x,x,3] , [x,x,3] , [x,x,3] ];
</code>```

and I want to make it like this (grouping each sub-array according to matching  arr[i][2] values):

```<code>var arr = [ [[x,x,1]] , [[x,x,2],[x,x,2]] , [[x,x,3],[x,x,3],[x,x,3]] ];
</code>```

My attempts are getting increasingly long-winded, and I'm ashamed of posting them here. Any efficient suggestions greatly appreciated!

ContentLicense: CC BY-SA 3.0

Body:
I have a multi-dimensional array like this:

var arr = [ [x,x,1] , [x,x,2] , [x,x,2] , [x,x,3] , [x,x,3] , [x,x,3] ];

and I want to make it like this (grouping each sub-array according to matching  arr[i][2] values):

var arr = [ [[x,x,1]] , [[x,x,2],[x,x,2]] , [[x,x,3],[x,x,3],[x,x,3]] ];

My attempts are getting increasingly long-winded, and I'm ashamed of posting them here. Any efficient suggestions greatly appreciated!

Body:
Array#forEach solution.

var arr = [["x","x", 1],["x","x", 2],["x","x", 2],["x","x", 3],["x","x", 3],["x","x", 3]], obj = {};

arr.forEach(v => (obj[v[2]] || (obj[v[2]] = [])).push(v));
var res = Object.keys(obj).map(v => obj[v]);

console.log(JSON.stringify(res));


问:
“Wrong FS… expected: file:///” when trying to copyFromLocalFile from HDFS in Java
I am trying to copy abc.json from port/example_File/2017 to another location /port/example_File/2018 in HDFS,
by below code

```<code>String exampleFile= "hdfs://port/example_File/2017/abc.json"
String targetFile="hdfs://port/example_File/2018"
hdfs.copyFromLocalFile(new Path(exampleFile),new Path(targetFile))
</code>```

I am getting below exception

```<code>    org.jboss.resteasy.spi.UnhandledException:
java.lang.IllegalArgumentException: Wrong FS:
 hdfs://port/example_File/2017/abc.json, expected: file:///
</code>```

How to copy file from one location to another in HDFS

Thanks,

答:
copyFromLocal is to copy files from Local Filesystem to HDFS.

To copy files within an HDFS cluster, use FileUtil.copy() and specify same Filesystem for both srcFS and dstFs.

Use DistCp when copying large number of files within a HDFS cluster or between two different HDFS clusters. Refer DistCp Java API here.

Body:
I am trying to copy abc.json from port/example_File/2017 to another location /port/example_File/2018 in HDFS,
by below code

String exampleFile= "hdfs://port/example_File/2017/abc.json"
String targetFile="hdfs://port/example_File/2018"
hdfs.copyFromLocalFile(new Path(exampleFile),new Path(targetFile))

I am getting below exception

    org.jboss.resteasy.spi.UnhandledException:
java.lang.IllegalArgumentException: Wrong FS:
 hdfs://port/example_File/2017/abc.json, expected: file:///

How to copy file from one location to another in HDFS

Thanks,


问:
What is a preferred way of closing a third-application thread without waiting for it to complete?
I am currently running the JAR that I cannot change, and sometimes it simply gets stuck for no good reason. I have tried finding the ways to interrupt the thread, stop the thread, etceteras, but no luck.

Each solution offered was about doing the complete exit or waiting for a thread to complete.

What I want to do is to simply close the thread, exactly when the timeout completes, and carry on with the program.

What I do not want to do is use the while loop with a timeout, java.util.concurrent.Future, System.exit, and make a Thread.interrupt call.

None of these will help!

答:
You can use Executor for this. It allows you to submit tasks (e.g. runnable) and executes those tasks parallely. Also, once you call shutdown(), it lets you configure the timeout and kills all the workers if they are not finished by that time. An example would look like this:

```<code>ExecutorService executor = Executors.newFixedThreadPool(1);
executor.execute(() -> {
//logic to call the method of third party jar
});
//Other business logic
executor.awaitTermination(1, TimeUnit.MINUTES);
executor.shutdownNow();
</code>```

TimeUnit is an enum, with values like SECONDS, HOURS, MINUTES etc (here's javadoc) so you can configure different time units. A couple of points:

Once shutdownNow is called, no new tasks will be accepted (i.e. you can't call execute or submit) and existing tasks will be stopped. So, we are basically waiting for a minute for tasks to be complete and if it is not complete, we are killing that task.

awaitTermination throws InterruptedException (as it interrupts the threads internally if they are not finished) so you will have to wrap it inside try-catch block.

Here's javadoc for Executor.

Body:
You can use Executor for this. It allows you to submit tasks (e.g. runnable) and executes those tasks parallely. Also, once you call shutdown(), it lets you configure the timeout and kills all the workers if they are not finished by that time. An example would look like this:

ExecutorService executor = Executors.newFixedThreadPool(1);
executor.execute(() -> {
//logic to call the method of third party jar
});
//Other business logic
executor.awaitTermination(1, TimeUnit.MINUTES);
executor.shutdownNow();

TimeUnit is an enum, with values like SECONDS, HOURS, MINUTES etc (here's javadoc) so you can configure different time units. A couple of points:

Once shutdownNow is called, no new tasks will be accepted (i.e. you can't call execute or submit) and existing tasks will be stopped. So, we are basically waiting for a minute for tasks to be complete and if it is not complete, we are killing that task.

awaitTermination throws InterruptedException (as it interrupts the threads internally if they are not finished) so you will have to wrap it inside try-catch block.

Here's javadoc for Executor.


问:
What does 'c' parameter do in coding?
What does parameter do in programming ?

For example

void main()

int n = 6;

int test(int n)

Is the int n inside the int test refer to the void main int 6 ?
Can anyone explain further for me.

Tq guys have better understanding now.

答: If that function is inside main then "int test(int n)" is declaration of function and u need to write that function outside main.When u call test function u just pass value and no declaration of variable is required.For example test(n) will refer the n in the main program.</p>

Title: What does 'c' parameter do in coding?


问:
Azure BotFramework
I was I asked to create this post.  I am using the bot service on azure.  I created a bot and everything worked great.  Then I deleted the bot and created a new on and now I get Microsoft App ID is not a valid GUID.  This happens when I hit the create bot button.  Thank you for all your help.</p>

答:
I've had similar errors when trying to re-create the bot with the same name right after I had deleted it.  If possible, try to use a different name for the bot.

Also, I noticed that when I deleted the Bot Service from Azure, it didn’t delete the bot that is registered on the bot framework portal (dev.botframework.com).  You should manually delete the bot there also.

Title: Azure BotFramework


问:
on Change event in select with knockout
I have a problem how to call onchanges knock js to my select option, i already have a function and html, but when i choose the select option, nothing changes

```<code><select data-bind="event:{change:setSelectedStation() },
                   options: seedData,
                   optionsText: 'text',
                   optionsValue: 'value'">
</select>
</code>```

here is my function

```<code>setSelectedStation: function(element, KioskId){
     this.getPopUp().closeModal();
     $('.selected-station').html(element);
     $('[name="popstation_detail"]').val(element);
     $('[name="popstation_address"]').val(KioskId);

     $('[name="popstation_text"]').val(element);
     // console.log($('[name="popstation_text"]').val());
     this.isSelectedStationVisible(true);
},
</code>```

答:
Use knockout's two-way data-binds instead of manually subscribing to UI events.

Knockout's value data-bind listens to UI changes and automatically keeps track of the latest value for you.

Instead of replacing HTML via jQuery methods, you use text, attr and other value bindings to update the UI whenever your selection changes.

If you want to perform additional work when a selection changes (e.g. closing a pop up), you subscribe to the selected value.

var VM = function() {
  this.seedData = [
    {
      text: "Item 1",
      data: "Some other stuff"
    },
    {
      text: "Item 2",
      data: "Something else"
    },
    {
      text: "Item 3",
      data: "Another thing"
    }
  ];

  this.selectedItem = ko.observable();

  this.selectedItem.subscribe(function(latest) {
    console.log("Input changed");
  }, this);
};

ko.applyBindings(new VM());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<select data-bind="
        value: selectedItem,
        options: seedData,
        optionsText: 'text'">
</select>

<!-- ko with: selectedItem -->
<p>
  Your selection: <span data-bind="text: data"></span>
</p>
<!-- /ko --></code>```

Title: on Change event in select with knockout

Body:
I have a problem how to call onchanges knock js to my select option, i already have a function and html, but when i choose the select option, nothing changes

<select data-bind="event:{change:setSelectedStation() },
                   options: seedData,
                   optionsText: 'text',
                   optionsValue: 'value'">
</select>

here is my function

setSelectedStation: function(element, KioskId){
     this.getPopUp().closeModal();
     $('.selected-station').html(element);
     $('[name="popstation_detail"]').val(element);
     $('[name="popstation_address"]').val(KioskId);

     $('[name="popstation_text"]').val(element);
     // console.log($('[name="popstation_text"]').val());
     this.isSelectedStationVisible(true);
},

Body:
Use knockout's two-way data-binds instead of manually subscribing to UI events.

Knockout's value data-bind listens to UI changes and automatically keeps track of the latest value for you.

Instead of replacing HTML via jQuery methods, you use text, attr and other value bindings to update the UI whenever your selection changes.

If you want to perform additional work when a selection changes (e.g. closing a pop up), you subscribe to the selected value.

var VM = function() {
  this.seedData = [
    {
      text: "Item 1",
      data: "Some other stuff"
    },
    {
      text: "Item 2",
      data: "Something else"
    },
    {
      text: "Item 3",
      data: "Another thing"
    }
  ];

  this.selectedItem = ko.observable();

  this.selectedItem.subscribe(function(latest) {
    console.log("Input changed");
  }, this);
};

ko.applyBindings(new VM());

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<select data-bind="
        value: selectedItem,
        options: seedData,
        optionsText: 'text'">
</select>

<!-- ko with: selectedItem -->
<p>
  Your selection: <span data-bind="text: data"></span>
</p>
<!-- /ko -->


问:
How to Delete Additional build files from the Project Solution in visual studio
How to delete additional build files from the project solution in Visual Studio?

I am forced to clear this files everytime manually when I want to give my executable program to anyone

Any solution?

I am using C# and C++.

答:
This is simple

Right click at the project

Go to build events. From there you can play with many things.


问:
Requesting a stack trace for a Java ThreadInfo?
I have an application that calls getStackTrace() on a java.lang.management.ThreadInfo object, but the StackTraceElement array produced by the invocation is zero length.

Inspecting the Javadoc shows this (emphasis mine):

```<code>public StackTraceElement[] getStackTrace()
</code>```

Returns the stack trace of the thread associated with this ThreadInfo. If no stack trace was requested for this thread info, this method will return a zero-length array. If the returned array is of non-zero length then the first element of the array represents the top of the stack, which is the most recent method invocation in the sequence. The last element of the array represents the bottom of the stack, which is the least recent method invocation in the sequence.

How do I request a stack trace for this thread info?

答:
How are you calling getThreadInfo()?

Are you specifying a stack trace depth?

getThreadInfo(long id, int maxDepth)
            Returns a thread info for a thread of the specified id, with stack
  trace of a specified number of stack
  trace elements.

ContentLicense: CC BY-SA 2.5

Body:
I have an application that calls getStackTrace() on a java.lang.management.ThreadInfo object, but the StackTraceElement array produced by the invocation is zero length.

Inspecting the Javadoc shows this (emphasis mine):

public StackTraceElement[] getStackTrace()

Returns the stack trace of the thread associated with this ThreadInfo. If no stack trace was requested for this thread info, this method will return a zero-length array. If the returned array is of non-zero length then the first element of the array represents the top of the stack, which is the most recent method invocation in the sequence. The last element of the array represents the bottom of the stack, which is the least recent method invocation in the sequence.

How do I request a stack trace for this thread info?


问:
301 Redirect and Mod_Rewrite Rule in .htaccess file cause a Redirection chain (Wordpress)
I am re-developing a Wordpress site and the site structure has changed drastically so I need to perform redirects from old URLs and force HTTPS in the .htaccess file.

The problem I am having is that my code produces two 301 Redirects in a row and I need to consolidate them into 1 301 Redirect.

Here is the .htaccess file:

Redirect the individual pages to the new URL:

```<code>Redirect 301 "/old-site-url-1" "/new-site-url-1"
Redirect 301 "/old-site-url-2" "/new-site-url-2”
Redirect 301 "/old-site-url-3" "/new-site-url-3”
</code>```

Globally Redirect all requests so use https://

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code>```

The result is this redirect chain:

301 - http:// mydomain/old-site-url-1 (old site is non-SSL)

301 - https:// mydomain/old-site-url-1 (The Mod-Rewrite rule forces https://)

200 - https:// mydomain/new-site-url-1 (The 301 Redirect kicks in and the new URL is found)

I wish to consolidate the two 301 redirects into one.

Is there any way I can use Flags (https://httpd.apache.org/docs/2.4/rewrite/flags.html) or something else to skip over the force SSL directive and switch the 301 Redirects to absolute URLs with HTTPS?

The Rewrite rule is always processed before the 301 redirect. Is there any way to defer it and then test if the page is already using HTTPS?

答:
The problem is that you are mixing mod-alias ( Redirect directive ) with mod-rewrite ( RewriteRule ) . They are part of two diffrent modules. Mod-rewrite always runs before mod-alias. You need to handle your old requests using rewriteRule instead of Redirect directive. Add the following rules after yous SSL redirect rules or before #wp rules :

```<code>RewriteRule ^old-path-1/?$ https://example.com/new-path-1 [L,R]
RewriteRule ^old-path-2/?$ https://example.com/new-path-2 [L,R]
</code>```

Body:
I am re-developing a Wordpress site and the site structure has changed drastically so I need to perform redirects from old URLs and force HTTPS in the .htaccess file.

The problem I am having is that my code produces two 301 Redirects in a row and I need to consolidate them into 1 301 Redirect.

Here is the .htaccess file:

Redirect the individual pages to the new URL:

Redirect 301 "/old-site-url-1" "/new-site-url-1"
Redirect 301 "/old-site-url-2" "/new-site-url-2”
Redirect 301 "/old-site-url-3" "/new-site-url-3”

Globally Redirect all requests so use https://

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

The result is this redirect chain:

301 - http:// mydomain/old-site-url-1 (old site is non-SSL)

301 - https:// mydomain/old-site-url-1 (The Mod-Rewrite rule forces https://)

200 - https:// mydomain/new-site-url-1 (The 301 Redirect kicks in and the new URL is found)

I wish to consolidate the two 301 redirects into one.

Is there any way I can use Flags (https://httpd.apache.org/docs/2.4/rewrite/flags.html) or something else to skip over the force SSL directive and switch the 301 Redirects to absolute URLs with HTTPS?

The Rewrite rule is always processed before the 301 redirect. Is there any way to defer it and then test if the page is already using HTTPS?

Body:
The problem is that you are mixing mod-alias ( Redirect directive ) with mod-rewrite ( RewriteRule ) . They are part of two diffrent modules. Mod-rewrite always runs before mod-alias. You need to handle your old requests using rewriteRule instead of Redirect directive. Add the following rules after yous SSL redirect rules or before #wp rules :

RewriteRule ^old-path-1/?$ https://example.com/new-path-1 [L,R]
RewriteRule ^old-path-2/?$ https://example.com/new-path-2 [L,R]


问:
Remove rows with missing values denoted by '?'
I have a .csv file that contains rows with missing values. Those values instead of null, are denoted by the character ?.

How can I remove the rows that contain at least one column with value ?, given that df.na.drop() won't work (since the missing values are not null) ?

The data looks like below (I've got 35 columns - missing values can be found in any of those columns)

```<code>+-------+--------+------+-------+
| col_1 | col_2  |  ... | col_35|
+-------+--------+------+-------+
| 0.75  |   ?    |  ... |   15  |
|   ?   | Helen  |  ... |   21  |
| -1.2  | George |  ... |    ?  |
|   ?   | Andrew |  ... |   129 |
| 0.12  | Maria  |  ... |   12  |   // Should not be deleted
+-------+--------+------+-------+
</code>```

And here's the code that reads the file.

```<code>val df = sparkSession.read
    .format("com.databricks.spark.csv")
    .option("header", "true")
    .option("mode", "DROPMALFORMED")
    .load("data.csv")
    .toDF()
</code>```

答:
If ? denotes missing values you just configure the reader to recognize that:

```<code>val df = spark.read
  .format("csv")
  .option("nullValue", "?")  // Use "?" as null character
  .option("header", "true")
  .option("mode", "DROPMALFORMED")
  .load("data.csv")
  .toDF()
</code>```

and use standard na.drop:

```<code>df.na.drop
</code>```

Body:
I have a .csv file that contains rows with missing values. Those values instead of null, are denoted by the character ?.

How can I remove the rows that contain at least one column with value ?, given that df.na.drop() won't work (since the missing values are not null) ?

The data looks like below (I've got 35 columns - missing values can be found in any of those columns)

+-------+--------+------+-------+
| col_1 | col_2  |  ... | col_35|
+-------+--------+------+-------+
| 0.75  |   ?    |  ... |   15  |
|   ?   | Helen  |  ... |   21  |
| -1.2  | George |  ... |    ?  |
|   ?   | Andrew |  ... |   129 |
| 0.12  | Maria  |  ... |   12  |   // Should not be deleted
+-------+--------+------+-------+

And here's the code that reads the file.

val df = sparkSession.read
    .format("com.databricks.spark.csv")
    .option("header", "true")
    .option("mode", "DROPMALFORMED")
    .load("data.csv")
    .toDF()

Body:
If ? denotes missing values you just configure the reader to recognize that:

val df = spark.read
  .format("csv")
  .option("nullValue", "?")  // Use "?" as null character
  .option("header", "true")
  .option("mode", "DROPMALFORMED")
  .load("data.csv")
  .toDF()

and use standard na.drop:

df.na.drop


问:
How to structure web pages
What's the technique behind when pages on a website is structured like this? example.com/pages/about

When looking in the code behind it is obvious that page in question is actually placed in the root (example.com) and furthermore it is possible append anything to the URL (like example.com/pages/about/qwerty) and yet it still returns the correct page?

I simply don't know what to google for.

I forgot to mention, that I work in classic ASP. It turned out that 'semantic URL' was what I was looking for. To make up for my 'thumbs down' for lack of research, here's a solution that I came up with this morning:

example.com/about/default.asp:

```<code><%session("jump")="about.asp"
response.redirect "http://example.com"%>
</code>```

example.com/default.asp should include:

```<code><%if len(session("jump"))>0 then server.transfer(session("jump"))%>
</code>```

This will make the semantic URL example.com/about useable and will not present the user with the URL of the resulting page: example.com/about.asp

答:
You're using Classic ASP, which doesn't have any established MVC framework, so MVC routing probably isn't going to be much help to you.  What you should probably google for is "URL Rewriting".  There's a pure ASP solution which involves creating a custom 404 page and using server.transfer within conditional statements (so you were starting to think along the right lines), but from a practical point of view what you probably want to use is the IIS URL Rewrite Module.

First of all you need to be using IIS7 or later, which I think we can safely assume now you will be, given that the Microsoft no longer supports OSs which had an earlier version.  You can add rules either through IIS manager or by adding them directly to your web.config file.  For example, if you wanted example.com/about to take you to about.asp, and example.com/contact to take you to contact.asp (both files in your root directory) then you would add the following to the <system.webServer> section of your web.config file

```<code><rewrite>
      <rules>
        <rule name="About" stopProcessing="true">
          <match url="^about$"/>
          <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true"/>
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true"/>
          </conditions>
          <action type="Rewrite" url="about.asp"/>
        </rule>
        <rule name="Contact" stopProcessing="true">
          <match url="^contact$"/>
          <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true"/>
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true"/>
          </conditions>
          <action type="Rewrite" url="contact.asp"/>
        </rule>
      </rules>
    </rewrite>
</code>```

There's a good tutorial on Microsoft's IIS website:

https://www.iis.net/learn/extensions/url-rewrite-module/creating-rewrite-rules-for-the-url-rewrite-module

Title: How to structure web pages

Body:
What's the technique behind when pages on a website is structured like this? example.com/pages/about

When looking in the code behind it is obvious that page in question is actually placed in the root (example.com) and furthermore it is possible append anything to the URL (like example.com/pages/about/qwerty) and yet it still returns the correct page?

I simply don't know what to google for.

I forgot to mention, that I work in classic ASP. It turned out that 'semantic URL' was what I was looking for. To make up for my 'thumbs down' for lack of research, here's a solution that I came up with this morning:

example.com/about/default.asp:

<%session("jump")="about.asp"
response.redirect "http://example.com"%>

example.com/default.asp should include:

<%if len(session("jump"))>0 then server.transfer(session("jump"))%>

This will make the semantic URL example.com/about useable and will not present the user with the URL of the resulting page: example.com/about.asp

Body:
You're using Classic ASP, which doesn't have any established MVC framework, so MVC routing probably isn't going to be much help to you.  What you should probably google for is "URL Rewriting".  There's a pure ASP solution which involves creating a custom 404 page and using server.transfer within conditional statements (so you were starting to think along the right lines), but from a practical point of view what you probably want to use is the IIS URL Rewrite Module.

First of all you need to be using IIS7 or later, which I think we can safely assume now you will be, given that the Microsoft no longer supports OSs which had an earlier version.  You can add rules either through IIS manager or by adding them directly to your web.config file.  For example, if you wanted example.com/about to take you to about.asp, and example.com/contact to take you to contact.asp (both files in your root directory) then you would add the following to the <system.webServer> section of your web.config file

<rewrite>
      <rules>
        <rule name="About" stopProcessing="true">
          <match url="^about$"/>
          <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true"/>
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true"/>
          </conditions>
          <action type="Rewrite" url="about.asp"/>
        </rule>
        <rule name="Contact" stopProcessing="true">
          <match url="^contact$"/>
          <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true"/>
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true"/>
          </conditions>
          <action type="Rewrite" url="contact.asp"/>
        </rule>
      </rules>
    </rewrite>

There's a good tutorial on Microsoft's IIS website:

https://www.iis.net/learn/extensions/url-rewrite-module/creating-rewrite-rules-for-the-url-rewrite-module


问:
How do I insert a space after a character in a textbox, depending on the total characters entered, JQuery?
Is it possible to add a space in a textbox depending on the total characters entered by the user.

For example if the user entered 'LU33RT' on blur I'd like it to display 'LU3 3RT'. The rule that I'm looking to incorporate is by counting 3 characters in from the right then add a space.

$('#postcode').blur(...

Any help would be greatly appreciated, Thanks

My Solution, Although it's basic:

```<code>$(document).ready(function(){

    $('#postcode').blur(function(){
        if(($(this).val().length == 6) && (/\S/)){
           var myString = $(this).val().slice(0, 3);
           var myString2 = $(this).val().slice(-3);
           $(this).val(myString + ' ' + myString2);
        }else{
            document.write('OOPS!');}
    });
});
</code>```

答:
Have you considered using something like MAsked Input Plugin?

I think it may be of use if properly adapted.

Body:
Is it possible to add a space in a textbox depending on the total characters entered by the user.

For example if the user entered 'LU33RT' on blur I'd like it to display 'LU3 3RT'. The rule that I'm looking to incorporate is by counting 3 characters in from the right then add a space.

$('#postcode').blur(...

Any help would be greatly appreciated, Thanks

My Solution, Although it's basic:

$(document).ready(function(){

    $('#postcode').blur(function(){
        if(($(this).val().length == 6) && (/\S/)){
           var myString = $(this).val().slice(0, 3);
           var myString2 = $(this).val().slice(-3);
           $(this).val(myString + ' ' + myString2);
        }else{
            document.write('OOPS!');}
    });
});


问:
C# add items to listview not working
```<code>private void showResultsList()
{
    IWebElement table = resultFinder.FindElementById("records");
    IList<IWebElement> trElements = table.FindElements(By.TagName("tr"));
    IList<IWebElement> tdElements;
    IList<IWebElement> aElements = table.FindElements(By.TagName("a"));

    mainWindow.Dispatcher.Invoke(() =>
    {
        ListView listView = (ListView)mainWindow.FindName("Search_ResultsList");
        ItemCollection resultsListItems = listView.Items;
        listView.Items.Clear();

        for (int i = 0; i < trElements.Count; i++)
        {
            IWebElement trElement = trElements[i];
            tdElements = trElement.FindElements(By.TagName("td"));
            aElements = trElement.FindElements(By.TagName("a"));
            string index = (i + 1).ToString();
            string text = tdElements[2].Text;
            // this line removes the last part of the content, which says "Aggiungi ai preferiti"
            string result = text.Substring(0, text.LastIndexOf('\n'));
            string hyperLink = aElements[0].GetAttribute("href");

            resultsListItems.Add(new ResultsListItem { Index = index, Result = result, HyperLink = hyperLink });
        }
    });
}
</code>```

XAML file

```<code><ListView Name="Search_ResultsList" HorizontalAlignment="Left" Height="886" Margin="10,10,0,0" VerticalAlignment="Top" Width="440" BorderBrush="#FF707070">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="N." Width="30" DisplayMemberBinding="{Binding Index}"/>
            <GridViewColumn Header="Result" Width="387" DisplayMemberBinding="{Binding Result}"/>
        </GridView>
    </ListView.View>
</ListView>
</code>```

ResultsListItem class

```<code>class ResultsListItem : ListViewItem
{
    public string Index { get; set; }
    public string Result { get; set; }
    public string HyperLink { get; set; }
}
</code>```

I'm trying to show this list into a ListView object by adding the ResultsListItem to the collection of items. When I run the program the list doesn't show the content of the listItems, just a list of empty items. What do I do wrong?
Thanks in advance.

答:
You are missing to set the ItemsSource to the Listview,try this</p>

```<code> Search_ResultsList.ItemsSource = resultsListItems;
</code>```

Title: C# add items to listview not working

Body:
private void showResultsList()
{
    IWebElement table = resultFinder.FindElementById("records");
    IList<IWebElement> trElements = table.FindElements(By.TagName("tr"));
    IList<IWebElement> tdElements;
    IList<IWebElement> aElements = table.FindElements(By.TagName("a"));

    mainWindow.Dispatcher.Invoke(() =>
    {
        ListView listView = (ListView)mainWindow.FindName("Search_ResultsList");
        ItemCollection resultsListItems = listView.Items;
        listView.Items.Clear();

        for (int i = 0; i < trElements.Count; i++)
        {
            IWebElement trElement = trElements[i];
            tdElements = trElement.FindElements(By.TagName("td"));
            aElements = trElement.FindElements(By.TagName("a"));
            string index = (i + 1).ToString();
            string text = tdElements[2].Text;
            // this line removes the last part of the content, which says "Aggiungi ai preferiti"
            string result = text.Substring(0, text.LastIndexOf('\n'));
            string hyperLink = aElements[0].GetAttribute("href");

            resultsListItems.Add(new ResultsListItem { Index = index, Result = result, HyperLink = hyperLink });
        }
    });
}

XAML file

<ListView Name="Search_ResultsList" HorizontalAlignment="Left" Height="886" Margin="10,10,0,0" VerticalAlignment="Top" Width="440" BorderBrush="#FF707070">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="N." Width="30" DisplayMemberBinding="{Binding Index}"/>
            <GridViewColumn Header="Result" Width="387" DisplayMemberBinding="{Binding Result}"/>
        </GridView>
    </ListView.View>
</ListView>

ResultsListItem class

class ResultsListItem : ListViewItem
{
    public string Index { get; set; }
    public string Result { get; set; }
    public string HyperLink { get; set; }
}

I'm trying to show this list into a ListView object by adding the ResultsListItem to the collection of items. When I run the program the list doesn't show the content of the listItems, just a list of empty items. What do I do wrong?
Thanks in advance.

Body:
You are missing to set the ItemsSource to the Listview,try this

 Search_ResultsList.ItemsSource = resultsListItems;


问:
Call Same Class Constructor Using same Class Method in Java
How can I call same class constructor from same class method?
 I can use this() but it raise the error.

```<code>class MyConstructor {
    public MyConstructor() {
        System.out.println("My Constructor") ;
    }
    public void MyCall () {
        // Call MyConstructor
    }
}

public class Constructor {
    public static void main(String[] args) {
        MyConstructor mycon = new MyConstructor() ;
    }
}
</code>```

答:
You can just call the constructor when instantiating a new Object with the new()-Keyword.It is not possible to call the constructor from within the class otherwise. But you can write another function whit all the logic from the constructor-MEthod. In the constructor you just call this method.</p>

```<code>    class MyConstructor {

    public MyConstructor() {
       helperMethod();
    }

    public void helperMethod(){
     System.out.println("My Constructor") ;
    }

public void MyCall () {
    // Call MyConstructor
   helperMethod();
}
</code>```

Body:
How can I call same class constructor from same class method?
 I can use this() but it raise the error.

class MyConstructor {
    public MyConstructor() {
        System.out.println("My Constructor") ;
    }
    public void MyCall () {
        // Call MyConstructor
    }
}

public class Constructor {
    public static void main(String[] args) {
        MyConstructor mycon = new MyConstructor() ;
    }
}

Body:
You can just call the constructor when instantiating a new Object with the new()-Keyword.It is not possible to call the constructor from within the class otherwise. But you can write another function whit all the logic from the constructor-MEthod. In the constructor you just call this method.

    class MyConstructor {

    public MyConstructor() {
       helperMethod();
    }

    public void helperMethod(){
     System.out.println("My Constructor") ;
    }

public void MyCall () {
    // Call MyConstructor
   helperMethod();
}


问:
php include .phar file not working
Im using os-ticket support script and have trouble in special line.

```<code>$this->cache_translations = include $this->STREAM;
</code>```

this line will include a .phar file.

something like this: phar:///dir/to/fa.phar/x.mo

php is not throwing any error but i get white page.
I test this code in a single php file and still get nothing.

btw this script is working in PHP Version 5.4.45
and my current version is 5.5.37.

thanks in advance

答:
If you are using suhosin to secure your php installation, you need to add this setting in your php.ini file under [suhosin]</p>

```<code>suhosin.executor.include.whitelist = phar
</code>```

Title: php include .phar file not working

Body:
Im using os-ticket support script and have trouble in special line.

$this->cache_translations = include $this->STREAM;

this line will include a .phar file.

something like this: phar:///dir/to/fa.phar/x.mo

php is not throwing any error but i get white page.
I test this code in a single php file and still get nothing.

btw this script is working in PHP Version 5.4.45
and my current version is 5.5.37.

thanks in advance

Body:
If you are using suhosin to secure your php installation, you need to add this setting in your php.ini file under [suhosin]

suhosin.executor.include.whitelist = phar


问:
Cannot remove 301 redirect
I stupidly did a 301 redirect on websiteA.com to websiteB.com. After removing it from the .htaccess file the redirect is still in operation. I tried from outside the local network and it is still redirecting. I have cleared my cache and tried a different browser.

Does anybody have any suggestions?

UPDATE:

If I add a 302 redirect to this .htaccess file the site honours it. When I remove it, the old 301 redirect still happens.

.htaccess file for websiteA.com:

```<code># -- concrete5 urls start --

Options -Indexes

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>
# -- concrete5 urls end --

#RewriteCond %{HTTP_HOST} ^.*$
#RewriteRule ^/?$ "http\:\/\/www\.websiteB\.co\.uk\/" [R=301,L]
</code>```

答:
Try to visit the website with Developers Console open (F12)

Make sure you check "Disable cache" under "Network" tab

This will bypass 301 redirect cache on browser-side.

Title: Cannot remove 301 redirect

Body:
I stupidly did a 301 redirect on websiteA.com to websiteB.com. After removing it from the .htaccess file the redirect is still in operation. I tried from outside the local network and it is still redirecting. I have cleared my cache and tried a different browser.

Does anybody have any suggestions?

UPDATE:

If I add a 302 redirect to this .htaccess file the site honours it. When I remove it, the old 301 redirect still happens.

.htaccess file for websiteA.com:

# -- concrete5 urls start --

Options -Indexes

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>
# -- concrete5 urls end --

#RewriteCond %{HTTP_HOST} ^.*$
#RewriteRule ^/?$ "http\:\/\/www\.websiteB\.co\.uk\/" [R=301,L]

ContentLicense: CC BY-SA 4.0


问:
Unable to use CMake to Generate OpenCV Project
Every time I try to build, I get the error:

CMake Error: The source directory "E:/Code/Test" does not appear to contain CMakeLists.txt.
Specify --help for usage, or press the help button on the CMake GUI.

Which doesn't make a ton of sense, because I very clearly have CMakeLists.txt included in that directory.  I tried looking for this problem on the internet, but it seems that I might be the only person to ever have this issue.  Has anyone run across this issue before?

Is there an easier way to be integrating OpenCV?  I've got a copy of Visual Studio, but the OpenCV wiki says that it's not supported any longer.

I'm on Windows 7, using the CMake-GUI

The guide I've followed to try and get started with this can be found here: http://redkiing.wordpress.com/2010/10/03/opencv-and-visual-studio-2010-with-cmake/

EDIT

I ended up using the prebuilt OpenCV for Windows.

答:
I had the problem,

I just rename the file by copy and past (CMakeLists.txt).

and it works


问:
Why did Neo4j change it's name to Neo5j?
They just announced, they changed their name to Neo5j.

I always thought that 4j meant for-Java.
And as Neo4j is implemented in Java and Scala and the ~4j suffix has been highly popular (in the 90's) it never occurred to me that the 4j and now 5j is actually a version denomination.

But it seems common in database circles to use that number + letter versioning scheme, like Oracle does with 9i, 11g and 12c.

Now the question is what does the 5j stand for? The article doesn't answer it. Can anyone help me resolve this?

答: It obviously stands so for jellous, because it makes other database vendors so.


问:
OWL API V5 read ontology from local file
in the current documentation example at the link:
https://github.com/owlcs/owlapi/blob/version5/contract/src/test/java/org/semanticweb/owlapi/examples/Examples.java
There is no example of how to load an ontology from a local file. There is only a way to load it from a string.

In the past when i used owl-api version 3
the following code worked perfectly:

```<code>    OWLOntologyManager manager =OWLManager.createOWLOntologyManager();
    File file = new File (path);
    OWLOntology ont = manager.loadOntologyFromOntologyDocument(IRI.create(file));
</code>```

however, in this version, the last line of the previous code:

```<code>manager.loadOntologyFromOntologyDocument(IRI.create(file));
</code>```

returns this error:

```<code>    Exception in thread "main" java.lang.NoSuchMethodError:
    org.semanticweb.owlapi.util.SAXParsers.initParserWithOWLAPIStandards(Lorg/xml/sax/ext/DeclHandler;)Ljavax/xml/parsers/SAXParser;
        at
org.semanticweb.owlapi.rdf.rdfxml.parser.RDFParser.parse(RDFParser.java:148)
    at org.semanticweb.owlapi.rdf.rdfxml.parser.RDFXMLParser.parse(RDFXMLParser.java:62)
    at uk.ac.manchester.cs.owl.owlapi.OWLOntologyFactoryImpl.loadOWLOntology(OWLOntologyFactoryImpl.java:173)
    at uk.ac.manchester.cs.owl.owlapi.OWLOntologyManagerImpl.load(OWLOntologyManagerImpl.java:954)
    at uk.ac.manchester.cs.owl.owlapi.OWLOntologyManagerImpl.loadOntology(OWLOntologyManagerImpl.java:918)
    at uk.ac.manchester.cs.owl.owlapi.OWLOntologyManagerImpl.loadOntologyFromOntologyDocument(OWLOntologyManagerImpl.java:859)
    at glass.main.ontology_Test_main2.readOntology(ontology_Test_main2.java:49)
    at glass.main.ontology_Test_main2.main(ontology_Test_main2.java:38)
</code>```

Kindly note the attachment, a small test java project, link:

dropbox.com/s/3787a3gsk2bwc26/test.tar.gz?dl=0

Kindly what am i doing wrong, i m sure that this code

Kindly would you please provide the correct way to do it, and add it to the tutorial example in the link https://github.com/owlcs/owlapi/blob/version5/contract/src/test/java/org/semanticweb/owlapi/examples/Examples.java

Thanks very much for your time.
Sincere regards

答:
The reason of the problem was:

The previous versions that i was using:
I was using Hermit version 1.3.8.500 and OWL-API previous version 5.0.5 got modified it seems.

Solution: use the newer versions Hermit 1.3.8.510 and OWL-API 5.1.0.

I posted this answer in case someone else is using the previous version and got affected.
Sincere regards.

Body:
in the current documentation example at the link:
https://github.com/owlcs/owlapi/blob/version5/contract/src/test/java/org/semanticweb/owlapi/examples/Examples.java
There is no example of how to load an ontology from a local file. There is only a way to load it from a string.

In the past when i used owl-api version 3
the following code worked perfectly:

    OWLOntologyManager manager =OWLManager.createOWLOntologyManager();
    File file = new File (path);
    OWLOntology ont = manager.loadOntologyFromOntologyDocument(IRI.create(file));

however, in this version, the last line of the previous code:

manager.loadOntologyFromOntologyDocument(IRI.create(file));

returns this error:

    Exception in thread "main" java.lang.NoSuchMethodError:
    org.semanticweb.owlapi.util.SAXParsers.initParserWithOWLAPIStandards(Lorg/xml/sax/ext/DeclHandler;)Ljavax/xml/parsers/SAXParser;
        at
org.semanticweb.owlapi.rdf.rdfxml.parser.RDFParser.parse(RDFParser.java:148)
    at org.semanticweb.owlapi.rdf.rdfxml.parser.RDFXMLParser.parse(RDFXMLParser.java:62)
    at uk.ac.manchester.cs.owl.owlapi.OWLOntologyFactoryImpl.loadOWLOntology(OWLOntologyFactoryImpl.java:173)
    at uk.ac.manchester.cs.owl.owlapi.OWLOntologyManagerImpl.load(OWLOntologyManagerImpl.java:954)
    at uk.ac.manchester.cs.owl.owlapi.OWLOntologyManagerImpl.loadOntology(OWLOntologyManagerImpl.java:918)
    at uk.ac.manchester.cs.owl.owlapi.OWLOntologyManagerImpl.loadOntologyFromOntologyDocument(OWLOntologyManagerImpl.java:859)
    at glass.main.ontology_Test_main2.readOntology(ontology_Test_main2.java:49)
    at glass.main.ontology_Test_main2.main(ontology_Test_main2.java:38)

Kindly note the attachment, a small test java project, link:

dropbox.com/s/3787a3gsk2bwc26/test.tar.gz?dl=0

Kindly what am i doing wrong, i m sure that this code

Kindly would you please provide the correct way to do it, and add it to the tutorial example in the link https://github.com/owlcs/owlapi/blob/version5/contract/src/test/java/org/semanticweb/owlapi/examples/Examples.java

Thanks very much for your time.
Sincere regards


问:
Way to create multiline comments in Bash?
I have recently started studying shell script and I'd like to be able to comment out a set of lines in a shell script. I mean like it is in case of C/Java :

```<code>/* comment1
   comment2
   comment3
*/`
</code>```

How could I do that?

答:
Use : ' to open and ' to close.

For example:

```<code>: '
This is a
very neat comment
in bash
'
</code>```

Body:
I have recently started studying shell script and I'd like to be able to comment out a set of lines in a shell script. I mean like it is in case of C/Java :

/* comment1
   comment2
   comment3
*/`

How could I do that?

Body:
Use : ' to open and ' to close.

For example:

: '
This is a
very neat comment
in bash
'


问:
Namespace and Classes - Resolving Naming Ambiguity
The issue I'm getting is "namespace is being used as a type" in a C# project. I get why it's happening and I understand what I have to do to fix it. But it makes little sense to me and so the question here is understanding the design of namespaces and classes in C# context.

I'm hoping this question is different enough from others because I'm not asking how to resolve the situation, but rather how to keep logical and relevant naming while dealing with the situation as I describe it.

I have followed MSDN conventions for naming solutions. So I have a solution called:

```<code>TesterStories.Voxam
</code>```

I have two projects within that. One is TesterStories.Voxam.App and looks like this:

```<code>namespace TesterStories.Voxam.App
{
    TesterStories.Voxam.Parser parser = new TesterStories.Voxam.Parser();

    class Program
    {
    }
}
</code>```

The problem is in that third line.

Presumably because I have another project called TesterStories.Voxam.Parser, which looks like this:

```<code>namespace TesterStories.Voxam.Parser
{
    public class Parser
    {
    }
}
</code>```

So is it saying that it doesn't like that I have "Parser" in my namespace for the project?

But according to MSDN guidelines, if the Parser is the feature, then that's what I should be calling the namespace: [Company].[Project].[Feature]. The class is Parser because, after all, that's what the class does.

So it seems like what I have to do is this:

```<code>namespace TesterStories.Voxam.Parser
{
    public class Xyzzy
    {
    }
}
</code>```

So here I changed my Parser class to Xyzzy class. Now back in my file that was causing the problem I can do this:

```<code>using TesterStories.Voxam.Parser;

namespace TesterStories.Voxam.App
{
    class Program
    {
        Xyzzy parser = new Xyzzy();
    }
}
</code>```

So I get it -- but it means I have to change my class to be something it's not. I realize I could call it AppParser or ParserApp or whatever.

In this context, what do developers tend to do? Do you change your namespace or do you change your class? Even though, in my case, I'm describing the feature as per MSDN guidelines and correctly naming the class based on what it does.)

答:
The namespaces and class names aren't the problem here.
In your original code, you need to designate what class from the TesterStories.Voxam.Parser namespace this 'parser' object should be.

Your original code:

```<code>TesterStories.Voxam.Parser parser = new TesterStories.Voxam.Parser();
</code>```

What class/type in the TesterStories.Voxam.Parser namespace is this supposed to be?

You would need to do:

```<code>TesterStories.Voxam.Parser.*Parser* parser = new TesterStories.Voxam.Parser.*Parser*();
</code>```

(* added for emphasis :) )

Or, like you did in your last code snippet, add a using statement:

```<code>using TesterStories.Voxam.Parser;
</code>```

So that you can do:

```<code>Parser parser = new Parser();
</code>```

Edit - More complete example (for the 'using' suggestion):

```<code>namespace TesterStories.Voxam.App
{
    using TesterStories.Voxam.Parser;

    class Program
    {
        Parser parser = new Parser();
    }
}

namespace TesterStories.Voxam.Parser
{
    public class Parser
    {
    }
}
</code>```

Body:
The issue I'm getting is "namespace is being used as a type" in a C# project. I get why it's happening and I understand what I have to do to fix it. But it makes little sense to me and so the question here is understanding the design of namespaces and classes in C# context.

I'm hoping this question is different enough from others because I'm not asking how to resolve the situation, but rather how to keep logical and relevant naming while dealing with the situation as I describe it.

I have followed MSDN conventions for naming solutions. So I have a solution called:

TesterStories.Voxam

I have two projects within that. One is TesterStories.Voxam.App and looks like this:

namespace TesterStories.Voxam.App
{
    TesterStories.Voxam.Parser parser = new TesterStories.Voxam.Parser();

    class Program
    {
    }
}

The problem is in that third line.

Presumably because I have another project called TesterStories.Voxam.Parser, which looks like this:

namespace TesterStories.Voxam.Parser
{
    public class Parser
    {
    }
}

So is it saying that it doesn't like that I have "Parser" in my namespace for the project?

But according to MSDN guidelines, if the Parser is the feature, then that's what I should be calling the namespace: [Company].[Project].[Feature]. The class is Parser because, after all, that's what the class does.

So it seems like what I have to do is this:

namespace TesterStories.Voxam.Parser
{
    public class Xyzzy
    {
    }
}

So here I changed my Parser class to Xyzzy class. Now back in my file that was causing the problem I can do this:

using TesterStories.Voxam.Parser;

namespace TesterStories.Voxam.App
{
    class Program
    {
        Xyzzy parser = new Xyzzy();
    }
}

So I get it -- but it means I have to change my class to be something it's not. I realize I could call it AppParser or ParserApp or whatever.

In this context, what do developers tend to do? Do you change your namespace or do you change your class? Even though, in my case, I'm describing the feature as per MSDN guidelines and correctly naming the class based on what it does.)

Body:
The namespaces and class names aren't the problem here.
In your original code, you need to designate what class from the TesterStories.Voxam.Parser namespace this 'parser' object should be.

Your original code:

TesterStories.Voxam.Parser parser = new TesterStories.Voxam.Parser();

What class/type in the TesterStories.Voxam.Parser namespace is this supposed to be?

You would need to do:

TesterStories.Voxam.Parser.*Parser* parser = new TesterStories.Voxam.Parser.*Parser*();

(* added for emphasis :) )

Or, like you did in your last code snippet, add a using statement:

using TesterStories.Voxam.Parser;

So that you can do:

Parser parser = new Parser();

Edit - More complete example (for the 'using' suggestion):

namespace TesterStories.Voxam.App
{
    using TesterStories.Voxam.Parser;

    class Program
    {
        Parser parser = new Parser();
    }
}

namespace TesterStories.Voxam.Parser
{
    public class Parser
    {
    }
}


问:
Accessing variables from included files in Ruby
How do you access variables which are defined in an included file?</p>

```<code># inc.rb
foo = "bar";

# main.rb
require 'inc.rb'
puts foo

# NameError: undefined local variable or method `foo' for main:Object
</code>```

答:
I usually just define them as methods. Similar to what nickf said.

File1:

```<code>def static_path
  '/opt/foo'
end
</code>```

File2:

```<code>static_path
</code>```

Then just add a:

require_relative 'file path/file name' or require_relative 'file name' <= if files are in same dir.

to the file you want to use the method/variable in.

Body:
How do you access variables which are defined in an included file?

# inc.rb
foo = "bar";

# main.rb
require 'inc.rb'
puts foo

# NameError: undefined local variable or method `foo' for main:Object

Body:
I usually just define them as methods. Similar to what nickf said.

File1:

def static_path
  '/opt/foo'
end

File2:

static_path

Then just add a:

require_relative 'file path/file name' or require_relative 'file name' <= if files are in same dir.

to the file you want to use the method/variable in.


问:
How to extract portion of a line in ruby?
I have a line say

line = "start running at Sat April 1 07:30:37 2017"

and I want to extract

"Sat April 1 07:30:37 2017"

I tried this...

```<code>line = "start running at Sat April 1 07:30:37 2017"
if (line =~ /start running at/)
   line.split("start running at ").last
end
</code>```

... but is there any other way of doing this?

答:
try</p>

```<code>line.sub(/start running at (.*)/, '\1')
</code>```

Body:
I have a line say

line = "start running at Sat April 1 07:30:37 2017"

and I want to extract

"Sat April 1 07:30:37 2017"

I tried this...

line = "start running at Sat April 1 07:30:37 2017"
if (line =~ /start running at/)
   line.split("start running at ").last
end

... but is there any other way of doing this?

Body:
try

line.sub(/start running at (.*)/, '\1')


问:
PHP: Is it better to concatenate on 1 line or multiple lines? Or is there a difference?
Is there a difference or is one better than the other of the following:

```<code>$var = '';
...
$var .= 'blah blah';
$var .= $var2;
$var .= 'blah blah';
</code>```

Or

```<code>$var = '';
...
$var .= 'blah blah' . $var2 . 'blah blah';
</code>```

Is there a speed difference or is there a reason why you'd pick one over the other?

答:
I don't think you'll notice for such a short situation. I typically decide for readability reasons which I'm going to use.  I only split on two situations, otherwise on one line:

a) Creating a multi-line response so the code somewhat mimics what the user will see. I've found it makes it easier to catch typos and mistakes this way.

```<code>$var  = "line 1 \n";
$var .= "line 2 \n";
</code>```

b) line length.  If the line will overflow my window I'll typically break it up so I don't have to go to the end of the line to read the end. Most languages support a line continuation character so I don't really need to break it physically in the code, but just a habit i have since I do work in some languages that don't have it.

OwnerDisplayName: Darryl Hein

Body:
Is there a difference or is one better than the other of the following:

$var = '';
...
$var .= 'blah blah';
$var .= $var2;
$var .= 'blah blah';

Or

$var = '';
...
$var .= 'blah blah' . $var2 . 'blah blah';

Is there a speed difference or is there a reason why you'd pick one over the other?

LastEditorDisplayName: Paul Dixon

Body:
I don't think you'll notice for such a short situation. I typically decide for readability reasons which I'm going to use.  I only split on two situations, otherwise on one line:

a) Creating a multi-line response so the code somewhat mimics what the user will see. I've found it makes it easier to catch typos and mistakes this way.

$var  = "line 1 \n";
$var .= "line 2 \n";

b) line length.  If the line will overflow my window I'll typically break it up so I don't have to go to the end of the line to read the end. Most languages support a line continuation character so I don't really need to break it physically in the code, but just a habit i have since I do work in some languages that don't have it.

OwnerDisplayName: Kevin


问:
How can I simplify this code? (Chess game obstruction testing)
I'm making a chess game in Java, and testing to make sure there are no pieces blocking the path of the piece being moved. The piece moves from (srcX,srcY) to (dstX,dstY).

I've written this code which checks if there are any obstructions for a rook:

```<code>    if(dstY == srcY) {

            // No change on Y axis, so moving east or west

            if(dstX > srcX) {
                // Moving east
                // Test every cell the piece will pass over
                for(int x = srcX+1; x < dstX; x++) {
                    // Is the cell set?
                    if(isPiece(x, srcY)) {
                        return true;
                    }
                }
            } else {
                // Must be moving west
                // Test every cell the piece will pass over
                for(int x = srcX-1; x > dstX; x--) {
                    // Is the cell set?
                    if(isPiece(x, srcY)) {
                        return true;
                    }
                }
            }

        } else if(dstX == srcX) {

            // No change on X axis, so moving north or south

            if(dstY > srcY) {
                // Moving north
                // Test every cell the piece will pass over
                for(int y = srcY+1; y < dstY; y++) {
                    // Is the cell set?
                    if(isPiece(srcX, y)) {
                        return true;
                    }
                }
            } else {
                // Must be moving south
                // Test every cell the piece will pass over
                for(int y = srcY-1; y > dstY; y--) {
                    // Is the cell set?
                    if(isPiece(srcX, y)) {
                        return true;
                    }
                }
            }
        }
</code>```

but it's a bit big and I'm sure it can be simplied.. any ideas?

ps, this is ONLY obstruction testing. I've already validated everything else.

答:
Once you've tested for direction, you can set dx, dy values (e.g. dx=1, dy=0 for east). Then you can have a single for loop for all cases and just increment x and y by dx and dy respectively at each iteration.

You can then simplify the direction checking into the following:

```<code>if dstY == srcY: dy = 0
else: dy = (dstY - srcY) / abs(dstY - srcY)
if dstX == srcX: dx = 0
else: dx = (dstX - srcX) / abs(dstX - srcX)
</code>```

Code:

```<code>int dx, dy;
if (dstY == srcY) dy = 0;
else dy = (dstY - srcY) / Math.abs(dstY - srcY);
if (dstX == srcX) dx = 0;
else dx = (dstX - srcX) / Math.abs(dstX - srcX);

while (srcX != dstX || srcY != dstY) {
  srcX += dx; srcY += dy;
  if (isPiece(srcX, srcY))
    return true;
}
return false;
</code>```

Also beware that this code (and yours) will fail if the move is not horizontal, vertical or diagonal.

Body:
I'm making a chess game in Java, and testing to make sure there are no pieces blocking the path of the piece being moved. The piece moves from (srcX,srcY) to (dstX,dstY).

I've written this code which checks if there are any obstructions for a rook:

    if(dstY == srcY) {

            // No change on Y axis, so moving east or west

            if(dstX > srcX) {
                // Moving east
                // Test every cell the piece will pass over
                for(int x = srcX+1; x < dstX; x++) {
                    // Is the cell set?
                    if(isPiece(x, srcY)) {
                        return true;
                    }
                }
            } else {
                // Must be moving west
                // Test every cell the piece will pass over
                for(int x = srcX-1; x > dstX; x--) {
                    // Is the cell set?
                    if(isPiece(x, srcY)) {
                        return true;
                    }
                }
            }

        } else if(dstX == srcX) {

            // No change on X axis, so moving north or south

            if(dstY > srcY) {
                // Moving north
                // Test every cell the piece will pass over
                for(int y = srcY+1; y < dstY; y++) {
                    // Is the cell set?
                    if(isPiece(srcX, y)) {
                        return true;
                    }
                }
            } else {
                // Must be moving south
                // Test every cell the piece will pass over
                for(int y = srcY-1; y > dstY; y--) {
                    // Is the cell set?
                    if(isPiece(srcX, y)) {
                        return true;
                    }
                }
            }
        }

but it's a bit big and I'm sure it can be simplied.. any ideas?

ps, this is ONLY obstruction testing. I've already validated everything else.

Body:
Once you've tested for direction, you can set dx, dy values (e.g. dx=1, dy=0 for east). Then you can have a single for loop for all cases and just increment x and y by dx and dy respectively at each iteration.

You can then simplify the direction checking into the following:

if dstY == srcY: dy = 0
else: dy = (dstY - srcY) / abs(dstY - srcY)
if dstX == srcX: dx = 0
else: dx = (dstX - srcX) / abs(dstX - srcX)

Code:

int dx, dy;
if (dstY == srcY) dy = 0;
else dy = (dstY - srcY) / Math.abs(dstY - srcY);
if (dstX == srcX) dx = 0;
else dx = (dstX - srcX) / Math.abs(dstX - srcX);

while (srcX != dstX || srcY != dstY) {
  srcX += dx; srcY += dy;
  if (isPiece(srcX, srcY))
    return true;
}
return false;

Also beware that this code (and yours) will fail if the move is not horizontal, vertical or diagonal.


问:
What does 'c' parameter do in coding?
What does parameter do in programming ?

For example

void main()

int n = 6;

int test(int n)

Is the int n inside the int test refer to the void main int 6 ?
Can anyone explain further for me.

Tq guys have better understanding now.

答:
Based on your description..
n = 6 both in the main function and the test function.

E.g.

```<code>void main()
{
   int n = 6;
   test(n); //shows 8
   print("%d", n); //shows 6
}
int test(int n)
{
   n = n + 2;
   return n;
}
</code>```

Here we have two 'n' in two functions representing two different values.

Title: What does 'c' parameter do in coding?

Body:
Based on your description..
n = 6 both in the main function and the test function.

E.g.

void main()
{
   int n = 6;
   test(n); //shows 8
   print("%d", n); //shows 6
}
int test(int n)
{
   n = n + 2;
   return n;
}

Here we have two 'n' in two functions representing two different values.


问:
Unable to test calls for real server after mocking mockwebserver on Android?
I am first running a mocked login test which returns status code 400 followed by a second test that logs in using real service call. The tests are below:

```<code>@Test
public void mock() throws IOException, InterruptedException {
    MockWebServer server = new MockWebServer();
    server.enqueue(new MockResponse().setResponseCode(400));
    server.start();
    NetworkServiceHelper.init(String.valueOf(server.url("/"))); // Change retrofit baseUrl to localhost

    loginWithoutWaiting(username, password);

    server.shutdown();
}

@Test
public void real() {
    NetworkServiceHelper.init(NetworkServiceHelper.DEFAULT_URL); // Change retrofit baseUrl to a real url
    loginWithoutWaiting(username, password);
}
</code>```

The real service does not get called. The EditText error message says

Unable to authenticate: Failed to connect to localhost/127.0.0.1:50162

Here is the NetworkServiceHelper.init() function that initializes Retrofit instance:

```<code>public static synchronized void init(String serverUrl) {

   // Override the GSON date format.
    Gson gson = new GsonBuilder()
            .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
            .create();

    // We want to make the network calls asynchronous, so use createWithScheduler()
    RxJavaCallAdapterFactory rxAdapter = RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io());

    // Finally, build the Retrofit client.
    retrofit = new Retrofit.Builder()
            .baseUrl(serverUrl)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .addCallAdapterFactory(rxAdapter)
            .client(buildClient())
            .build();
}
</code>```

答:
make sure that you lazily invoke the activity like following way

```<code>@Rule
    public ActivityTestRule<EmergencyMainActivity> mActivityTestRule =
            new ActivityTestRule<>(EmergencyMainActivity.class, true, false);
</code>```

and then invoke the activity after the server network call has been setup.

Body:
I am first running a mocked login test which returns status code 400 followed by a second test that logs in using real service call. The tests are below:

@Test
public void mock() throws IOException, InterruptedException {
    MockWebServer server = new MockWebServer();
    server.enqueue(new MockResponse().setResponseCode(400));
    server.start();
    NetworkServiceHelper.init(String.valueOf(server.url("/"))); // Change retrofit baseUrl to localhost

    loginWithoutWaiting(username, password);

    server.shutdown();
}

@Test
public void real() {
    NetworkServiceHelper.init(NetworkServiceHelper.DEFAULT_URL); // Change retrofit baseUrl to a real url
    loginWithoutWaiting(username, password);
}

The real service does not get called. The EditText error message says

Unable to authenticate: Failed to connect to localhost/127.0.0.1:50162

Here is the NetworkServiceHelper.init() function that initializes Retrofit instance:

public static synchronized void init(String serverUrl) {

   // Override the GSON date format.
    Gson gson = new GsonBuilder()
            .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
            .create();

    // We want to make the network calls asynchronous, so use createWithScheduler()
    RxJavaCallAdapterFactory rxAdapter = RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io());

    // Finally, build the Retrofit client.
    retrofit = new Retrofit.Builder()
            .baseUrl(serverUrl)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .addCallAdapterFactory(rxAdapter)
            .client(buildClient())
            .build();
}

Body:
make sure that you lazily invoke the activity like following way

@Rule
    public ActivityTestRule<EmergencyMainActivity> mActivityTestRule =
            new ActivityTestRule<>(EmergencyMainActivity.class, true, false);

and then invoke the activity after the server network call has been setup.


问:
pod setup Cloning into 'master' error: RPC failed; result=56, HTTP code = 200
I am trying to pod setup, but I am getting following error:

[!] /usr/bin/git clone https://github.com/CocoaPods/Specs.git master --depth=1

Cloning into 'master'...

error: RPC failed; result=56, HTTP code = 200

fatal: The remote end hung up unexpectedly

fatal: early EOF

fatal: index-pack failed

network status is ok.

I don't know what's going on.

答:
The only thing that worked for me was forcing git to use git:// instead of https://.

Add following to ~/.gitconfig:

```<code>[url "git://github.com/"]
  insteadOf = https://github.com/
</code>```

This way pod install works for me too.

UPDATE (2019-07)

This answer is being down-voted recently - possibly it no longer works?

UPDATE (2019-08)

This is a working solution. Tested!

Body:
The only thing that worked for me was forcing git to use git:// instead of https://.

Add following to ~/.gitconfig:

[url "git://github.com/"]
  insteadOf = https://github.com/

This way pod install works for me too.

UPDATE (2019-07)

This answer is being down-voted recently - possibly it no longer works?

UPDATE (2019-08)

This is a working solution. Tested!


问:
Is transaction (multi, exec) supported in spring data redis in a cluster mode?
I had implemented (and tested) transaction operation in redis using multi and exec functionality in a single REDIS instance successfully. However, the same code running in a cluster setup erroring out with the following exception message. I am using spring-data-redis-1.8.1.RELEASE and jedis-2.9.0.

```<code>Exception in thread "main" org.springframework.dao.InvalidDataAccessApiUsageException: MUTLI is currently not supported in cluster mode.
    at org.springframework.data.redis.connection.jedis.JedisClusterConnection.multi(JedisClusterConnection.java:2457)
    at org.springframework.data.redis.connection.DefaultStringRedisConnection.multi(DefaultStringRedisConnection.java:608)
    at org.springframework.data.redis.core.RedisTemplate$21.doInRedis(RedisTemplate.java:871)
    at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:207)
    at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:169)
    at org.springframework.data.redis.core.RedisTemplate.multi(RedisTemplate.java:868)
    at com.glu.centech.chat.RedisClusterTest$1.execute(RedisClusterTest.java:58)
    at com.glu.centech.chat.RedisClusterTest$1.execute(RedisClusterTest.java:1)
    at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:229)
    at com.glu.centech.chat.RedisClusterTest.main(RedisClusterTest.java:55)
</code>```

Is transaction (multi, exec) currently supported in spring data redis in a cluster mode? If so, what am I missing? If not, is there any workaround or when it'll be supported?

答: There's no transaction support for Redis Cluster with Spring Data Redis and you should not expect it to be implemented. See Is there any Redis client (Java prefered) which supports transactions on Redis cluster? for further reference.</p>

Body:
I had implemented (and tested) transaction operation in redis using multi and exec functionality in a single REDIS instance successfully. However, the same code running in a cluster setup erroring out with the following exception message. I am using spring-data-redis-1.8.1.RELEASE and jedis-2.9.0.

Exception in thread "main" org.springframework.dao.InvalidDataAccessApiUsageException: MUTLI is currently not supported in cluster mode.
    at org.springframework.data.redis.connection.jedis.JedisClusterConnection.multi(JedisClusterConnection.java:2457)
    at org.springframework.data.redis.connection.DefaultStringRedisConnection.multi(DefaultStringRedisConnection.java:608)
    at org.springframework.data.redis.core.RedisTemplate$21.doInRedis(RedisTemplate.java:871)
    at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:207)
    at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:169)
    at org.springframework.data.redis.core.RedisTemplate.multi(RedisTemplate.java:868)
    at com.glu.centech.chat.RedisClusterTest$1.execute(RedisClusterTest.java:58)
    at com.glu.centech.chat.RedisClusterTest$1.execute(RedisClusterTest.java:1)
    at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:229)
    at com.glu.centech.chat.RedisClusterTest.main(RedisClusterTest.java:55)

Is transaction (multi, exec) currently supported in spring data redis in a cluster mode? If so, what am I missing? If not, is there any workaround or when it'll be supported?


问:
Reliabily unload dll in java
I am trying to unload a dll in java. I have read this and this but it seems that you can not guarantee that the dll will actually be unloaded at a certain time. This is because System.gc() simply "asks kindly" for the garbage collector to run.

So here is a break down of the situation. I have a dll that provides some functionality via JNI. Lets call this dll MainDll. MainDll is loaded from a call to System.load("MainDll"). I need to be able to unload and load this dll on the fly.

Is it possible to create another dll that's sole purpose is to load and unload MainDll. Lets call this dll LoaderDll. I could then simple call System.load("LoaderDll") and have some native functions to load and unload MainDll. The reason for doing this, is I have access to functions on the native system that can load and unload the dll on the fly. The tricky part with this is, will I have still be able to access the native functions I have written in MainDll if it loaded from inside LoaderDll.

Sorry if this is a confusing question. It seems its a little difficult to explain.

Thanks

答: Based on your clarifying comments, I think the simplest approach would be to spawn a new JVM, whose sole responsibility is managing your DLL. Probably exposing an RMI interface to access those classes (although a simple stream may be sufficient).</p>

Title: Reliabily unload dll in java


问:
Remove rows with missing values denoted by '?'
I have a .csv file that contains rows with missing values. Those values instead of null, are denoted by the character ?.

How can I remove the rows that contain at least one column with value ?, given that df.na.drop() won't work (since the missing values are not null) ?

The data looks like below (I've got 35 columns - missing values can be found in any of those columns)

```<code>+-------+--------+------+-------+
| col_1 | col_2  |  ... | col_35|
+-------+--------+------+-------+
| 0.75  |   ?    |  ... |   15  |
|   ?   | Helen  |  ... |   21  |
| -1.2  | George |  ... |    ?  |
|   ?   | Andrew |  ... |   129 |
| 0.12  | Maria  |  ... |   12  |   // Should not be deleted
+-------+--------+------+-------+
</code>```

And here's the code that reads the file.

```<code>val df = sparkSession.read
    .format("com.databricks.spark.csv")
    .option("header", "true")
    .option("mode", "DROPMALFORMED")
    .load("data.csv")
    .toDF()
</code>```

答:
You can convert the ? to null values using UDFs in spark data frames.

Sample code below:

```<code>import org.apache.spark.sql.functions.udf

val df = sc.parallelize(
  Seq(("a", "B", "c"), ("D", "e", "?"), ("G", "?", "I"))).toDF("x", "y", "z")
// Function returns the input itself or null if it is a '?'
def replace: (String => String) = { value => if (value == "?") null else value }
// We create a UDF of that function because we want to run this on the entire column
val replaceudf = udf(replace)
Apply the method to all columns of the data frame
df.select(df.columns.map(c => replaceudf(col(c)).alias(c)): _*)

df.show
/* Output
+---+----+----+
|  x|   y|   z|
+---+----+----+
|  a|   B|   c|
|  D|   e|null|
|  G|null|   I|
+---+----+----+
*/
</code>```

Now you can apply all the NA operations on the data frame. I hope this helps.

Body:
I have a .csv file that contains rows with missing values. Those values instead of null, are denoted by the character ?.

How can I remove the rows that contain at least one column with value ?, given that df.na.drop() won't work (since the missing values are not null) ?

The data looks like below (I've got 35 columns - missing values can be found in any of those columns)

+-------+--------+------+-------+
| col_1 | col_2  |  ... | col_35|
+-------+--------+------+-------+
| 0.75  |   ?    |  ... |   15  |
|   ?   | Helen  |  ... |   21  |
| -1.2  | George |  ... |    ?  |
|   ?   | Andrew |  ... |   129 |
| 0.12  | Maria  |  ... |   12  |   // Should not be deleted
+-------+--------+------+-------+

And here's the code that reads the file.

val df = sparkSession.read
    .format("com.databricks.spark.csv")
    .option("header", "true")
    .option("mode", "DROPMALFORMED")
    .load("data.csv")
    .toDF()

Body:
You can convert the ? to null values using UDFs in spark data frames.

Sample code below:

import org.apache.spark.sql.functions.udf

val df = sc.parallelize(
  Seq(("a", "B", "c"), ("D", "e", "?"), ("G", "?", "I"))).toDF("x", "y", "z")
// Function returns the input itself or null if it is a '?'
def replace: (String => String) = { value => if (value == "?") null else value }
// We create a UDF of that function because we want to run this on the entire column
val replaceudf = udf(replace)
Apply the method to all columns of the data frame
df.select(df.columns.map(c => replaceudf(col(c)).alias(c)): _*)

df.show
/* Output
+---+----+----+
|  x|   y|   z|
+---+----+----+
|  a|   B|   c|
|  D|   e|null|
|  G|null|   I|
+---+----+----+
*/

Now you can apply all the NA operations on the data frame. I hope this helps.


问:
Run trigger at specific date and time
I want to run a trigger at specific date and time (+or - 15 min).

I have a date min string with YYYY-MM-DD HH:MM format say 2017-04-01 18:05 How will I modify the below script to run at 18 hours and 5 minutes.

```<code> var triggerDay = new Date(2017, 04, 01);
 ScriptApp.newTrigger("myFunction")
   .timeBased()
   .at(triggerDay)
   .create();
</code>```

答:
You can try this:

```<code>function createTimeDrivenTriggers() {
// Trigger on 2017-04-01 around 18:00 (±15 min).
ScriptApp.newTrigger('myFunction')
    .timeBased()
    .atDate(2017, 04, 01)
    .atHour(18)
    .create();
}
</code>```

https://developers.google.com/apps-script/reference/script/clock-trigger-builder

Title: Run trigger at specific date and time

Body:
I want to run a trigger at specific date and time (+or - 15 min).

I have a date min string with YYYY-MM-DD HH:MM format say 2017-04-01 18:05 How will I modify the below script to run at 18 hours and 5 minutes.

 var triggerDay = new Date(2017, 04, 01);
 ScriptApp.newTrigger("myFunction")
   .timeBased()
   .at(triggerDay)
   .create();

Body:
You can try this:

function createTimeDrivenTriggers() {
// Trigger on 2017-04-01 around 18:00 (±15 min).
ScriptApp.newTrigger('myFunction')
    .timeBased()
    .atDate(2017, 04, 01)
    .atHour(18)
    .create();
}

https://developers.google.com/apps-script/reference/script/clock-trigger-builder


问:
Deleting duplicates from single-linked list
Is there a way to modify linked list that way so we delete all duplicates from it.

The think is it needs to be done for linear time and constant memory usage. I tried to put all elements of the list into HashMap which gives us constant time but linear memory usage.

Is there another way?

答:
You can use stream().distinct() method to do it for linear time:

```<code>List<String> result = list.stream()
        .distinct()
        .collect(Collectors.toList());
</code>```

Body:
You can use stream().distinct() method to do it for linear time:

List<String> result = list.stream()
        .distinct()
        .collect(Collectors.toList());


问:
C# byte vs int for short integer values
This question is related to the physical memory of a C# Program. As we know that, byte variable consumes 1 byte of memory and on the other hand an int (32-bit) variable consumes 4-bytes of memory. So, when we need variables with possibly smaller values (such as a counter variable i to iterate a loop 100 times) which one should we use in the below for loop? byte or int ?

```<code> for(byte i=0; i<100; ++i)
</code>```

Kindly please give your opinion with reason and share you precious knowledge. I shall be glad and thankful to you :-)

Note: I use byte instead of int in such cases. But I have seen that many experienced programmers use int even when the expected values are less than 255. Please let me know if I am wrong. :-)

答:
In most cases, you won't get any benefit from using byte instead of int. The reason is:
If the loop variable is stored in a CPU register: Since modern CPUs have a register width of 32 bits, and since you can't use only one fourth of a register, the resulting code would be pretty much the same either way.

If the loop variable is not stored in a CPU register, then it will most likely be stored on the stack. Compilers try to align memory locations at addresses which are multiples of 4, this has to do with performance, thus the compiler would also assign 4 bytes to your byte variable on the stack.

Depending on details of your code, the compiler would even add extra code to make sure that the memory location (on the stack or in a register) never exceeds 255, which would add extra code and makes it slower.
It's a totally different story with 8 bit microcontrollers like those from Atmel and Microchip, there your approach would make sense.

Title: C# byte vs int for short integer values

Body:
This question is related to the physical memory of a C# Program. As we know that, byte variable consumes 1 byte of memory and on the other hand an int (32-bit) variable consumes 4-bytes of memory. So, when we need variables with possibly smaller values (such as a counter variable i to iterate a loop 100 times) which one should we use in the below for loop? byte or int ?

 for(byte i=0; i<100; ++i)

Kindly please give your opinion with reason and share you precious knowledge. I shall be glad and thankful to you :-)

Note: I use byte instead of int in such cases. But I have seen that many experienced programmers use int even when the expected values are less than 255. Please let me know if I am wrong. :-)


问:
add a (x,y) point to area chart in Excel
using the following coordinates I have the following graph

```<code>0.22    581.5
0.32    800
0.46    800
</code>```

I would like to add a point at (0.32,400) how is the possible procedure in excel?

I have tried to combine graphs together but unsuccessfully

答:
Right click on your chart and select "select data"

Add 1st and 3rd column in series

Right click on chart and select "change series chart type"

Select chart "Line with markers"

You can hide line by clicking on line and select format data series

Body:
using the following coordinates I have the following graph

0.22    581.5
0.32    800
0.46    800

I would like to add a point at (0.32,400) how is the possible procedure in excel?

I have tried to combine graphs together but unsuccessfully


问:
Ajax Response JSON data to select box in html
below is my ajax call and i am getting r JSON data

```<code>$.ajax ({
            type: "POST",
            url: "getrecieverlist.php",
            data: { strSenderID: sendmeid },
            success: function (r) {
            }
       });
</code>```

I am getting r response as JSON data below

```<code>{
 "receiverDetails": [
{
  "receiver_id": "55555",
  "name": "Nitin",
  "mobile": "7777777777",
  "ifsc_code": "IFSC54545",
  "acc_no": "16-01-2017"
},
{
  "receiver_id": "66666",
  "name": "Vikram",
  "mobile": "9191919191",
  "ifsc_code": "IFSC54545",
  "acc_no": "13-01-2017"
}
],
 "success": 1
 }
</code>```

and my select box html code is below

```<code><select id="recieverlist" name="select" class="main-form">
      <option value="">None Selected</option>
    </select>
</code>```

what i want is to populate select box options with text as name from the JSON data and value of the options to be receiverid, i tried many things but did not worked out for me need the proper guide how to do it?

答:
You can also $.each function.</p>

```<code>                $.each(data.receiverDetails, function(index, value)
                    $("#recieverlist").append('<option value="'+value.receiver_id+'">'+value.name+'</option>');
                  });
</code>```

Body:
below is my ajax call and i am getting r JSON data

$.ajax ({
            type: "POST",
            url: "getrecieverlist.php",
            data: { strSenderID: sendmeid },
            success: function (r) {
            }
       });

I am getting r response as JSON data below

{
 "receiverDetails": [
{
  "receiver_id": "55555",
  "name": "Nitin",
  "mobile": "7777777777",
  "ifsc_code": "IFSC54545",
  "acc_no": "16-01-2017"
},
{
  "receiver_id": "66666",
  "name": "Vikram",
  "mobile": "9191919191",
  "ifsc_code": "IFSC54545",
  "acc_no": "13-01-2017"
}
],
 "success": 1
 }

and my select box html code is below

<select id="recieverlist" name="select" class="main-form">
      <option value="">None Selected</option>
    </select>

what i want is to populate select box options with text as name from the JSON data and value of the options to be receiverid, i tried many things but did not worked out for me need the proper guide how to do it?

Body:
You can also $.each function.

                $.each(data.receiverDetails, function(index, value)
                    $("#recieverlist").append('<option value="'+value.receiver_id+'">'+value.name+'</option>');
                  });