问:
run rails app with an ubuntu server with global ip
Currently, we are running our rails app, on AWS but we tried to move it to Heroku, which didn't work at all, now We are trying to run the app on Virtual Machine on hetzner. I can run the app on local server easily, my question is that, How can we run our rails app with a specific IP and then we can access that app anywhere in the world from that ip? is that possible to do so? We are using PUMA for server.

答:
Yes, you can access to to your site with specific IP.

In description of hetzner Virtual Server says that server have 1 specific IP. So than you deployed and run you application y can access to app with 1.1.1.1:80 or another port.

If i understand you. Also what happened with heroku?


来源: stackexchange

问:
why is ng-model not checking default radio button?
Below is the fiddle i am working:

http://jsfiddle.net/3c0dxf4d/

The ng-model has an object and the ng-value maps to object, why is my default value {"id":1,"name":"Bill"}
 not getting selected by default.

答:
Check out this fiddle http://jsfiddle.net/roz98eda/

var app = angular.module("app", []);

app.controller("ctrl", function($scope) {
  $scope.customers = [{
    "id": 1,
    "name": "Bill"
  }, {
    "id": 2,
    "name": "Bob"
  }, {
    "id": 3,
    "name": "Biff"
  }];
  $scope.customer = {};
  $scope.currentCustomer = {
    "id": 1
  };

})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="ctrl">
    <table>
      <tr ng-repeat="theCustomer in customers">
        <td>
          <input type="radio" ng-model="$parent.currentCustomer.id" ng-value="theCustomer.id">{{theCustomer.name}}</td>
      </tr>
    </table>
    <br>
    <div>{{currentCustomer}}</div>
  </div>
</div></code>```

ContentLicense: CC BY-SA 3.0

Body:
Check out this fiddle http://jsfiddle.net/roz98eda/

var app = angular.module("app", []);

app.controller("ctrl", function($scope) {
  $scope.customers = [{
    "id": 1,
    "name": "Bill"
  }, {
    "id": 2,
    "name": "Bob"
  }, {
    "id": 3,
    "name": "Biff"
  }];
  $scope.customer = {};
  $scope.currentCustomer = {
    "id": 1
  };

})

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="ctrl">
    <table>
      <tr ng-repeat="theCustomer in customers">
        <td>
          <input type="radio" ng-model="$parent.currentCustomer.id" ng-value="theCustomer.id">{{theCustomer.name}}</td>
      </tr>
    </table>
    <br>
    <div>{{currentCustomer}}</div>
  </div>
</div>


问:
Django: choose 'company' from company model, if company not present create one
I have a use case where in UserProfile model, user details are stored. One of the field is user_company_name.

```<code>class UserProfile(BaseModel):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    user_company_name = models.CharField(max_length=254)
</code>```

Instead of a CharField I want the field to be a ChoiceField, having drop down of the Company (names) currently present in the database. If the current company of the user is not present in the dropdown I plan to give the user an option to add his or her company to the DB.
Suppose I have a Company model as such:

```<code>class Company(BaseModel):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name
</code>```

What should be my Field Choice in the UserProfile model for user_company_name field.

答:
You can use foreign key in the models for user_company and in forms use ChoiceField to get a drop down.

Check the code below:-

In models:-

```<code>class UserProfile(BaseModel):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
user_company = models.ForeignKey(Company)
</code>```

In Forms:-

```<code>user_company = forms.ModelChoiceField(queryset=Company.objects.all())
</code>```

Body:
I have a use case where in UserProfile model, user details are stored. One of the field is user_company_name.

class UserProfile(BaseModel):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    user_company_name = models.CharField(max_length=254)

Instead of a CharField I want the field to be a ChoiceField, having drop down of the Company (names) currently present in the database. If the current company of the user is not present in the dropdown I plan to give the user an option to add his or her company to the DB.
Suppose I have a Company model as such:

class Company(BaseModel):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

What should be my Field Choice in the UserProfile model for user_company_name field.

Body:
You can use foreign key in the models for user_company and in forms use ChoiceField to get a drop down.

Check the code below:-

In models:-

class UserProfile(BaseModel):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
user_company = models.ForeignKey(Company)

In Forms:-

user_company = forms.ModelChoiceField(queryset=Company.objects.all())


问:
How to call a function that contains a comma in R?
When using S3 or S4 classes in R, it's common to set a class as generic my_generic and then use dots for each subtype my_generic.my_type. Lately, I've been seeing this pattern, but using commas instead of periods my_generic,my_type. The problem is that I can't use the help operator ? or enter the function name in the console because the comma is treated as an error. Is there a workaround? I've tried using backticks, but it doesn't work.

An example of this is the draw method in the ComplexHeatmap package:

```<code>methods(draw)
[1] draw.colorkey             draw.details       draw,HeatmapAnnotation-method
[4] draw,HeatmapList-method draw,Heatmap-method      draw.key
draw,SingleAnnotation-method
</code>```

Doing ?draw.colorkey works, but ?draw,HeatmapAnnotation-method doesn't.

答:
First of all, it is terribly bad practice to call methods directly, especially with S4. The "functions with a comma" you're looking at, are actually S4 methods.

Help pages

To find the help page (if it exists), you can use quotation marks like this:

```<code>?"draw,Heatmap-method"
</code>```

But success is not guaranteed. This heavily depends on whether the author of the package has separate help files for the methods, or used the correct aliases. In this particular case, you see that on the help page ?draw the author of the package added a couple of links to the specific methods.

Find all S4 methods

To get an idea about all the S4 methods alone , use showMethods instead of methods.

```<code>> library(ComplexHeatmap)
> showMethods("draw")
Function: draw (package ComplexHeatmap)
object="Heatmap"
object="HeatmapAnnotation"
object="HeatmapList"
object="SingleAnnotation"
</code>```

See the internal code of a method

To get the actual method so you can see the internal code, use getMethod:

```<code>getMethod(draw, signature = "Heatmap")
Method Definition:

function (object, ...)
{...
    }
    .local(object, ...)
}
<environment: namespace:ComplexHeatmap>

Signatures:
        object
target  "Heatmap"
defined "Heatmap"
</code>```

Use a specific S4 method (but don't really)

You can assign the result of that call and use that as a function:

```<code>mat = matrix(rnorm(80, 2), 8, 10)
mat = rbind(mat, matrix(rnorm(40, -2), 4, 10))
rownames(mat) = letters[1:12]
colnames(mat) = letters[1:10]

ht = Heatmap(mat)
myMethod <- getMethod(draw, signature = "Heatmap")

myMethod(ht)
</code>```

But you shouldn't try to call a method directly. The result of that last call is the exact same as

```<code>draw(ht)
</code>```

So you better use the generic function and let the dispatching do its work.

Body:
When using S3 or S4 classes in R, it's common to set a class as generic my_generic and then use dots for each subtype my_generic.my_type. Lately, I've been seeing this pattern, but using commas instead of periods my_generic,my_type. The problem is that I can't use the help operator ? or enter the function name in the console because the comma is treated as an error. Is there a workaround? I've tried using backticks, but it doesn't work.

An example of this is the draw method in the ComplexHeatmap package:

methods(draw)
[1] draw.colorkey             draw.details       draw,HeatmapAnnotation-method
[4] draw,HeatmapList-method draw,Heatmap-method      draw.key
draw,SingleAnnotation-method

Doing ?draw.colorkey works, but ?draw,HeatmapAnnotation-method doesn't.

Body:
First of all, it is terribly bad practice to call methods directly, especially with S4. The "functions with a comma" you're looking at, are actually S4 methods.

Help pages

To find the help page (if it exists), you can use quotation marks like this:

?"draw,Heatmap-method"

But success is not guaranteed. This heavily depends on whether the author of the package has separate help files for the methods, or used the correct aliases. In this particular case, you see that on the help page ?draw the author of the package added a couple of links to the specific methods.

Find all S4 methods

To get an idea about all the S4 methods alone , use showMethods instead of methods.

> library(ComplexHeatmap)
> showMethods("draw")
Function: draw (package ComplexHeatmap)
object="Heatmap"
object="HeatmapAnnotation"
object="HeatmapList"
object="SingleAnnotation"

See the internal code of a method

To get the actual method so you can see the internal code, use getMethod:

getMethod(draw, signature = "Heatmap")
Method Definition:

function (object, ...)
{...
    }
    .local(object, ...)
}
<environment: namespace:ComplexHeatmap>

Signatures:
        object
target  "Heatmap"
defined "Heatmap"

Use a specific S4 method (but don't really)

You can assign the result of that call and use that as a function:

mat = matrix(rnorm(80, 2), 8, 10)
mat = rbind(mat, matrix(rnorm(40, -2), 4, 10))
rownames(mat) = letters[1:12]
colnames(mat) = letters[1:10]

ht = Heatmap(mat)
myMethod <- getMethod(draw, signature = "Heatmap")

myMethod(ht)

But you shouldn't try to call a method directly. The result of that last call is the exact same as

draw(ht)

So you better use the generic function and let the dispatching do its work.


问:
Interface Builder could not open the document ".storyboard" because it does not exist
This problem is getting me really crazy. Xcode is looking for a storyboard in my project in a differente location from my project. I tryed removing the file, adding it again, cleaning the project, etc but didn't have luck.

This is the error.

```<code>cd /Users/fmartin91/Projects/loovin/loovin-ios
setenv IBSC_MINIMUM_COMPATIBILITY_VERSION 7.0
setenv PATH "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
setenv XCODE_DEVELOPER_USR_PATH /Applications/Xcode.app/Contents/Developer/usr/bin/..
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/ibtool --errors --warnings --notices --minimum-deployment-target 7.0 --output-format human-readable-text --compile /Users/fmartin91/Projects/loovin/loovin-ios/Build/Products/Debug-iphonesimulator/loovin.app/Base.lproj/LOOVProductIndex.storyboardc /Users/fmartin91/Projects/Base.lproj/LOOVProductIndex.storyboard

