问:
slice "error using griddedInterpolant" in matlab
I'm trying to plot a slice diagram of soil volumetric data but I get this error trying to plot the slices (most of the error text comes from the hierarchy of my code as I execute the code through a Gui but the top is the most important problem):

```<code>Error using griddedInterpolant
The grid vectors do not define a grid of points that match the given values.

Error in interp3 (line 142)
            F = griddedInterpolant(X, Y, Z, V, method,extrap);

Error in slice (line 100)
    vi = interp3(x,y,z,v,xi,yi,zi,method);

Error in ANALYSE>Bouton3D_Callback (line 939)
slice(x,y,z,VOLUME_DATA,xslice,yslice,zslice,'nearest')

Error in gui_mainfcn (line 95)
        feval(varargin{:});

Error in ANALYSE (line 42)
    gui_mainfcn(gui_State, varargin{:});

Error in @(hObject,eventdata)ANALYSE('Bouton3D_Callback',hObject,eventdata,guidata(hObject))

Error while evaluating UIControl Callback
</code>```

And here is my code that's problematic (the line it points to is the last one):

```<code>function Bouton3D_Callback(hObject, eventdata, handles)
% hObject    handle to Bouton3D (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
NB_LIGNES =str2num(get(handles.nb_lignes,'string'));
NB_COLONNES = str2num(get(handles.nb_colonnes,'string'));
SENSIBILITE_AMPLITUDE_SIGNAL =1;

TEMP = dir('L1/f1.csv');
FICHIER_SIGNAL_SPECTRAL= ['L1/',TEMP.name];
TABLEAU_SIGNAL_SPECTRAL = xlsread(FICHIER_SIGNAL_SPECTRAL);
NB_FREQ = size(TABLEAU_SIGNAL_SPECTRAL,1);

FREQUENCES = TABLEAU_SIGNAL_SPECTRAL(:,2);

VOLUME_DATA = zeros(NB_LIGNES,NB_COLONNES,NB_FREQ);

for L =1:NB_LIGNES
    for C =1:NB_COLONNES
        TEMP = dir(['L',num2str(L),'/f',num2str(C),'.csv']);
        FICHIER_SIGNAL_SPECTRAL= ['L',num2str(L),'/',TEMP.name];

        TABLEAU_SIGNAL_SPECTRAL = xlsread(FICHIER_SIGNAL_SPECTRAL);

        VOLUME_DATA(L,C,:)=(TABLEAU_SIGNAL_SPECTRAL(:,3)*SENSIBILITE_AMPLITUDE_SIGNAL); % En dB

    end
end

[x,y,z] = meshgrid(1:5,1:9,FREQUENCES);
xslice = 1;
yslice = 1;
zslice = 1:FREQUENCES(end)/5:FREQUENCES(end)-1;
slice(x,y,z,VOLUME_DATA,xslice,yslice,zslice,'nearest')
colormap hsv
</code>```

答:
I tried your code and it seems to me that VOLUME_DATA has a wrong size. if I modify your code a little bit it throws no errors:

```<code>FREQUENCES = 1:6;
[x,y,z] = meshgrid(1:5,1:9,FREQUENCES);
VOLUME_DATA = x.*exp(-x.^2-y.^2-z.^2); % a function of x,y,z such that the output dimension fits the inputs dimensions
xslice = 1;
yslice = 1;
zslice = 1:FREQUENCES(end)/5:FREQUENCES(end)-1;
slice(x,y,z,VOLUME_DATA,xslice,yslice,zslice,'nearest')
colormap hsv
</code>```

or maybe try:

```<code>[x,y,z] = meshgrid(1:size(VOLUME_DATA,1),1:size(VOLUME_DATA,2),FREQUENCES);
</code>```

Body:
I'm trying to plot a slice diagram of soil volumetric data but I get this error trying to plot the slices (most of the error text comes from the hierarchy of my code as I execute the code through a Gui but the top is the most important problem):

Error using griddedInterpolant
The grid vectors do not define a grid of points that match the given values.

Error in interp3 (line 142)
            F = griddedInterpolant(X, Y, Z, V, method,extrap);

Error in slice (line 100)
    vi = interp3(x,y,z,v,xi,yi,zi,method);

Error in ANALYSE>Bouton3D_Callback (line 939)
slice(x,y,z,VOLUME_DATA,xslice,yslice,zslice,'nearest')

Error in gui_mainfcn (line 95)
        feval(varargin{:});

Error in ANALYSE (line 42)
    gui_mainfcn(gui_State, varargin{:});

Error in @(hObject,eventdata)ANALYSE('Bouton3D_Callback',hObject,eventdata,guidata(hObject))

Error while evaluating UIControl Callback

And here is my code that's problematic (the line it points to is the last one):

