问:
Show an ASP.NET Validation Summary in a jQuery UI Modal Message
I've made an ASP.NET web form that uses the standard ASP.NET validation.  I'd like to make the error summary show up in a jQuery UI Modal Message as well as below the actual form.

Is it possible to execute the script if the validation finds an error?

答:
I used the idea in the link provided by GeReV
and here is what I came up with, in case someone needs it:
Check here.

Let me add a note: Don't vote-down this post in case if it has to be a comment. I don't see a option to add comment.


来源: stackexchange

问:
How to add shapiro test p-value to the density plot in R
How can I add the p value of the Shapiro test (checking normality) into the density plot? I tried to use geom_text(aes(y = 1, label = p.value), data = shapiro.test, size = 1) but I got the error.

```<code> formula <- as.formula(paste0("cbind(", paste(names(mtcars)[-c(4,9)], collapse = ","), ") ~ hp*am"))
    fit <- aov(formula, data=mtcars)
    res.data.plot <-data.frame(melt(resid(fit)))
    res.data.test <-data.frame(resid(fit))
#plot
        res.plot <- ggplot(res.data.plot, aes(x=value)) +
                    geom_histogram(aes(y=..density..), binwidth=.5,colour="black", fill="white")+
                    geom_density(alpha=.2, fill="#FF6666")+ facet_wrap( ~X2, scales="free")

# shapiro test
        kk<-Map(function(x)cbind(shapiro.test(x)$statistic,shapiro.test(x)$p.value),res.data.test)
        shapiro.test <-ldply(kk)
        names(shapiro.test)<-c("var","W","p.value")
        shapiro.test<- plyr::arrange(shapiro.test, var, desc(p.value))
</code>```

答:
The data in the shapiro.test object is not the same length as res.data.plot, they need to be the same length for geom_text to work as you expect.

You can merge both objects, so plotting becomes straightforward.

```<code>res.data.plot.new <- merge(res.data.plot, shapiro.test, by.x = "Var2", by.y = "var")

ggplot(res.data.plot.new, aes(x=value)) +
  geom_histogram(aes(y=..density..), binwidth=.5, colour="black", fill="white") +
  geom_density(alpha=.2, fill="#FF6666") +
  facet_wrap( ~Var2, scales="free") +
  geom_text(aes(x = 1, y = 1, label = round(p.value, 4)))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How can I add the p value of the Shapiro test (checking normality) into the density plot? I tried to use geom_text(aes(y = 1, label = p.value), data = shapiro.test, size = 1) but I got the error.

 formula <- as.formula(paste0("cbind(", paste(names(mtcars)[-c(4,9)], collapse = ","), ") ~ hp*am"))
    fit <- aov(formula, data=mtcars)
    res.data.plot <-data.frame(melt(resid(fit)))
    res.data.test <-data.frame(resid(fit))
#plot
        res.plot <- ggplot(res.data.plot, aes(x=value)) +
                    geom_histogram(aes(y=..density..), binwidth=.5,colour="black", fill="white")+
                    geom_density(alpha=.2, fill="#FF6666")+ facet_wrap( ~X2, scales="free")

# shapiro test
        kk<-Map(function(x)cbind(shapiro.test(x)$statistic,shapiro.test(x)$p.value),res.data.test)
        shapiro.test <-ldply(kk)
        names(shapiro.test)<-c("var","W","p.value")
        shapiro.test<- plyr::arrange(shapiro.test, var, desc(p.value))

Body:
The data in the shapiro.test object is not the same length as res.data.plot, they need to be the same length for geom_text to work as you expect.

You can merge both objects, so plotting becomes straightforward.

res.data.plot.new <- merge(res.data.plot, shapiro.test, by.x = "Var2", by.y = "var")

ggplot(res.data.plot.new, aes(x=value)) +
  geom_histogram(aes(y=..density..), binwidth=.5, colour="black", fill="white") +
  geom_density(alpha=.2, fill="#FF6666") +
  facet_wrap( ~Var2, scales="free") +
  geom_text(aes(x = 1, y = 1, label = round(p.value, 4)))


问:
Angular UI router permissions / access control
I am having a lot of trouble determining how to add permissions / access-control to our Angular app. Right now we have this:

```<code>    app.config(['$stateProvider', function ($stateProvider) {

      $stateProvider

      .state('default', {
        url: '',
        templateUrl: 'pages/home/view/home.html',
        controller: 'HomeCtrl'
      })

      .state('home', {
        url: '/home',
        templateUrl: 'pages/home/view/home.html',
        controller: 'HomeCtrl',

        permissions: {                    // ?
          only: ['Admin','Moderator']
        },

        access: {                         // ?
         roles: ['*']
        },

        resolve: {                        // ?
          authenticate: function($state, $q, $timeout){

          },

        }

      })

}]);
</code>```

I having trouble determining which methodology to use to create access control to each page.

Right now, the logged in user is stored in an Angular value:

```<code>app.value('USER', JSON.parse('{{{user}}}'));
</code>```

The USER value contains the information about which roles / permissions the user has.

But I cannot inject USER into app.config() callback, it says "unknown provider".

How can I do access-control based of the USER parameters?

答:
This is how I got it to work. I am not sure if it's the best way, but it does work.

You cannot inject services/values in the app.config(), but you can inject services/values into the resolve.authenticate function.

I decided to use the resolve.authenticate methodology.

```<code> .state('home', {
    url: '/home',
    templateUrl: 'pages/home/view/home.html',
    controller: 'HomeCtrl',
    resolve: {
      authenticate: handlePageRequest['home']   // <<<<
    }
  })
</code>```

and then we have a handler:

```<code>  let handlePageRequest = {

    'default': function ($q, USER, $state, $timeout, AuthService) {
      // this page is always ok to access
      return $q.when();
    },

    'home': function ($q, USER, $state, $timeout, AuthService) {

      if(AuthService.isHomePageAccessible(USER)){
        return $q.when();
      }
      else{
        $timeout(function () {
          $state.go('not-found'); // we can prevent user from accessing home page this way
        }, 100);

        return $q.reject()
      }
    },
  };
</code>```

Body:
I am having a lot of trouble determining how to add permissions / access-control to our Angular app. Right now we have this:

    app.config(['$stateProvider', function ($stateProvider) {

      $stateProvider

      .state('default', {
        url: '',
        templateUrl: 'pages/home/view/home.html',
        controller: 'HomeCtrl'
      })

      .state('home', {
        url: '/home',
        templateUrl: 'pages/home/view/home.html',
        controller: 'HomeCtrl',

        permissions: {                    // ?
          only: ['Admin','Moderator']
        },

        access: {                         // ?
         roles: ['*']
        },

        resolve: {                        // ?
          authenticate: function($state, $q, $timeout){

          },

        }

      })

}]);

I having trouble determining which methodology to use to create access control to each page.

Right now, the logged in user is stored in an Angular value:

app.value('USER', JSON.parse('{{{user}}}'));

The USER value contains the information about which roles / permissions the user has.

But I cannot inject USER into app.config() callback, it says "unknown provider".

How can I do access-control based of the USER parameters?

Body:
This is how I got it to work. I am not sure if it's the best way, but it does work.

You cannot inject services/values in the app.config(), but you can inject services/values into the resolve.authenticate function.

I decided to use the resolve.authenticate methodology.

 .state('home', {
    url: '/home',
    templateUrl: 'pages/home/view/home.html',
    controller: 'HomeCtrl',
    resolve: {
      authenticate: handlePageRequest['home']   // <<<<
    }
  })

and then we have a handler:

  let handlePageRequest = {

    'default': function ($q, USER, $state, $timeout, AuthService) {
      // this page is always ok to access
      return $q.when();
    },

    'home': function ($q, USER, $state, $timeout, AuthService) {

      if(AuthService.isHomePageAccessible(USER)){
        return $q.when();
      }
      else{
        $timeout(function () {
          $state.go('not-found'); // we can prevent user from accessing home page this way
        }, 100);

        return $q.reject()
      }
    },
  };


问:
Load JavaScript into a page I do not own before any of its JavaScript executes
I have found a web page I don't have control over. I can see in its console that it is throwing a "missing jQuery" error from its Bootstrap script.

I'd like to load jQuery before this script executes when I navigate to this page so I can see if the site operates differently.

答:
TL;DR
Yes, it's possible, but not the conventional way

Why no

You can't run Javascript on arbitrary Web pages that you do not control the content of. It would be a huge security hole if that were not true.

Think about it: you could run Javascript and wait for someone to log on to their internet banking and then do something with the characters input.

Why yes

However, if you just want to get the page working, you can use Tampermonkey. You can use it to execute custom scripts on page load for any website you want. You can find some basic tutorials here: https://hibbard.eu/tampermonkey-tutorial/


问:
Simpler Alternative to Reset Password in Powershell (not using AD) for WIndows 10
I am Looking for RESETING ALL PASSWORDS ON ALL LOCAL USERS on a local windows 10 machine (NOT Server). To reset passwords for all accounts on that system NOT USING Active Directory.  I saw many posts that use AD to reset passwords.

I am not interested in that. Is there any alternatives to these? Using Powershell, Batch, That you guys use. Surely there is a simpler alternative for non servers.

I have seen this. But it uses alot of dependencies of LocalGroup module being installed And Exchange.

```<code>$newpwd = Read-Host "Enter the new password" -AsSecureString
Get-LocalUser | ForEach-Object {
    $_ | Set-LocalUser -Password $newpwd
}
</code>```

I have Seen this

```<code># Specify the OU.
$OU = [ADSI]"LDAP://ou=West,dc=MyDomain,dc=com"