/* com.apple.ibtool.errors */
/Users/fmartin91/Projects/Base.lproj/LOOVProductIndex.storyboard:
error: Interface Builder could not open the document
"LOOVProductIndex.storyboard" because it does not exist.
</code>```

答: For me resetting the container folder of Main.storyboard file worked

Body:
This problem is getting me really crazy. Xcode is looking for a storyboard in my project in a differente location from my project. I tryed removing the file, adding it again, cleaning the project, etc but didn't have luck.

This is the error.

cd /Users/fmartin91/Projects/loovin/loovin-ios
setenv IBSC_MINIMUM_COMPATIBILITY_VERSION 7.0
setenv PATH "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
setenv XCODE_DEVELOPER_USR_PATH /Applications/Xcode.app/Contents/Developer/usr/bin/..
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/ibtool --errors --warnings --notices --minimum-deployment-target 7.0 --output-format human-readable-text --compile /Users/fmartin91/Projects/loovin/loovin-ios/Build/Products/Debug-iphonesimulator/loovin.app/Base.lproj/LOOVProductIndex.storyboardc /Users/fmartin91/Projects/Base.lproj/LOOVProductIndex.storyboard

/* com.apple.ibtool.errors */
/Users/fmartin91/Projects/Base.lproj/LOOVProductIndex.storyboard:
error: Interface Builder could not open the document
"LOOVProductIndex.storyboard" because it does not exist.


问:
Problem in c# windows service using linq
I am having a bit of a problem in a windows service I have developed, I seem to be having a DB conflict using linq, I think i understand why the problem is happening but would like to get some advice in resolving it.

I have a database with a table that holds messages that need to be sent every at certain intervals from the service here is my code snippet.

```<code>protected override void OnStart(string[] args)
    {
        timer = new Timer(10000);
        timer.Elapsed += new ElapsedEventHandler(TimeElapsed);
        timer.Interval = 10000;
        timer.Start();
        EventLogger.LogEvent("Timer started succesfuly", EventLogEntryType.Information);

    }

    protected override void OnStop()
    {
        if (timer != null)
            timer.Stop();
        EventLogger.LogEvent("Timer stopped.", EventLogEntryType.Information);
    }

    private void TimeElapsed(object source, ElapsedEventArgs e)
    {
        try
        {
            EventLogger.LogEvent("Checking for reversals", EventLogEntryType.Information);
            //We now need to check for reversals that are waiting to be sent
            ReversalsDataContext db = new ReversalsDataContext();
            var reversals = db.FiReversals.Where(r => r.Status == Reversal.ReversalStatus.WAITING_TO_SEND);

            if (reversals.Any())
            {
                EventLogger.LogEvent(reversals.Count() + " reversals found and being processed.", EventLogEntryType.Information);
                //Mark the reversal
                foreach (var rev in reversals)
                {
                    MarkReversal(rev);
                }
                db.SubmitChanges();

                //We now need to send the reversal
                foreach (var rev in reversals)
                {
                    SendReversal(rev);
                }
                db.SubmitChanges();
                EventLogger.LogEvent("Finished processing reversal queue", EventLogEntryType.Information);
            }
        }
        catch (Exception ex)
        {
            EventLogger.LogEvent(ex.Message + "\n" + ex.StackTrace, EventLogEntryType.Error);
        }
    }
</code>```

The error I get now is

Row not found or changed.
   at System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode)
   at System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode)
   at System.Data.Linq.DataContext.SubmitChanges()
   at EftcObReversalService.EftcObReversalService.TimeElapsed(Object source, ElapsedEventArgs e)

From what I can see is this is caused from the following code,

```<code>if (reversals.Any())
            {
                EventLogger.LogEvent(reversals.Count() + " reversals found and being processed.", EventLogEntryType.Information);
                //Mark the reversal
                foreach (var rev in reversals)
                {
                    MarkReversal(rev);
                }
                db.SubmitChanges();

                //We now need to send the reversal
                foreach (var rev in reversals)
                {
                    SendReversal(rev);
                }
                db.SubmitChanges();
                EventLogger.LogEvent("Finished processing reversal queue", EventLogEntryType.Information);
            }
</code>```

What happens here is, I read in from the table what is marked with a "WAITING_TO_SEND", once I have that I decide to mark the entries with a "PENDING" status. I do this as i do not want the entries to be read in again when the timer swings through and this thread has not completed yet.

Once I have marked all the entires I then handle each one in the SendReversal method, where I also mark the status as "COMPLETED" when it was completed OK or change the status back to "WAITING_TO_SEND".

I think this error is being cause from the 2 db.SubmitChanges, as the entry has changes and been written by the first submit and is different from the second submit?

If anyone has any thoughts or solutions please let me know.

答:
I was about to suggest that the simplest solution would be to requery for "pending"... but of course that doesn't actually solve the problem if the process is going to overrun.

There are a couple of options that I can see quickly:

Change the logic so that you can only run one instance of the processing loop at a time - basically if you're already processing you can't start so skip or reschedule.

In addition to changing the state you also need to add a batch number so that you can requery after the first save but restrict that query to items pending for a particular batch number - I've done this in the past and had it work reasonably well providing the error handling was smart enough to be able to tidy up afterward if something went strange.

ContentLicense: CC BY-SA 2.5

Body:
I am having a bit of a problem in a windows service I have developed, I seem to be having a DB conflict using linq, I think i understand why the problem is happening but would like to get some advice in resolving it.

I have a database with a table that holds messages that need to be sent every at certain intervals from the service here is my code snippet.

protected override void OnStart(string[] args)
    {
        timer = new Timer(10000);
        timer.Elapsed += new ElapsedEventHandler(TimeElapsed);
        timer.Interval = 10000;
        timer.Start();
        EventLogger.LogEvent("Timer started succesfuly", EventLogEntryType.Information);

    }

    protected override void OnStop()
    {
        if (timer != null)
            timer.Stop();
        EventLogger.LogEvent("Timer stopped.", EventLogEntryType.Information);
    }

    private void TimeElapsed(object source, ElapsedEventArgs e)
    {
        try
        {
            EventLogger.LogEvent("Checking for reversals", EventLogEntryType.Information);
            //We now need to check for reversals that are waiting to be sent
            ReversalsDataContext db = new ReversalsDataContext();
            var reversals = db.FiReversals.Where(r => r.Status == Reversal.ReversalStatus.WAITING_TO_SEND);

            if (reversals.Any())
            {
                EventLogger.LogEvent(reversals.Count() + " reversals found and being processed.", EventLogEntryType.Information);
                //Mark the reversal
                foreach (var rev in reversals)
                {
                    MarkReversal(rev);
                }
                db.SubmitChanges();

                //We now need to send the reversal
                foreach (var rev in reversals)
                {
                    SendReversal(rev);
                }
                db.SubmitChanges();
                EventLogger.LogEvent("Finished processing reversal queue", EventLogEntryType.Information);
            }
        }
        catch (Exception ex)
        {
            EventLogger.LogEvent(ex.Message + "\n" + ex.StackTrace, EventLogEntryType.Error);
        }
    }

The error I get now is

Row not found or changed.
   at System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode)
   at System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode)
   at System.Data.Linq.DataContext.SubmitChanges()
   at EftcObReversalService.EftcObReversalService.TimeElapsed(Object source, ElapsedEventArgs e)

From what I can see is this is caused from the following code,

if (reversals.Any())
            {
                EventLogger.LogEvent(reversals.Count() + " reversals found and being processed.", EventLogEntryType.Information);
                //Mark the reversal
                foreach (var rev in reversals)
                {
                    MarkReversal(rev);
                }
                db.SubmitChanges();

                //We now need to send the reversal
                foreach (var rev in reversals)
                {
                    SendReversal(rev);
                }
                db.SubmitChanges();
                EventLogger.LogEvent("Finished processing reversal queue", EventLogEntryType.Information);
            }

What happens here is, I read in from the table what is marked with a "WAITING_TO_SEND", once I have that I decide to mark the entries with a "PENDING" status. I do this as i do not want the entries to be read in again when the timer swings through and this thread has not completed yet.

Once I have marked all the entires I then handle each one in the SendReversal method, where I also mark the status as "COMPLETED" when it was completed OK or change the status back to "WAITING_TO_SEND".

I think this error is being cause from the 2 db.SubmitChanges, as the entry has changes and been written by the first submit and is different from the second submit?

If anyone has any thoughts or solutions please let me know.


问:
Failed to resolve RecyclerView version 24.2.1
I tried to compile with the RecyclerView version 24.2.1, but I get always the build.gradle error Failed to resolve: com.android.support:RecyclerView- ....
I also tried differnt versions but always with the same failure.

My build.gradle has the following form:

```<code>android {
  compileSdkVersion 24
  buildToolsVersion "24.0.1"
  .....
dependencies {
  compile fileTree(dir: 'libs', include: ['*.jar'])
  androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
  })
  compile 'com.android.support:appcompat-v7:24.2.1'
  compile 'com.android.support:design:24.2.1'
  compile 'com.android.support:cardview-v7:24.2.1'
  compile 'com.android.support:RecyclerView-v7:24.2.1'
  compile 'org.greenrobot:eventbus:3.0.0'
  compile 'org.nanohttpd:nanohttpd:2.2.0'
  testCompile 'junit:junit:4.12'
}
</code>```

Through SDK-Manager I installed:

Android SDK Tool 25.2.5

Android SDK Platform-tools 25.0.3

Android SDK Build-tools 24.0.1

API 25

API 24

Android Support Repository Rev 42

Google Repository Rev 42

How can I fix this failure?
Thanks in advance

答:
public function user_login_process() {</p>

```<code>    $this->form_validation->set_rules('username', 'Username', 'trim|required');
    $this->form_validation->set_rules('password', 'Password', 'trim|required');

    if ($this->form_validation->run() == FALSE)
    {
        if(isset($this->session->userdata['logged_in']))
        {
            $this->load->view('includes/header');
            $this->load->view('home/home_view');
            $this->load->view('includes/footer');
        }
        else{
            $this->load->view('includes/header');
            $this->load->view('account/login_view');
            $this->load->view('includes/footer');
        }
    }
    else
    {
        $data = array(
                        'username' => $this->input->post('username'),
                        'password' => $this->input->post('password')
                                );

        $result_is_staff = $this->login_database->login_staff($data);
        $result_is_knowledge_seeker = $this->login_database->login_know_seeker($data);

        if ($result_is_knowledge_seeker == TRUE)
        {
            $username = $this->input->post('username');

            $result = $this->login_database->read_knowledgeseeker_information($username);

            if ($result != false)
            {
                $session_data = array(
                                'username' => $result[0]->username
                                );

                // Add user data in session
                $this->session->set_userdata('logged_in', $session_data);

                $this->load->view('includes/header');
                $this->load->view('home/home_view');
                $this->load->view('includes/footer');
                //$this->load->view('admin_page');
            }
        }
        elseif($result_is_staff == TRUE)
        {
            $username = $this->input->post('username');

            $result = $this->login_database->read_staff_information($username);

            if ($result != false)
            {
                $session_data = array(
                                'username' => $result[0]->username
                                );

                // Add user data in session
                $this->session->set_userdata('logged_in', $session_data);

                $this->load->view('includes/header');
                $this->load->view('admin/admin_view');
                $this->load->view('includes/footer');
                //$this->load->view('admin_page');
            }
        }
        else
        {
            $data =array(
                        'error_message' => 'Invalid Username or Password'
                        );

            //$this->load->view('login_form', $data);

            $this->load->view('includes/header');
            $this->load->view('account/login_view',$data);
            $this->load->view('includes/footer');
        }
    }
}
</code>```

Body:
I tried to compile with the RecyclerView version 24.2.1, but I get always the build.gradle error Failed to resolve: com.android.support:RecyclerView- ....
I also tried differnt versions but always with the same failure.

My build.gradle has the following form:

android {
  compileSdkVersion 24
  buildToolsVersion "24.0.1"
  .....
dependencies {
  compile fileTree(dir: 'libs', include: ['*.jar'])
  androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
  })
  compile 'com.android.support:appcompat-v7:24.2.1'
  compile 'com.android.support:design:24.2.1'
  compile 'com.android.support:cardview-v7:24.2.1'
  compile 'com.android.support:RecyclerView-v7:24.2.1'
  compile 'org.greenrobot:eventbus:3.0.0'
  compile 'org.nanohttpd:nanohttpd:2.2.0'
  testCompile 'junit:junit:4.12'
}

Through SDK-Manager I installed:

Android SDK Tool 25.2.5

Android SDK Platform-tools 25.0.3

Android SDK Build-tools 24.0.1

API 25

API 24

Android Support Repository Rev 42

Google Repository Rev 42

How can I fix this failure?
Thanks in advance

Body:
public function user_login_process() {

    $this->form_validation->set_rules('username', 'Username', 'trim|required');
    $this->form_validation->set_rules('password', 'Password', 'trim|required');

    if ($this->form_validation->run() == FALSE)
    {
        if(isset($this->session->userdata['logged_in']))
        {
            $this->load->view('includes/header');
            $this->load->view('home/home_view');
            $this->load->view('includes/footer');
        }
        else{
            $this->load->view('includes/header');
            $this->load->view('account/login_view');
            $this->load->view('includes/footer');
        }
    }
    else
    {
        $data = array(
                        'username' => $this->input->post('username'),
                        'password' => $this->input->post('password')
                                );

        $result_is_staff = $this->login_database->login_staff($data);
        $result_is_knowledge_seeker = $this->login_database->login_know_seeker($data);

        if ($result_is_knowledge_seeker == TRUE)
        {
            $username = $this->input->post('username');

            $result = $this->login_database->read_knowledgeseeker_information($username);

            if ($result != false)
            {
                $session_data = array(
                                'username' => $result[0]->username
                                );

                // Add user data in session
                $this->session->set_userdata('logged_in', $session_data);

                $this->load->view('includes/header');
                $this->load->view('home/home_view');
                $this->load->view('includes/footer');
                //$this->load->view('admin_page');
            }
        }
        elseif($result_is_staff == TRUE)
        {
            $username = $this->input->post('username');

            $result = $this->login_database->read_staff_information($username);

            if ($result != false)
            {
                $session_data = array(
                                'username' => $result[0]->username
                                );

                // Add user data in session
                $this->session->set_userdata('logged_in', $session_data);

                $this->load->view('includes/header');
                $this->load->view('admin/admin_view');
                $this->load->view('includes/footer');
                //$this->load->view('admin_page');
            }
        }
        else
        {
            $data =array(
                        'error_message' => 'Invalid Username or Password'
                        );

            //$this->load->view('login_form', $data);

            $this->load->view('includes/header');
            $this->load->view('account/login_view',$data);
            $this->load->view('includes/footer');
        }
    }
}


问:
Attempting to capture multiple groups but only the last group is captured
I am trying to use regex to help to convert the following string into a Dictionary:

```<code>{TheKey|TheValue}{AnotherKey|AnotherValue}
</code>```

Like such:

```<code>["TheKey"] = "TheValue"
["AnotherKey"] = "AnotherValue"
</code>```

To parse the string for the dictionary, I am using the regex expression:

```<code> ^(\{(.+?)\|(.+?)\})*?$
</code>```

But it will only capture the last group of {AnotherKey|AnotherValue}.

How do I get it to capture all of the groups?

I am using C#.

Alternatively, is there a more straightforward way to approach this rather than using Regex?

Code (Properties["PromptedValues"] contains the string to be parsed):

```<code>var regex = Regex.Matches(Properties["PromptedValues"], @"^(\{(.+?)\|(.+?)\})*?$");