function Bouton3D_Callback(hObject, eventdata, handles)
% hObject    handle to Bouton3D (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
NB_LIGNES =str2num(get(handles.nb_lignes,'string'));
NB_COLONNES = str2num(get(handles.nb_colonnes,'string'));
SENSIBILITE_AMPLITUDE_SIGNAL =1;

TEMP = dir('L1/f1.csv');
FICHIER_SIGNAL_SPECTRAL= ['L1/',TEMP.name];
TABLEAU_SIGNAL_SPECTRAL = xlsread(FICHIER_SIGNAL_SPECTRAL);
NB_FREQ = size(TABLEAU_SIGNAL_SPECTRAL,1);

FREQUENCES = TABLEAU_SIGNAL_SPECTRAL(:,2);

VOLUME_DATA = zeros(NB_LIGNES,NB_COLONNES,NB_FREQ);

for L =1:NB_LIGNES
    for C =1:NB_COLONNES
        TEMP = dir(['L',num2str(L),'/f',num2str(C),'.csv']);
        FICHIER_SIGNAL_SPECTRAL= ['L',num2str(L),'/',TEMP.name];

        TABLEAU_SIGNAL_SPECTRAL = xlsread(FICHIER_SIGNAL_SPECTRAL);

        VOLUME_DATA(L,C,:)=(TABLEAU_SIGNAL_SPECTRAL(:,3)*SENSIBILITE_AMPLITUDE_SIGNAL); % En dB

    end
end

[x,y,z] = meshgrid(1:5,1:9,FREQUENCES);
xslice = 1;
yslice = 1;
zslice = 1:FREQUENCES(end)/5:FREQUENCES(end)-1;
slice(x,y,z,VOLUME_DATA,xslice,yslice,zslice,'nearest')
colormap hsv

Body:
I tried your code and it seems to me that VOLUME_DATA has a wrong size. if I modify your code a little bit it throws no errors:

FREQUENCES = 1:6;
[x,y,z] = meshgrid(1:5,1:9,FREQUENCES);
VOLUME_DATA = x.*exp(-x.^2-y.^2-z.^2); % a function of x,y,z such that the output dimension fits the inputs dimensions
xslice = 1;
yslice = 1;
zslice = 1:FREQUENCES(end)/5:FREQUENCES(end)-1;
slice(x,y,z,VOLUME_DATA,xslice,yslice,zslice,'nearest')
colormap hsv

or maybe try:

[x,y,z] = meshgrid(1:size(VOLUME_DATA,1),1:size(VOLUME_DATA,2),FREQUENCES);


来源: stackexchange

问:
Go get from private git repository fails due to .git in url
When using github.com, the url used to browse to a repo does not contain the .git extension:

https://github.com/someuser/helloworld

but the "clone with https" url does:

https://github.com/someuser/helloworld.git

And you go get it like this:

go get github.com/someuser/helloworld

In our private git repo, we create bare repos in a directory ending in .git (based on convention):

helloworld.git

But the url (served using https://github.com/klaussilveira/gitlist) to browse to the repo also contains .git:

https://git.test.net/helloworld.git

This causes go get to fail because it doesn't expect the .git:

```<code>C:\>go get -u -f -insecure git.test.net/helloworld.git
# cd .; git clone git.test.net/helloworld   C:\Temp\golang\src\git.test.net\helloworld.git
fatal: repository 'git.test.net/helloworld' does not exist
package git.test.net/helloworld.git: exit status 128
</code>```

Leaving off the .git part also fails:

```<code>C:\>go get -u -f -insecure git.test.net/helloworld
    package git.test.net/helloworld: unrecognized import path "git.test.net/helloworld" (parse https://git.test.net/helloworld?go-get=1: no go-impor
    t meta tags ())
</code>```

Renaming the bare repo to just helloworld solves the problem. But this isn't the convention.

What am I missing? Is there a server setting we are missing so that we can leave off the .git extension when browsing? Should we just just leave off .git when naming the bare repo? Why does github.com have different behavior?

答:
On the repo server, use a soft link along side each of the repos. So in this case, just do a

```<code>ln -s helloworld.git helloworld
</code>```

and it should work based on the fact that the rename worked.

Um, if it's a Windows server... I'm sure you can google a way to create a soft link, sometimes called a symlink.

ContentLicense: CC BY-SA 3.0

Body:
When using github.com, the url used to browse to a repo does not contain the .git extension:

https://github.com/someuser/helloworld

but the "clone with https" url does:

https://github.com/someuser/helloworld.git

And you go get it like this:

go get github.com/someuser/helloworld

In our private git repo, we create bare repos in a directory ending in .git (based on convention):

helloworld.git

But the url (served using https://github.com/klaussilveira/gitlist) to browse to the repo also contains .git:

https://git.test.net/helloworld.git

This causes go get to fail because it doesn't expect the .git:

C:\>go get -u -f -insecure git.test.net/helloworld.git
# cd .; git clone git.test.net/helloworld   C:\Temp\golang\src\git.test.net\helloworld.git
fatal: repository 'git.test.net/helloworld' does not exist
package git.test.net/helloworld.git: exit status 128

Leaving off the .git part also fails:

C:\>go get -u -f -insecure git.test.net/helloworld
    package git.test.net/helloworld: unrecognized import path "git.test.net/helloworld" (parse https://git.test.net/helloworld?go-get=1: no go-impor
    t meta tags ())

Renaming the bare repo to just helloworld solves the problem. But this isn't the convention.

What am I missing? Is there a server setting we are missing so that we can leave off the .git extension when browsing? Should we just just leave off .git when naming the bare repo? Why does github.com have different behavior?

Body:
On the repo server, use a soft link along side each of the repos. So in this case, just do a

ln -s helloworld.git helloworld

and it should work based on the fact that the rename worked.

Um, if it's a Windows server... I'm sure you can google a way to create a soft link, sometimes called a symlink.


问:
js-hotkeys, function raised twice when combination is more than 1 key
I am using js-hotkeys. I have a problem where when my key combination is more than 1 key, eg. "Shift+Tab", my function is raised twice. </p>

```<code>$("textarea").bind("keydown", "shift+tab", function() { ... });
</code>```

<p>See what happens here -> http://jsbin.com/osuza5/2/edit. seems like with 1 key it also triggers twice there. </p>

答:
This has happened since jQuery 1.4.2, it's a known issue.  Luckily, John Resig forked this and created a much cleaner version a while back that also ...well - it works, you can check it out here.

Updating your jsbin to point at this plugin version: https://github.com/jeresig/jquery.hotkeys/raw/master/jquery.hotkeys.js (and that's the only change), it works.  You can test it out here.

ContentLicense: CC BY-SA 2.5

Body:
I am using js-hotkeys. I have a problem where when my key combination is more than 1 key, eg. "Shift+Tab", my function is raised twice.

$("textarea").bind("keydown", "shift+tab", function() { ... });

See what happens here -> http://jsbin.com/osuza5/2/edit. seems like with 1 key it also triggers twice there.


问:
How to trigger error on fs.rename command if file already exists?
I have the following code that moves files from one directory to another:

```<code>var fs = require('fs'),
    oldPath = 'firstfile.txt',
    newPath = 'temp/firstfile.txt';

fs.rename(oldPath, newPath, function (err) {
    console.log('rename callback ', err);
});
</code>```

Is it possible to trigger error if newPath file already exists?

答:
Indeed, you need to do it in one instruction to avoid the race condition (as explained in the comments).

There is at my knowledge no way to do it with the core fs library, but there is a function for doing it in the extended version.

See the move function, whose default behavior doesen't allow to overwride files:

https://github.com/jprichardson/node-fs-extra/blob/master/docs/move.md

```<code>const fs = require('fs-extra')

fs.move('/tmp/somefile', '/tmp/does/not/exist/yet/somefile', err => {
  if (err) return console.error(err)

  console.log('success!')
})
</code>```

Body:
I have the following code that moves files from one directory to another:

var fs = require('fs'),
    oldPath = 'firstfile.txt',
    newPath = 'temp/firstfile.txt';

fs.rename(oldPath, newPath, function (err) {
    console.log('rename callback ', err);
});

Is it possible to trigger error if newPath file already exists?

Body:
Indeed, you need to do it in one instruction to avoid the race condition (as explained in the comments).

There is at my knowledge no way to do it with the core fs library, but there is a function for doing it in the extended version.

See the move function, whose default behavior doesen't allow to overwride files:

https://github.com/jprichardson/node-fs-extra/blob/master/docs/move.md

const fs = require('fs-extra')

fs.move('/tmp/somefile', '/tmp/does/not/exist/yet/somefile', err => {
  if (err) return console.error(err)

  console.log('success!')
})


问:
password checking jQuery plugin
i am searching for a password strenght checking jQuery plugin.

i found this one: http://shouvik.net/pwdmeter.php

but it seems it doesn't work with jQuery 1.4.3.

can you guide me?

thanks in advance.

答:
Here you have a bunch of scripts :)

http://www.webresourcesdepot.com/10-password-strength-meter-scripts-for-a-better-registration-interface/

Title: password checking jQuery plugin


问:
How I delete custom dexterity objects in Plone 4?
I'm trying delete some custom dexterity objects, bellow have snipets code of this custom object.

```<code>class IDigitalFile(model.Schema):
        """Dexterity-Schema
        """

    ...

    directives.read_permission(auto="cmf.ManagePortal")
    directives.write_permission(auto="cmf.ManagePortal")
    fieldset('Admins Only', fields=['auto', 'uploded_at', 'codLote'] )
    auto = schema.Bool(
        title=_(u"Upload via Script?"),
        required=True,
        default=False,
    )
    ...
</code>```

And I try use sudo plone_daemon bin/client2 -O Plone debug and apply this code:

```<code>from zope.site.hooks import setSite
site = 'Plone'
context = app[site]
setSite(context)
portal_catalog = context.portal_catalog
itens = portal_catalog(portal_type='digitalfile', path='/ged/')
print itens
</code>```

After rum this script my output is [], just epmty but if i use the similar code in ZMI I have all brains.

So, in ZMI we can't user methods to delete 'cuz have restrictions.
And my goal is delete all objects digitalfileif flag Truein autofield.

How can I do it if my results are empties?
Or what I did wrong for output is empty?

[UPDATE 1]

This problem apper to me:

```<code>zero@srv-d:/opt/Plone439/zeocluster$ sudo -u plone_daemon bin/client2 -O Plone debug
Starting debugger (the name "app" is bound to the top-level Zope object)
2017-03-31 10:09:04 WARNING ZODB.blob (18048) Blob dir /opt/Plone439/zeocluster/var/blobstorage/ has insecure mode setting
Traceback (most recent call last):
  File "/opt/Plone439/zeocluster/parts/client2/bin/interpreter", line 281, in <module>
    exec(_val)
  File "<string>", line 1, in <module>
  File "/opt/Plone439/buildout-cache/eggs/Zope2-2.13.24-py2.7.egg/ZPublisher/BaseRequest.py", line 623, in traverse
    response.unauthorized()
  File "/opt/Plone439/buildout-cache/eggs/Zope2-2.13.24-py2.7.egg/ZPublisher/HTTPResponse.py", line 756, in unauthorized
    raise Unauthorized, m
zExceptions.unauthorized.Unauthorized: You are not authorized to access this resource.
</code>```

[UPDATE 2 - SOLVED]

Maybe have a easy way to do, but in this moment, this script solved my problem and I'm sharing if someone need...

```<code># -*- coding: utf-8 -*-
from zope.site.hooks import setSite
from plone import api
import transaction

# Setting the plone portal in var context
site = 'Plone'
context = app[site]
setSite(context)

# grabbing portal_catalog tool
portal_catalog = context.portal_catalog

# setting the user that have permission
with api.env.adopt_user(username='admin'):
    # grabbing all items digitalfile
    brains = portal_catalog(portal_type='digitalfile', path='/ged')

for brain in brains:
    if 'TO BE DELETE' in brain.Description:
        item = api.content.get(path=brain.getPath())
        api.content.delete(obj=item)
        transaction.commit()
</code>```

答: Try to add the id of the Plone site in the path for the catalog search: portal_catalog(portal_type='digitalfile', path='/Plone/ged/')

Body:
I'm trying delete some custom dexterity objects, bellow have snipets code of this custom object.

class IDigitalFile(model.Schema):
        """Dexterity-Schema
        """

    ...

    directives.read_permission(auto="cmf.ManagePortal")
    directives.write_permission(auto="cmf.ManagePortal")
    fieldset('Admins Only', fields=['auto', 'uploded_at', 'codLote'] )
    auto = schema.Bool(
        title=_(u"Upload via Script?"),
        required=True,
        default=False,
    )
    ...

And I try use sudo plone_daemon bin/client2 -O Plone debug and apply this code:

from zope.site.hooks import setSite
site = 'Plone'
context = app[site]
setSite(context)
portal_catalog = context.portal_catalog
itens = portal_catalog(portal_type='digitalfile', path='/ged/')
print itens

After rum this script my output is [], just epmty but if i use the similar code in ZMI I have all brains.

So, in ZMI we can't user methods to delete 'cuz have restrictions.
And my goal is delete all objects digitalfileif flag Truein autofield.

How can I do it if my results are empties?
Or what I did wrong for output is empty?

[UPDATE 1]

This problem apper to me:

zero@srv-d:/opt/Plone439/zeocluster$ sudo -u plone_daemon bin/client2 -O Plone debug
Starting debugger (the name "app" is bound to the top-level Zope object)
2017-03-31 10:09:04 WARNING ZODB.blob (18048) Blob dir /opt/Plone439/zeocluster/var/blobstorage/ has insecure mode setting
Traceback (most recent call last):
  File "/opt/Plone439/zeocluster/parts/client2/bin/interpreter", line 281, in <module>
    exec(_val)
  File "<string>", line 1, in <module>
  File "/opt/Plone439/buildout-cache/eggs/Zope2-2.13.24-py2.7.egg/ZPublisher/BaseRequest.py", line 623, in traverse
    response.unauthorized()
  File "/opt/Plone439/buildout-cache/eggs/Zope2-2.13.24-py2.7.egg/ZPublisher/HTTPResponse.py", line 756, in unauthorized
    raise Unauthorized, m
zExceptions.unauthorized.Unauthorized: You are not authorized to access this resource.

[UPDATE 2 - SOLVED]

Maybe have a easy way to do, but in this moment, this script solved my problem and I'm sharing if someone need...

# -*- coding: utf-8 -*-
from zope.site.hooks import setSite
from plone import api
import transaction

# Setting the plone portal in var context
site = 'Plone'
context = app[site]
setSite(context)

# grabbing portal_catalog tool
portal_catalog = context.portal_catalog

# setting the user that have permission
with api.env.adopt_user(username='admin'):
    # grabbing all items digitalfile
    brains = portal_catalog(portal_type='digitalfile', path='/ged')

for brain in brains:
    if 'TO BE DELETE' in brain.Description:
        item = api.content.get(path=brain.getPath())
        api.content.delete(obj=item)
        transaction.commit()


问:
SQL LEFT JOIN/INNER JOIN different result
I don't know what I'm doing wrong but can't found solution for my statement. Current statement is:

```<code>SELECT tb1.RestaurantID, Title, City
FROM Restaurant AS tb1
LEFT JOIN RestaurantLunch AS tb2 ON tb1.RestaurantID = tb2.RestaurantID
WHERE (MATCH (tb1.Title, tb1.City) AGAINST ('+string1* +string2*' IN BOOLEAN MODE)) LIMIT 5;
</code>```

Offcourse i would also like to search for string in other table(tb2) and i change my statement to:

```<code>SELECT tb1.RestaurantID, Title, City
FROM Restaurant AS tb1
LEFT JOIN RestaurantLunch AS tb2 ON tb1.RestaurantID = tb2.RestaurantID
WHERE (MATCH (tb1.Title, tb1.City, tb2.Text) AGAINST ('+string1* +string2*' IN BOOLEAN MODE)) LIMIT 5;
</code>```

After submit i get different result, which is not logic at all. Why is that?

答:
The InnoDB tables do not allow searches over several fulltext indexes in the same MATCH clause. Therefore, you may get different result when adding more fields to same MATCH  clause. Here your fields do not all belong to the same table, therefore they are covered by different indexes.

I think you should split your search to use one single fulltext index per MATCH clause. You could try

```<code>SELECT
   tb1.RestaurantID, Title, City
FROM Restaurant AS tb1
LEFT JOIN RestaurantLunch AS tb2 ON tb1.RestaurantID = tb2.RestaurantID
WHERE (MATCH (tb1.Title, tb1.City) AGAINST ('+string1* +string2*' IN BOOLEAN MODE))
      OR (tb2.Text IS NOT NULL AND MATCH (tb2.Text) AGAINST ('+string1* +string2*' IN BOOLEAN MODE))
LIMIT 5;
</code>```

Body:
I don't know what I'm doing wrong but can't found solution for my statement. Current statement is:

SELECT tb1.RestaurantID, Title, City
FROM Restaurant AS tb1
LEFT JOIN RestaurantLunch AS tb2 ON tb1.RestaurantID = tb2.RestaurantID
WHERE (MATCH (tb1.Title, tb1.City) AGAINST ('+string1* +string2*' IN BOOLEAN MODE)) LIMIT 5;

Offcourse i would also like to search for string in other table(tb2) and i change my statement to:

SELECT tb1.RestaurantID, Title, City
FROM Restaurant AS tb1
LEFT JOIN RestaurantLunch AS tb2 ON tb1.RestaurantID = tb2.RestaurantID
WHERE (MATCH (tb1.Title, tb1.City, tb2.Text) AGAINST ('+string1* +string2*' IN BOOLEAN MODE)) LIMIT 5;

After submit i get different result, which is not logic at all. Why is that?

Body:
The InnoDB tables do not allow searches over several fulltext indexes in the same MATCH clause. Therefore, you may get different result when adding more fields to same MATCH  clause. Here your fields do not all belong to the same table, therefore they are covered by different indexes.

I think you should split your search to use one single fulltext index per MATCH clause. You could try

SELECT
   tb1.RestaurantID, Title, City
FROM Restaurant AS tb1
LEFT JOIN RestaurantLunch AS tb2 ON tb1.RestaurantID = tb2.RestaurantID
WHERE (MATCH (tb1.Title, tb1.City) AGAINST ('+string1* +string2*' IN BOOLEAN MODE))
      OR (tb2.Text IS NOT NULL AND MATCH (tb2.Text) AGAINST ('+string1* +string2*' IN BOOLEAN MODE))
LIMIT 5;


问:
Stop a random string when the correct values are displayed
I have this code

PFont f;
int displayWidth = 1280;
int displayHeight = 720;

int count;
int countAdvance;

void setup() {
  size(displayWidth, displayHeight);
  background(239,238,238);
  f = createFont("Heebo Black", 36, true);
  count = 1;
  countAdvance = 1;
}

void draw() {
 //I love you sentance
  String[] W1 = {
    "I", "love", "you", "."
  };
  String[] W2 = {
    "I", "love", "you", "."
  };
  String[] W3 = {
    "I", "love", "you", "."
  };
  String[] W4 = {
    "I", "love", "you", "."
  };

  int w1 = int(random(W1.length));
  int w2 = int(random(W2.length));
  int w3 = int(random(W3.length));
  int w4 = int(random(W4.length));

  String Sentence = W1[w1]+" "+W2[w2]+" "+W3[w3]+" "+W4[w4];
  println(Sentence);

  background(239,238,238);
  textAlign(CENTER);
  textFont(f);
  fill(66,134,244);
  text(Sentence, 0.5*displayWidth, 0.5*displayHeight+25);

 //loop
  delay(1000);

}
```

and simply put, I want it to stop looping random values when the string writes out the correct sentence, in this case its "I love you.". What do I need to add in to make it stop so that W1[0] W2[1] etc.

Using Processing to write it if that matters.

答:
This ought to work but I've never used Processing, so I'm not sure how correct your original code was.</p>

```<code>void draw() {
  //I love you sentance
  String[] W1 = {
    "I", "love", "you", "."
  };
  String[] W2 = {
    "I", "love", "you", "."
  };
  String[] W3 = {
    "I", "love", "you", "."
  };
  String[] W4 = {
    "I", "love", "you", "."
  };
  String Sentence = "";
  while (!Sentence.equals("I love you .")) {//the last space is required
      int w1 = int(random(W1.length));
      int w2 = int(random(W2.length));
      int w3 = int(random(W3.length));
      int w4 = int(random(W4.length));

      Sentence = W1[w1]+" "+W2[w2]+" "+W3[w3]+" "+W4[w4];
      println(Sentence);

      background(239,238,238);
      textAlign(CENTER);
      textFont(f);
      fill(66,134,244);
      text(Sentence, 0.5*displayWidth, 0.5*displayHeight+25);

      delay(1000);
  }
}
</code>```

Body:
I have this code

PFont f;
int displayWidth = 1280;
int displayHeight = 720;

int count;
int countAdvance;

void setup() {
  size(displayWidth, displayHeight);
  background(239,238,238);
  f = createFont("Heebo Black", 36, true);
  count = 1;
  countAdvance = 1;
}

void draw() {
 //I love you sentance
  String[] W1 = {
    "I", "love", "you", "."
  };
  String[] W2 = {
    "I", "love", "you", "."
  };
  String[] W3 = {
    "I", "love", "you", "."
  };
  String[] W4 = {
    "I", "love", "you", "."
  };

  int w1 = int(random(W1.length));
  int w2 = int(random(W2.length));
  int w3 = int(random(W3.length));
  int w4 = int(random(W4.length));

  String Sentence = W1[w1]+" "+W2[w2]+" "+W3[w3]+" "+W4[w4];
  println(Sentence);

  background(239,238,238);
  textAlign(CENTER);
  textFont(f);
  fill(66,134,244);
  text(Sentence, 0.5*displayWidth, 0.5*displayHeight+25);

 //loop
  delay(1000);

}

and simply put, I want it to stop looping random values when the string writes out the correct sentence, in this case its "I love you.". What do I need to add in to make it stop so that W1[0] W2[1] etc.

Using Processing to write it if that matters.

Body:
This ought to work but I've never used Processing, so I'm not sure how correct your original code was.

void draw() {
  //I love you sentance
  String[] W1 = {
    "I", "love", "you", "."
  };
  String[] W2 = {
    "I", "love", "you", "."
  };
  String[] W3 = {
    "I", "love", "you", "."
  };
  String[] W4 = {
    "I", "love", "you", "."
  };
  String Sentence = "";
  while (!Sentence.equals("I love you .")) {//the last space is required
      int w1 = int(random(W1.length));
      int w2 = int(random(W2.length));
      int w3 = int(random(W3.length));
      int w4 = int(random(W4.length));

      Sentence = W1[w1]+" "+W2[w2]+" "+W3[w3]+" "+W4[w4];
      println(Sentence);

      background(239,238,238);
      textAlign(CENTER);
      textFont(f);
      fill(66,134,244);
      text(Sentence, 0.5*displayWidth, 0.5*displayHeight+25);

      delay(1000);
  }
}


问:
File not found exception in Application_Error
Hi all i am new in asp.net mvc. Sometimes i have an exception in Application_Error and i write it to my log file:

```<code>Error in  global.asax
System.Web.HttpException: File does not exist.
   at System.Web.StaticFileHandler.ProcessRequestForNonMapPathBasedVirtualFile(HttpRequest request, HttpResponse response)
   at System.Web.StaticFileHandler.ProcessRequestInternal(HttpContext context)
   at System.Web.DefaultHttpHandler.BeginProcessRequest(HttpContext context, AsyncCallback callback, Object state)
   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
</code>```

I trying debug but i not see file name? How to see witch file cannot be found ?
Thanks

答:
when you debug, can you see in the request that the request is for a resource like an image, js file or something like that?

i sometimes get this messages when i get a request for an image (maybe referenced in a css file) which does not exists.

Body:
Hi all i am new in asp.net mvc. Sometimes i have an exception in Application_Error and i write it to my log file:

Error in  global.asax
System.Web.HttpException: File does not exist.
   at System.Web.StaticFileHandler.ProcessRequestForNonMapPathBasedVirtualFile(HttpRequest request, HttpResponse response)
   at System.Web.StaticFileHandler.ProcessRequestInternal(HttpContext context)
   at System.Web.DefaultHttpHandler.BeginProcessRequest(HttpContext context, AsyncCallback callback, Object state)
   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

I trying debug but i not see file name? How to see witch file cannot be found ?
Thanks


问:
NoMethodError: undefined method `env' for nil:NilClass
I am using rails testing for my app and when I run this test

```<code>class ShowingQuizzesTest < ActionDispatch::IntegrationTest
    include Devise::TestHelpers
    setup { host! 'example.com' }
    test 'return quiz by id' do
        instructor=Instructor.create(name:"same7", email:"abcdefg@eng.asu.edu.com", password:"123abc")
        sign_in instructor
        quiz = Quiz.create(name: 'Quiz1', subject: 'physics', duration: 10, no_of_MCQ: 5, no_of_rearrangeQ: 5)
        current_instructor.quizzes << quiz
        get "api/quizzes/#{quiz.id}"
        assert_equal 200, response.status

        quiz_response = json(response.body)
        assert_equal quiz.name, quiz_response[:name]
    end
end
</code>```

This error appears:
1) Error:
ShowingQuizzesTest#test_return_quiz_by_id:
NoMethodError: undefined method `env' for nil:NilClass

the method I am testing:

```<code>   def show
            current_instructor.quizzes.find(params[:id])
            render json: data:{:quiz => quiz}, status: 200
        end
</code>```

答:
Are you on Rails 5?

It looks like Rails 5 deprecated the old method of including test helpers - as the Rails team has made significant improvements to the speed of integration tests.  Currently, all controllers are tested in integration tests - Link

I'm getting the same error when dealing with devise & testing.  I was able to make the error go away by commenting out # include Devise::Test::ControllerHelpers from my test file or the test_helpers.rb if you inherit your test helpers there.

Body:
I am using rails testing for my app and when I run this test

class ShowingQuizzesTest < ActionDispatch::IntegrationTest
    include Devise::TestHelpers
    setup { host! 'example.com' }
    test 'return quiz by id' do
        instructor=Instructor.create(name:"same7", email:"abcdefg@eng.asu.edu.com", password:"123abc")
        sign_in instructor
        quiz = Quiz.create(name: 'Quiz1', subject: 'physics', duration: 10, no_of_MCQ: 5, no_of_rearrangeQ: 5)
        current_instructor.quizzes << quiz
        get "api/quizzes/#{quiz.id}"
        assert_equal 200, response.status

        quiz_response = json(response.body)
        assert_equal quiz.name, quiz_response[:name]
    end
end

This error appears:
1) Error:
ShowingQuizzesTest#test_return_quiz_by_id:
NoMethodError: undefined method `env' for nil:NilClass

the method I am testing:

   def show
            current_instructor.quizzes.find(params[:id])
            render json: data:{:quiz => quiz}, status: 200
        end


问:
How can hide sensitive info in SQL
I want to do this in SQL server:

If I have a name like 'Johnny English',

how can I show in a query this 'J***** E******'?

Thanks!

答:
This code will add stars to the first word. It assumes the subsequent words are separated by at least one space</p>

```<code>declare @test varchar(20)='Johnny English'
declare @StarNum int

set @StarNum=charindex(' ',@test)-2

select stuff(@test,2,@StarNum,replicate('*',@StarNum))
</code>```

Title: How can hide sensitive info in SQL

Body:
This code will add stars to the first word. It assumes the subsequent words are separated by at least one space

declare @test varchar(20)='Johnny English'
declare @StarNum int

set @StarNum=charindex(' ',@test)-2

select stuff(@test,2,@StarNum,replicate('*',@StarNum))


问:
How can I set Bootstrap modal to bottom-right corner?
I'm trying to lock a bootstrap modal at bottom right of the window.

What i have is :

HTML

```<code><div class="modal custom fade" id="trackModal" tabindex="-1" role="dialog" aria-labelledby="trackModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">

            <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                <h3 class="getlaid" id="trackModalLabel">Hello</h4>

            </div>

            <div class="modal-body">
            <p>TEST</p>
            </div>

            <div class="modal-footer">
                <div class="btnmodal" data-dismiss="modal">Close ✖</div>

            </div>
        </div>
    </div>
</div>
</code>```

CSS

```<code>.modal.custom .modal-dialog {
    width:120%;
    position:fixed;
        bottom:0px;
        right:0px;
        margin:0px;

}
</code>```

With this code block I'm not able to display modal at the bottom right of the window and it's keep displaying in the middle of the page. What is wrong here?

答:
Maybe you meant to use 20% instead of 120%?

```<code>.modal.custom .modal-dialog {
    width:20%;
    position:fixed;
    bottom:0;
    right:0;
    margin:0;
}
</code>```

http://www.codeply.com/go/6GXNLGHyoW

Body:
I'm trying to lock a bootstrap modal at bottom right of the window.

What i have is :

HTML

            <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Hello

TEST

Close ✖

CSS

.modal.custom .modal-dialog {
    width:120%;
    position:fixed;
        bottom:0px;
        right:0px;
        margin:0px;

}

With this code block I'm not able to display modal at the bottom right of the window and it's keep displaying in the middle of the page. What is wrong here?

Body:
Maybe you meant to use 20% instead of 120%?

.modal.custom .modal-dialog {
    width:20%;
    position:fixed;
    bottom:0;
    right:0;
    margin:0;
}

http://www.codeply.com/go/6GXNLGHyoW


问:
Checking if an object is a given type in Swift
I have an array that is made up of AnyObject. I want to iterate over it, and find all elements that are array instances.

How can I check if an object is of a given type in Swift?

答:
Be warned about this:

```<code>var string = "Hello" as NSString
var obj1:AnyObject = string
var obj2:NSObject = string

print(obj1 is NSString)
print(obj2 is NSString)
print(obj1 is String)
print(obj2 is String)
</code>```

All of the four last lines return true, this is because if you type

```<code>var r1:CGRect = CGRect()
print(r1 is String)
</code>```

... it prints "false" of course, but a Warning says that the Cast from CGRect to String fails. So some type are bridged, ans the 'is' keyword calls an implicit cast.

You should better use one of these:

```<code>myObject.isKind(of: MyClass.self))
myObject.isMember(of: MyClass.self))
</code>```

Body:
Be warned about this:

var string = "Hello" as NSString
var obj1:AnyObject = string
var obj2:NSObject = string

print(obj1 is NSString)
print(obj2 is NSString)
print(obj1 is String)
print(obj2 is String)

All of the four last lines return true, this is because if you type

var r1:CGRect = CGRect()
print(r1 is String)

... it prints "false" of course, but a Warning says that the Cast from CGRect to String fails. So some type are bridged, ans the 'is' keyword calls an implicit cast.

You should better use one of these:

myObject.isKind(of: MyClass.self))
myObject.isMember(of: MyClass.self))