# Enumerate all objects in the OU.
$arrChildren = $OU.Get_Children()
ForEach ($User In $arrChildren)
{
    # Only consider user objects.
    If ($User.Class -eq "user")
   {
       # Set password.
       $User.Invoke("SetPassword", "MyPassword")
       # Expire the password.
       $User.pwdLastSet = 0
       $User.SetInfo()
   }
}
</code>```

答:
There is a built in module for this, that is included in Windows 10 as of 1607 (best I can tell), called Microsoft.PowerShell.LocalAccounts

What you've got there should work, the only requirement on it being that you're on version 1607 or higher. You might also want to make sure that you're only affecting enabled accounts or some some other sort of filtering so you don't accidentally change the password on something you didn't intend.

The example from the help on Set-LocalUser is:

```<code>$Password = Read-Host -AsSecureString
$UserAccount = Get-LocalUser -Name "User02"
$UserAccount | Set-LocalUser -Password $Password
</code>```

If you're going to loop it, I'd personally be using Get-LocalUser with no arguments, piping it to where an only selecting accounts that are currently enabled.

ContentLicense: CC BY-SA 4.0

Body:
I am Looking for RESETING ALL PASSWORDS ON ALL LOCAL USERS on a local windows 10 machine (NOT Server). To reset passwords for all accounts on that system NOT USING Active Directory.  I saw many posts that use AD to reset passwords.

I am not interested in that. Is there any alternatives to these? Using Powershell, Batch, That you guys use. Surely there is a simpler alternative for non servers.

I have seen this. But it uses alot of dependencies of LocalGroup module being installed And Exchange.

$newpwd = Read-Host "Enter the new password" -AsSecureString
Get-LocalUser | ForEach-Object {
    $_ | Set-LocalUser -Password $newpwd
}

I have Seen this

# Specify the OU.
$OU = [ADSI]"LDAP://ou=West,dc=MyDomain,dc=com"

# Enumerate all objects in the OU.
$arrChildren = $OU.Get_Children()
ForEach ($User In $arrChildren)
{
    # Only consider user objects.
    If ($User.Class -eq "user")
   {
       # Set password.
       $User.Invoke("SetPassword", "MyPassword")
       # Expire the password.
       $User.pwdLastSet = 0
       $User.SetInfo()
   }
}

Body:
There is a built in module for this, that is included in Windows 10 as of 1607 (best I can tell), called Microsoft.PowerShell.LocalAccounts

What you've got there should work, the only requirement on it being that you're on version 1607 or higher. You might also want to make sure that you're only affecting enabled accounts or some some other sort of filtering so you don't accidentally change the password on something you didn't intend.

The example from the help on Set-LocalUser is:

$Password = Read-Host -AsSecureString
$UserAccount = Get-LocalUser -Name "User02"
$UserAccount | Set-LocalUser -Password $Password

If you're going to loop it, I'd personally be using Get-LocalUser with no arguments, piping it to where an only selecting accounts that are currently enabled.


问:
automation of Antivirus update in window machines on distributes systems
I have a requirement of automation of Antivirus update in window machines on distributes systems , McAfee dat file updation on all windows7 machines . currently we are manually running dat file into all the Windows machines.

We are looking for something to run/schedule from the single machine on the network or the work-group of computers .
As per the research on the net,
1. McAfee ePO
2. batch script to run on each machine ( which is exactly same as the running manually)

P.S: no Internet access in any of the computers.
any suggestions on this would be greatly appreciated.
Thanks

答:
Option 2 (batch file) would be free, obviously, and you could have it kick off via a scheduled task in Windows on each client, or you could put together a script that runs through a list of machines, stops the McShield service on each one, then copies the .dat over, and restarts the McShield service.

The way to go, though, is an ePO server. If you have enterprise licensing for McAfee products then ePO should be included. An ePO server would allow you to centrally manage all your AV clients and set policies appropriately.

Running a script to update servers is kludgy and messy. You'll have no feedback from your machines as to what got updates and what didn't.


问:
How to read a column of 'dictionary' into pandas
I have a csv file with a column whose type is a dictionary (column 'b' in the example below). But b in df is a string type even though I define it as the dictionary type. I didn't find the solution to this question. Any suggestions?

```<code>a = pd.DataFrame({'a': [1,2,3], 'b':[{'a':3, 'haha':4}, {'c':3}, {'d':4}]})
a.to_csv('tmp.csv', index=None)
df = pd.read_csv('tmp.csv', dtype={'b':dict})
</code>```

答: I wonder if your CSV column is actually meant to be a Python dict column, or rather JSON.  If it's JSON, you can read the column as dtype=str, then use json_normalize() on that column to explode it into multiple columns.  This is an efficient solution assuming the column contains valid JSON.

Body:
I have a csv file with a column whose type is a dictionary (column 'b' in the example below). But b in df is a string type even though I define it as the dictionary type. I didn't find the solution to this question. Any suggestions?

a = pd.DataFrame({'a': [1,2,3], 'b':[{'a':3, 'haha':4}, {'c':3}, {'d':4}]})
a.to_csv('tmp.csv', index=None)
df = pd.read_csv('tmp.csv', dtype={'b':dict})


问:
Android Talkback Announcement Localization
I have a duo lingo (English + Spanish) android application. I am implementing accessibility in my application, and I want the Talkback to read the Spanish words in Spanish and the English words in English. The English and Spanish words are going to be in separate Text views. My app locale is English and hence the Talkback + google text to speech engine are not reading the Spanish words in Spanish, they are read in English and more often their letters are read out (expected behavior).

Is there any work around or android recommended solution to achieve the same.

Ultimately I want the Talkback or the custom accessibility service to read out the English words in English and the Spanish words in Spanish.

答:
DISCLAIMER: You have to be exceptionally careful with this solution!  Overriding TTS behavior of TalkBack is very, VERY sketchy.  There are many edge cases that could make this behavior awkward, unwieldy and very bad from an accessibility perspective.  This solution should only be used when the style of the announcement is behavior specific to the app and REQUIRED functionality. Otherwise this solution breaks all sorts of WCAG 2.0 success criteria regarding compatibility with user agents and is generically a terrible idea from an accessibility/usability standpoint!

In many cases when I see questions like this, I'm hesitant to provide an answer, so as not to give developers a tool that they don't understand.  PLEASE PLEASE PLEASE DO NOT DO THIS in a typical application, it is a terrible idea. That being said, I believe this particular situation calls for it, and that this is a very clean solution given the circumstances. In the on create of your activity do the following:

```<code>findViewById(android.R.id.content).setAccessibilityDelegate(new View.AccessibilityDelegate() {

    private TextToSpeech mTts = new TextToSpeech(MainActivity.this, new TextToSpeech.OnInitListener() {
        @Override
        public void onInit(int status) {
            mTts.setLanguage(new Locale("es"));
            //Probably other things you should do to ensure TTS is initialized before requesting it speaks something.
        }
    });

    private boolean isSpanishView(View view) {
        return true;
    }

    @Override
    public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, AccessibilityEvent event) {

        switch (event.getEventType()) {
            case AccessibilityEvent.TYPE_ANNOUNCEMENT:
            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: {
                if (isSpanishView(child)) {
                    String speakableText = null;

                    if (event.getText() != null) {
                        speakableText = event.getText().toString();
                    } else if (event.getContentDescription() != null) {
                        speakableText = event.getContentDescription().toString();
                    }

                    if (speakableText != null) {
                        mTts.speak(speakableText.toString(), TextToSpeech.QUEUE_ADD, null);

                        //Prevent the default propagation of this event, have have handled it.
                        return false;
                    }
                }
            }

            default:
                return super.onRequestSendAccessibilityEvent(host, child, event);
        }
    }
});
</code>```

Basically what we have said here is attach an accessibility delegate to the root view of our activity. Look at ALL of the accessibility events that are popping up. Check to see that it is an event that announces something. If it is, check to see that it is a view that contains Spanish text. If it is, allow our Spanish TTS Engine to announce it, instead of allowing the vent to propagate.  In all other circumstances let android do its thing.

Body:
DISCLAIMER: You have to be exceptionally careful with this solution!  Overriding TTS behavior of TalkBack is very, VERY sketchy.  There are many edge cases that could make this behavior awkward, unwieldy and very bad from an accessibility perspective.  This solution should only be used when the style of the announcement is behavior specific to the app and REQUIRED functionality. Otherwise this solution breaks all sorts of WCAG 2.0 success criteria regarding compatibility with user agents and is generically a terrible idea from an accessibility/usability standpoint!

In many cases when I see questions like this, I'm hesitant to provide an answer, so as not to give developers a tool that they don't understand.  PLEASE PLEASE PLEASE DO NOT DO THIS in a typical application, it is a terrible idea. That being said, I believe this particular situation calls for it, and that this is a very clean solution given the circumstances. In the on create of your activity do the following:

findViewById(android.R.id.content).setAccessibilityDelegate(new View.AccessibilityDelegate() {

    private TextToSpeech mTts = new TextToSpeech(MainActivity.this, new TextToSpeech.OnInitListener() {
        @Override
        public void onInit(int status) {
            mTts.setLanguage(new Locale("es"));
            //Probably other things you should do to ensure TTS is initialized before requesting it speaks something.
        }
    });

    private boolean isSpanishView(View view) {
        return true;
    }

    @Override
    public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, AccessibilityEvent event) {

        switch (event.getEventType()) {
            case AccessibilityEvent.TYPE_ANNOUNCEMENT:
            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: {
                if (isSpanishView(child)) {
                    String speakableText = null;

                    if (event.getText() != null) {
                        speakableText = event.getText().toString();
                    } else if (event.getContentDescription() != null) {
                        speakableText = event.getContentDescription().toString();
                    }

                    if (speakableText != null) {
                        mTts.speak(speakableText.toString(), TextToSpeech.QUEUE_ADD, null);

                        //Prevent the default propagation of this event, have have handled it.
                        return false;
                    }
                }
            }

            default:
                return super.onRequestSendAccessibilityEvent(host, child, event);
        }
    }
});

Basically what we have said here is attach an accessibility delegate to the root view of our activity. Look at ALL of the accessibility events that are popping up. Check to see that it is an event that announces something. If it is, check to see that it is a view that contains Spanish text. If it is, allow our Spanish TTS Engine to announce it, instead of allowing the vent to propagate.  In all other circumstances let android do its thing.


问:
Google App Maker: Prevent Duplicate Entries
How do I prevent the user from adding a duplicate entry in a specific field. I have a database in which I want a field to contain unique identifying names for equipment, how do I ensure a user can't add equipment to the database with the same identifier. </p>

答:
You can add onSave and onCreate Event handlers (Model -> Events) which will check if identifier is in use:

var query = app.models.Hardware.newQuery();
query.filters.HardwareId._equals = record.HardwareId;
if (query.run().length) {
  throw 'Hardware ID "' + record.HardwareId + '" is in use.';
}```

Also in CloudSQL you can define unique index on the field.

Body:
You can add onSave and onCreate Event handlers (Model -> Events) which will check if identifier is in use:

var query = app.models.Hardware.newQuery();
query.filters.HardwareId._equals = record.HardwareId;
if (query.run().length) {
  throw 'Hardware ID "' + record.HardwareId + '" is in use.';
}

Also in CloudSQL you can define unique index on the field.


问:
Center middle of 3 images, left and right images align to middle image
Is it possible to have the middle of 3 images centered horizontally, then have the left image align to the left of the middle image, and the right image align to the right of the middle image?

https://jsfiddle.net/0wk84qaf/

```<code><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<div style="text-align:center;">
    <div style="display:inline-block;">
        <img src="http://rubyandgrace.cdudigital.com/wp-content/uploads/2017/06/award1-2.jpg" style="vertical-align:middle;" />
        <img src="http://rubyandgrace.cdudigital.com/wp-content/uploads/2017/06/award3-2.jpg" style="vertical-align:middle;" />
        <img src="http://rubyandgrace.cdudigital.com/wp-content/uploads/2017/06/award2-2.jpg" style="vertical-align:middle;" />
    </div>
</div>
</code>```

You can see, currently, the whole div is centered, but the middle image is slightly off-center, whereas I'd like it to be bang in the middle...

答:
You can achieve this by using flex, it's really good for things like this. The output you may have to tweak yourself but what you requested is there.

Take a look at this link to view more on flex.

.img-holder {
  display: flex;
  flex-direction: row;
  width: 100%;
}

.img-holder .img {
  width: 100%;
  justify-content: space-between;
}