foreach(Match match in regex) {

    if(match.Groups.Count == 4) {

        var key = match.Groups[2].Value.ToLower();
        var value = match.Groups[3].Value;

        values.Add(key, new StringPromptedFieldHandler(key, value));
     }

}
</code>```

This is coded to work for the single value, I would be looking to update it once I can get it to capture multiple values.

答:
The $ says that: The match must occur at the end of the string or before \n at the end of the line or string.

The ^ says that: The match must start at the beginning of the string or line.

Read this for more regex syntax: msdn RegEx

Once you remove the ^ and $ your regex will match all of the sets You should read: Match.Groups and get something like the following:

```<code>public class Example
{
   public static void Main()
   {
      string pattern = @"\{(.+?)\|(.+?)\}";
      string input = "{TheKey|TheValue}{AnotherKey|AnotherValue}";
      MatchCollection matches = Regex.Matches(input, pattern);

      foreach (Match match in matches)
      {
         Console.WriteLine("The Key: {0}", match.Groups[1].Value);
         Console.WriteLine("The Value: {0}", match.Groups[2].Value);
         Console.WriteLine();
      }
      Console.WriteLine();
   }
}
</code>```

Body:
I am trying to use regex to help to convert the following string into a Dictionary:

{TheKey|TheValue}{AnotherKey|AnotherValue}

Like such:

["TheKey"] = "TheValue"
["AnotherKey"] = "AnotherValue"

To parse the string for the dictionary, I am using the regex expression:

 ^(\{(.+?)\|(.+?)\})*?$

But it will only capture the last group of {AnotherKey|AnotherValue}.

How do I get it to capture all of the groups?

I am using C#.

Alternatively, is there a more straightforward way to approach this rather than using Regex?

Code (Properties["PromptedValues"] contains the string to be parsed):

var regex = Regex.Matches(Properties["PromptedValues"], @"^(\{(.+?)\|(.+?)\})*?$");

foreach(Match match in regex) {

    if(match.Groups.Count == 4) {

        var key = match.Groups[2].Value.ToLower();
        var value = match.Groups[3].Value;

        values.Add(key, new StringPromptedFieldHandler(key, value));
     }

}

This is coded to work for the single value, I would be looking to update it once I can get it to capture multiple values.

Body:
The $ says that: The match must occur at the end of the string or before \n at the end of the line or string.

The ^ says that: The match must start at the beginning of the string or line.

Read this for more regex syntax: msdn RegEx

Once you remove the ^ and $ your regex will match all of the sets You should read: Match.Groups and get something like the following:

public class Example
{
   public static void Main()
   {
      string pattern = @"\{(.+?)\|(.+?)\}";
      string input = "{TheKey|TheValue}{AnotherKey|AnotherValue}";
      MatchCollection matches = Regex.Matches(input, pattern);

      foreach (Match match in matches)
      {
         Console.WriteLine("The Key: {0}", match.Groups[1].Value);
         Console.WriteLine("The Value: {0}", match.Groups[2].Value);
         Console.WriteLine();
      }
      Console.WriteLine();
   }
}


问:
browser errors (firefox) Asp.net webforms
Firefox gives me error

```<code>     XML Parsing Error: no root element found
</code>```

Location: http://localhost:1126/5cebf834d54b41f1b944492c2bf2c852/arterySignalR/send?transport=longPolling&connectionToken=AQAAANCMnd8BFdERjHoAwE%2FCl%2BsBAAAASoOM%2FXZ%2B1UWqyQ%2FYXO2FqQAAAAACAAAAAAAQZgAAAAEAACAAAAAUFu%2Fjd8uVno2WCgoC%2BqL%2FTyk4%2F9G0tGOhVKr4EpHnIwAAAAAOgAAAAAIAACAAAACfousertSIl6j8HdDRfemeNPHDjgXABbFasP4BpsaBRjAAAADqZuISuyN4C6Z1BUb4BSojyAs0sj5vyMKuBZrkMzPz6r4vFC13EdNhT0%2BqeNlqyfpAAAAAs2SeXXAfiPKVMcCDkZ%2B3%2Fnii%2BKaLZxyKMLgriAsGDqANLiRjEVgu6ErSX%2F1ZCiiuOW02QGy5aZWT5E4Vm8IMqQ%3D%3D&requestUrl=http%3A%2F%2Flocalhost%3A4055%2FPages%2FSignIn.aspx&browserName=Firefox
Line Number 1, Column 1:

I double checked all tags starts and ends with no help :( any suggestions??

edit: Here is my sample code

```<code><%@ Page Title="" Language="C#" MasterPageFile="~/Pages/gateMasterPage.Master" AutoEventWireup="true" CodeBehind="SignIn.aspx.cs" Inherits="Gate.SignIn" %>
</code>```

```<code><div class="login" id="loginDiv">
    <style scoped="scoped" >
        @import "../css/custom.min.css";
    </style>

  <a class="hiddenanchor" id="signup"></a>
  <a class="hiddenanchor" id="signin"></a>

  <div class="login_wrapper">
    <div class="animate form login_form">
      <section class="login_content">
          <form runat="server" id="signinForm">
              <asp:ScriptManager ID="ScriptManager1" runat="server"
                  EnablePageMethods="True">
              </asp:ScriptManager>
              <h1>تسجيل الدخول</h1>
              <div>
                  <input type="text" class="form-control" placeholder="إسم المستخدم" name="nameTXTBOX" id="usernameTXT" required="required" dir="rtl" />
              </div>
              <div>
                  <input type="password" class="form-control" placeholder="كلمة المرور" name="passTXTBOX" id="passTXT" required="required" dir="rtl" />
              </div>
              <div>
                  <%--<asp:Button  class="btn btn-default submit" text="دخول" runat="server"></asp:Button>--%>
                  <a class="btn btn-default submit" id="signIn">دخول</a>
                  <a class="reset_pass" href="#">فقدت كلمة المرور؟</a>
              </div>

              <div class="clearfix"></div>

              <div class="separator">
                  <p class="change_link">
                      جديد بالموقع؟
              <a href="#signup" class="to_register">إنشاء حساب جديد </a>
                  </p></div>
          </form>
      </section>
    </div>

    <div id="register" class="animate form registration_form">
      <section class="login_content">
        <form id="signupForm" class="col-md-offset-4 form-group ">
          <h1>إنشاء حساب</h1>
          <div>
            <input type="text" class="form-control" placeholder="اسم المستخدم" required="" dir="rtl" />
          </div>
          <div>
            <input type="email" class="form-control" placeholder="البريد الالكتروني" required="" dir="rtl" />
          </div>
          <div>
            <input type="password" class="form-control" placeholder="كلمة المرور" required="" dir="rtl"/>
          </div>
          <div>
            <a class="btn btn-default submit" href="index.html">انشاء الحساب</a>
          </div>

          <div class="clearfix"></div>

          <div class="separator">
            <p class="change_link">مسجل بالفعل
              <a href="#signin" class="to_register"> تسجيل الدخول </a>
            </p>
              </div>

        </form>
      </section>
    </div>
  </div>
</div>
</code>```

      $(function () {

```<code>      $("#signIn").click(function () {

          var name = $("#usernameTXT").val();
          var pass = $("#passTXT").val();
          console.log(name + ":" + pass);
          PageMethods.login_btn_click(name, pass, onSucceed, onError);

      });

      function onSucceed(res) {

          console.log(res);
          //$("#loginDiv").load("Profile.aspx?id=" + res);
          console.log('success');
          window.location.href = "Profile.aspx?id=" + res;
          alert(res);
      }
      function onError(err) {
          alert('fail');
          console.log("login_btn_click PageMethod Throw Error" + err);
      }
  });//End of OnLoad
</code>```

Is There is any way to regenerate page, if there is any missing tag end that i couldn't notice?

答:
your XMl need to well form, all xml document must have one root element for example</p>

```<code><persons>
   <person Id=1>
      <name>Smith</name>
   </person>
   <person Id=2>
      <name>Jack</name>
   </person>