问:
Python unescape URL
I have got a url in this form - http:\\/\\/en.wikipedia.org\\/wiki\\/The_Truman_Show. How can I make it normal url. I have tried using urllib.unquote without much success.

I can always use regular expressions or some simple string replace stuff. But I believe that there is a better way to handle this...

答:
Have you tried using json.loads from the json module?

```<code>>>> json.loads('"http:\\/\\/en.wikipedia.org\\/wiki\\/The_Truman_Show"')
'http://en.wikipedia.org/wiki/The_Truman_Show'
</code>```

The input that I'm showing isn't exactly what you have. I've wrapped it in double quotes to make it valid json.

When you first get it from the json, how are you decoding it? That's probably where the problem is.

Title: Python unescape URL

Body:
Have you tried using json.loads from the json module?

>>> json.loads('"http:\\/\\/en.wikipedia.org\\/wiki\\/The_Truman_Show"')
'http://en.wikipedia.org/wiki/The_Truman_Show'

The input that I'm showing isn't exactly what you have. I've wrapped it in double quotes to make it valid json.

When you first get it from the json, how are you decoding it? That's probably where the problem is.


问:
How do You monitor sidekiq processes?
I'm working on a production app that has multiple rails servers behind nginx loadbalancer. We are monitoring sidekiq processes with monit, and it works just fine - when sidekiq proces dies monit starts it right back.