.img-holder img {
  width: 90%;
  height: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<div class="img-holder">

<div class="img">
  <img src="http://rubyandgrace.cdudigital.com/wp-content/uploads/2017/06/award1-2.jpg" style="vertical-align:middle;" />
</div>

<div class="img img-smaller">
  <img src="http://rubyandgrace.cdudigital.com/wp-content/uploads/2017/06/award3-2.jpg" style="vertical-align:middle;" />
</div>

<div class="img">
  <img src="http://rubyandgrace.cdudigital.com/wp-content/uploads/2017/06/award2-2.jpg" style="vertical-align:middle;" />
</div>
</div></code>```

Body:
Is it possible to have the middle of 3 images centered horizontally, then have the left image align to the left of the middle image, and the right image align to the right of the middle image?

https://jsfiddle.net/0wk84qaf/

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

You can see, currently, the whole div is centered, but the middle image is slightly off-center, whereas I'd like it to be bang in the middle...

Body:
You can achieve this by using flex, it's really good for things like this. The output you may have to tweak yourself but what you requested is there.

Take a look at this link to view more on flex.

.img-holder {
  display: flex;
  flex-direction: row;
  width: 100%;
}

.img-holder .img {
  width: 100%;
  justify-content: space-between;
}

.img-holder img {
  width: 90%;
  height: auto;
}

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<div class="img-holder">

<div class="img">
  <img src="http://rubyandgrace.cdudigital.com/wp-content/uploads/2017/06/award1-2.jpg" style="vertical-align:middle;" />
</div>

<div class="img img-smaller">
  <img src="http://rubyandgrace.cdudigital.com/wp-content/uploads/2017/06/award3-2.jpg" style="vertical-align:middle;" />
</div>

<div class="img">
  <img src="http://rubyandgrace.cdudigital.com/wp-content/uploads/2017/06/award2-2.jpg" style="vertical-align:middle;" />
</div>
</div>


问:
Talend - tmysqlcommit with tmysqloutput - error
I have a talend job, with the following sequence

tmssqlinput --> tmap --> tmysqloutput
|onsubjobok
tmssqlrow

I do want the autocommit option in tmysqloutput. I want to use the tmysqlcommit, but how should I used it? I have already determined the connection details in tmysqloutput. If I connect tmysqloutput to tmysqlcommit, I get an error in the 'Component list' of tmysqloutput. It is expecting a value there and its drop down with no values in it

How do I use tmysqlcommit in this scenario?

Thanks in advance
Rathi

答:
tMysqlCommit can only be used with tMysqlConnection, that's why you're getting an error as there are non connection components to be selected in the drop down list. It should be like this :

```<code>tMysqlConnection -- OnSubJobOk -- tMysqlInput -- tMap -- tMysqlOutput -- OnComponentOk -- tMysqlCommit
</code>```

And you should handle insert errors like this :

```<code><<Same subjob>> -- tMysqlOutput -- OnComponentError -- tMysqlRollback
</code>```

Body:
tMysqlCommit can only be used with tMysqlConnection, that's why you're getting an error as there are non connection components to be selected in the drop down list. It should be like this :

tMysqlConnection -- OnSubJobOk -- tMysqlInput -- tMap -- tMysqlOutput -- OnComponentOk -- tMysqlCommit

And you should handle insert errors like this :

<<Same subjob>> -- tMysqlOutput -- OnComponentError -- tMysqlRollback


问:
Will the MAMP(PRO) mysql conflict with brew install mysql on macos
I'm trying to install a clean mysql on my macos Sierra. As I already installed brew, I decided to use this stackoverflow answer. Nevertheless, before installation, these pre-install check is done:

I have already checked the bash line with mysql command, and found no such command.

I brew info mysql, and found mysql Not Installed.

However, I still have doubt over that I might not have a clean installation environment. So I use the find / -name mysql -type d to search all the directory for mysql. And I've found there are mysql included in MAMP. As these line writes:

```<code>/Applications/MAMP/db/mysql
/Applications/MAMP/db/mysql/mysql
/Applications/MAMP/Library/lib/perl5/site_perl/5.22.0/darwin-2level/auto/DBD/mysql
/Applications/MAMP/Library/lib/perl5/site_perl/5.22.0/darwin-2level/DBD/mysql
</code>```

I've installed MAMP about two years ago. Now I just want to learn mysql in command line rather than one-click environment like MAMP. And I wonder if I can install the mysql using brew to get a generic mysql environment if I don't uninstall the MAMP? And WHY is that the MAMP will/will not affect the mysql installed from brew?

答:
Not really, they wont' be on conflict.

Mamp use another port, and brew use default mysqm port 3306

Mamp use this foder: /Applications/MAMP/Library/bin/mysql

Brew use his own folder :  /usr/local/Cellar/mysql/(version...)

with brew you don't need use path to execute bin files, just type 'mysql -uroot -p' on the terminal.

Body:
I'm trying to install a clean mysql on my macos Sierra. As I already installed brew, I decided to use this stackoverflow answer. Nevertheless, before installation, these pre-install check is done:

I have already checked the bash line with mysql command, and found no such command.

I brew info mysql, and found mysql Not Installed.

However, I still have doubt over that I might not have a clean installation environment. So I use the find / -name mysql -type d to search all the directory for mysql. And I've found there are mysql included in MAMP. As these line writes:

/Applications/MAMP/db/mysql
/Applications/MAMP/db/mysql/mysql
/Applications/MAMP/Library/lib/perl5/site_perl/5.22.0/darwin-2level/auto/DBD/mysql
/Applications/MAMP/Library/lib/perl5/site_perl/5.22.0/darwin-2level/DBD/mysql

I've installed MAMP about two years ago. Now I just want to learn mysql in command line rather than one-click environment like MAMP. And I wonder if I can install the mysql using brew to get a generic mysql environment if I don't uninstall the MAMP? And WHY is that the MAMP will/will not affect the mysql installed from brew?


问:
possible EventEmitter memory leak detected
I am getting following warning:

(node) warning: possible EventEmitter memory leak detected. 11 listeners added. Use emitter.setMaxListeners() to increase limit.
Trace:
    at EventEmitter.<anonymous> (events.js:139:15)
    at EventEmitter.<anonymous> (node.js:385:29)
    at Server.<anonymous> (server.js:20:17)
    at Server.emit (events.js:70:17)
    at HTTPParser.onIncoming (http.js:1514:12)
    at HTTPParser.onHeadersComplete (http.js:102:31)
    at Socket.ondata (http.js:1410:22)
    at TCP.onread (net.js:354:27)
```

<p>I wrote code like this in server.js:</p>

```http.createServer(
    function (req, res) { ... }).listen(3013);
```

How to fix this ?

答:
The accepted answer provides the semantics on how to increase the limit, but as @voltrevo pointed out that warning is there for a reason and your code probably has a bug.

Consider the following buggy code:

```<code>//Assume Logger is a module that emits errors
var Logger = require('./Logger.js');

for (var i = 0; i < 11; i++) {
    //BUG: This will cause the warning
    //As the event listener is added in a loop
    Logger.on('error', function (err) {
        console.log('error writing log: ' + err)
    });

    Logger.writeLog('Hello');
}
</code>```

Now observe the correct way of adding the listener:

```<code>//Good: event listener is not in a loop
Logger.on('error', function (err) {
    console.log('error writing log: ' + err)
});

for (var i = 0; i < 11; i++) {
    Logger.writeLog('Hello');
}
</code>```

Search for similar issues in your code before changing the maxListeners (which is explained in other answers)

Body:
I am getting following warning:

(node) warning: possible EventEmitter memory leak detected. 11 listeners added. Use emitter.setMaxListeners() to increase limit.
Trace:
    at EventEmitter.<anonymous> (events.js:139:15)
    at EventEmitter.<anonymous> (node.js:385:29)
    at Server.<anonymous> (server.js:20:17)
    at Server.emit (events.js:70:17)
    at HTTPParser.onIncoming (http.js:1514:12)
    at HTTPParser.onHeadersComplete (http.js:102:31)
    at Socket.ondata (http.js:1410:22)
    at TCP.onread (net.js:354:27)

I wrote code like this in server.js:

http.createServer(
    function (req, res) { ... }).listen(3013);

How to fix this ?

Body:
The accepted answer provides the semantics on how to increase the limit, but as @voltrevo pointed out that warning is there for a reason and your code probably has a bug.

Consider the following buggy code:

//Assume Logger is a module that emits errors
var Logger = require('./Logger.js');

for (var i = 0; i < 11; i++) {
    //BUG: This will cause the warning
    //As the event listener is added in a loop
    Logger.on('error', function (err) {
        console.log('error writing log: ' + err)
    });

    Logger.writeLog('Hello');
}

Now observe the correct way of adding the listener:

//Good: event listener is not in a loop
Logger.on('error', function (err) {
    console.log('error writing log: ' + err)
});

for (var i = 0; i < 11; i++) {
    Logger.writeLog('Hello');
}

Search for similar issues in your code before changing the maxListeners (which is explained in other answers)


问:
How to Divide Control Class into Implementation vs. Public Interface?
I've created an MFC control class, which I derived from CWnd.

The control is written from scratch and does not use any child controls. This single class implements all the control logic, including state maintenance, painting, responding to events, etc.

In addition, I need a more "public" interface to be used by the code that uses the control. Ideally, it seems like this would be a simpler class with a much simpler interface. However, having two MFC classes associated with the same Window seems to cause all sorts of problems, or is not even possible.

I'm not really sure the best way to approach this. I'm interested in thoughts on how best to provide a simple interface class to a control like this.

Note that the control is not precompiled into a library or anything. It will be compiled as part of the application.

答:
The MFC interfaces are simple because they don't actually implement the class, they just wrap the public API (C & WM) to make your coding easier in C++.

For instance you could sendMessage hwnd WM_SetText to the edit field, or use CEdit(hwnd).setText() to do the same.

2 Classes is the go I think,
You could make the interface class the parent of the implementation, or perhaps go for a PIMPL model to join the interface with the implementation.

ContentLicense: CC BY-SA 2.5


问:
Load Balancing micro services using Spring cloud Netflix OSS
I have a microservice built using Spring Boot and Netflix OSS. I have used Central config server, Eureka and Zuul. Because of scalability multiple instances of the services is running on different port. All the instances are registered in Eureka but requests are going to only last registered server.

How to load balance services. Should I use ribbon in Zuul to load balance? Please let me know how to achieve load balancing on same service running on multiple instances.

If there is a code change required a snippet then please post a code snippet as well.

Application Config

```<code>spring.application.name=book-service
server.port=0

eureka.client.region = default
eureka.client.registryFetchIntervalSeconds = 5
eureka.client.serviceUrl.defaultZone=http://discUser:discPassword@localhost:10082/eureka/

#eureka.instance.metadataMap.instanceId=${spring.application.name}:${spring.application.instance_id:${random.value}}
eureka.instance.instanceId=${spring.application.name}:${spring.application.instance_id:${random.value}}
eureka.instance.leaseRenewalIntervalInSeconds=5
eureka.instance.leaseExpirationDurationInSeconds=5
</code>```

Eureka Config

```<code>spring.application.name=discovery
server.port=10082

eureka.instance.hostname=localhost

eureka.client.serviceUrl.defaultZone=http://discUser:discPassword@localhost:10082/eureka/
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false

spring.session.store-type=hash-map
</code>```

ZUUL Config

```<code>spring.application.name=gateway
server.port=10080

eureka.client.region = default
eureka.client.registryFetchIntervalSeconds = 5

management.security.sessions=always

zuul.routes.book-service.path=/book-service/**
zuul.routes.book-service.sensitive-headers=Set-Cookie,Authorization
hystrix.command.book-service.execution.isolation.thread.timeoutInMilliseconds=600000

#zuul.routes.rating-service.path=/rating-service/**
#zuul.routes.rating-service.sensitive-headers=Set-Cookie,Authorization
#hystrix.command.rating-service.execution.isolation.thread.timeoutInMilliseconds=600000

zuul.routes.discovery.path=/discovery/**
zuul.routes.discovery.sensitive-headers=Set-Cookie,Authorization
zuul.routes.discovery.url=http://localhost:8082
hystrix.command.discovery.execution.isolation.thread.timeoutInMilliseconds=600000

logging.level.org.springframework.web.=debug
logging.level.org.springframework.security=debug
logging.level.org.springframework.cloud.netflix.zuul=debug

spring.session.store-type=hash-map
</code>```

答:
Registering application properly with Eureka will do the trick.

Below entries will uniquely register services with Eureka.

```<code>#eureka.instance.metadataMap.instanceId=${spring.application.name}:${spring.application.instance_id:${random.value}}
eureka.instance.instanceId=${spring.application.name}:${spring.application.instance_id:${random.value}}
</code>```

Body:
I have a microservice built using Spring Boot and Netflix OSS. I have used Central config server, Eureka and Zuul. Because of scalability multiple instances of the services is running on different port. All the instances are registered in Eureka but requests are going to only last registered server.

How to load balance services. Should I use ribbon in Zuul to load balance? Please let me know how to achieve load balancing on same service running on multiple instances.

If there is a code change required a snippet then please post a code snippet as well.

Application Config

spring.application.name=book-service
server.port=0

eureka.client.region = default
eureka.client.registryFetchIntervalSeconds = 5
eureka.client.serviceUrl.defaultZone=http://discUser:discPassword@localhost:10082/eureka/

#eureka.instance.metadataMap.instanceId=${spring.application.name}:${spring.application.instance_id:${random.value}}
eureka.instance.instanceId=${spring.application.name}:${spring.application.instance_id:${random.value}}
eureka.instance.leaseRenewalIntervalInSeconds=5
eureka.instance.leaseExpirationDurationInSeconds=5

Eureka Config

spring.application.name=discovery
server.port=10082

eureka.instance.hostname=localhost

eureka.client.serviceUrl.defaultZone=http://discUser:discPassword@localhost:10082/eureka/
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false

spring.session.store-type=hash-map

ZUUL Config

spring.application.name=gateway
server.port=10080

eureka.client.region = default
eureka.client.registryFetchIntervalSeconds = 5

management.security.sessions=always

zuul.routes.book-service.path=/book-service/**
zuul.routes.book-service.sensitive-headers=Set-Cookie,Authorization
hystrix.command.book-service.execution.isolation.thread.timeoutInMilliseconds=600000

#zuul.routes.rating-service.path=/rating-service/**
#zuul.routes.rating-service.sensitive-headers=Set-Cookie,Authorization
#hystrix.command.rating-service.execution.isolation.thread.timeoutInMilliseconds=600000

zuul.routes.discovery.path=/discovery/**
zuul.routes.discovery.sensitive-headers=Set-Cookie,Authorization
zuul.routes.discovery.url=http://localhost:8082
hystrix.command.discovery.execution.isolation.thread.timeoutInMilliseconds=600000

logging.level.org.springframework.web.=debug
logging.level.org.springframework.security=debug
logging.level.org.springframework.cloud.netflix.zuul=debug

spring.session.store-type=hash-map

Body:
Registering application properly with Eureka will do the trick.

Below entries will uniquely register services with Eureka.

#eureka.instance.metadataMap.instanceId=${spring.application.name}:${spring.application.instance_id:${random.value}}
eureka.instance.instanceId=${spring.application.name}:${spring.application.instance_id:${random.value}}


问:
mysqli search like only works with 1 parameter
I'm trying to do a mysqli search like query to search based on first and last name. When I type the first and last name into the search, I get no results. However, when I type just the first name or just the last name, I get results.

Here's my code:

```<code><?php
if (isset($_POST['search'])) {
$name = $_POST['search'];
$sql = "SELECT * FROM users WHERE fname LIKE '%$name%' OR lname LIKE '%$name%'";
$res = mysqli_query($conn, $sql);

}
while ($row = mysqli_fetch_assoc($res)) {
    $fname = $row['fname'];
    $lname = $row['lname'];
    $city = $row['city'];
    $state = $row['state'];
    $id = $row['id'];
    $url = '<a href ="profile/?id='.$id.'">';
    if ($id !== ($_SESSION['id'])){
    $pic = "SELECT profilephotopatch FROM users WHERE id = '$id'";
    $res = mysqli_query($conn, $pic);
    $row = mysqli_fetch_assoc($res);
    $picloc = $row['profilephotopatch'];
    $displaypic = '<div id="userphoto"><img src="../'.$picloc. '"style="width: 100%;max-height: 100%"></div>';
    $output = $displaypic. $url. '<div id="name">'. $fname. ' '. $lname. ' '. $city. $state. '</a></div><br>';
 echo ($output);
}
 }
 ?>
</code>```

Thanks in advance for the help!

答:
Here, if I understand correctly try this explode valeu from input field</p>

```<code>$search= explode(" ",$_POST['search']);
$name = $search[0];
$surname = $search[1];
$sql = "SELECT * FROM users WHERE fname LIKE '%$name%' OR lname LIKE '%$surname %'";
</code>```

Body:
I'm trying to do a mysqli search like query to search based on first and last name. When I type the first and last name into the search, I get no results. However, when I type just the first name or just the last name, I get results.

Here's my code:

<?php
if (isset($_POST['search'])) {
$name = $_POST['search'];
$sql = "SELECT * FROM users WHERE fname LIKE '%$name%' OR lname LIKE '%$name%'";
$res = mysqli_query($conn, $sql);

}
while ($row = mysqli_fetch_assoc($res)) {
    $fname = $row['fname'];
    $lname = $row['lname'];
    $city = $row['city'];
    $state = $row['state'];
    $id = $row['id'];
    $url = '';
    if ($id !== ($_SESSION['id'])){
    $pic = "SELECT profilephotopatch FROM users WHERE id = '$id'";
    $res = mysqli_query($conn, $pic);
    $row = mysqli_fetch_assoc($res);
    $picloc = $row['profilephotopatch'];
    $displaypic = '

';
    $output = $displaypic. $url. '
'. $fname. ' '. $lname. ' '. $city. $state. '

';
 echo ($output);
}
 }
 ?>

Thanks in advance for the help!

Body:
Here, if I understand correctly try this explode valeu from input field

$search= explode(" ",$_POST['search']);
$name = $search[0];
$surname = $search[1];
$sql = "SELECT * FROM users WHERE fname LIKE '%$name%' OR lname LIKE '%$surname %'";


问:
How to speed up the following python3 code?
So i'm trying to parse a huge file and the code below is taking too long to parse. The File is 2gb in size. I'm hoping some can help me speed it up.

```<code>import os, shlex

def extractLinkField(inDir, outDir):
    fileList = os.listdir(inDir)
    links = set()

    for File in fileList:
        print(File)
        with open(os.path.join(inDir, File), encoding="utf8") as inFile:
            for line in inFile:
                try:
                    links.add(shlex.split(line)[2])
                except Exception:
                    continue

        outFile = open(os.path.join(outDir, 'extractedLinks.txt'), 'a+', encoding="utf8")
        for link in list(links):
            outFile.write(link + '\n')
        outFile.close()

Path = os.path.join(os.getcwd(), 'logs')
extractLinkField(Path, os.getcwd())
</code>```

File format is as follows:

```<code>90 "m  z pd gk y xr   vo" "n l v   ogtc  dj wzb" "d  zi  pfgyo b tmhek" "df qu  venr ls hzw j"
82 "p  wgd lv f kt eb uq" " ij   cw  v a r y qp" "  pf qdlcgm jz  os y" "f xm   n  cr  ublzig"
89 "c  pgib  a   ost whk" "ria m h  fvcb  es  z" "qzoy g xbr      makc" "ms    lqc v  ektb w "
66 "zxm pe hb  vi   dj  " "rg  ebfwp y  zv oakm" "b nut ko je  m  crsh" " imsxtzfw  g ka j l "
2 "uyhnpt  l dj qak    " "o hned j  pqub t a  " "v  hlyc   afwi sgr p" "h wtvi g o  nc sujqx"
17 "apo ufliz  qctbd xh " "k  lxgbrcwzf mnhtq p" "z    gk   m   rsbu l" "  ds  m au w cior   "
9 "  h t  ac  jpn ok mz" "aty rs w box vk zefp" "nm fbc x egt  zruap " "xg  oi j z wyf v dqp"
82 "xs q  ve     k oi c " " z lfa  dwiprxb ku g" "kua p  f  b oqz jrt " "   t wlvy d po qrx e"
51 "cx   iq wuvhb gkmo y" " u p yx    bv mjz  r" "oatc wuxd yfgjs  ri " "vbg  w     h ife myl"
91 "cdqkp rn  u ow   h f" "ko rt y c eis d q jl" "  lv fe r zpju yw   " "  wz  vtxa  jn lg  s"
83 "bts   dl kjycre ozv " " k  i q m r ypsu lh " "pr exw sznqa  yvu i " "  uq   tzk nomrx  e "
</code>```

Please note that the strings in the file wrapped by the quotes should not be split and must be parsed out as whole (that is still  wrapped in the quotes)

答:
The culprit is, obviously, shlex.split(). It's quite an expensive operation (creates a whole new object with a lot of boilerplate for each split), so if your data follows the format presented you can try parsing your data manually.

So, here's a method that performs the same way on your sample data as shlex.split():

```<code>def manual_split(data):
    data = data.strip()  # clear artifacts
    tokens = []
    head = 0
    open_quote = False
    while True:
        if open_quote:
            quote = data.find('"', head)
            if quote == -1:  # this should not happen, no matching quotes
                break
            tokens.append(data[head:quote])
            head = quote + 1
            open_quote = False
        else:
            space = data.find(' ', head)
            quote = data.find('"', head)
            if space == -1 and quote == -1:  # nothing more to split
                break
            if space < quote:
                if not tokens or space - head > 1:
                    tokens.append(data[head:space])
                head = space + 1
                open_quote = False
            else:
                open_quote = True
                head = quote + 1
    if head < len(data):  # add leftovers, if any, as the last token
        tokens.append(data[head:])
    return tokens
</code>```

Compared to shlex.split(), running over the same sample data (including the loop) here are some times for you:

```<code>shlex.split:  10,000 loops: 11.51 s, per loop: 1.151 ms
manual_split: 10,000 loops: 0.951 s, per loop: 95.11 µs
</code>```

So, more than 12 times faster. But we can do better... The problem with this approach is that it has plenty of slow str.find() calls (although going character by character would be even slower) and string shuffling on the Python side so the fast C side doesn't get the chance to do its magic. If you were to implement this in C (with a few optimizations) and load it as a module it would be blazingly fast, but alas...

So, I thought regex might do it faster given that it executes mostly on the C side of things, and even if you give it more complex rules it should be able to outperform pure Python string searching & manipulation over large enough data. So, the next candidate:

```<code>import re

FIELDS_PATTERN = re.compile(r"(?:\"(.*?)\"|(\S+))")

def regex_split(data):
    return [x[0] or x[1] for x in FIELDS_PATTERN.findall(data)]
</code>```

And now we have the final benchmark:

```<code>shlex.split:  10,000 loops: 11.51 s, per loop: 1.151 ms
manual_split: 10,000 loops: 0.951 s, per loop: 95.11 µs
regex_split:  10,000 loops: 0.482 s, per loop: 48.16 µs
</code>```

Yes, the regex one is almost 24x faster than shlex.split()! And they all produce the same split result for your test data.

BUT before you jump in and kick out shlex, you need to thoroughly test both of these to make sure they fit your data - for example, they don't recognize escaped quotes or special POSIX unraveling of quoted strings so if you have such cases in your data you'll have to take that into account.

Also, unrelated, if you want to add a tiny bit of speed up, write to your output immediately instead of storing in a set just to loop through it at a later time:

```<code>with open(os.path.join(out_dir, 'extractedLinks.txt'), 'a+', encoding="utf8") as out_file:
    links = set()  # temp store to ensure uniqueness...
    for current_file in file_list:
        with open(os.path.join(in_dir, current_file), encoding="utf8") as in_file:
            for line in in_file:
                try:
                    link = shlex.split(line)[2]  # or whatever other function
                    if link not in links:
                        links.add(link)
                        out_file.write(link + "\n")
                except Exception:
                    continue
</code>```

Under the assumption that you'll gather millions of lines in that huge input file of yours, this could shave off a second or two...

Body:
So i'm trying to parse a huge file and the code below is taking too long to parse. The File is 2gb in size. I'm hoping some can help me speed it up.

import os, shlex

def extractLinkField(inDir, outDir):
    fileList = os.listdir(inDir)
    links = set()

    for File in fileList:
        print(File)
        with open(os.path.join(inDir, File), encoding="utf8") as inFile:
            for line in inFile:
                try:
                    links.add(shlex.split(line)[2])
                except Exception:
                    continue

        outFile = open(os.path.join(outDir, 'extractedLinks.txt'), 'a+', encoding="utf8")
        for link in list(links):
            outFile.write(link + '\n')
        outFile.close()

Path = os.path.join(os.getcwd(), 'logs')
extractLinkField(Path, os.getcwd())

File format is as follows:

90 "m  z pd gk y xr   vo" "n l v   ogtc  dj wzb" "d  zi  pfgyo b tmhek" "df qu  venr ls hzw j"
82 "p  wgd lv f kt eb uq" " ij   cw  v a r y qp" "  pf qdlcgm jz  os y" "f xm   n  cr  ublzig"
89 "c  pgib  a   ost whk" "ria m h  fvcb  es  z" "qzoy g xbr      makc" "ms    lqc v  ektb w "
66 "zxm pe hb  vi   dj  " "rg  ebfwp y  zv oakm" "b nut ko je  m  crsh" " imsxtzfw  g ka j l "
2 "uyhnpt  l dj qak    " "o hned j  pqub t a  " "v  hlyc   afwi sgr p" "h wtvi g o  nc sujqx"
17 "apo ufliz  qctbd xh " "k  lxgbrcwzf mnhtq p" "z    gk   m   rsbu l" "  ds  m au w cior   "
9 "  h t  ac  jpn ok mz" "aty rs w box vk zefp" "nm fbc x egt  zruap " "xg  oi j z wyf v dqp"
82 "xs q  ve     k oi c " " z lfa  dwiprxb ku g" "kua p  f  b oqz jrt " "   t wlvy d po qrx e"
51 "cx   iq wuvhb gkmo y" " u p yx    bv mjz  r" "oatc wuxd yfgjs  ri " "vbg  w     h ife myl"
91 "cdqkp rn  u ow   h f" "ko rt y c eis d q jl" "  lv fe r zpju yw   " "  wz  vtxa  jn lg  s"
83 "bts   dl kjycre ozv " " k  i q m r ypsu lh " "pr exw sznqa  yvu i " "  uq   tzk nomrx  e "

Please note that the strings in the file wrapped by the quotes should not be split and must be parsed out as whole (that is still  wrapped in the quotes)

Body:
The culprit is, obviously, shlex.split(). It's quite an expensive operation (creates a whole new object with a lot of boilerplate for each split), so if your data follows the format presented you can try parsing your data manually.

So, here's a method that performs the same way on your sample data as shlex.split():

def manual_split(data):
    data = data.strip()  # clear artifacts
    tokens = []
    head = 0
    open_quote = False
    while True:
        if open_quote:
            quote = data.find('"', head)
            if quote == -1:  # this should not happen, no matching quotes
                break
            tokens.append(data[head:quote])
            head = quote + 1
            open_quote = False
        else:
            space = data.find(' ', head)
            quote = data.find('"', head)
            if space == -1 and quote == -1:  # nothing more to split
                break
            if space < quote:
                if not tokens or space - head > 1:
                    tokens.append(data[head:space])
                head = space + 1
                open_quote = False
            else:
                open_quote = True
                head = quote + 1
    if head < len(data):  # add leftovers, if any, as the last token
        tokens.append(data[head:])
    return tokens

Compared to shlex.split(), running over the same sample data (including the loop) here are some times for you:

shlex.split:  10,000 loops: 11.51 s, per loop: 1.151 ms
manual_split: 10,000 loops: 0.951 s, per loop: 95.11 µs

So, more than 12 times faster. But we can do better... The problem with this approach is that it has plenty of slow str.find() calls (although going character by character would be even slower) and string shuffling on the Python side so the fast C side doesn't get the chance to do its magic. If you were to implement this in C (with a few optimizations) and load it as a module it would be blazingly fast, but alas...

So, I thought regex might do it faster given that it executes mostly on the C side of things, and even if you give it more complex rules it should be able to outperform pure Python string searching & manipulation over large enough data. So, the next candidate:

import re

FIELDS_PATTERN = re.compile(r"(?:\"(.*?)\"|(\S+))")

def regex_split(data):
    return [x[0] or x[1] for x in FIELDS_PATTERN.findall(data)]

And now we have the final benchmark:

shlex.split:  10,000 loops: 11.51 s, per loop: 1.151 ms
manual_split: 10,000 loops: 0.951 s, per loop: 95.11 µs
regex_split:  10,000 loops: 0.482 s, per loop: 48.16 µs

Yes, the regex one is almost 24x faster than shlex.split()! And they all produce the same split result for your test data.

BUT before you jump in and kick out shlex, you need to thoroughly test both of these to make sure they fit your data - for example, they don't recognize escaped quotes or special POSIX unraveling of quoted strings so if you have such cases in your data you'll have to take that into account.

Also, unrelated, if you want to add a tiny bit of speed up, write to your output immediately instead of storing in a set just to loop through it at a later time:

with open(os.path.join(out_dir, 'extractedLinks.txt'), 'a+', encoding="utf8") as out_file:
    links = set()  # temp store to ensure uniqueness...
    for current_file in file_list:
        with open(os.path.join(in_dir, current_file), encoding="utf8") as in_file:
            for line in in_file:
                try:
                    link = shlex.split(line)[2]  # or whatever other function
                    if link not in links:
                        links.add(link)
                        out_file.write(link + "\n")
                except Exception:
                    continue

Under the assumption that you'll gather millions of lines in that huge input file of yours, this could shave off a second or two...


问:
Circular iterator / generator for list of custom class items
Say I have a custom class:

```<code>public class CustomClass {
    private String name;
    private String data;

    public CustomClass(String name, String data) {
        this.name = name;
        this.data = data;
    }
}
</code>```

I also have a list of my custom class objects:

```<code>CustomClass[] list = new CustomClass[] {
    new CustomClass("Item 1", "data"),
    new CustomClass("Item 2", "data"),
    new CustomClass("Item 3", "data"),
    new CustomClass("Item 4", "data"),
    new CustomClass("Item 5", "data"),
};
</code>```

How can I create an iterator (or, rather, generator) to iterate through the list K times (K > list.length) giving me next element every time?

I prefer an "inline" solution (without creating any new classes).

Say, I need to get my CustomClass list items one after another K = 7 times. The solution should retrieve me following CustomClass objects:

Item 1

Item 2

Item 3

Item 4

Item 5

Item 1

Item 2

答:
Use the index modulo array length:

```<code>for( int i = 0; i < K; i++ ) {
   list[ i % list.length ];
}
</code>```

When it comes to first index (here it's named i) greater or equal to list length, it will "reset" it, because operation modulo (%) returns the remainder after integer division.

The solution does not introduce any classes.

Body:
Say I have a custom class:

public class CustomClass {
    private String name;
    private String data;

    public CustomClass(String name, String data) {
        this.name = name;
        this.data = data;
    }
}

I also have a list of my custom class objects:

CustomClass[] list = new CustomClass[] {
    new CustomClass("Item 1", "data"),
    new CustomClass("Item 2", "data"),
    new CustomClass("Item 3", "data"),
    new CustomClass("Item 4", "data"),
    new CustomClass("Item 5", "data"),
};

How can I create an iterator (or, rather, generator) to iterate through the list K times (K > list.length) giving me next element every time?

I prefer an "inline" solution (without creating any new classes).

Say, I need to get my CustomClass list items one after another K = 7 times. The solution should retrieve me following CustomClass objects:

Item 1

Item 2

Item 3

Item 4

Item 5

Item 1

Item 2

Body:
Use the index modulo array length:

for( int i = 0; i < K; i++ ) {
   list[ i % list.length ];
}

When it comes to first index (here it's named i) greater or equal to list length, it will "reset" it, because operation modulo (%) returns the remainder after integer division.

The solution does not introduce any classes.


问:
How to Restrict Private Content?
I have a website that has some private content that should only be viewable after the user has paid. I am thinking about using something like Google Checkout (other recommendations are fine too), but from a coding standpoint, how would you go about securely flagging a user as 'paid' and give them access to the private pages? Google checkout seems to be able to accept payments, but how do I know the payment went through programmatically?

Is this something that wordpress or drupal is good for?

答: to expand on the previous answer. you will want to have your customers create an account before you process their payment, and then set their account privileges accordingly on their payment. At that point you can control multiple levels of access through your own user-management system.</p>

Title: How to Restrict Private Content?


问:
Interface with friend operator<<: why can't it link?
I have created a small interface for objects that can be represented in text mode using the operator<< like so:

```<code>// ICliObject.h

class ICliObject
{
public:

    ~ICliObject() = default;
    friend std::ostream& operator<<(std::ostream& p_stream, const ICliObject& p_cliUiObject);

protected:
    virtual void print(std::ostream& p_stream) const = 0;

};

std::ostream& operator<<(std::ostream& p_stream, const ICliObject& p_cliUiObject)
{
    p_cliUiObject.print(p_stream);

    return p_stream;
}
</code>```

When I inherit from this interface and try to build, the compilation works but I get the following linking error: In blablabla.cpp: multiple definition of operator<<(std::ostream& p_stream, const ICliObject& p_cliUiObject)

In all derived classes, I have took care of not re-defining/declaring the operator. The only way I can solve my problem is in inlining the operator in ICliObject.h. What is going on?

Note: I use GCC on Ubuntu.

答:
This has nothing to do with friend or with operator<< or with inheritance.

Like any function (or object) defined at namespace scope, if you do so multiple times in your program (including by having it in a header file that you #include in multiple translation units), you will get this error.

And, like in all those other cases, the solution is to either move the implementation to a "source file", or stick the inline keyword on it (which you already suggested, but it's literally the solution so I don't know why it's not acceptable).

Body:
I have created a small interface for objects that can be represented in text mode using the operator<< like so:

// ICliObject.h

class ICliObject
{
public:

    ~ICliObject() = default;
    friend std::ostream& operator<<(std::ostream& p_stream, const ICliObject& p_cliUiObject);

protected:
    virtual void print(std::ostream& p_stream) const = 0;

};

std::ostream& operator<<(std::ostream& p_stream, const ICliObject& p_cliUiObject)
{
    p_cliUiObject.print(p_stream);

    return p_stream;
}

When I inherit from this interface and try to build, the compilation works but I get the following linking error: In blablabla.cpp: multiple definition of operator<<(std::ostream& p_stream, const ICliObject& p_cliUiObject)

In all derived classes, I have took care of not re-defining/declaring the operator. The only way I can solve my problem is in inlining the operator in ICliObject.h. What is going on?

Note: I use GCC on Ubuntu.


问:
with c_f_pointer is fortran array reshape in-place or not
I have a question related to one asked some years ago on Intel Developer Forum about the in-place reshaping of an array.

In short, the answer was that an array of a certain rank can be allocated, and a pointer created that refers to the same memory location (i.e. in-place), but with a different rank, e.g.:

```<code>use, intrinsic :: ISO_C_BINDING
integer, allocatable, target :: rank1_array(:)
integer, pointer :: rank3_array(:,:,:)
integer :: i

! Allocate rank1_array
allocate(rank1_array(24))

! Created rank3_pointer to rank1_array
call C_F_POINTER (C_LOC(rank1_array), rank3_array, [3,2,4])

! Now rank3_array is the same data as rank1_array, but a 3-dimension array with bounds (3,2,4)
</code>```

My question is now that if I deallocate the original array rank1_array, why is it that the pointer rank3_array is still associated, and can be used without a problem (seemingly). Thus, if I append the code segment from above with:

```<code>! initialise the allocated array
rank1_array = [(i, i=1,24)]

! then deallocate it
deallocate(rank1_array)

! now do stuff with the pointer
print *, associated(rank3_array)
rank3_array(2,2,1) = 99
print *, rank3_array
</code>```

Compiling and running this program gives me the output

```<code>gfortran -Wall my_reshape.f90 -o my_reshape
./my_reshape
T
1 2 3 4 99 6 7 ... 23 24
</code>```

If the memory of rank1_array was deallocated, why does rank3_array still function unless it is a copy of the original? Was the initial reshape then in-place or not? Would be very grateful if someone could explain this behaviour to me.

I'm using gfortran 6.1.0 of that is of interest.

Edit/Update:

As the accepted answer by @francescalus indicates, the real issue here is how I (incorrectly!) handled pointers in general and not the in-place reshape with C_F_POINTER in particular. The strange behaviour I saw was just a result of undefined behaviour due to non-compliant fortran code I wrote. Based on @francescalus answer and comments, I did more reading online and thought it might be useful to give a link to a relevant section of a Fortran Reference Manual that very clearly explains how pointers and allocatable arrays should be handled.

答:
That c_f_pointer is used instead of "normal" pointer assignment is not relevant to the problem, nor is the changing shape.

After the call to c_f_pointer the pointer rank3_array is pointer associated with the target rank1_array.  There is no copy made.

When rank1_array is deallocated in the statement

```<code> deallocate(rank1_array)
</code>```

this has an effect on the pointer which has rank1_array as a target.  In particular, the pointer association status of rank3_array becomes undefined.  (Whenever a pointer's target is deallocated except through the pointer, the pointer's association status becomes undefined.)

With the pointer of undefined association status the next part

```<code>print *, associated(rank3_array)
</code>```

is not allowed.  At this point the program is not a Fortran-compliant program (and the compiler needn't detect that) and the processor is allowed to print .TRUE. here if it wants to.

Equally, with

```<code>rank3_array(2,2,1) = 99
print *, rank3_array
</code>```

rank3_array itself is undefined and those references are also not allowed.  Again, any effect is available to the compiler.

Now, as in another answer on a similar topic: just because rank1_array has been deallocated that doesn't mean that the memory gets purged.  Probably all that happens is some array descriptor for the first array has its status changed.  It isn't the compiler's responsibility to do the same to all related pointers/descriptors.  (And so the pointer's descriptor may indeed still say "associated".)

It's important to note, though: it may look like it's working, but I wouldn't advise betting your job on it.

Body:
I have a question related to one asked some years ago on Intel Developer Forum about the in-place reshaping of an array.

In short, the answer was that an array of a certain rank can be allocated, and a pointer created that refers to the same memory location (i.e. in-place), but with a different rank, e.g.:

use, intrinsic :: ISO_C_BINDING
integer, allocatable, target :: rank1_array(:)
integer, pointer :: rank3_array(:,:,:)
integer :: i

! Allocate rank1_array
allocate(rank1_array(24))

! Created rank3_pointer to rank1_array
call C_F_POINTER (C_LOC(rank1_array), rank3_array, [3,2,4])

! Now rank3_array is the same data as rank1_array, but a 3-dimension array with bounds (3,2,4)

My question is now that if I deallocate the original array rank1_array, why is it that the pointer rank3_array is still associated, and can be used without a problem (seemingly). Thus, if I append the code segment from above with:

! initialise the allocated array
rank1_array = [(i, i=1,24)]

! then deallocate it
deallocate(rank1_array)

! now do stuff with the pointer
print *, associated(rank3_array)
rank3_array(2,2,1) = 99
print *, rank3_array

Compiling and running this program gives me the output

gfortran -Wall my_reshape.f90 -o my_reshape
./my_reshape
T
1 2 3 4 99 6 7 ... 23 24

If the memory of rank1_array was deallocated, why does rank3_array still function unless it is a copy of the original? Was the initial reshape then in-place or not? Would be very grateful if someone could explain this behaviour to me.

I'm using gfortran 6.1.0 of that is of interest.

Edit/Update:

As the accepted answer by @francescalus indicates, the real issue here is how I (incorrectly!) handled pointers in general and not the in-place reshape with C_F_POINTER in particular. The strange behaviour I saw was just a result of undefined behaviour due to non-compliant fortran code I wrote. Based on @francescalus answer and comments, I did more reading online and thought it might be useful to give a link to a relevant section of a Fortran Reference Manual that very clearly explains how pointers and allocatable arrays should be handled.

Body:
That c_f_pointer is used instead of "normal" pointer assignment is not relevant to the problem, nor is the changing shape.

After the call to c_f_pointer the pointer rank3_array is pointer associated with the target rank1_array.  There is no copy made.

When rank1_array is deallocated in the statement

 deallocate(rank1_array)

this has an effect on the pointer which has rank1_array as a target.  In particular, the pointer association status of rank3_array becomes undefined.  (Whenever a pointer's target is deallocated except through the pointer, the pointer's association status becomes undefined.)

With the pointer of undefined association status the next part

print *, associated(rank3_array)

is not allowed.  At this point the program is not a Fortran-compliant program (and the compiler needn't detect that) and the processor is allowed to print .TRUE. here if it wants to.

Equally, with

rank3_array(2,2,1) = 99
print *, rank3_array

rank3_array itself is undefined and those references are also not allowed.  Again, any effect is available to the compiler.

Now, as in another answer on a similar topic: just because rank1_array has been deallocated that doesn't mean that the memory gets purged.  Probably all that happens is some array descriptor for the first array has its status changed.  It isn't the compiler's responsibility to do the same to all related pointers/descriptors.  (And so the pointer's descriptor may indeed still say "associated".)

It's important to note, though: it may look like it's working, but I wouldn't advise betting your job on it.


问:
How to provide an initial plotting platform to add additional plots in R?
I'm trying to use a for loop to draw 3 side by side curves in R but without getting any error message nothing shows?

I suspect something should provide an initial plotting platform for the first curve, and then the second and the third plots can be added. Can the initial plotting platform be plot.new() for example?

Note: I'm definitely trying to avoid using long if else statements as a solution.

Here is my R code:

```<code>for(i in 1:3){

  p = c(.1, .5, .9)[i]
col = c("red3", "green3", "blue")[i]

curve( dbinom(x, size = 100, prob = p), add = T, ty = "h", xlim = c(0, 100),
   col = col, xlab = "Number of Agreements", ylab = "Probability", las = 1 )

}
</code>```

答:
What worked for me was the following:</p>

```<code>for(i in 1:3){

  p = c(.1, .5, .9)[i]
col = c("red3", "green3", "blue")[i]

curve( dbinom(x, size = 100, prob = p), 0, 100, add = ifelse(i > 1, T, F), ty = "h", xlim = c(0, 100),
   col = col, ylab = "Probability", xlab = "Number of Agreements", las = 1)
}
</code>```

Body:
I'm trying to use a for loop to draw 3 side by side curves in R but without getting any error message nothing shows?

I suspect something should provide an initial plotting platform for the first curve, and then the second and the third plots can be added. Can the initial plotting platform be plot.new() for example?

Note: I'm definitely trying to avoid using long if else statements as a solution.

Here is my R code:

for(i in 1:3){

  p = c(.1, .5, .9)[i]
col = c("red3", "green3", "blue")[i]

curve( dbinom(x, size = 100, prob = p), add = T, ty = "h", xlim = c(0, 100),
   col = col, xlab = "Number of Agreements", ylab = "Probability", las = 1 )

}

Body:
What worked for me was the following:

for(i in 1:3){

  p = c(.1, .5, .9)[i]
col = c("red3", "green3", "blue")[i]

curve( dbinom(x, size = 100, prob = p), 0, 100, add = ifelse(i > 1, T, F), ty = "h", xlim = c(0, 100),
   col = col, ylab = "Probability", xlab = "Number of Agreements", las = 1)
}


问:
abbr several times with one tag
I'm writing a walk-through, and I'd like the reader to be able to hover over a word from anywhere within the script and get the definition, but I'd like to only define the abbr once.  Is there a way in html or css that I can do this?</p>

答:
One way you can accomplish this is to use a custom tooltip with a pseudo element.

First, in your HTML, you wrap the words you want to define in a span (or maybe an  or whatever):

```<code><p>This is a word I want to <span class="tooltip">define</span>.</p>
</code>```

You can then give the tooltips a second class that you can use to set their content. This way, you can wrap all the words you want to define in your HTML but control their content from one central place (your stylesheet) and not have to modify the HTML if a definition needs tweaking.

```<code><p>This is a word I want to <span class="tooltip define">define</span>.</p>
</code>```

In your stylesheet, you'd set the basic styles for the pseudo element that goes with .tooltip, then do something like this to set the particular content using the second class:

```<code>.tooltip.define::before {
  content: 'determine or identify the essential qualities or meaning of';
}
</code>```

The trickiest part of this is really getting the style of the tooltip to something you like.

In the example below, I have set white-space: nowrap in lieu of a minimum width on the pseudo element. Otherwise, you'll find that the text wraps at a very small width. This works well with all relatively short definitions, but if you have some definitions that would require a lot of text and others that would have one- or two-word definitions, you may need to also include the width of the pseudo element in the styles that goes along with your second class (that you use to specify the content) so as to avoid a situation where you have huge containers for tiny content or tons of word wrapping for long definitions.

For example:

```<code>.tooltip.longtext {
  content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam interdum magna sit amet magna condimentum, id gravida tellus luctus. Nullam posuere eget lacus sit amet pulvinar.';
  min-width: 300px;
}
.tooltip.shorttext {
  content: 'Lorem ipsum';
  min-width: 0;
}
</code>```

span {
  position: relative;
  color: blue;
}
.tooltip::before {
  display: block;
  position: absolute;
  z-index: -1;
  top: -100%;
  left: -50%;
  padding: 2px 5px;
  white-space: nowrap;
  font-size: 12px;
  text-align: center;
  background: #565656;
  color: white;
  visibility: hidden;
}
.tooltip:hover {
  cursor: pointer;
}
.tooltip:hover::before {
  visibility: visible;
  z-index: 1;
}
.tooltip.lots::before {
  content: 'many, several';
}
.tooltip.words::before {
  content: 'things that are said';
}
.tooltip.going::before {
  content: 'taking a certain course';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p style="margin-top: 30px;">This is a very long paragraph that has <span class="tooltip lots">lots</span> and <span class="tooltip lots">lots</span> of <span class="tooltip words">words</span> you want to define, and it just keeps <span class="tooltip going">going</span> and <span class="tooltip going">going</span>, and some of the <span class="tooltip words">words</span> are the same, and you don't want to have to define them more than once.</p></code>```

Title: abbr several times with one tag

Body:
One way you can accomplish this is to use a custom tooltip with a pseudo element.

First, in your HTML, you wrap the words you want to define in a span (or maybe an <a> or whatever):

<p>This is a word I want to <span class="tooltip">define</span>.</p>

You can then give the tooltips a second class that you can use to set their content. This way, you can wrap all the words you want to define in your HTML but control their content from one central place (your stylesheet) and not have to modify the HTML if a definition needs tweaking.

<p>This is a word I want to <span class="tooltip define">define</span>.</p>

In your stylesheet, you'd set the basic styles for the pseudo element that goes with .tooltip, then do something like this to set the particular content using the second class:

.tooltip.define::before {
  content: 'determine or identify the essential qualities or meaning of';
}

The trickiest part of this is really getting the style of the tooltip to something you like.

In the example below, I have set white-space: nowrap in lieu of a minimum width on the pseudo element. Otherwise, you'll find that the text wraps at a very small width. This works well with all relatively short definitions, but if you have some definitions that would require a lot of text and others that would have one- or two-word definitions, you may need to also include the width of the pseudo element in the styles that goes along with your second class (that you use to specify the content) so as to avoid a situation where you have huge containers for tiny content or tons of word wrapping for long definitions.

For example:

.tooltip.longtext {
  content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam interdum magna sit amet magna condimentum, id gravida tellus luctus. Nullam posuere eget lacus sit amet pulvinar.';
  min-width: 300px;
}
.tooltip.shorttext {
  content: 'Lorem ipsum';
  min-width: 0;
}

span {
  position: relative;
  color: blue;
}
.tooltip::before {
  display: block;
  position: absolute;
  z-index: -1;
  top: -100%;
  left: -50%;
  padding: 2px 5px;
  white-space: nowrap;
  font-size: 12px;
  text-align: center;
  background: #565656;
  color: white;
  visibility: hidden;
}
.tooltip:hover {
  cursor: pointer;
}
.tooltip:hover::before {
  visibility: visible;
  z-index: 1;
}
.tooltip.lots::before {
  content: 'many, several';
}
.tooltip.words::before {
  content: 'things that are said';
}
.tooltip.going::before {
  content: 'taking a certain course';
}

<p style="margin-top: 30px;">This is a very long paragraph that has <span class="tooltip lots">lots</span> and <span class="tooltip lots">lots</span> of <span class="tooltip words">words</span> you want to define, and it just keeps <span class="tooltip going">going</span> and <span class="tooltip going">going</span>, and some of the <span class="tooltip words">words</span> are the same, and you don't want to have to define them more than once.</p>


问:
Why is this RewriteRule altering QUERY_STRING, but leaving REQUEST_URI untouched?
I have a copy of Concrete5, a PHP-based CMS, running on example.com.

Concrete5 comes with the following basic instructions for pretty URLs (redirecting all URLs to a central index.php)

```<code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} !^/c5.7
RewriteRule ^.*$ c5.7/$0 [L]    # Concrete5 is running in the c5.7/ subdirectory
</IfModule>
</code>```

Pretty straightforward.

Now I have a certain set of URLs that take the form

```<code> /product/{productname}
</code>```

that I need to forward to the Concrete5 (virtual) URL

```<code>/products/details?name={productname}
</code>```

That URL is set up and works as expected when I enter it manually in the browser.

So I added a line to the htaccess file and it now looks like this:

```<code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

# New rule for products
RewriteCond %{REQUEST_URI} ^/product/
RewriteRule ^product/(.+)$ /products/details?name=$1 [QSA]

RewriteCond %{REQUEST_URI} !^/c5.7
RewriteRule ^.*$ c5.7/$0 [L]

</IfModule>
</code>```

I can confirm the RewriteRule gets triggered when I choose a random, external URL as the redirection target.

But whenever it is an internal redirect like above, what happens is, I get a 404 inside Concrete5. When I inspect what was passed to it, I see:

```<code> REQUEST_URI:  /product/my-random-product
 QUERY_STRING: name=my-random-product
</code>```

So it appears that the rule is triggered and does some rewriting, but REQUEST_URI remains unchanged!

Why?

Is it because PHP 7.1 is running via CGI?

I have tried a zillion variations and all the flags in the book, with little success.

答:
REQUEST_URI in PHP will always be the original request URI.
Because this is already explained by LSerni and SuperDuperApps, I won't elaborate.
Instead, I'm offering a quick solution: modify the REQUEST_URI and add a name parameter in PHP instead of in .htaccess.

Add the following code to the start of your Concrete5 index.php to make sure that REQUEST_URI is modified
before any Concrete5 code runs:

if(preg_match('-^/product/([^?]*)-',$_SERVER['REQUEST_URI'],$matches)){
    $_SERVER['REQUEST_URI'] = '/products/details';
    $_GET['name'] = $matches[1];
}
```

Body:
I have a copy of Concrete5, a PHP-based CMS, running on example.com.

Concrete5 comes with the following basic instructions for pretty URLs (redirecting all URLs to a central index.php)

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} !^/c5.7
RewriteRule ^.*$ c5.7/$0 [L]    # Concrete5 is running in the c5.7/ subdirectory
</IfModule>

Pretty straightforward.

Now I have a certain set of URLs that take the form

 /product/{productname}

that I need to forward to the Concrete5 (virtual) URL

/products/details?name={productname}

That URL is set up and works as expected when I enter it manually in the browser.

So I added a line to the htaccess file and it now looks like this:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

# New rule for products
RewriteCond %{REQUEST_URI} ^/product/
RewriteRule ^product/(.+)$ /products/details?name=$1 [QSA]

RewriteCond %{REQUEST_URI} !^/c5.7
RewriteRule ^.*$ c5.7/$0 [L]

</IfModule>

I can confirm the RewriteRule gets triggered when I choose a random, external URL as the redirection target.

But whenever it is an internal redirect like above, what happens is, I get a 404 inside Concrete5. When I inspect what was passed to it, I see:

 REQUEST_URI:  /product/my-random-product
 QUERY_STRING: name=my-random-product

So it appears that the rule is triggered and does some rewriting, but REQUEST_URI remains unchanged!

Why?

Is it because PHP 7.1 is running via CGI?

I have tried a zillion variations and all the flags in the book, with little success.


问:
I'm trying to make a group of cells in processing and I want to transmit data from one to the other as they get close to each other
I've got code but it won't even slightly work does anyone have any sort of an idea??
I don't need efficiency I just need some sort of idea.</p>

答:
It's hard to answer general "how do I do this" type questions. You'll have much better luck if you ask a specific "I tried X, expected Y, but got Z instead" type question instead.

But I can help in a general sense:

First off, you need to break your problem down into smaller steps and take on those steps one at a time. Can you create a simple program that just shows two hardcoded circles that change color when they get near each other? You'll have to use basic circle-circle collision detection.

You probably also want to create classes that encapsulate your data. You might have a Cell class that encapsulates the data and behavior of one cell.

When you have that working, then you can think about your overall design. You might loop over every Cell, and then find out which other Cell instances are nearby. When you have that, then you can think about transmitting data between them. You'd do this by calling a function on the instance.

Here's some pseudo-code:

```<code>for(every Cell thisCell in cells){
   for(every Cell otherCell in cells){
      if(thisCell is near otherCell){
         otherCell.setData(thisCell.data);
      }
   }
}
</code>```

That's just the general idea though. The specifics of exactly how you approach each step are up to you. If you do get stuck on a specific step, please post a MCVE in a new question, and we'll go from there. Good luck.

Body:
It's hard to answer general "how do I do this" type questions. You'll have much better luck if you ask a specific "I tried X, expected Y, but got Z instead" type question instead.

But I can help in a general sense:

First off, you need to break your problem down into smaller steps and take on those steps one at a time. Can you create a simple program that just shows two hardcoded circles that change color when they get near each other? You'll have to use basic circle-circle collision detection.

You probably also want to create classes that encapsulate your data. You might have a Cell class that encapsulates the data and behavior of one cell.

When you have that working, then you can think about your overall design. You might loop over every Cell, and then find out which other Cell instances are nearby. When you have that, then you can think about transmitting data between them. You'd do this by calling a function on the instance.

Here's some pseudo-code:

for(every Cell thisCell in cells){
   for(every Cell otherCell in cells){
      if(thisCell is near otherCell){
         otherCell.setData(thisCell.data);
      }
   }
}

That's just the general idea though. The specifics of exactly how you approach each step are up to you. If you do get stuck on a specific step, please post a MCVE in a new question, and we'll go from there. Good luck.


问:
Power Query Combine Binaries messes up data
I'm combining a number of files from folder in Power Query 2013. For some reason, it adds the names of the first 2 columns to some random rows in the last two columns, or even replaces data with other column name.

First, I thought it's due to difference in column schemas (some files didn't have the last column). I aligned all files, but the issue didn't go away.

答:
Combining binaries in Excel can cause formatting problems. To understand the problem, you'd probably need to share your files (you could remove any sensitive data, but include enough columns to reproduce the problem).

Alternatively, if you use Power BI Desktop there's a new feature for combining binary files in a safer way.


问:
Sorting API values in a table using php
I'm trying to build something like https://coinranking.com/. I plan on doing this by sorting the results from the API at http://www.coincap.io/front using the position24 value as sorting parameter.
So far, I managed to pull an ordered list with the prices, but I'd like to display the values from other objects (volume, mktcap, etc) as well in a table. Would I have to repeat this function for every object?

```<code><php?
function compare($a, $b) {
    return intval($a->position24) - intval($b->position24);
}

$json = file_get_contents('http://www.coincap.io/front');
$data = json_decode($json);
usort($data, 'compare');
foreach ($data as $item) {
    echo $item->price . "\n"<;
}
?>
</code>```

答:
You can just call it. For example like this:

```<code>echo $item->volume;
echo $item->mktcap;
</code>```

in a table that would look like this:

```<code><table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Price</th>
            <th>Market Capitalization</th>
            <th>Volume</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach($data as $row) { ?>
        <tr>
            <td><?= $row->long; ?></td>
            <td><?= $row->price; ?></td>
            <td><?= $row->mktcap; ?></td>
            <td><?= $row->volume; ?></td>
        </tr>
        <?php } ?>
    </tbody>
</table>
</code>```

Title: Sorting API values in a table using php

Body:
I'm trying to build something like https://coinranking.com/. I plan on doing this by sorting the results from the API at http://www.coincap.io/front using the position24 value as sorting parameter.
So far, I managed to pull an ordered list with the prices, but I'd like to display the values from other objects (volume, mktcap, etc) as well in a table. Would I have to repeat this function for every object?

<php?
function compare($a, $b) {
    return intval($a->position24) - intval($b->position24);
}

$json = file_get_contents('http://www.coincap.io/front');
$data = json_decode($json);
usort($data, 'compare');
foreach ($data as $item) {
    echo $item->price . "\n"<;
}
?>

Body:
You can just call it. For example like this:

echo $item->volume;
echo $item->mktcap;

in a table that would look like this:

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Price</th>
            <th>Market Capitalization</th>
            <th>Volume</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach($data as $row) { ?>
        <tr>
            <td><?= $row->long; ?></td>
            <td><?= $row->price; ?></td>
            <td><?= $row->mktcap; ?></td>
            <td><?= $row->volume; ?></td>
        </tr>
        <?php } ?>
    </tbody>
</table>


问:
IntegrityError on update_or_create
I'm getting an IntegrityError that seems like an impossibility:

```<code>ShippingAddress.objects.update_or_create(
    subscription=subscription,
    defaults=address_dict,
)
</code>```

(where "subscription" is an instance of a model related via a OneToOneField) raises the error

```<code>IntegrityError: (1062, "Duplicate entry '42' for key 'subscription_id'")
</code>```

despite subscription being the only key added to the filter. Even more strangely, neither

```<code>ShippingAddress.objects.get(
    subscription=subscription,
)
</code>```

nor

```<code>ShippingAddress.objects.filter(
    subscription=subscription,
)
</code>```

raise the same error. What could be messing up the update() call?

答: The error turned out to be because the address_dict contained an "id" key that I hadn't noticed when generating it.</p>

Title: IntegrityError on update_or_create

Body:
I'm getting an IntegrityError that seems like an impossibility:

ShippingAddress.objects.update_or_create(
    subscription=subscription,
    defaults=address_dict,
)

(where "subscription" is an instance of a model related via a OneToOneField) raises the error

IntegrityError: (1062, "Duplicate entry '42' for key 'subscription_id'")

despite subscription being the only key added to the filter. Even more strangely, neither

ShippingAddress.objects.get(
    subscription=subscription,
)

nor

ShippingAddress.objects.filter(
    subscription=subscription,
)

raise the same error. What could be messing up the update() call?


问:
Wordpress Accesspress Parallax Theme: Custom Header don't work like the Live Demo
i try to understand why my header don't work like the live demo.

The javascript which create the smooth transistion seems not working with my header..

My one page navigation jumps to far and without the smooth transition :/

The live demo: Live Demo Accesspress Parallax

Anybody know how i can fix it ?

My header(transition jumps to the section without the smooth transition and jumps to far)

答:
Are you sure you installed the theme correctly? You might have missed something.
I would recommend to check the console to see what Java Script error you are getting.