</persons>
</code>```

Body:
Firefox gives me error

     XML Parsing Error: no root element found

Location: <a href="http://localhost:1126/5cebf834d54b41f1b944492c2bf2c852/arterySignalR/send?transport=longPolling&connectionToken=AQAAANCMnd8BFdERjHoAwE%2FCl%2BsBAAAASoOM%2FXZ%2B1UWqyQ%2FYXO2FqQAAAAACAAAAAAAQZgAAAAEAACAAAAAUFu%2Fjd8uVno2WCgoC%2BqL%2FTyk4%2F9G0tGOhVKr4EpHnIwAAAAAOgAAAAAIAACAAAACfousertSIl6j8HdDRfemeNPHDjgXABbFasP4BpsaBRjAAAADqZuISuyN4C6Z1BUb4BSojyAs0sj5vyMKuBZrkMzPz6r4vFC13EdNhT0%2BqeNlqyfpAAAAAs2SeXXAfiPKVMcCDkZ%2B3%2Fnii%2BKaLZxyKMLgriAsGDqANLiRjEVgu6ErSX%2F1ZCiiuOW02QGy5aZWT5E4Vm8IMqQ%3D%3D&requestUrl=http%3A%2F%2Flocalhost%3A4055%2FPages%2FSignIn.aspx&browserName=Firefox" rel="nofollow noreferrer">http://localhost:1126/5cebf834d54b41f1b944492c2bf2c852/arterySignalR/send?transport=longPolling&connectionToken=AQAAANCMnd8BFdERjHoAwE%2FCl%2BsBAAAASoOM%2FXZ%2B1UWqyQ%2FYXO2FqQAAAAACAAAAAAAQZgAAAAEAACAAAAAUFu%2Fjd8uVno2WCgoC%2BqL%2FTyk4%2F9G0tGOhVKr4EpHnIwAAAAAOgAAAAAIAACAAAACfousertSIl6j8HdDRfemeNPHDjgXABbFasP4BpsaBRjAAAADqZuISuyN4C6Z1BUb4BSojyAs0sj5vyMKuBZrkMzPz6r4vFC13EdNhT0%2BqeNlqyfpAAAAAs2SeXXAfiPKVMcCDkZ%2B3%2Fnii%2BKaLZxyKMLgriAsGDqANLiRjEVgu6ErSX%2F1ZCiiuOW02QGy5aZWT5E4Vm8IMqQ%3D%3D&requestUrl=http%3A%2F%2Flocalhost%3A4055%2FPages%2FSignIn.aspx&browserName=Firefox
Line Number 1, Column 1:

I double checked all tags starts and ends with no help :( any suggestions??

edit: Here is my sample code

<%@ Page Title="" Language="C#" MasterPageFile="~/Pages/gateMasterPage.Master" AutoEventWireup="true" CodeBehind="SignIn.aspx.cs" Inherits="Gate.SignIn" %>

          <form runat="server" id="signinForm">
              <asp:ScriptManager ID="ScriptManager1" runat="server"
                  EnablePageMethods="True">
              </asp:ScriptManager>

تسجيل الدخول

                  <input type="text" class="form-control" placeholder="إسم المستخدم" name="nameTXTBOX" id="usernameTXT" required="required" dir="rtl" />

                  <input type="password" class="form-control" placeholder="كلمة المرور" name="passTXTBOX" id="passTXT" required="required" dir="rtl" />

                  <%--<asp:Button  class="btn btn-default submit" text="دخول" runat="server"></asp:Button>--%>
                  دخول
                  فقدت كلمة المرور؟

                      جديد بالموقع؟
              إنشاء حساب جديد

          </form>

        <form id="signupForm" class="col-md-offset-4 form-group ">

إنشاء حساب

            <input type="text" class="form-control" placeholder="اسم المستخدم" required="" dir="rtl" />

            <input type="email" class="form-control" placeholder="البريد الالكتروني" required="" dir="rtl" />

            <input type="password" class="form-control" placeholder="كلمة المرور" required="" dir="rtl"/>

            انشاء الحساب

مسجل بالفعل
               تسجيل الدخول

        </form>

      $(function () {

      $("#signIn").click(function () {

          var name = $("#usernameTXT").val();
          var pass = $("#passTXT").val();
          console.log(name + ":" + pass);
          PageMethods.login_btn_click(name, pass, onSucceed, onError);

      });

      function onSucceed(res) {

          console.log(res);
          //$("#loginDiv").load("Profile.aspx?id=" + res);
          console.log('success');
          window.location.href = "Profile.aspx?id=" + res;
          alert(res);
      }
      function onError(err) {
          alert('fail');
          console.log("login_btn_click PageMethod Throw Error" + err);
      }
  });//End of OnLoad

Is There is any way to regenerate page, if there is any missing tag end that i couldn't notice?

Body:
your XMl need to well form, all xml document must have one root element for example

<persons>
   <person Id=1>
      <name>Smith</name>
   </person>
   <person Id=2>
      <name>Jack</name>
   </person>
</persons>


问:
bat file to delete files using path from argument
I have been trying to get this stupid BAT file to run and am having issues: I want to pass it a path to a directory and delete everything (folders/files) in it. However the bat file just deletes everything where it is currently located. I believe the issue is in the parameter not getting set but I don't understand where I am going wrong.

Command:

```<code>delete.bat "C:\deleteme\"
</code>```

Tried setting parameter these ways:

```<code>SET deletePath = %~1
SET deletePath = "%~1"
SET deletePath = %1
SET deletePath = "%1"
</code>```

Echoing the parameter never prints the value passed.

```<code>if "%~1"=="" goto BLANK
if NOT "%~1"=="" goto DELETE

:BLANK
ECHO Need delete path passed as parameter
TIMEOUT 10
END
Exit

:DELETE
SET deletePath = %~1
echo %deletePath%
pause
del %deletePath%. /F /Q
rmdir /s .q %deletePath%
END
exit
</code>```

答:
Batch is sensitive to spaces in a SET statement. SET FLAG = N sets a variable named "FLAGSpace" to a value of "SpaceN"

So - remove the errant spaces

Body:
I have been trying to get this stupid BAT file to run and am having issues: I want to pass it a path to a directory and delete everything (folders/files) in it. However the bat file just deletes everything where it is currently located. I believe the issue is in the parameter not getting set but I don't understand where I am going wrong.

Command:

delete.bat "C:\deleteme\"

Tried setting parameter these ways:

SET deletePath = %~1
SET deletePath = "%~1"
SET deletePath = %1
SET deletePath = "%1"

Echoing the parameter never prints the value passed.

if "%~1"=="" goto BLANK
if NOT "%~1"=="" goto DELETE

:BLANK
ECHO Need delete path passed as parameter
TIMEOUT 10
END
Exit

:DELETE
SET deletePath = %~1
echo %deletePath%
pause
del %deletePath%. /F /Q
rmdir /s .q %deletePath%
END
exit


问:
MQTT subscription gets lost in Bluemix container
I am using the Bluemix IoT service. My program consists of the following elements:

Publisher (Local Machine)

Subscribed (Bluemix)

Publisher (Bluemix)

Subscriber (Local Machine)

I am currently following the steps
Publisher (local machine) > Subscriber (Bluemix) > Publisher (Bluemix) > Subscriber (local machine)

The issue I am facing is the moment I try to use both the subscribers together the service unsubscribes from both the ends. If I keep only subscriber the steps work perfect. The topics I am using are as follows:

topic = "iot-2/type/mymqttdevice/id/mynewdev/evt/iotData/fmt/json"

topic2 = "iot-2/type/mymqttdevice/id/mynewdev/evt/iotFile/fmt/json"

Can someone guide what am I doing wrong here?

EDIT: Adding code

Publisher on local machine is a python file consisting of typical connect and publish method. After each publish I disconnect from the IoT service.

Subscriber code on Bluemix:

```<code># -*- coding: utf-8 -*-

#!/usr/bin/env python

import paho.mqtt.client as mqtt
import os, json
import time

organization = "xel7"
username = ""
password = ""

#Set the variables for connecting to the iot service
broker = ""
devicename = "mynewdev"
topic = "iot-2/type/mymqttdevice/id/mynewdev/evt/iotData/fmt/json"

deviceType = "mymqttdevice"

topic2 = "iot-2/type/mymqttdevice/id/mynewdev/evt/iotFile/fmt/json"

clientID = "a:" + organization + ":appId"

broker = organization + ".messaging.internetofthings.ibmcloud.com"
mqttc = mqtt.Client(clientID)

if username is not "":
 mqttc.username_pw_set(username, password=password)

def on_connect(client, userdata, flags, rc):
 print("Connected with result code "+str(rc))

def on_subscribe(mosq, obj, mid, granted_qos):
 print("Subscribed: " + str(mid) + " " + str(granted_qos))

def on_message(client, userdata, msg):
    with open('indurator.txt', 'w') as fd:
     txt = (msg.payload.decode('string_escape'))
     fd.write(txt)
     #print txt
     fd.close()
     mqttc.publish(topic2,msg.payload);

mqttc.connect(host=broker, port=1883, keepalive=60)
test = mqttc.subscribe(topic,0)

mqttc.on_connect = on_connect
mqttc.on_subscribe = on_subscribe
mqttc.on_message = on_message

mqttc.loop_forever()
</code>```

Subscriber code on local machine to receive file published from Bluemix subscriber:

-- coding: utf-8 --

```<code>#!/usr/bin/env python

import paho.mqtt.client as mqtt
import os, json
import time

organization = "xel7"
username = ""
password = ""

#Set the variables for connecting to the iot service
broker = ""
devicename = "mynewdev"

deviceType = "mymqttdevice"

topic = "iot-2/type/mymqttdevice/id/mynewdev/evt/iotFile/fmt/json"

clientID = "a:" + organization + ":appId"

broker = organization + ".messaging.internetofthings.ibmcloud.com"
mqttc = mqtt.Client(clientID)

if username is not "":
 mqttc.username_pw_set(username, password=password)

def on_connect(client, userdata, flags, rc):
 print("Connected with result code "+str(rc))

def on_subscribe(mosq, obj, mid, granted_qos):
 print("Subscribed: " + str(mid) + " " + str(granted_qos))

def on_message(client, userdata, msg):
    with open('receivednew.txt', 'w') as fd:
     txt = (msg.payload.decode('string_escape'))
     fd.write(txt)
     #print txt
     fd.close()

mqttc.connect(host=broker, port=1883, keepalive=60)
test = mqttc.subscribe(topic,0)

mqttc.on_connect = on_connect
mqttc.on_subscribe = on_subscribe
mqttc.on_message = on_message