However recently encountered a situation where one of these processes was running and visible to monit, but for some reason not visible to sidekiq. That resulted in many failed jobs and took us some time to notice that we're missing one process in sidekiq Web UI, since monit was telling us everything was fine and all processes were running. Simple restart fixed the problem.

And that bring me to my question: how do you monitor your sidekiq processes? I know i can use something like rollbar to notify me when jobs fail, but i'd like to know if there is a way to monitor process count and preferably send mail when one dies. Any suggestions?

Something that would ping sidekiq/stats and verify response.

答:
My approach is the following:

create a background job that does something

call the job regularly

check that the thing is being done!

so; using a cron script (or something like whenever) every 5 mins, I run :

```<code>CheckinJob.perform_later
</code>```

It's now up to sidekiq (or delayed_job, or whatever active job you're using) to actually run the job.

The job just has to do something which you can check.

I used to get the job to update a record in my Status table (essentially a list of key/value records). Then I'd have a /status page which returns a :500 status code if the record hasn't been updated in the last 6 minutes.

(obviously your timing may vary)

Then I use a monitoring service to monitor the status page! (something like StatusCake)

Nowdays I have a simpler approach; I just get the background job to check in with a cron monitoring service like

IsItWorking

Dead Mans Snitch

Health Checks

The monitoring service which expects your task to check in every X mins. If your task doesn't check in - then the monitoring service will let you know.

Integration is dead simple for all the services. For Is It Working it would be:

```<code>IsItWorkingInfo::Checkin.ping(key:"CHECKIN_IDENTIFIER")
</code>```

full disclosure: I wrote IsItWorking !

ContentLicense: CC BY-SA 4.0

Title: How do You monitor sidekiq processes?

Body:
My approach is the following:

create a background job that does something

call the job regularly

check that the thing is being done!

so; using a cron script (or something like whenever) every 5 mins, I run :

CheckinJob.perform_later

It's now up to sidekiq (or delayed_job, or whatever active job you're using) to actually run the job.

The job just has to do something which you can check.

I used to get the job to update a record in my Status table (essentially a list of key/value records). Then I'd have a /status page which returns a :500 status code if the record hasn't been updated in the last 6 minutes.

(obviously your timing may vary)

Then I use a monitoring service to monitor the status page! (something like StatusCake)

Nowdays I have a simpler approach; I just get the background job to check in with a cron monitoring service like

IsItWorking

Dead Mans Snitch

Health Checks

The monitoring service which expects your task to check in every X mins. If your task doesn't check in - then the monitoring service will let you know.

Integration is dead simple for all the services. For Is It Working it would be:

IsItWorkingInfo::Checkin.ping(key:"CHECKIN_IDENTIFIER")

full disclosure: I wrote IsItWorking !


问:
Visual Studio 2015 Professioanl is raising the following error :- Could not load file or assembly 'Microsoft.Activities.Design.Services
I have the following inside my Dev machine:-

Windows server r2 2012.

SharePoint server 2016.

I download/Install Visual studio 2015 Professioanl.

I download Microsoft Office Developer Tools Preview 2 for Visual Studio 2015

i created a new empty sharepoint 2016 project inside VS 2015 community.

inside the project i added a new Event Receiver.

i build the project successfully.

but when i click on start debugging the got this weird exception :-

Severity Code Description Project File Line Suppression State Error
Unable to load one or more of the requested types. Retrieve the
LoaderExceptions property for more information. SharePointProject6

here is how my SP 2016 solution looks like:-

also my project is showing this warning:-

Severity Code Description Project File Line Suppression State Warning
Unhandled exception occurred while calling method
'projectService_ProjectInitialized' of type
'Microsoft.VisualStudio.SharePoint.WorkflowDesignerSupport.PackageBootstrapper,
Microsoft.VisualStudio.SharePoint.WorkflowDesignerSupport,
Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
Exception: System.IO.FileNotFoundException. Message: Could not load
file or assembly 'Microsoft.Activities.Design.Services,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or
one of its dependencies. The system cannot find the file specified.
SharePointProject6 0

so can anyone advice on this please?
Thanks

EDIT

here is the references

 :-

EDIT-2
when i checked my current references from the following location "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5", i got the following:-

EDIT-3

now i went to another machine which have visual studio 2015 installed (actually it is my dev laptop), and i copies the Microsoft.Activities.Design.Services.dll from C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Microsoft.Activities.Design.Services\v4.0_1.0.0.0__31bf3856ad364e35, then i paste it inside my server which have sharepoint and visual studio installed:-

then i open the visual studio project, i browse for the Microsoft.Activities.Design.Services.dll, and i add it inside my visual studio project, as follow:-

but i am still facing the same error. now i try running the visual studio as Admin.Plus i clear the bin folder of my project. Plus i repair the visual studio and i repair the development tools for visual studio... but when i run the project I will receive the same error...

Edit-4
now i have repair Visual Studio 2015, and i got these messages:-

so i am not sure if these messages can be related to the problem i am facing ?

答:
Microsoft.VisualStudio.SharePoint.WorkflowDesignerSupport and thus Microsoft.Activities.Design.Services.dll are loaded by Visual Studio (devenv.exe) itself, not by the component you're writing, so VS won't look for it in your project directories.

You could probably work around the problem by copying Microsoft.Activities.Design.Services.dll into the same directory as Microsoft.VisualStudio.SharePoint.WorkflowDesignerSupport, C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\SharePoint\Extensions\WFDesignerSupport\.

The best way to do it is certainly to install the missing Workflow Manager component of which this DLL is a part. It can be downloaded from Microsoft as described here : https://msdn.microsoft.com/en-us/library/jj193448(v=azure.10).aspx

Edit

According to https://msdn.microsoft.com/en-us/library/yx7xezcf(v=vs.110).aspx, an executable can specify in it's config file where to look for assemblies, which VS does. devenv.exe.config contains :

```<code><probing privatePath="PublicAssemblies;PrivateAssemblies;...
</code>```

so it should look for the dlls in C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\PrivateAssemblies.

Body:
Microsoft.VisualStudio.SharePoint.WorkflowDesignerSupport and thus Microsoft.Activities.Design.Services.dll are loaded by Visual Studio (devenv.exe) itself, not by the component you're writing, so VS won't look for it in your project directories.

You could probably work around the problem by copying Microsoft.Activities.Design.Services.dll into the same directory as Microsoft.VisualStudio.SharePoint.WorkflowDesignerSupport, C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\SharePoint\Extensions\WFDesignerSupport\.

The best way to do it is certainly to install the missing Workflow Manager component of which this DLL is a part. It can be downloaded from Microsoft as described here : https://msdn.microsoft.com/en-us/library/jj193448(v=azure.10).aspx

Edit

According to https://msdn.microsoft.com/en-us/library/yx7xezcf(v=vs.110).aspx, an executable can specify in it's config file where to look for assemblies, which VS does. devenv.exe.config contains :

<probing privatePath="PublicAssemblies;PrivateAssemblies;...

so it should look for the dlls in C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\PrivateAssemblies.