mqttc.loop_forever()
</code>```

答:
Glad you figured out the solution.  To summarize as hardillb and amadain mentioned,  the same client ID should not be used simultaneously per the Watson IoT Platform documentation.

If a client ID is being re-used, when you attempt to connect to the IoT platform, your device or application receives an error. This may indicate your disconnects are due to the clientID being re-used or “stolen”.

If you have two devices connecting with the same clientId and credentials – that leads to the clientId stealing. Only one unique connection is allowed per clientID; you can not have two concurrent connections using the same ID.
If 2 clients attempt to connect to IoT at the same time using the same client ID, a connection error occurs

Body:
I am using the Bluemix IoT service. My program consists of the following elements:

Publisher (Local Machine)

Subscribed (Bluemix)

Publisher (Bluemix)

Subscriber (Local Machine)

I am currently following the steps
Publisher (local machine) > Subscriber (Bluemix) > Publisher (Bluemix) > Subscriber (local machine)

The issue I am facing is the moment I try to use both the subscribers together the service unsubscribes from both the ends. If I keep only subscriber the steps work perfect. The topics I am using are as follows:

topic = "iot-2/type/mymqttdevice/id/mynewdev/evt/iotData/fmt/json"

topic2 = "iot-2/type/mymqttdevice/id/mynewdev/evt/iotFile/fmt/json"

Can someone guide what am I doing wrong here?

EDIT: Adding code

Publisher on local machine is a python file consisting of typical connect and publish method. After each publish I disconnect from the IoT service.

Subscriber code on Bluemix:

# -*- coding: utf-8 -*-

#!/usr/bin/env python

import paho.mqtt.client as mqtt
import os, json
import time

organization = "xel7"
username = ""
password = ""

#Set the variables for connecting to the iot service
broker = ""
devicename = "mynewdev"
topic = "iot-2/type/mymqttdevice/id/mynewdev/evt/iotData/fmt/json"

deviceType = "mymqttdevice"

topic2 = "iot-2/type/mymqttdevice/id/mynewdev/evt/iotFile/fmt/json"

clientID = "a:" + organization + ":appId"

broker = organization + ".messaging.internetofthings.ibmcloud.com"
mqttc = mqtt.Client(clientID)

if username is not "":
 mqttc.username_pw_set(username, password=password)

def on_connect(client, userdata, flags, rc):
 print("Connected with result code "+str(rc))

def on_subscribe(mosq, obj, mid, granted_qos):
 print("Subscribed: " + str(mid) + " " + str(granted_qos))

def on_message(client, userdata, msg):
    with open('indurator.txt', 'w') as fd:
     txt = (msg.payload.decode('string_escape'))
     fd.write(txt)
     #print txt
     fd.close()
     mqttc.publish(topic2,msg.payload);

mqttc.connect(host=broker, port=1883, keepalive=60)
test = mqttc.subscribe(topic,0)

mqttc.on_connect = on_connect
mqttc.on_subscribe = on_subscribe
mqttc.on_message = on_message

mqttc.loop_forever()

Subscriber code on local machine to receive file published from Bluemix subscriber:

-- coding: utf-8 --

#!/usr/bin/env python

import paho.mqtt.client as mqtt
import os, json
import time

organization = "xel7"
username = ""
password = ""

#Set the variables for connecting to the iot service
broker = ""
devicename = "mynewdev"

deviceType = "mymqttdevice"

topic = "iot-2/type/mymqttdevice/id/mynewdev/evt/iotFile/fmt/json"

clientID = "a:" + organization + ":appId"

broker = organization + ".messaging.internetofthings.ibmcloud.com"
mqttc = mqtt.Client(clientID)

if username is not "":
 mqttc.username_pw_set(username, password=password)

def on_connect(client, userdata, flags, rc):
 print("Connected with result code "+str(rc))

def on_subscribe(mosq, obj, mid, granted_qos):
 print("Subscribed: " + str(mid) + " " + str(granted_qos))

def on_message(client, userdata, msg):
    with open('receivednew.txt', 'w') as fd:
     txt = (msg.payload.decode('string_escape'))
     fd.write(txt)
     #print txt
     fd.close()

mqttc.connect(host=broker, port=1883, keepalive=60)
test = mqttc.subscribe(topic,0)

mqttc.on_connect = on_connect
mqttc.on_subscribe = on_subscribe
mqttc.on_message = on_message

mqttc.loop_forever()


问:
"System error 5 has occurred, access denied" when using NET TIME \\[REMOTE] /SET
Following on from this answer to my question, I'm getting access denied errors when trying to set time from one PC to another.

I can't find any references for this on StackOverflow, so I think it's a useful resource to have here.

What are the general troubleshooting steps for this problem? (And more specifically, in my case with two XP embedded in Workgroup mode)

答:
Found an excellent resource for debugging workgroup problems here, I'm copying some of that page here, but please follow the link to get the full details.

Check for a personal firewall problem. A misconfigured or
  malfunctioning personal firewall, on
  either computer, can block browser
  access. Do you have antivirus
  protection? Make sure that your
  antivirus is not part of a package
  that contains a personal firewall, and
  does not contain a component that acts
  as a firewall.

Look carefully for a hardware firewall, sitting inside your
  computer. The nVidia nForce is
  probably the first, but surely not the
  last, device of this type.

Some newer, WiFi routers, have a complete firewall between ALL client
  computers, connected wired or
  wireless. Look for an "Isolation Mode"
  setting, if no computers are visible
  to each other. Each vendor uses a
  different name for this feature, so
  read your user guide carefully, if you
  suspect that this is a problem.

Make sure that NetBIOS Over TCP is consistently set, in TCP/IP Properties
  for each computer in your network.

Does your LAN include any computers running Windows Vista? If so, be aware
  of the additional issues involved in
  Windows Vista and Windows Networking.

Do you have a share setup on each computer? With Windows XP / Vista,
  only computers with non-administrative
  shares (not ending in "$") will be
  visible in My Network Places (aka
  Network Neighborhood).

Make sure that all computers are in the same workgroup, if you expect to
  see them in the root of Network
  Neighborhood (My Network Places).

Check for several well known and lesser known registry settings, which
  will affect visibility of, and access
  to, your server.

Look at the content of the error message. Do you see either "error = 5"
  (aka "access denied"), or "error = 53"
  (aka "name not found")? Read the
  appropriate article, and follow the
  links.

Look again at the complete and exact text in any observed error
  messages. Some very obscure errors
  have very simple resolutions.

Run, and examine output from, "browstat status", "ipconfig /all",
  and "net config server" and "net
  config workstation", for each
  computer.

Post output from the above step for expert interpretation and advice.
  Include relevant background details in
  your post. When including diagnostic
  logs, such as "browstat status",
  "ipconfig /all", or background
  details, format them properly when you
  post them.


问:
What the following macro means in competitive programming?
I watched various tips to make my algorithm take less time on online judges. But I was stuck on the following code. </p>

```<code>#ifndef ONLINE_JUDGE
freopen(fi, "r", stdin);
freopen(fo, "w", stdout);
#else
// online submission
#endif
</code>```

答: This is not about algorithm time. freopen allows you to redirect standard streams to your files. Some online judges always use standard input/output streams. And you must read from stdin and write to stdout. This macro allows you to write code that will read/write from/to stdin/stdout, but locally it will use your custom files for input and output data.

Body:
I watched various tips to make my algorithm take less time on online judges. But I was stuck on the following code.

#ifndef ONLINE_JUDGE
freopen(fi, "r", stdin);
freopen(fo, "w", stdout);
#else
// online submission
#endif


问:
How do I put indexes and words together to make 1 final string/array? (Java)
Background to question

I have been working on developing code that is able to read a string, compress it an send it to a new file in a compressed form. (e.g. "hello, hello" -> "hello[0, 1]) and this works great at the moment. Here is the link for anyone who wants to use it: https://pastebin.com/v6YF34mU . The next stage is being able to re-create the file using the indexes and the words.

Question

I currently have got this code:

```<code>public static void main(String[] args) {
        // TODO code application logic here
        Pattern seaPattern = Pattern.compile("(.*?)\\[(.*?)\\],");
            String compressedSea = "see[2, 4, 5],sea[0, 1, 3],";
            Matcher seaMatcher = seaPattern.matcher(compressedSea);
            while (seaMatcher.find()) {
                String seaWords = seaMatcher.group(1);
                String[] seaIndexes = seaMatcher.group(2).split(", ");
                for (String str : seaIndexes) {
                    int seaIndex = Integer.parseInt(str);
                    System.out.print(seaIndex);
                    }
</code>```

In short. I reads the string and splits it up into to different arrays. One of the arrays contains the indexes and the other contains the words. The next stage is putting these together and creating 1 string that is able to be compressed. I am relatively new to Java so I am not completely sure how I would go about doing this.

If anyone has got any ideas on how to do this it would be much appreciated!

答:
I would suggest you to create a class for combining your word and indexes.

I have posted a suggestion below:

Updated answer after OP clarified what he wanted to output

```<code>public static void main(String[] args) throws FileNotFoundException {

        Map<Integer, String> wordMap = new HashMap<Integer, String>();

        Pattern seaPattern = Pattern.compile("(.*?)\\[(.*?)\\],");
        String compressedSea = "see[2, 4, 5],sea[0, 1, 3],";
        Matcher seaMatcher = seaPattern.matcher(compressedSea);
        while (seaMatcher.find()) {
            String word = seaMatcher.group(1);
            String[] seaIndexes= seaMatcher.group(2).split(", ");
            for(String s : seaIndexes){
                wordMap.put(Integer.valueOf(s), word);
            }
        }
//HashMap will printout ordered by the key value.
//This is because the key is an Integer
//The hashed key value is therefore the key value itself.
        System.out.println(wordMap);
    }
</code>```

Output

```<code>{0=sea, 1=sea, 2=see, 3=sea, 4=see, 5=see}
</code>```

Bonus

If you want to iterate though the HashMap, you can do the following:

```<code>Iterator it = wordMap.entrySet().iterator();
    while(it.hasNext()){
         Map.Entry pair = (Map.Entry)it.next();
         System.out.println(pair.getValue());
    }
</code>```

Output

```<code>sea
sea
see
sea
see
see
</code>```

Body:
Background to question

I have been working on developing code that is able to read a string, compress it an send it to a new file in a compressed form. (e.g. "hello, hello" -> "hello[0, 1]) and this works great at the moment. Here is the link for anyone who wants to use it: https://pastebin.com/v6YF34mU . The next stage is being able to re-create the file using the indexes and the words.

Question

I currently have got this code:

public static void main(String[] args) {
        // TODO code application logic here
        Pattern seaPattern = Pattern.compile("(.*?)\\[(.*?)\\],");
            String compressedSea = "see[2, 4, 5],sea[0, 1, 3],";
            Matcher seaMatcher = seaPattern.matcher(compressedSea);
            while (seaMatcher.find()) {
                String seaWords = seaMatcher.group(1);
                String[] seaIndexes = seaMatcher.group(2).split(", ");
                for (String str : seaIndexes) {
                    int seaIndex = Integer.parseInt(str);
                    System.out.print(seaIndex);
                    }

In short. I reads the string and splits it up into to different arrays. One of the arrays contains the indexes and the other contains the words. The next stage is putting these together and creating 1 string that is able to be compressed. I am relatively new to Java so I am not completely sure how I would go about doing this.

If anyone has got any ideas on how to do this it would be much appreciated!

Body:
I would suggest you to create a class for combining your word and indexes.

I have posted a suggestion below:

Updated answer after OP clarified what he wanted to output

public static void main(String[] args) throws FileNotFoundException {

        Map<Integer, String> wordMap = new HashMap<Integer, String>();

        Pattern seaPattern = Pattern.compile("(.*?)\\[(.*?)\\],");
        String compressedSea = "see[2, 4, 5],sea[0, 1, 3],";
        Matcher seaMatcher = seaPattern.matcher(compressedSea);
        while (seaMatcher.find()) {
            String word = seaMatcher.group(1);
            String[] seaIndexes= seaMatcher.group(2).split(", ");
            for(String s : seaIndexes){
                wordMap.put(Integer.valueOf(s), word);
            }
        }
//HashMap will printout ordered by the key value.
//This is because the key is an Integer
//The hashed key value is therefore the key value itself.
        System.out.println(wordMap);
    }

Output

{0=sea, 1=sea, 2=see, 3=sea, 4=see, 5=see}

Bonus

If you want to iterate though the HashMap, you can do the following:

Iterator it = wordMap.entrySet().iterator();
    while(it.hasNext()){
         Map.Entry pair = (Map.Entry)it.next();
         System.out.println(pair.getValue());
    }

Output

sea
sea
see
sea
see
see


问:
jquery get first text element attribute from selected dropdown
both simple and complicate question:
I have my dropdown item created programmatically from ajax request and that is ok. So i serve name and surname for convenient aestetic way, but i need to send an ajax post with only surname and value is needed for other purposes.

```<code>$('#dropDocente').append('<option value="'+value.idDocente+'"">' + value.surname   + ' ' + value.name  +'</option>');
</code>```

what i would achieve is:

```<code>var testd = $("#dropDocente option:selected").text();
console.log("Surname is : "+testd);
desired output == Surname is : Doe
</code>```

so, in other hand, i would like get only first element of text in selected dropbox.

I can help me to understand how to reach my goal?

答:
you can add value.surname as a data-surname data tag onto the option and then retrieve that value by selecting the option and using .data('surname'). you can do this for any other value you want to single out as well

$(document).ready(function() {
  var values = [
    { surname: "Doe", name: "John", idDocente: "some value here" },
    { surname: "Shmo", name: "John", idDocente: "some value here2" },
    { surname: "Little", name: "John", idDocente: "some value here3" },
  ];

  for (var i = 0; i < values.length; i++) {
  var value = values[i];
    $('#dropDocente').append('<option value="'+value.idDocente+
   '" data-surname="'+ value.surname +'">' + value.surname   + ' '
   + value.name  +'</option>');
  }

  // default first
  $('.results').text($("#dropDocente option:first").data('surname') + ', ' + $("#dropDocente option:first").val());

  // on change, get the surname
  $('#dropDocente').on('change', function() {
    $('.results').text($("#dropDocente option:selected").data('surname')+ ', ' + $("#dropDocente option:selected").val());
  });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dropDocente">
</select>
<br/><br/><br/>
<div class="results">
</div></code>```

Body:
both simple and complicate question:
I have my dropdown item created programmatically from ajax request and that is ok. So i serve name and surname for convenient aestetic way, but i need to send an ajax post with only surname and value is needed for other purposes.

$('#dropDocente').append('<option value="'+value.idDocente+'"">' + value.surname   + ' ' + value.name  +'</option>');

what i would achieve is:

var testd = $("#dropDocente option:selected").text();
console.log("Surname is : "+testd);
desired output == Surname is : Doe

so, in other hand, i would like get only first element of text in selected dropbox.

I can help me to understand how to reach my goal?

Body:
you can add value.surname as a data-surname data tag onto the option and then retrieve that value by selecting the option and using .data('surname'). you can do this for any other value you want to single out as well

$(document).ready(function() {
  var values = [
    { surname: "Doe", name: "John", idDocente: "some value here" },
    { surname: "Shmo", name: "John", idDocente: "some value here2" },
    { surname: "Little", name: "John", idDocente: "some value here3" },
  ];

  for (var i = 0; i < values.length; i++) {
  var value = values[i];
    $('#dropDocente').append('<option value="'+value.idDocente+
   '" data-surname="'+ value.surname +'">' + value.surname   + ' '
   + value.name  +'</option>');
  }

  // default first
  $('.results').text($("#dropDocente option:first").data('surname') + ', ' + $("#dropDocente option:first").val());

  // on change, get the surname
  $('#dropDocente').on('change', function() {
    $('.results').text($("#dropDocente option:selected").data('surname')+ ', ' + $("#dropDocente option:selected").val());
  });

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dropDocente">
</select>
<br/><br/><br/>
<div class="results">
</div>


问:
angular 2 routing url issue
this is my app.module.ts file.

```<code> imports: [
        UniversalModule, // Must be first import. This automatically imports BrowserModule, HttpModule, and JsonpModule too.
        RouterModule.forRoot([
            { path: '', redirectTo: 'home', pathMatch: 'full' },
            { path: 'subscriber', component: SubscriberComponent },
            { path: '**', redirectTo: 'home' }
        ]),
        //HttpModule
        FormsModule
    ]
</code>```

inside my subscriber component i am getting a parameter from url inside ngOnInit

```<code>ngOnInit() {

    let id = '';
    this.activatedRoute.params.subscribe((params: Params) => {
        id = params['id'];
        if (id != '') {
            this.viewData(id);
        }
        console.log(id);
    });
}
</code>```

which works fine but every time i use the url to get the param(xxx) e.g. http://localhost:60009/xxx
i am getting an error because the routing redirects to this url which obviously i dont have anythig linked. Any idea how to skip redirect from routing?

答:
If you are using route parameters, you'll need to specify them in your routing config.  You are trying to read parameter id, but id isn't specified in on the route in your config.  Try adding it to your config:

```<code>{ path: ':id', redirectTo: 'home', pathMatch: 'full' },
</code>```

EDIT

Angular has both router parameters and query parameters.  Route params are specified in the route config like so:

```<code>{ path: ':id', redirectTo: 'home', pathMatch: 'full' },
</code>```

You would access those in the component with:

```<code>this.route.params.subscribe(data => data['id']);
</code>```

Then you also have query params.  These are not specified in the route config.  They look like this in the url:  ?id=something  And you would access them in your component with:

```<code>this.route.queryParams.subscribe(queryParams =>  queryParams['id']);
</code>```

The main difference is whether you use params or queryParams on the activated route and whether or not the params are specified in the route config.

Title: angular 2 routing url issue

Body:
this is my app.module.ts file.

 imports: [
        UniversalModule, // Must be first import. This automatically imports BrowserModule, HttpModule, and JsonpModule too.
        RouterModule.forRoot([
            { path: '', redirectTo: 'home', pathMatch: 'full' },
            { path: 'subscriber', component: SubscriberComponent },
            { path: '**', redirectTo: 'home' }
        ]),
        //HttpModule
        FormsModule
    ]

inside my subscriber component i am getting a parameter from url inside ngOnInit

ngOnInit() {

    let id = '';
    this.activatedRoute.params.subscribe((params: Params) => {
        id = params['id'];
        if (id != '') {
            this.viewData(id);
        }
        console.log(id);
    });
}

which works fine but every time i use the url to get the param(xxx) e.g. http://localhost:60009/xxx
i am getting an error because the routing redirects to this url which obviously i dont have anythig linked. Any idea how to skip redirect from routing?

Body:
If you are using route parameters, you'll need to specify them in your routing config.  You are trying to read parameter id, but id isn't specified in on the route in your config.  Try adding it to your config:

{ path: ':id', redirectTo: 'home', pathMatch: 'full' },

EDIT

Angular has both router parameters and query parameters.  Route params are specified in the route config like so:

{ path: ':id', redirectTo: 'home', pathMatch: 'full' },

You would access those in the component with:

this.route.params.subscribe(data => data['id']);

Then you also have query params.  These are not specified in the route config.  They look like this in the url:  ?id=something  And you would access them in your component with:

this.route.queryParams.subscribe(queryParams =>  queryParams['id']);

The main difference is whether you use params or queryParams on the activated route and whether or not the params are specified in the route config.


问:
Using Flexbox, how do I programmatically move a div?
I have a div within a flex container. I need to programmatically position - change top and left - and size - change width and height this div. How do I do this. Flex ignores changes to top and left but does seem to accept changes to width and height.

答: I actually found the answer. Set the container to display:block for the element I want to move interactively. This restores the default 'non-flex' context.


问:
How to restart a loop with eval with timeout in R?
```<code>while (!exists("j")) {
    i <- 1

    repeat {
        tryCatch(expr = {
            print(i)

            raw.result <- evalWithTimeout(Sys.sleep(i), timeout = 3)

            if (i == 1) {
                j <- i
            } else {
                j <- c(j, i)
            }

            i <- i + 1
        }, TimeoutException = function(ex) {
            rm("j")
        })
    }
}
</code>```

The above code is getting stuck at i=4 and keeps executing the function for i=4, however I want it to restart from i=1, whenever there is an error.

Can someone please guide on where am I doing it wrong?

答:
In your codeTimeoutException is unable to find j as it is evaluated in a different environment. Even if it was able to find it, nothing would change. As tryCatch is stopping an error from breaking a repeat loop, thus repeat will continue with the current i. You could explicitly break out from the repeat, but in that case you have deleted j, thus your while will stop.

I am not quite sure why you need while loop here.

Here is a modification of your code that will work as you want.
Fist explicitly set i <- 1, and rest it again to i <<-1 (Note <<- as i is one environment above tryCatch).

```<code>i <- 1

repeat {
  tryCatch(
    expr = {
      print(i)

      raw.result <- R.utils:evalWithTimeout(Sys.sleep(i), timeout = 3)

      if (i == 1) {
        j <- i
      } else {
        j <- c(j, i)
      }

      i <- i + 1
    },
    TimeoutException = function(ex) {
      i <<- 1
    }
  )
}
</code>```

Body:
while (!exists("j")) {
    i <- 1

    repeat {
        tryCatch(expr = {
            print(i)

            raw.result <- evalWithTimeout(Sys.sleep(i), timeout = 3)

            if (i == 1) {
                j <- i
            } else {
                j <- c(j, i)
            }

            i <- i + 1
        }, TimeoutException = function(ex) {
            rm("j")
        })
    }
}

The above code is getting stuck at i=4 and keeps executing the function for i=4, however I want it to restart from i=1, whenever there is an error.

Can someone please guide on where am I doing it wrong?

Body:
In your codeTimeoutException is unable to find j as it is evaluated in a different environment. Even if it was able to find it, nothing would change. As tryCatch is stopping an error from breaking a repeat loop, thus repeat will continue with the current i. You could explicitly break out from the repeat, but in that case you have deleted j, thus your while will stop.

I am not quite sure why you need while loop here.

Here is a modification of your code that will work as you want.
Fist explicitly set i <- 1, and rest it again to i <<-1 (Note <<- as i is one environment above tryCatch).

i <- 1

repeat {
  tryCatch(
    expr = {
      print(i)

      raw.result <- R.utils:evalWithTimeout(Sys.sleep(i), timeout = 3)

      if (i == 1) {
        j <- i
      } else {
        j <- c(j, i)
      }

      i <- i + 1
    },
    TimeoutException = function(ex) {
      i <<- 1
    }
  )
}


问:
Laravel Scout - searching trashed records and keeping soft deleted models updated
By default Laravel Scout will remove any model from the search index upon it being deleted, even if that model is soft deleted.

Instead of being removed, how can we keep the model in the search index and update it to have the current timestamp for deleted_at?

答:
The key lies in the source code for laravel-scout. First we should get familiar with the Searchable.php file, after-all it's the trait we apply to our model that kicks off all the magic. The methods searchable and unsearchable are pretty clear to their purpose.

Now notice the two static methods enableSearchSyncing and disableSearchSyncing. This will let us control the syncing behavior. If we look back at the introduction to laravel scout, it gives us this hint:

Using model observers, Scout will automatically keep your search
  indexes in sync with your Eloquent records.

So we should turn our attention to the ModelObserver.php. This is where it all happens. The observer looks after four model events, created, updated, deleted, and restored.

updated, and restored simply call the created method, which will check if to make sure syncing is not disabled, then run $model->searchable().

deleted, what we want to prevent from happening is very similar. It will check to see if syncing is enabled, and then run $model->unsearchable();.

Solution:

Now that we understand how it works, it's relatively simple to get our desired effect. We will take a page out of scouts book and do use observers as well to update our search index when it is deleted. Here's what it looks like:

```<code>class UserObserver
{
    /**
     * Listen to the User deleting event.
     *
     * @param User $user
     */
    public function deleting(User $user)
    {
        $user::disableSearchSyncing();
    }

    /**
     * Listen to the User deleted event.
     *
     * @param User $user
     */
    public function deleted(User $user)
    {
        $user::enableSearchSyncing();

        $user->searchable();
    }
}
</code>```

After creating the observer make sure you don't forget to add it to your AppServiceProvider's boot method, otherwise it will never get registered.

```<code>class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        User::observe(UserObserver::class);
    }

...
</code>```

To recap on how this works. Before the model is deleted (deleting event), we tell scout to stop syncing. Then when the model is deleted, we re-enable syncing, and call the searchable method to perform the update. Our record in our search database will now be updated with the proper deleted_at timestamp.

Body:
The key lies in the source code for laravel-scout. First we should get familiar with the Searchable.php file, after-all it's the trait we apply to our model that kicks off all the magic. The methods searchable and unsearchable are pretty clear to their purpose.

Now notice the two static methods enableSearchSyncing and disableSearchSyncing. This will let us control the syncing behavior. If we look back at the introduction to laravel scout, it gives us this hint:

Using model observers, Scout will automatically keep your search
  indexes in sync with your Eloquent records.

So we should turn our attention to the ModelObserver.php. This is where it all happens. The observer looks after four model events, created, updated, deleted, and restored.

updated, and restored simply call the created method, which will check if to make sure syncing is not disabled, then run $model->searchable().

deleted, what we want to prevent from happening is very similar. It will check to see if syncing is enabled, and then run $model->unsearchable();.

Solution:

Now that we understand how it works, it's relatively simple to get our desired effect. We will take a page out of scouts book and do use observers as well to update our search index when it is deleted. Here's what it looks like:

class UserObserver
{
    /**
     * Listen to the User deleting event.
     *
     * @param User $user
     */
    public function deleting(User $user)
    {
        $user::disableSearchSyncing();
    }

    /**
     * Listen to the User deleted event.
     *
     * @param User $user
     */
    public function deleted(User $user)
    {
        $user::enableSearchSyncing();

        $user->searchable();
    }
}

After creating the observer make sure you don't forget to add it to your AppServiceProvider's boot method, otherwise it will never get registered.

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        User::observe(UserObserver::class);
    }

...

To recap on how this works. Before the model is deleted (deleting event), we tell scout to stop syncing. Then when the model is deleted, we re-enable syncing, and call the searchable method to perform the update. Our record in our search database will now be updated with the proper deleted_at timestamp.


问:
I cannot get jQuery to work in wordpress
Tried many different techniques to get jquery working in my custom wordpress theme but still haven't got anywhere.

I've included two different methods that I've tried below near the end of the code, with one commented out here.

Can anyone see why this code might not be working?

PHP:

```<code><?php

function wpb_custom_new_menu() {
    register_nav_menu('my-custom-menu',__( 'My Custom Menu' ));
}

add_action( 'init', 'wpb_custom_new_menu' );

function enqueue_stylesheets() {
    wp_enqueue_style('style', get_stylesheet_directory_uri() . '/css/style.css');
    wp_enqueue_style('fonts', 'https://fonts.googleapis.com/css?family=Montserrat:400,600,700|Raleway:400,500,600,700');
    wp_enqueue_style( 'fontAwesome', 'https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css' );
}

/*function wp_enqeue_scripts() {
    wp_register_script('navbarScroll', home_url() . '/js/navbarScroll.js', array( 'jquery' ));
    wp_enqueue_script('navbarScroll');
    //wp_enqueue_script( 'bootstrap-js', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js', array('jquery'), '3.3.4', true );
}*/

function navbar_script() {
    wp_register_script( 'jquery.navbarScroll', get_template_directory_uri() . '/js/jquery.navbarScroll.js', array( 'jquery' ) );
    wp_enqueue_script( 'jquery.navbarScroll' );
}

add_action('wp_enqueue_scripts', 'enqueue_stylesheets', 'enqueue_scripts', 'navbar_script');
</code>```

My Test JS (I've used both $ and jquery):

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

jquery('#jQueryTest').html('jQuery is Working');

jQuery('nav').hover(function() {
    $(this).css('display', 'none');
})

/*var a = $('nav').offset().top;

$(document).scroll(function() {
    if ($(this).scrollTop() > a)
    {
       $(this).removeClass('nav');
       $(this).addClass('nav-scrolled');
    } else {
       $(this).removeClass('nav-scrolled');
    }
});*/

});
</code>```

答:
Its easy if you can have a code like this to solve correctly and without confusiong. You have forgotten to pass add_action for your scripts.

```<code>function wpb_custom_new_menu() {
    register_nav_menu('my-custom-menu',__( 'My Custom Menu' ));
}

add_action( 'init', 'wpb_custom_new_menu' );

function enqueue_stylesheets() {
    //For registering Styles
    wp_enqueue_style('style', get_stylesheet_directory_uri() . '/css/style.css');
    wp_enqueue_style('fonts', 'https://fonts.googleapis.com/css?family=Montserrat:400,600,700|Raleway:400,500,600,700');
    wp_enqueue_style( 'fontAwesome', 'https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css' );

    //For registering Scripts files
    wp_enqueue_script( 'jquery');
    wp_enqueue_script( 'bootstrap-js', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js', array('jquery'), '3.3.4', true );
    wp_register_script('navbarScroll', get_stylesheet_directory_uri() . '/js/navbarScroll.js', array( 'jquery' ), '', true );
    wp_enqueue_script('navbarScroll');
    wp_register_script( 'jquery.navbarScroll', get_template_directory_uri() . '/js/jquery.navbarScroll.js', array( 'jquery' ), '', true );
    wp_enqueue_script( 'jquery.navbarScroll' );
}
add_action( 'wp_enqueue_scripts', 'enqueue_stylesheets' );
</code>```

Hope this works for you.

THanks

Body:
Tried many different techniques to get jquery working in my custom wordpress theme but still haven't got anywhere.

I've included two different methods that I've tried below near the end of the code, with one commented out here.

Can anyone see why this code might not be working?

PHP:

<?php

function wpb_custom_new_menu() {
    register_nav_menu('my-custom-menu',__( 'My Custom Menu' ));
}

add_action( 'init', 'wpb_custom_new_menu' );

function enqueue_stylesheets() {
    wp_enqueue_style('style', get_stylesheet_directory_uri() . '/css/style.css');
    wp_enqueue_style('fonts', 'https://fonts.googleapis.com/css?family=Montserrat:400,600,700|Raleway:400,500,600,700');
    wp_enqueue_style( 'fontAwesome', 'https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css' );
}

/*function wp_enqeue_scripts() {
    wp_register_script('navbarScroll', home_url() . '/js/navbarScroll.js', array( 'jquery' ));
    wp_enqueue_script('navbarScroll');
    //wp_enqueue_script( 'bootstrap-js', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js', array('jquery'), '3.3.4', true );
}*/

function navbar_script() {
    wp_register_script( 'jquery.navbarScroll', get_template_directory_uri() . '/js/jquery.navbarScroll.js', array( 'jquery' ) );
    wp_enqueue_script( 'jquery.navbarScroll' );
}

add_action('wp_enqueue_scripts', 'enqueue_stylesheets', 'enqueue_scripts', 'navbar_script');

My Test JS (I've used both $ and jquery):

jquery(document).ready(function() {

jquery('#jQueryTest').html('jQuery is Working');

jQuery('nav').hover(function() {
    $(this).css('display', 'none');
})

/*var a = $('nav').offset().top;

$(document).scroll(function() {
    if ($(this).scrollTop() > a)
    {
       $(this).removeClass('nav');
       $(this).addClass('nav-scrolled');
    } else {
       $(this).removeClass('nav-scrolled');
    }
});*/

});

Body:
Its easy if you can have a code like this to solve correctly and without confusiong. You have forgotten to pass add_action for your scripts.

function wpb_custom_new_menu() {
    register_nav_menu('my-custom-menu',__( 'My Custom Menu' ));
}

add_action( 'init', 'wpb_custom_new_menu' );

function enqueue_stylesheets() {
    //For registering Styles
    wp_enqueue_style('style', get_stylesheet_directory_uri() . '/css/style.css');
    wp_enqueue_style('fonts', 'https://fonts.googleapis.com/css?family=Montserrat:400,600,700|Raleway:400,500,600,700');
    wp_enqueue_style( 'fontAwesome', 'https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css' );

    //For registering Scripts files
    wp_enqueue_script( 'jquery');
    wp_enqueue_script( 'bootstrap-js', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js', array('jquery'), '3.3.4', true );
    wp_register_script('navbarScroll', get_stylesheet_directory_uri() . '/js/navbarScroll.js', array( 'jquery' ), '', true );
    wp_enqueue_script('navbarScroll');
    wp_register_script( 'jquery.navbarScroll', get_template_directory_uri() . '/js/jquery.navbarScroll.js', array( 'jquery' ), '', true );
    wp_enqueue_script( 'jquery.navbarScroll' );
}
add_action( 'wp_enqueue_scripts', 'enqueue_stylesheets' );

Hope this works for you.

THanks


问:
ASPX Webform - Programmatically created linkbutton never trigger event in UpdatePanel
I have a simple test app with a MasterPage, a Default.aspx page containing an UpdatePanel with few html and asp controls.

My purpose is to create dynamically controls and bind events.

I know the issue about IDs on controls and binding event handlers, as the the fact that you need to register an asynccontrol to the scriptmanager.

I tried many things but my dynamically created linkbutton goes in PostBack, in the MasterPage on_load but NEVER in my attached click event.

Extra infos : the declarative asp button triggers its click event after Default.aspx Page_Load and performing a Postback, the LinkButton dynamically created goes as well in the Default Page_Load but never trigger btnTest_Click2. This app is on .NET 4.5 (Visual Studio 2015).

Any idea ?

Thx.

Default.aspx :

```<code><%@ Page Title="Home Page" Language="VB" MasterPageFile="~/Site.Master" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="TestUpdatePanel._Default" %>

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
    <h1>This will never change !</h1>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
        <ContentTemplate>
            <asp:Button runat="server" ID="btnTest" CssClass="btn btn-success" OnClick="btnTest_Click" Text="Hit me hard !" />
        <div runat="server" id="testDiv">
            <p>Hello this a test</p>
        </div>
        </ContentTemplate>
        <Triggers>
        </Triggers>
    </asp:UpdatePanel>

</asp:Content>
</code>```

Default.aspx.vb code-behind :

```<code>Public Class _Default
    Inherits Page

    Dim currentsm As ScriptManager

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load

        currentsm = CType(Page.Master.FindControl("sm1"), ScriptManager)

        If Not IsPostBack Then
            MsgBox("It's not a postback", MsgBoxStyle.DefaultButton1)
        Else
            MsgBox("It's a Postback !", MsgBoxStyle.DefaultButton1)
        End If

    End Sub

    Protected Sub btnTest_Click(sender As Object, e As EventArgs)

        BuildButton()

    End Sub

    Private Sub BuildButton()

        Dim link = New LinkButton

        link.ID = "linkTest"
        link.ClientIDMode = ClientIDMode.Static
        link.Text = "This is a new Ajax link :-)"

        AddHandler link.Click, AddressOf btnTest_Click2

        Dim trigger As AsyncPostBackTrigger = New AsyncPostBackTrigger
        trigger.ControlID = link.ClientID
        trigger.EventName = "Click"
        UpdatePanel1.Triggers.Add(trigger)

        currentsm.RegisterAsyncPostBackControl(link)

        testDiv.Controls.Add(link)
        UpdatePanel1.Update()

    End Sub

    Private Sub BuildDiv()

        Dim divToCreate = New HtmlGenericControl

        divToCreate.TagName = "div"
        divToCreate.ID = "newDiv"
        divToCreate.ClientIDMode = ClientIDMode.Static
        divToCreate.Attributes("class") = ("btn btn-alert")
        divToCreate.InnerText = "It works !"

        testDiv.Controls.Add(divToCreate)

        UpdatePanel1.Update()

    End Sub

    Protected Sub btnTest_Click2(sender As Object, e As EventArgs)

        BuildDiv()

    End Sub
</code>```

答:
I finally got it with the use of the OnInit event to instanciate the dynamically created controls like this :</p>

```<code>Protected Overrides Sub OnInit(e As EventArgs)
    MyBase.OnInit(e)
    If IsPostBack Then
        currentsm = CType(Page.Master.FindControl("sm1"), ScriptManager)
        Dim sender = Request.Form("__EVENTTARGET").ToString
        If sender.Contains("btnTest") Then
            BuildButton()
        ElseIf sender.Contains("linkTest") Then
            BuildDiv()
        End If
    End If
End Sub
</code>```

Body:
I have a simple test app with a MasterPage, a Default.aspx page containing an UpdatePanel with few html and asp controls.

My purpose is to create dynamically controls and bind events.

I know the issue about IDs on controls and binding event handlers, as the the fact that you need to register an asynccontrol to the scriptmanager.

I tried many things but my dynamically created linkbutton goes in PostBack, in the MasterPage on_load but NEVER in my attached click event.

Extra infos : the declarative asp button triggers its click event after Default.aspx Page_Load and performing a Postback, the LinkButton dynamically created goes as well in the Default Page_Load but never trigger btnTest_Click2. This app is on .NET 4.5 (Visual Studio 2015).

Any idea ?

Thx.

Default.aspx :

<%@ Page Title="Home Page" Language="VB" MasterPageFile="~/Site.Master" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="TestUpdatePanel._Default" %>

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">

This will never change !

    <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
        <ContentTemplate>
            <asp:Button runat="server" ID="btnTest" CssClass="btn btn-success" OnClick="btnTest_Click" Text="Hit me hard !" />

Hello this a test

        </ContentTemplate>
        <Triggers>
        </Triggers>
    </asp:UpdatePanel>

</asp:Content>

Default.aspx.vb code-behind :

Public Class _Default
    Inherits Page

    Dim currentsm As ScriptManager

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load

        currentsm = CType(Page.Master.FindControl("sm1"), ScriptManager)

        If Not IsPostBack Then
            MsgBox("It's not a postback", MsgBoxStyle.DefaultButton1)
        Else
            MsgBox("It's a Postback !", MsgBoxStyle.DefaultButton1)
        End If

    End Sub

    Protected Sub btnTest_Click(sender As Object, e As EventArgs)

        BuildButton()

    End Sub

    Private Sub BuildButton()

        Dim link = New LinkButton

        link.ID = "linkTest"
        link.ClientIDMode = ClientIDMode.Static
        link.Text = "This is a new Ajax link :-)"

        AddHandler link.Click, AddressOf btnTest_Click2

        Dim trigger As AsyncPostBackTrigger = New AsyncPostBackTrigger
        trigger.ControlID = link.ClientID
        trigger.EventName = "Click"
        UpdatePanel1.Triggers.Add(trigger)

        currentsm.RegisterAsyncPostBackControl(link)

        testDiv.Controls.Add(link)
        UpdatePanel1.Update()

    End Sub

    Private Sub BuildDiv()

        Dim divToCreate = New HtmlGenericControl

        divToCreate.TagName = "div"
        divToCreate.ID = "newDiv"
        divToCreate.ClientIDMode = ClientIDMode.Static
        divToCreate.Attributes("class") = ("btn btn-alert")
        divToCreate.InnerText = "It works !"

        testDiv.Controls.Add(divToCreate)

        UpdatePanel1.Update()

    End Sub

    Protected Sub btnTest_Click2(sender As Object, e As EventArgs)

        BuildDiv()

    End Sub

Body:
I finally got it with the use of the OnInit event to instanciate the dynamically created controls like this :

Protected Overrides Sub OnInit(e As EventArgs)
    MyBase.OnInit(e)
    If IsPostBack Then
        currentsm = CType(Page.Master.FindControl("sm1"), ScriptManager)
        Dim sender = Request.Form("__EVENTTARGET").ToString
        If sender.Contains("btnTest") Then
            BuildButton()
        ElseIf sender.Contains("linkTest") Then
            BuildDiv()
        End If
    End If
End Sub


问:
bash split csv file and output same extension and remove last empty line
I have the following input file:

```<code>srcfile.csv
</code>```

which looks like:

```<code>3.8,1.9,1000
3.8,2,1000
3.8,2.1,1000
3.8,2.2,1000
3.8,2.3,1000
3.8,2.4,1000
3.8,2.5,1000
3.8,2.6,1000
3.8,2.7,1000
3.8,2.8,1000
3.8,2.9,1000
3.8,3,1000
3.8,3.1,1000
</code>```

I am splitting it into files of equal number of lines:

```<code>split -l 20 -d srcfile.csv outputFile_
</code>```

the resulting files don't have csv extension and they have an extra empty line at the end of the each output file.

How can I fix it?

答:
Use the additional suffix flag: </p>

```<code>   --additional-suffix=SUFFIX
          append an additional SUFFIX to file names
</code>```

<p>Like so: </p>

```<code>split -l 20 --additional-suffix='.csv' -d srcfile.csv outputFile_
</code>```

Body:
I have the following input file:

srcfile.csv

which looks like:

3.8,1.9,1000
3.8,2,1000
3.8,2.1,1000
3.8,2.2,1000
3.8,2.3,1000
3.8,2.4,1000
3.8,2.5,1000
3.8,2.6,1000
3.8,2.7,1000
3.8,2.8,1000
3.8,2.9,1000
3.8,3,1000
3.8,3.1,1000

I am splitting it into files of equal number of lines:

split -l 20 -d srcfile.csv outputFile_

the resulting files don't have csv extension and they have an extra empty line at the end of the each output file.

How can I fix it?

Body:
Use the additional suffix flag:

   --additional-suffix=SUFFIX
          append an additional SUFFIX to file names

Like so:

split -l 20 --additional-suffix='.csv' -d srcfile.csv outputFile_


问:
Subtotaling cost data from another worksheet
For starters, I am fairly new to coding in VBA. I have a background with C++, MATLAB and some (very little) JAVA programming.

I have a large excel report with various projects with costs and managers associated with each. Each project has many rows of cost data. I need to create a program to walk through the report and subtotal all the costs allocated with a single project and create a row on another worksheet with the project manager, Project name and the subtotal value of the costs. Then, I need the program to move to the next project of a different name in the report and repeat until all unique projects have been subtotaled on the 2nd worksheet.

I hope I described the situation well enough for anyone to understand and help...

Thanks!!

答:
This isn't an answer per say but I think what I am going to say will take more characters than a comments will allow

The key concepts you need to use to get to this point:

Sorting the worksheet. This might be a fun task and no sure if covered (in SO documentation that is). A quick google search will find you tons of examples. https://msdn.microsoft.com/en-us/library/office/ff840646.aspx

Looping through ranges in a worksheets. Covered sufficiently in the documentation

Referencing cell values so you can do comparisons (project to project etc). If you're used to lite programming already assigning variable values should be pretty easy.

Learning how to place values in a new location using the Offset property. Also, covered in the documentation.

This should be plenty for you to get started and come back once you have a specific question with code you've already tried.


答:
Your regex tries to match against the entire line. You can get individual pairs if you don't use anchors:

```<code>var input = Regex.Matches("{TheKey|TheValue}{AnotherKey|AnotherValue}");
var matches=Regex.Matches(input,@"(\{(.+?)\|(.+?)\})");
Debug.Assert(matches.Count == 2);
</code>```

It's better to name the fields though:

```<code>var matches=Regex.Matches(input,@"\{(?<key>.+?)\|(?<value>.+?)\}");
</code>```

This allows you to access the fields by name, and even use LINQ:

```<code>var pairs= from match in matches.Cast<Match>()
           select new {
                          key=match.Groups["key"].Value,
                          value=match.Groups["value"].Value
                      };
</code>```

Title: Attempting to capture multiple groups but only the last group is captured

Body:
I am trying to use regex to help to convert the following string into a Dictionary:

{TheKey|TheValue}{AnotherKey|AnotherValue}

Like such:

["TheKey"] = "TheValue"
["AnotherKey"] = "AnotherValue"

To parse the string for the dictionary, I am using the regex expression:

 ^(\{(.+?)\|(.+?)\})*?$

But it will only capture the last group of {AnotherKey|AnotherValue}.

How do I get it to capture all of the groups?

I am using C#.

Alternatively, is there a more straightforward way to approach this rather than using Regex?

Code (Properties["PromptedValues"] contains the string to be parsed):

var regex = Regex.Matches(Properties["PromptedValues"], @"^(\{(.+?)\|(.+?)\})*?$");

foreach(Match match in regex) {

    if(match.Groups.Count == 4) {

        var key = match.Groups[2].Value.ToLower();
        var value = match.Groups[3].Value;

        values.Add(key, new StringPromptedFieldHandler(key, value));
     }

}

This is coded to work for the single value, I would be looking to update it once I can get it to capture multiple values.

Body:
Your regex tries to match against the entire line. You can get individual pairs if you don't use anchors:

var input = Regex.Matches("{TheKey|TheValue}{AnotherKey|AnotherValue}");
var matches=Regex.Matches(input,@"(\{(.+?)\|(.+?)\})");
Debug.Assert(matches.Count == 2);

It's better to name the fields though:

var matches=Regex.Matches(input,@"\{(?<key>.+?)\|(?<value>.+?)\}");

This allows you to access the fields by name, and even use LINQ:

var pairs= from match in matches.Cast<Match>()
           select new {
                          key=match.Groups["key"].Value,
                          value=match.Groups["value"].Value
                      };