问:
how to save arraylist<object> after app is closed
how to save arraylist after the app is closed.
This is my global class

```<code>public class GlobalClass extends Application {

ArrayList<Trip> allTrips = new ArrayList<>();

public ArrayList<String> allTripsString() {
    ArrayList<String> allTripsString = new ArrayList<String>();
    for (Trip trip : allTrips){
        allTripsString.add(trip.getName());
    }
    return allTripsString;
    }
}
</code>```

This is my trip class

```<code>public class Trip {

/** A map with category as key and the associed list of items as value */
Map<String,List<Item>> expanses;

private String name;
public ArrayList<String> ExpensesCategory = new ArrayList<>();
public ArrayList<String> Adults = new ArrayList<>();
public ArrayList<String> Children = new ArrayList<>();
public ArrayList<String> ShoppingName = new ArrayList<>();
public ArrayList<Double> ShoppingPrice = new ArrayList<>();
public ArrayList<String> ShoppingCategory = new ArrayList<>();
public double budget = 0;

/** An item in the expanses list */
static class Item {
    final String name;
    final double cost;
    final String Category;
    public Item(String name, double cost, String Category) {
        this.name = name;
        this.cost = cost;
        this.Category = Category;
    }
    @Override public String toString() {
        return this.name + " (" + this.cost + "$)";
    }
    public String getName(){
        return name;
    }
    public String getCategory(){
        return Category;
    }
    public double getCost(){
        return cost;
    }
}

public Trip(String name) {
    this.name = name;
    this.expanses = new HashMap<String,List<Item>>();
    for (String cat: ExpensesCategory) { // init the categories with empty lists
        this.expanses.put(cat, new ArrayList<Item>());
    }
}

public String getName(){
    return name;
}

/** Register a new expanse to the trip. */
public void add(String item, double cost, String category) {
    List<Item> list = this.expanses.get(category);
    if (list == null)
        throw new IllegalArgumentException("Category '"+category+"' does not exist.");
    list.add( new Item(item, cost, category) );
}

/** Get the expanses, given a category.
 * @return  a fresh ArrayList containing the category elements, or null if the category does not exists
 */
public List<Item> getItems(String category) {
    List<Item> list = this.expanses.get(category);
    if (list == null)
        return null;
    return new ArrayList<Item>(list);
}

/** Get the expanses, given a category.
 * @return  a fresh ArrayList containing all the elements
 */
public List<Item> getItems() {
    List<Item> list = new ArrayList<Item>();
    for (List<Item> l: this.expanses.values()) // fill with each category items
        list.addAll(l);
    return list;
}

public ArrayList<String> getItemsString() {
    List<Item> list = new ArrayList<Item>();
    for (List<Item> l: this.expanses.values()) // fill with each category items
        list.addAll(l);
    ArrayList<String> listString = new ArrayList<String>();
    for (Item item : list){
        listString.add(item.getName());
    }
    return listString;
}

public ArrayList<Double> getItemsCost(){
    List<Item> list = new ArrayList<Item>();
    for (List<Item> l: this.expanses.values()) // fill with each category items
        list.addAll(l);
    ArrayList<Double> listDouble = new ArrayList<>();
    for (Item item : list){
        listDouble.add(item.getCost());
    }
    return listDouble;
}

public ArrayList<String> getItemsCategory() {
    List<Item> list = new ArrayList<Item>();
    for (List<Item> l: this.expanses.values()) // fill with each category items
        list.addAll(l);
    ArrayList<String> listString = new ArrayList<String>();
    for (Item item : list){
        listString.add(item.getCategory());
    }
    return listString;
}

/** Get the total cost, given a category. */
public double getCost(String category) {
    List<Item> list = this.expanses.get(category);
    if (list == null)
        return -1;
    double cost = 0;
    for (Item item: list)
        cost += item.cost;
    return cost;
}

/** Get the total cost. */
public double getCost() {
    double cost = 0;
    for (List<Item> l: this.expanses.values())
        for (Item item: l)
            cost += item.cost;
    cost *= 1000;
    cost = (int)(cost);
    cost /= 1000;
    return cost;
    }
}
</code>```

I want to save the array list and when I close and open the app the array list (alltrips) is saved. How to do this?

I want to use shared preferences but I don't know how to do this because it is not a string it array list with Trip. Can anyone help me to save the arraylist in shared preferences?

答: I think the most easiest way to so this is you can save your data in SharedPrefences and populate your arraylist from the sharedPrefernces. As sharedPrefernces only store primitive types you can use Gson for converting your object into String and then store that in the sharedPrefrence. Hope that helps!.

Body:
how to save arraylist after the app is closed.
This is my global class

public class GlobalClass extends Application {

ArrayList<Trip> allTrips = new ArrayList<>();

public ArrayList<String> allTripsString() {
    ArrayList<String> allTripsString = new ArrayList<String>();
    for (Trip trip : allTrips){
        allTripsString.add(trip.getName());
    }
    return allTripsString;
    }
}

This is my trip class

public class Trip {

/** A map with category as key and the associed list of items as value */
Map<String,List<Item>> expanses;

private String name;
public ArrayList<String> ExpensesCategory = new ArrayList<>();
public ArrayList<String> Adults = new ArrayList<>();
public ArrayList<String> Children = new ArrayList<>();
public ArrayList<String> ShoppingName = new ArrayList<>();
public ArrayList<Double> ShoppingPrice = new ArrayList<>();
public ArrayList<String> ShoppingCategory = new ArrayList<>();
public double budget = 0;

/** An item in the expanses list */
static class Item {
    final String name;
    final double cost;
    final String Category;
    public Item(String name, double cost, String Category) {
        this.name = name;
        this.cost = cost;
        this.Category = Category;
    }
    @Override public String toString() {
        return this.name + " (" + this.cost + "$)";
    }
    public String getName(){
        return name;
    }
    public String getCategory(){
        return Category;
    }
    public double getCost(){
        return cost;
    }
}

public Trip(String name) {
    this.name = name;
    this.expanses = new HashMap<String,List<Item>>();
    for (String cat: ExpensesCategory) { // init the categories with empty lists
        this.expanses.put(cat, new ArrayList<Item>());
    }
}

public String getName(){
    return name;
}

/** Register a new expanse to the trip. */
public void add(String item, double cost, String category) {
    List<Item> list = this.expanses.get(category);
    if (list == null)
        throw new IllegalArgumentException("Category '"+category+"' does not exist.");
    list.add( new Item(item, cost, category) );
}

/** Get the expanses, given a category.
 * @return  a fresh ArrayList containing the category elements, or null if the category does not exists
 */
public List<Item> getItems(String category) {
    List<Item> list = this.expanses.get(category);
    if (list == null)
        return null;
    return new ArrayList<Item>(list);
}

/** Get the expanses, given a category.
 * @return  a fresh ArrayList containing all the elements
 */
public List<Item> getItems() {
    List<Item> list = new ArrayList<Item>();
    for (List<Item> l: this.expanses.values()) // fill with each category items
        list.addAll(l);
    return list;
}

public ArrayList<String> getItemsString() {
    List<Item> list = new ArrayList<Item>();
    for (List<Item> l: this.expanses.values()) // fill with each category items
        list.addAll(l);
    ArrayList<String> listString = new ArrayList<String>();
    for (Item item : list){
        listString.add(item.getName());
    }
    return listString;
}

public ArrayList<Double> getItemsCost(){
    List<Item> list = new ArrayList<Item>();
    for (List<Item> l: this.expanses.values()) // fill with each category items
        list.addAll(l);
    ArrayList<Double> listDouble = new ArrayList<>();
    for (Item item : list){
        listDouble.add(item.getCost());
    }
    return listDouble;
}

public ArrayList<String> getItemsCategory() {
    List<Item> list = new ArrayList<Item>();
    for (List<Item> l: this.expanses.values()) // fill with each category items
        list.addAll(l);
    ArrayList<String> listString = new ArrayList<String>();
    for (Item item : list){
        listString.add(item.getCategory());
    }
    return listString;
}

/** Get the total cost, given a category. */
public double getCost(String category) {
    List<Item> list = this.expanses.get(category);
    if (list == null)
        return -1;
    double cost = 0;
    for (Item item: list)
        cost += item.cost;
    return cost;
}

/** Get the total cost. */
public double getCost() {
    double cost = 0;
    for (List<Item> l: this.expanses.values())
        for (Item item: l)
            cost += item.cost;
    cost *= 1000;
    cost = (int)(cost);
    cost /= 1000;
    return cost;
    }
}

I want to save the array list and when I close and open the app the array list (alltrips) is saved. How to do this?

I want to use shared preferences but I don't know how to do this because it is not a string it array list with Trip. Can anyone help me to save the arraylist in shared preferences?


问:
Grails. JSON. his methods?
I was up all night looking for information on how to use JSON in Grails. And I found the information that in JSON closure, we can use only one method - array -  no other. is it true?

and next small question:

i find here: http://www.jiramot.info/mini-guide-to-rendering-json-with-grails example:

```<code>render(contentType:‘text/json’){
        collection{
                pair(name:‘value’)
                pair(name:‘value1′)
        }
}
</code>```

Will be rendered as:

```<code>{collection:[{"name":"value"},{"name":"value1"}]
</code>```

but when i try do it, i have this result:

```<code>{"collection":{"pair":{"name":"value1"}}}
</code>```

What conclusion can we do?
i do some wrong or wrong example on site?

答:
try </p>

```<code>render(contentType:‘text/json’){
        collection {
                array {
                   pair(name:"value")
                   pair(name:"value1")
                }
        }
}
</code>```

Title: Grails. JSON. his methods?

Body:
I was up all night looking for information on how to use JSON in Grails. And I found the information that in JSON closure, we can use only one method - array -  no other. is it true?

and next small question:

i find here: http://www.jiramot.info/mini-guide-to-rendering-json-with-grails example:

render(contentType:‘text/json’){
        collection{
                pair(name:‘value’)
                pair(name:‘value1′)
        }
}

Will be rendered as:

{collection:[{"name":"value"},{"name":"value1"}]

but when i try do it, i have this result:

{"collection":{"pair":{"name":"value1"}}}

What conclusion can we do?
i do some wrong or wrong example on site?

Body:
try

render(contentType:‘text/json’){
        collection {
                array {
                   pair(name:"value")
                   pair(name:"value1")
                }
        }
}


问:
convert numbers to 26base with only letters
I need to convert number in "Alphabetic" Counting System, similar to excel spreadsheets:

convert(1) == "A";

  convert(2) == "B";

  ...

  convert(26) == "Z";

  convert(27) == "AA";

  ...

  convert(52) == "AZ";

  convert(53) == "BA";

  ...

  convert(702 ) == "ZZ";

  convert(703 ) == "AAA";

this is my code:

```<code>function convert($n){
    if ($n> 26) {
        $tmp = floor($n / 26);
        $n= $n % 26;
        $result = chr(($tmp - 1) + 65) . chr(($n - 1) + 65);
    } else {
        $result = chr(($n- 1) + 65);
    }
    return $result;
}
</code>```

but the output is a bit off:

@, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z,

  AA, AB, AC, AD, AE, AF, AG, AH, AI, AJ, AK, AL, AM, AN, AO, AP, AQ, AR, AS, AT, AU, AV, AW, AX, AY,

  B@, BA

I tried to tweak the numbers but I can not make it right, any suggestion for a better algorithm ?

答:
Based on @NiettheDarkAbsol comment,
this is a quick solution if the expected calls are for small numbers:

```<code>function convert($n) {
    for($out = 'A'; --$n > 0; $out++);
    return $out;
}
</code>```

From docs

PHP follows Perl's convention when dealing with arithmetic operations on character variables and not C's. For example, in PHP and Perl $a = 'Z'; $a++; turns $a into 'AA', while in C a = 'Z'; a++; turns a into '[' (ASCII value of 'Z' is 90, ASCII value of '[' is 91). Note that character variables can be incremented but not decremented and even so only plain ASCII alphabets and digits (a-z, A-Z and 0-9) are supported. Incrementing/decrementing other character variables has no effect, the original string is unchanged.

Body:
I need to convert number in "Alphabetic" Counting System, similar to excel spreadsheets:

convert(1) == "A";

  convert(2) == "B";

  ...

  convert(26) == "Z";

  convert(27) == "AA";

  ...

  convert(52) == "AZ";

  convert(53) == "BA";

  ...

  convert(702 ) == "ZZ";

  convert(703 ) == "AAA";

this is my code:

function convert($n){
    if ($n> 26) {
        $tmp = floor($n / 26);
        $n= $n % 26;
        $result = chr(($tmp - 1) + 65) . chr(($n - 1) + 65);
    } else {
        $result = chr(($n- 1) + 65);
    }
    return $result;
}

but the output is a bit off:

@, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z,

  AA, AB, AC, AD, AE, AF, AG, AH, AI, AJ, AK, AL, AM, AN, AO, AP, AQ, AR, AS, AT, AU, AV, AW, AX, AY,

  B@, BA

I tried to tweak the numbers but I can not make it right, any suggestion for a better algorithm ?

Body:
Based on @NiettheDarkAbsol comment,
this is a quick solution if the expected calls are for small numbers:

function convert($n) {
    for($out = 'A'; --$n > 0; $out++);
    return $out;
}

From docs

PHP follows Perl's convention when dealing with arithmetic operations on character variables and not C's. For example, in PHP and Perl $a = 'Z'; $a++; turns $a into 'AA', while in C a = 'Z'; a++; turns a into '[' (ASCII value of 'Z' is 90, ASCII value of '[' is 91). Note that character variables can be incremented but not decremented and even so only plain ASCII alphabets and digits (a-z, A-Z and 0-9) are supported. Incrementing/decrementing other character variables has no effect, the original string is unchanged.


问:
When to install packages with a preseed file and when to provision packages with Packer?
So I have been busy tweaking my Packer Ubuntu Configuration for a few days.

I am busy installing Ubuntu only and reached the point where I need to install the packages that I need for my machine. The end result is to make a vagrant box with packages preinstalled on it

Currently, I put all of my package configuration in my preseed.cfg file and I do not have a provision block at the moment. My understanding is that you can install packages within the preseed.cfg or provision block (via script or something like chef)

This is the line in my preseed.cfg file:

```<code>d-i pkgsel/include string  build-essential linux-headers-$(uname -r) openssh-server ubuntu-minimal
</code>```

So my question is when is it appropriate from a packer point of view to install packages via preseed.cfg and when is it appropriate to use a provisioner??

答:
When you write a provisioning script, I (I talk only for myself, other are welcome to put their comments) aim at 2 things:

I install packages but not only, generally I will install with a set of configuration (so for example, I install Apache but I want to configure a virtualhost or something)

I want cross-system script so I can re-use them to provision any server (so I try to avoid shell scripting as much as possible - and if I need to end writing shell command if I develop new provisionner module, I do it for most of linux family I could use)

After my personal use of packer/vagrant is to use packer to create minimal box so I would not even put my provisioning there (only in a case the provisioning step is taking too long and I need to create new vagrant VM instances from scratch quite often) - I put the provisioning step in vagrant and it will be run when vagrant will spin the new VM.

Going back to your question, I would use the preseed for general package that do not require configuration and are absolutely necessary for the system to work; put the rest in the provisioning

Body:
So I have been busy tweaking my Packer Ubuntu Configuration for a few days.

I am busy installing Ubuntu only and reached the point where I need to install the packages that I need for my machine. The end result is to make a vagrant box with packages preinstalled on it

Currently, I put all of my package configuration in my preseed.cfg file and I do not have a provision block at the moment. My understanding is that you can install packages within the preseed.cfg or provision block (via script or something like chef)

This is the line in my preseed.cfg file:

d-i pkgsel/include string  build-essential linux-headers-$(uname -r) openssh-server ubuntu-minimal

So my question is when is it appropriate from a packer point of view to install packages via preseed.cfg and when is it appropriate to use a provisioner??


问:
Invoke Class Method using Reflection with different params in constructor?
Hello i am very new to c# reflection and i have the following problem.

I have a CommandDispatcher class that invokes a certain Command class that does something.

For now i use a switch to determinate what command to invoke.

i wanted to simplify the code by using reflection to invoke the right command and get rid of the switch for good.

But each command takes a certain service or more in its constructor. I don't want to change that part . I understand that if i had no services passed in the constructor the code would work fine.

So how can i invoke my commands with reflection when each command takes one or many services.

Here is an image for better understanding: The code with color indicators

I left the switch not commented out for easier reading.

Here is the code in pastebin: https://pastebin.com/AMQeh1zw

My search did not result in finding anything to solve my problem.

答:
I suggest to use Dependency Injection library for example Ninject and
nuget link.
For your purporse  you can use next construction:

This code init your Dependency Injection core

```<code>    var kernel = new StandardKernel();
    kernel.Load(Assembly.GetExecutingAssembly());
</code>```

And your switch:

```<code>switch (commandName)
        {
            case "RegisterUser":
                RegisterUserCommand registerUser = kernel.Get<RegisterUserCommand>();
                result = registerUser.Execute(commandParameters);
                break;
            case "Login":
                LoginCommand loginCommand = kernel.Get<LoginCommand>();
                result = loginCommand.Execute(commandParameters);
                break;
    }
</code>```

Body:
I suggest to use Dependency Injection library for example Ninject and
nuget link.
For your purporse  you can use next construction:

This code init your Dependency Injection core

    var kernel = new StandardKernel();
    kernel.Load(Assembly.GetExecutingAssembly());

And your switch:

switch (commandName)
        {
            case "RegisterUser":
                RegisterUserCommand registerUser = kernel.Get<RegisterUserCommand>();
                result = registerUser.Execute(commandParameters);
                break;
            case "Login":
                LoginCommand loginCommand = kernel.Get<LoginCommand>();
                result = loginCommand.Execute(commandParameters);
                break;
    }


问:
What is the exact difference between Fix and Self on the Calculus of Constructions?
The Self Types for Dependently Typed Lambda Encodings paper (by Peng Fu and Aaron Stump) proposes self types, which are, supposedly, sufficient to encode the induction principle and Scott-encoded datatypes on the Calculus of Constructions, without making the system inconsistent or introducing paradoxes.

The notation of that paper is too heavy for me to fully understand how to implement it.

What is, precisely, the main difference of Fix and Self? Or, in other words: in what points a naively implemented Fix should be restricted, so that it leaves no inconsistencies on the core calculus?

答:
This is what I have understood after browsing the paper.

A Fix type satisfies the typing equivalence (assuming equirecursive types)

```<code>G |- M : Fix x. t   <=>     G |- M : t{Fix x. t / x}
</code>```

i.e. you can unfold the type over itself. Note how the term M does not play any role here. If using isorecursive types, M would get some isomorphism applied (e.g. a Haskell's newtype constructor), but it is not that important.

Instead, Self types satisfy the following

```<code>G |- M : Self x. t   <=>     G |- M : t{M / x}
</code>```

Now, x is not a type variable, but a term variable. The term gets "moved" inside the type. This is not a recursive type at all.

Body:
This is what I have understood after browsing the paper.

A Fix type satisfies the typing equivalence (assuming equirecursive types)

G |- M : Fix x. t   <=>     G |- M : t{Fix x. t / x}

i.e. you can unfold the type over itself. Note how the term M does not play any role here. If using isorecursive types, M would get some isomorphism applied (e.g. a Haskell's newtype constructor), but it is not that important.

Instead, Self types satisfy the following

G |- M : Self x. t   <=>     G |- M : t{M / x}

Now, x is not a type variable, but a term variable. The term gets "moved" inside the type. This is not a recursive type at all.


问:
Subscribing to Observable in service from component
I have searched for quite some time to understand how to subscribe to an array whose values are constantly updated.

I need to understand how to setup my Angular 2+ service observable correctly and subscribe to it in my component correctly. Please assume all other parts of the code works correctly.

```<code>@Injectable()
export class AutocompleteService {

    searchTerm: string;
    results = [];
    observe$ = Observable.from(this.results);

    searchTest(term){
        this.searchTerm = term.toLowerCase();

        if(this.searchTerm.length > 2){
            this.recruiters.forEach(function(el){
                if(el.name.toLowerCase().indexOf(term) != -1) {
                    this.results.push(el);
                }
            });

        }
    }

    getCurrentResults():Observable<Object> {
        return this.observe$;
    }
</code>```

Everything in the service works as expected. If I log the term I get user input from my component. Or the results array after matching search results are pushed onto it.

```<code>@Component({
    selector: 'autocomplete',
    templateUrl: './autocomplete.component.html',
    providers: [AutocompleteService]
})
export class AutocompleteComponent implements OnInit{
    constructor(private autocompleteService: AutocompleteService){}

    value: string = '';
    searchControl = new FormControl();

    // fired when input happens
    getResults(event){
        this.autocompleteService.searchTest(event.target.value);

        this.autocompleteService.getCurrentResults().subscribe(
            value => console.log(value)
        );

    }
</code>```

I have setup the observable pattern to the best of my ability but I'm not getting anything out of the .subscribe in getResults

答:
There are many errors in your code

There isn't a this.recruiters field in your service

this.results.push(el); won't push anything to results because you are using forEach(function(el){ it should've been forEach((el)=> so that your this inside the scope would refer to your service.

Example plunker: http://plnkr.co/edit/5L0dE7ZNgpJSK4AbK0oM?p=preview

Body:
I have searched for quite some time to understand how to subscribe to an array whose values are constantly updated.

I need to understand how to setup my Angular 2+ service observable correctly and subscribe to it in my component correctly. Please assume all other parts of the code works correctly.

@Injectable()
export class AutocompleteService {

    searchTerm: string;
    results = [];
    observe$ = Observable.from(this.results);

    searchTest(term){
        this.searchTerm = term.toLowerCase();

        if(this.searchTerm.length > 2){
            this.recruiters.forEach(function(el){
                if(el.name.toLowerCase().indexOf(term) != -1) {
                    this.results.push(el);
                }
            });

        }
    }

    getCurrentResults():Observable<Object> {
        return this.observe$;
    }

Everything in the service works as expected. If I log the term I get user input from my component. Or the results array after matching search results are pushed onto it.

@Component({
    selector: 'autocomplete',
    templateUrl: './autocomplete.component.html',
    providers: [AutocompleteService]
})
export class AutocompleteComponent implements OnInit{
    constructor(private autocompleteService: AutocompleteService){}

    value: string = '';
    searchControl = new FormControl();

    // fired when input happens
    getResults(event){
        this.autocompleteService.searchTest(event.target.value);

        this.autocompleteService.getCurrentResults().subscribe(
            value => console.log(value)
        );

    }

I have setup the observable pattern to the best of my ability but I'm not getting anything out of the .subscribe in getResults


问:
How to prevent using too much if statements in this situation?
I want to write a python3x program that does something when user enter a special command. For example I have commands like this : !add, !edit, !remove
and I have functions to do what I want ,like : add()  edit()  remove().
One way to do this is to write program using if statements but I have lot's of commands and I am looking for a better idea.
I appreciate your help :)</p>

答:
Here is a small example on how you can call functions by using a string to identify the name of the function you want to call:

```<code>def hello():
    print("Hello")

def world():
    print("World")

helloFunc = globals()["hello"]
helloFunc()

worldFunc = locals()["world"]
worldFunc()
</code>```

The output will look like this:

```<code>Hello
World
</code>```

In essence, you can substitute the string literal for a variable, which would be part of the command that the user entered

Body:
Here is a small example on how you can call functions by using a string to identify the name of the function you want to call:

def hello():
    print("Hello")

def world():
    print("World")

helloFunc = globals()["hello"]
helloFunc()

worldFunc = locals()["world"]
worldFunc()

The output will look like this:

Hello
World

In essence, you can substitute the string literal for a variable, which would be part of the command that the user entered


答:
You need to save your data into the database or you can follow this Stackoverflow question
Question</p>

Title: how to save arraylist<object> after app is closed


问:
Set navigation bar image in iOS 7
I want to convert my current project from iOS 6 to iOS 7.
In iOS 6 my project is working fine, but in iOS 7 navigation bar image is not showing properly.

I used this code snippet for iOS 6,

```<code>UIImage *imgNav = [UIImage imageNamed:@"navigation.png"];
self.navigationController.navigationBar.frame = CGRectMake(0, 0, 320, 44);
[self.navigationController.navigationBar setBackgroundImage:imgNav forBarMetrics:
     UIBarMetricsDefault];
</code>```

How can I set the navigation bar image in iOS 7?

答:
Try this code in appDelegate class it will help you.</p>

```<code>[[UINavigationBar appearance] setBackgroundImage:[[UIImage imageNamed:@"navbarimg.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)] forBarMetrics:UIBarMetricsDefault];
</code>```

Title: Set navigation bar image in iOS 7

Body:
I want to convert my current project from iOS 6 to iOS 7.
In iOS 6 my project is working fine, but in iOS 7 navigation bar image is not showing properly.

I used this code snippet for iOS 6,

UIImage *imgNav = [UIImage imageNamed:@"navigation.png"];
self.navigationController.navigationBar.frame = CGRectMake(0, 0, 320, 44);
[self.navigationController.navigationBar setBackgroundImage:imgNav forBarMetrics:
     UIBarMetricsDefault];

How can I set the navigation bar image in iOS 7?

Body:
Try this code in appDelegate class it will help you.

[[UINavigationBar appearance] setBackgroundImage:[[UIImage imageNamed:@"navbarimg.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)] forBarMetrics:UIBarMetricsDefault];


问:
How to stop camel http retry
We are using toD component of camel 2.18.1 to post a body to http web service but when the url is invalid camel is internally retrying for 2-3 minutes, which is something I do not want.

I explored further and found out that camel is internally using org.apache.commons.httpclient.HttpMethodDirector to perform the retry operation. How can stop Camel from doing this.

Part exception log is below.

```<code><2017-03-29 16:33:59,084>:<>:<>:<>:<org.apache.commons.httpclient.HttpMethodDirector>:<INFO >:[Camel (camel-1) thread #20 - Threads]::<I/O exception (java.net.ConnectException) caught when processing request: Connection timed out (Connection timed out)>
<2017-03-29 16:33:59,085>:<>:<>:<>:<org.apache.commons.httpclient.HttpMethodDirector>:<INFO >:[Camel (camel-1) thread #20 - Threads]::<Retrying request>
<2017-03-29 16:36:06,313>:<>:<>:<>:<org.apache.commons.httpclient.HttpMethodDirector>:<INFO >:[Camel (camel-1) thread #20 - Threads]::<I/O exception (java.net.ConnectException) caught when processing request: Connection timed out (Connection timed out)>
<2017-03-29 16:36:06,314>:<>:<>:<>:<org.apache.commons.httpclient.HttpMethodDirector>:<INFO >:[Camel (camel-1) thread #20 - Threads]::<Retrying request>
<2017-03-29 16:38:13,545>:<>:<>:<>:<org.apache.commons.httpclient.HttpMethodDirector>:<INFO >:[Camel (camel-1) thread #20 - Threads]::<I/O exception (java.net.ConnectException) caught when processing request: Connection timed out (Connection timed out)>
<2017-03-29 16:38:13,546>:<>:<>:<>:<org.apache.commons.httpclient.HttpMethodDirector>:<INFO >:[Camel (camel-1) thread #20 - Threads]::<Retrying request>
</code>```

here is the stack trace which I am getting

```<code>java.net.ConnectException: Connection timed out (Connection timed out)
        at java.net.PlainSocketImpl.socketConnect(Native Method)
        at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
        at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
        at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
        at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
        at java.net.Socket.connect(Socket.java:589)
        at java.net.Socket.connect(Socket.java:538)
        at java.net.Socket.<init>(Socket.java:434)
        at java.net.Socket.<init>(Socket.java:286)
        at org.apache.commons.httpclient.protocol.DefaultProtocolSocketFactory.createSocket(DefaultProtocolSocketFactory.java:80)
        at org.apache.commons.httpclient.protocol.DefaultProtocolSocketFactory.createSocket(DefaultProtocolSocketFactory.java:122)
        at org.apache.commons.httpclient.HttpConnection.open(HttpConnection.java:707)
        at org.apache.commons.httpclient.MultiThreadedHttpConnectionManager$HttpConnectionAdapter.open(MultiThreadedHttpConnectionManager.java:1361)
        at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:387)
        at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171)
        at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397)
        at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:323)
        at org.apache.camel.component.http.HttpProducer.executeMethod(HttpProducer.java:257)
        at org.apache.camel.component.http.HttpProducer.process(HttpProducer.java:152)
        at org.apache.camel.util.AsyncProcessorConverterHelper$ProcessorToAsyncProcessorBridge.process(AsyncProcessorConverterHelper.java:61)
        at org.apache.camel.processor.SendDynamicProcessor$1.doInAsyncProducer(SendDynamicProcessor.java:124)
        at org.apache.camel.impl.ProducerCache.doInAsyncProducer(ProducerCache.java:436)
        at org.apache.camel.processor.SendDynamicProcessor.process(SendDynamicProcessor.java:119)
        at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:77)
        at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:197)
        at org.apache.camel.processor.Pipeline.process(Pipeline.java:120)
        at org.apache.camel.processor.Pipeline.process(Pipeline.java:83)
        at org.apache.camel.processor.TryProcessor.process(TryProcessor.java:113)
        at org.apache.camel.processor.TryProcessor.process(TryProcessor.java:84)
        at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:77)
        at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:542)
        at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:197)
        at org.apache.camel.processor.Pipeline.process(Pipeline.java:120)
        at org.apache.camel.processor.Pipeline.process(Pipeline.java:83)
        at org.apache.camel.processor.Pipeline.process(Pipeline.java:120)
        at org.apache.camel.processor.Pipeline.access$100(Pipeline.java:44)
        at org.apache.camel.processor.Pipeline$1.done(Pipeline.java:138)
        at org.apache.camel.processor.ThreadsProcessor$ProcessCall.run(ThreadsProcessor.java:88)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)
</code>```

finally here is the code being used in the route builder

```<code> from("disruptor:" + "CallAPostService")
                    .routeId("CallAPostService")
                    .threads()
                    .log(LoggingLevel.INFO, LOG, "Processing id ${id} disruptor")
                    .doTry()
                        .process(new populateRequestBody()) // this processor sets the request xml to excahnge body
                                    .log(LoggingLevel.INFO, LOG, "Request XML = ${body}")
                                    .setHeader(Exchange.HTTP_METHOD, simple("POST"))
                                    .setHeader(Exchange.HTTP_BASE_URI, constant(""))
                                    .setHeader(Exchange.HTTP_PATH, constant(""))
                                    .setHeader(Exchange.HTTP_URI, simple(""))
                                                                    .setHeader(Exchange.HTTP

_URL, simple(""))
                                                                .toD("http://172.0.0.0:7001/myapp/cosumemessage" + "?bridgeEndpoint=true")
 .doCatch(Exception.class)
 .log(LoggingLevel.ERROR, LOG, "Processing id ${id} disruptor, Unknown Exception")
.doFinally();
</code>```

答:
Implement a HttpClientConfigurer and at it to the registry.

```<code>@Bean(name = "httpConfigurer")
public HttpClientConfigurer createCustomConfigurer() {
    return new HttpClientConfigurer() {

        @Override
        public void configureHttpClient(HttpClient client) {
            client.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 10000);
            client.getParams().setParameter("http.method.retry-handler", new DefaultHttpMethodRetryHandler(0, false));            }
    };
}
</code>```

Set HttpComponent's httpClientConfigurer like the following:

```<code>.toD("http://1.2.3.4/xyz?httpClientConfigurer=httpConfigurer")
</code>```

Title: How to stop camel http retry

Body:
We are using toD component of camel 2.18.1 to post a body to http web service but when the url is invalid camel is internally retrying for 2-3 minutes, which is something I do not want.

I explored further and found out that camel is internally using org.apache.commons.httpclient.HttpMethodDirector to perform the retry operation. How can stop Camel from doing this.

Part exception log is below.

<2017-03-29 16:33:59,084>:<>:<>:<>:<org.apache.commons.httpclient.HttpMethodDirector>:<INFO >:[Camel (camel-1) thread #20 - Threads]::
<2017-03-29 16:33:59,085>:<>:<>:<>:<org.apache.commons.httpclient.HttpMethodDirector>:<INFO >:[Camel (camel-1) thread #20 - Threads]::<Retrying request>
<2017-03-29 16:36:06,313>:<>:<>:<>:<org.apache.commons.httpclient.HttpMethodDirector>:<INFO >:[Camel (camel-1) thread #20 - Threads]::
<2017-03-29 16:36:06,314>:<>:<>:<>:<org.apache.commons.httpclient.HttpMethodDirector>:<INFO >:[Camel (camel-1) thread #20 - Threads]::<Retrying request>
<2017-03-29 16:38:13,545>:<>:<>:<>:<org.apache.commons.httpclient.HttpMethodDirector>:<INFO >:[Camel (camel-1) thread #20 - Threads]::
<2017-03-29 16:38:13,546>:<>:<>:<>:<org.apache.commons.httpclient.HttpMethodDirector>:<INFO >:[Camel (camel-1) thread #20 - Threads]::<Retrying request>

here is the stack trace which I am getting

java.net.ConnectException: Connection timed out (Connection timed out)
        at java.net.PlainSocketImpl.socketConnect(Native Method)
        at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
        at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
        at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
        at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
        at java.net.Socket.connect(Socket.java:589)
        at java.net.Socket.connect(Socket.java:538)
        at java.net.Socket.<init>(Socket.java:434)
        at java.net.Socket.<init>(Socket.java:286)
        at org.apache.commons.httpclient.protocol.DefaultProtocolSocketFactory.createSocket(DefaultProtocolSocketFactory.java:80)
        at org.apache.commons.httpclient.protocol.DefaultProtocolSocketFactory.createSocket(DefaultProtocolSocketFactory.java:122)
        at org.apache.commons.httpclient.HttpConnection.open(HttpConnection.java:707)
        at org.apache.commons.httpclient.MultiThreadedHttpConnectionManager$HttpConnectionAdapter.open(MultiThreadedHttpConnectionManager.java:1361)
        at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:387)
        at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171)
        at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397)
        at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:323)
        at org.apache.camel.component.http.HttpProducer.executeMethod(HttpProducer.java:257)
        at org.apache.camel.component.http.HttpProducer.process(HttpProducer.java:152)
        at org.apache.camel.util.AsyncProcessorConverterHelper$ProcessorToAsyncProcessorBridge.process(AsyncProcessorConverterHelper.java:61)
        at org.apache.camel.processor.SendDynamicProcessor$1.doInAsyncProducer(SendDynamicProcessor.java:124)
        at org.apache.camel.impl.ProducerCache.doInAsyncProducer(ProducerCache.java:436)
        at org.apache.camel.processor.SendDynamicProcessor.process(SendDynamicProcessor.java:119)
        at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:77)
        at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:197)
        at org.apache.camel.processor.Pipeline.process(Pipeline.java:120)
        at org.apache.camel.processor.Pipeline.process(Pipeline.java:83)
        at org.apache.camel.processor.TryProcessor.process(TryProcessor.java:113)
        at org.apache.camel.processor.TryProcessor.process(TryProcessor.java:84)
        at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:77)
        at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:542)
        at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:197)
        at org.apache.camel.processor.Pipeline.process(Pipeline.java:120)
        at org.apache.camel.processor.Pipeline.process(Pipeline.java:83)
        at org.apache.camel.processor.Pipeline.process(Pipeline.java:120)
        at org.apache.camel.processor.Pipeline.access$100(Pipeline.java:44)
        at org.apache.camel.processor.Pipeline$1.done(Pipeline.java:138)
        at org.apache.camel.processor.ThreadsProcessor$ProcessCall.run(ThreadsProcessor.java:88)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)

finally here is the code being used in the route builder

 from("disruptor:" + "CallAPostService")
                    .routeId("CallAPostService")
                    .threads()
                    .log(LoggingLevel.INFO, LOG, "Processing id ${id} disruptor")
                    .doTry()
                        .process(new populateRequestBody()) // this processor sets the request xml to excahnge body
                                    .log(LoggingLevel.INFO, LOG, "Request XML = ${body}")
                                    .setHeader(Exchange.HTTP_METHOD, simple("POST"))
                                    .setHeader(Exchange.HTTP_BASE_URI, constant(""))
                                    .setHeader(Exchange.HTTP_PATH, constant(""))
                                    .setHeader(Exchange.HTTP_URI, simple(""))
                                                                    .setHeader(Exchange.HTTP

_URL, simple(""))
                                                                .toD("http://172.0.0.0:7001/myapp/cosumemessage" + "?bridgeEndpoint=true")
 .doCatch(Exception.class)
 .log(LoggingLevel.ERROR, LOG, "Processing id ${id} disruptor, Unknown Exception")
.doFinally();

Body:
Implement a HttpClientConfigurer and at it to the registry.

@Bean(name = "httpConfigurer")
public HttpClientConfigurer createCustomConfigurer() {
    return new HttpClientConfigurer() {

        @Override
        public void configureHttpClient(HttpClient client) {
            client.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 10000);
            client.getParams().setParameter("http.method.retry-handler", new DefaultHttpMethodRetryHandler(0, false));            }
    };
}

Set HttpComponent's httpClientConfigurer like the following:

.toD("http://1.2.3.4/xyz?httpClientConfigurer=httpConfigurer")


问:
How do I detect a failed state on multiple files when running md5sum on multiple files
I use:

```<code>md5sum * > checklist.chk # Generates a list of checksums and files.
</code>```

and use:

```<code>md5sum -c checklist.chk   # runs through the list to check them
</code>```

How can I automate a PASS or FAIL state? I basically want to get a notification if something on my app changes. Whether by hacker or unauthorized change by a developer. I want to write a script that will notify of any changes to my code.

I found a few scripts online but they only appear to work for single files, I have been unable to adapt the script to work for multiple files with pass or fail states.

```<code>if [ "$(md5sum < File.name)" = "24f4ce42e0bc39ddf7b7e879a  -" ]
then
  echo Pass
else
  echo Fail
fi
</code>```

Reference:

Shell scripts and the md5/md5sum command: need to decide when to use which one
https://unix.stackexchange.com/questions/290240/md5sum-check-no-file

答:
Store your checksums directly in the script. Then just run the md5sum -c.

Something like:

```<code>#!/bin/bash

get_stored_checksums() {
grep -P '^[0-9a-f]{32}  .' <<-'EOF'
#########################################################
# Stored checksums in the script itself
# the output from the md5sum for the files you want guard
5e3f61b243679426d7f74c22b863438b  Workbook1.xls
777a161c82fe0c810e00560411fb076e  Workbook1.xlsx

# empty lines and comments - theyre simply ignored
d41d8cd98f00b204e9800998ecf8427e  abc def.xxx

# this very important file
809f911bcde79d6d0f6dc8801d367bb5  jj.xxx
#########################################################
EOF
}

#MAIN
cd /where/the/files/are

#run the md5sum in the check-mode
result=$( md5sum -c <(get_stored_checksums) )
if (( $? ))
then
    #found some problems
    echo "$result"
    #mail -s "PROBLEM" security.manager@example.com <<<"$result"
#else
#   echo "all OK"
fi
</code>```

If something is wrong, you will see something like:

```<code>Workbook1.xls: OK
Workbook1.xlsx: OK
abc def.xxx: FAILED
jj.xxx: OK
md5sum: WARNING: 1 of 4 computed checksums did NOT match
</code>```

Of course, you can change the get_stored_checksums function to anything other, like:

```<code>get_stored_checksums() {
    curl -s 'http://integrityserver.example.com/mytoken'
}
</code>```

and you will fetch the guarded checksums from the remote server...

Body:
I use:

md5sum * > checklist.chk # Generates a list of checksums and files.

and use:

md5sum -c checklist.chk   # runs through the list to check them

How can I automate a PASS or FAIL state? I basically want to get a notification if something on my app changes. Whether by hacker or unauthorized change by a developer. I want to write a script that will notify of any changes to my code.

I found a few scripts online but they only appear to work for single files, I have been unable to adapt the script to work for multiple files with pass or fail states.

if [ "$(md5sum < File.name)" = "24f4ce42e0bc39ddf7b7e879a  -" ]
then
  echo Pass
else
  echo Fail
fi

Reference:

Shell scripts and the md5/md5sum command: need to decide when to use which one
https://unix.stackexchange.com/questions/290240/md5sum-check-no-file

Body:
Store your checksums directly in the script. Then just run the md5sum -c.

Something like:

#!/bin/bash

get_stored_checksums() {
grep -P '^[0-9a-f]{32}  .' <<-'EOF'
#########################################################
# Stored checksums in the script itself
# the output from the md5sum for the files you want guard
5e3f61b243679426d7f74c22b863438b  Workbook1.xls
777a161c82fe0c810e00560411fb076e  Workbook1.xlsx

# empty lines and comments - theyre simply ignored
d41d8cd98f00b204e9800998ecf8427e  abc def.xxx

# this very important file
809f911bcde79d6d0f6dc8801d367bb5  jj.xxx
#########################################################
EOF
}

#MAIN
cd /where/the/files/are

#run the md5sum in the check-mode
result=$( md5sum -c <(get_stored_checksums) )
if (( $? ))
then
    #found some problems
    echo "$result"
    #mail -s "PROBLEM" security.manager@example.com <<<"$result"
#else
#   echo "all OK"
fi

If something is wrong, you will see something like:

Workbook1.xls: OK
Workbook1.xlsx: OK
abc def.xxx: FAILED
jj.xxx: OK
md5sum: WARNING: 1 of 4 computed checksums did NOT match

Of course, you can change the get_stored_checksums function to anything other, like:

get_stored_checksums() {
    curl -s 'http://integrityserver.example.com/mytoken'
}

and you will fetch the guarded checksums from the remote server...


问:
CakePHP: Append default string to Page Titles
I'm setting individual page titles in my controllers' actions using:

```<code>$this->set( 'title_for_layout', 'Some Title' );
</code>```

What I want to achieve is append a site title string to all these titles before rendering, i.e. say, "Some Title :: Site Name".

The easiest way out would be to add this string manually to each point where the page title is set - but that's like the brute force way.

What I tried was to override the beforeRender() method of each controller and add this statement:

```<code>$this->set( 'title_for_layout', $this->title_for_layout . ' » ' . Configure::read( 'Site.title' ) );
</code>```

I thought this would append the site's title to the page title for each action - but what I get instead is:

```<code>Notice (8): Undefined variable: SomeController::title_for_layout [APP\controllers\some_controller.php, line xx]
</code>```

It seems like the title_for_layout (set in individual actions in the controller) hasn't been set yet - which is throwing up this error.

My question is, where & How can I append the site title globally to all page titles - if not in this way?

Thanks,
m^e

答: use $this->pageTitle instead of $this->title_for_layout

Body:
I'm setting individual page titles in my controllers' actions using:

$this->set( 'title_for_layout', 'Some Title' );

What I want to achieve is append a site title string to all these titles before rendering, i.e. say, "Some Title :: Site Name".

The easiest way out would be to add this string manually to each point where the page title is set - but that's like the brute force way.

What I tried was to override the beforeRender() method of each controller and add this statement:

$this->set( 'title_for_layout', $this->title_for_layout . ' » ' . Configure::read( 'Site.title' ) );

I thought this would append the site's title to the page title for each action - but what I get instead is:

Notice (8): Undefined variable: SomeController::title_for_layout [APP\controllers\some_controller.php, line xx]

It seems like the title_for_layout (set in individual actions in the controller) hasn't been set yet - which is throwing up this error.

My question is, where & How can I append the site title globally to all page titles - if not in this way?

Thanks,
m^e