问:
How to convert from Octal to Decimal in Swift
Hi I am trying to convert an octal number to decimal in swift. What would be the easiest way to do this? </p>

答:
you can convert from octal to decimal easily. Swift supports octal syntax natively. You have to write "0o" before the octal number.

```<code>let number = 0o10
print(number) // it prints the number 8 in decimal
</code>```

Integer Literals

Integer literals represent integer values of unspecified precision. By
  default, integer literals are expressed in decimal; you can specify an
  alternate base using a prefix. Binary literals begin with 0b, octal
  literals begin with 0o, and hexadecimal literals begin with 0x.

Here is the documentation's reference.

I hope it helps you

Body:
you can convert from octal to decimal easily. Swift supports octal syntax natively. You have to write "0o" before the octal number.

let number = 0o10
print(number) // it prints the number 8 in decimal

Integer Literals

Integer literals represent integer values of unspecified precision. By
  default, integer literals are expressed in decimal; you can specify an
  alternate base using a prefix. Binary literals begin with 0b, octal
  literals begin with 0o, and hexadecimal literals begin with 0x.

Here is the documentation's reference.

I hope it helps you


来源: stackexchange

问:
How facebook App links work as deferred link on iOS
How facebook app links or Tapstream deep links provide support for deferred links on iOS.
For example when app is not installed on device then it redirect to app store which is fine; but it also sends the data to app on installation which was there with link.</p>

答:
There is no way to pass data through the App Store, so all deferred deep linking works by using a remote server to close the loop. You can build this yourself, but you really shouldn't for a lot of reasons, not the least of which being you have more important things to do. This is how Facebook and Tapstream provide deferred deep linking, and using third party tools for this is industry standard — even big names like Yelp and Tinder do so..

Facebook App Links are a completely different concept, and they have no support for deferred deep linking. They are essentially unsupported by any app on iOS (including Facebook) at this time, so they're not really worth your effort to implement.

The deferred deep link functionality provided by both Facebook and Tapstream is incomplete and unreliable. You should investigate a free service like Branch.io (full disclosure: they're so awesome I work with them) or Firebase Dynamic Links to handle all of this for you.

ContentLicense: CC BY-SA 3.0


问:
Embedding Java in Firefox 53+
After researching Java support in Firefox 53+ they dropped support on plugin NPAPI and recommend using Java Web Start. It seems like the only way to get Web Start to run is by having a link to the JNLP file which has you download the file and run it out of the browser. Is there anyway now or in the future Java will be able to be embedded in a webpage in Firefox 53+?

*Note: I am aware that Firefox ESR exists, but to my knowledge they will be dropping Java Plugin support in early 2018. I have also read that IE and Safari will continue to support the Java Plugin, but I'm looking to run it embedded in Firefox 53+.

答:
Is there anyway now or in the future Java will be able to be embedded in a webpage in Firefox 53+?

Short answer, no. Long answer nope.

See Java Plugin support deprecated and Moving to a Plugin-Free Web.

Title: Embedding Java in Firefox 53+


问:
How to make Uploader in CGI shell script
I want to make uploader script in CGI bash (shell script)

with a "browse" and "submit" to upload files from it

note : the uploader without ftp and without user and password of ftp or cpanel or sftp

or:

I want to make CGI script "bash", so script can upload files into the web.

答:
I did this using the example in Uploading Binary Files in Bash CGI Script but there's a small mistake which we fixed later:</p>

```<code>file=/tmp/$$-$RANDOM

# CGI output must start with at least empty line (or headers)
printf '\r\n'
  cat <<EOF
<html>
<head>
<title>Upload</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>
<body>
EOF

IFS=$'\r'
read -r delim_line

IFS=''
delim_line="${delim_line}--"$'\r'

read -r line
filename=$(echo $line | sed 's/^.*filename=//' | sed 's/\"//g' | sed 's/.$//')
fileext=${filename##*.}

while read -r line; do
    test "$line" = '' && break
    test "$line" = $'\r' && break
done

# Note: This will result in junk at end of line (see format above)
cat > $file

# Get the line count
LINES=$(wc -l $file | cut -d ' ' -f 1)

# Remove the last line
head -$((LINES - 1)) $file >$file.1

# Copy eveything but the last line to a temp file
head -$((LINES - 2)) $file.1 >$file.2

# Copy the new last line but remove trailing \r\n
tail -1 $file.1 > $file.3
tail -c 2 $file.3 > $file.5
CRLF=$(hexdump -ve '/1 "%.2x"' $file.5)
# Check if the last two bytes are \r\n
if [ "$CRLF" = "0d0a" ];then
   BYTES=$(wc -c $file.3 | cut -d ' ' -f 1)
   truncate -s $((BYTES-2)) $file.3
fi

rm $file.5
cat $file.2 $file.3 > $file.4
cp $file.4 $file

cat <<EOF
<h1>Upload Successful</h1>
EOF

cat <<EOF
</body>
</html>
EOF

exit 0
</code>```

Body:
I did this using the example in Uploading Binary Files in Bash CGI Script but there's a small mistake which we fixed later:

file=/tmp/$$-$RANDOM

# CGI output must start with at least empty line (or headers)
printf '\r\n'
  cat <<EOF
<html>
<head>
<title>Upload</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>
<body>
EOF

IFS=$'\r'
read -r delim_line

IFS=''
delim_line="${delim_line}--"$'\r'

read -r line
filename=$(echo $line | sed 's/^.*filename=//' | sed 's/\"//g' | sed 's/.$//')
fileext=${filename##*.}

while read -r line; do
    test "$line" = '' && break
    test "$line" = $'\r' && break
done

# Note: This will result in junk at end of line (see format above)
cat > $file

# Get the line count
LINES=$(wc -l $file | cut -d ' ' -f 1)

# Remove the last line
head -$((LINES - 1)) $file >$file.1

# Copy eveything but the last line to a temp file
head -$((LINES - 2)) $file.1 >$file.2

# Copy the new last line but remove trailing \r\n
tail -1 $file.1 > $file.3
tail -c 2 $file.3 > $file.5
CRLF=$(hexdump -ve '/1 "%.2x"' $file.5)
# Check if the last two bytes are \r\n
if [ "$CRLF" = "0d0a" ];then
   BYTES=$(wc -c $file.3 | cut -d ' ' -f 1)
   truncate -s $((BYTES-2)) $file.3
fi

rm $file.5
cat $file.2 $file.3 > $file.4
cp $file.4 $file

cat <<EOF
<h1>Upload Successful</h1>
EOF

cat <<EOF
</body>
</html>
EOF

exit 0


问:
jQuery slideDown beneath menu button moves all other buttons in FF
I've been working on a menu and have it perfectly working in Chrome/Safari.
The URL is http://www.penuli.nl/aboutvanwow.html.

But FF is giving me a hard time with the tooltip.
Each time I hover over a button, all the other buttons (which are divs inside a list item) jump down to the bottom of their parent, the list item.
I can't understand why they do that, since all the items are big enough to fit into each other without 'pushing' other items around.

IN THE COMMENT BOX IS A LINK TO AN ILLUSTRATION I MADE ABOUT THE MENU
(i don't have enough reputation points to post images)

The thing that makes it maybe a bit more complicated (but it shouldn't got anything to do with it), is that the buttons animate into the page. This means that their position is relative.

I've found one solution thanks to you guys of Stackoverflow, reading another question, but this would mean I have to alter my animation:
overflow: hidden does work when I apply it to the list item, but I have an animation after a click events which makes all the button 'fall' down the page. When nothing works I can of course cancel that animation, it's more important the site works neatly then an animation more or less, but a solution which works for both would be excellent!
Thanks in advance.

Some CSS (without some lines for the start and end animation):

```<code>#wrap ol#menu{
margin-left: 0;
padding-left: 0;
width: 1000px;
height: 160px;
}

#wrap ol#menu li{
display: inline-block;
list-style-type: none;
width: 138px;
height: 160px;
background-image: url("/images/backgroundbutton.png");
background-repeat:no-repeat;
background-color: white;
cursor: pointer;
position: relative;
z-index: 0;
}

#wrap ol#menu li .button{
width: 138px;
height: 82px;
z-index: 2;
position: relative;
background-repeat:no-repeat;
}

ol#menu li:nth-child(7n+1) .button {
background-image: url("/images/button-1.png");
}

#wrap ol#menu li .tooltip{
background-image: url("/images/tooltip.png");
position: relative;
background-repeat:no-repeat;
top: -30px;
width: 138px;
height: 130px;
z-index: 1;
display: none;
}
</code>```

答: Wow, that is pretty weird. Maybe change your list items to a collection of divs?

ContentLicense: CC BY-SA 2.5

Body:
I've been working on a menu and have it perfectly working in Chrome/Safari.
The URL is http://www.penuli.nl/aboutvanwow.html.

But FF is giving me a hard time with the tooltip.
Each time I hover over a button, all the other buttons (which are divs inside a list item) jump down to the bottom of their parent, the list item.
I can't understand why they do that, since all the items are big enough to fit into each other without 'pushing' other items around.

IN THE COMMENT BOX IS A LINK TO AN ILLUSTRATION I MADE ABOUT THE MENU
(i don't have enough reputation points to post images)

The thing that makes it maybe a bit more complicated (but it shouldn't got anything to do with it), is that the buttons animate into the page. This means that their position is relative.

I've found one solution thanks to you guys of Stackoverflow, reading another question, but this would mean I have to alter my animation:
overflow: hidden does work when I apply it to the list item, but I have an animation after a click events which makes all the button 'fall' down the page. When nothing works I can of course cancel that animation, it's more important the site works neatly then an animation more or less, but a solution which works for both would be excellent!
Thanks in advance.

Some CSS (without some lines for the start and end animation):

#wrap ol#menu{
margin-left: 0;
padding-left: 0;
width: 1000px;
height: 160px;
}

#wrap ol#menu li{
display: inline-block;
list-style-type: none;
width: 138px;
height: 160px;
background-image: url("/images/backgroundbutton.png");
background-repeat:no-repeat;
background-color: white;
cursor: pointer;
position: relative;
z-index: 0;
}

#wrap ol#menu li .button{
width: 138px;
height: 82px;
z-index: 2;
position: relative;
background-repeat:no-repeat;
}

ol#menu li:nth-child(7n+1) .button {
background-image: url("/images/button-1.png");
}

#wrap ol#menu li .tooltip{
background-image: url("/images/tooltip.png");
position: relative;
background-repeat:no-repeat;
top: -30px;
width: 138px;
height: 130px;
z-index: 1;
display: none;
}


问:
Display line breaks as `\n` in pdf to text conversion using pdf.js
I used the code from this tutorial http://ourcodeworld.com/articles/read/405/how-to-convert-pdf-to-text-extract-text-from-pdf-with-javascript to set up the pdf to text conversion.

Looked all over on this site https://mozilla.github.io/pdf.js/ for some hints as to how to format the conversion, but couldn't find anything. I am just wondering if anyone has any idea of how to display line breaks as \n when parsing text using pdf.js.

Thanks in advance.

答:
In PDF there no such thing as controlling layout using control chars such as '\n' -- glyphs in PDF positioned using exact coordinates. Use text y-coordinate (can be extracted from transform matrix) to detect a line change.

var url = "https://cdn.mozilla.net/pdfjs/tracemonkey.pdf";
var pageNumber = 2;
// Load document
PDFJS.getDocument(url).then(function (doc) {
  // Get a page
  return doc.getPage(pageNumber);
}).then(function (pdfPage) {
  // Get page text content
  return pdfPage.getTextContent();
}).then(function (textContent) {
  var p = null;
  var lastY = -1;
  textContent.items.forEach(function (i) {
    // Tracking Y-coord and if changed create new p-tag
    if (lastY != i.transform[5]) {
      p = document.createElement("p");
      document.body.appendChild(p);
      lastY = i.transform[5];
    }
    p.textContent += i.str;
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://npmcdn.com/pdfjs-dist/build/pdf.js"></script></code>```

Body:
In PDF there no such thing as controlling layout using control chars such as '\n' -- glyphs in PDF positioned using exact coordinates. Use text y-coordinate (can be extracted from transform matrix) to detect a line change.

var url = "https://cdn.mozilla.net/pdfjs/tracemonkey.pdf";
var pageNumber = 2;
// Load document
PDFJS.getDocument(url).then(function (doc) {
  // Get a page
  return doc.getPage(pageNumber);
}).then(function (pdfPage) {
  // Get page text content
  return pdfPage.getTextContent();
}).then(function (textContent) {
  var p = null;
  var lastY = -1;
  textContent.items.forEach(function (i) {
    // Tracking Y-coord and if changed create new p-tag
    if (lastY != i.transform[5]) {
      p = document.createElement("p");
      document.body.appendChild(p);
      lastY = i.transform[5];
    }
    p.textContent += i.str;
  });
});

<script src="https://npmcdn.com/pdfjs-dist/build/pdf.js"></script>


问:
Change VM options generte a error
I changed vm options and add Xxs16m , now when i try open idea.sh i have this error in console.

Unrecognized option: -Xxs16m
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.

答:
-Xxs is not the right option, either you should use.

```<code>1. -Xss - sets the thread stack size
2. -Xms - sets th initial and minimum Java heap size
3. -Xmx - sets the maximum Java heap size
</code>```

Regarding other options find here

Title: Change VM options generte a error

Body:
-Xxs is not the right option, either you should use.

1. -Xss - sets the thread stack size
2. -Xms - sets th initial and minimum Java heap size
3. -Xmx - sets the maximum Java heap size

Regarding other options find here


问:
Spring Security returns 52e
I am trying to do LDAP authentication by Spring Security.
But it returns an error:

error code 49 - 80090308: LdapErr: DSID-0C0903D9, comment: AcceptSecurityContext error, data 52e, v2580 ]

My code:

auth.ldapAuthentication()
            .contextSource().url("ldap://server:389/dc=main,dc=domain,dc=ru")
            .managerDn("uid=user,ou=Domain Users,dc=mydomain,dc=ru").managerPassword("password")
            .and()
            .userSearchBase("ou=student")
            .userSearchFilter("(cn={0})");
}
```

What can be the kind of mistake (excluding wrong credentials)?

答:
It's work ... maybe anybody willbe helpfull
       auth.authenticationProvider(ldapAuthenticationProvider());
       auth.eraseCredentials(true);</p>

```<code>@Bean
public DefaultSpringSecurityContextSource contextSource(){

DefaultSpringSecurityContextSource contextSource =
        new DefaultSpringSecurityContextSource(Arrays.asList("ldap://url:389/"),"dc=ttu,dc=ru");
contextSource.setUserDn(userDn);
contextSource.setPassword(passwordForLDAP);
contextSource.setReferral("follow");
return contextSource;
}

@Bean
public LdapAuthenticationProvider ldapAuthenticationProvider(){
return new
LdapAuthenticationProvider(ldapAuthenticator(),ldapAuthoritiesPopulator());
}

@Bean
public LdapAuthenticator ldapAuthenticator(){
BindAuthenticator authenticator = new BindAuthenticator(contextSource());
authenticator.setUserSearch(userSearch());
return authenticator;
}

@Bean
public DefaultLdapAuthoritiesPopulator ldapAuthoritiesPopulator(){
 DefaultLdapAuthoritiesPopulator ldapAuthoritiesPopulator =
        new DefaultLdapAuthoritiesPopulator(contextSource(),"ou=TTU");
ldapAuthoritiesPopulator.setSearchSubtree(true);
ldapAuthoritiesPopulator.setIgnorePartialResultException(true);
//ldapAuthoritiesPopulator.setGroupSearchFilter("member={0}");
ldapAuthoritiesPopulator.setRolePrefix("ROLE_");
ldapAuthoritiesPopulator.setConvertToUpperCase(true);
return ldapAuthoritiesPopulator;
}

@Bean
public FilterBasedLdapUserSearch userSearch(){
FilterBasedLdapUserSearch filterBasedLdapUserSearch =
        new FilterBasedLdapUserSearch("","(sAMAccountName={0})",contextSource());
filterBasedLdapUserSearch.setSearchSubtree(true);
return filterBasedLdapUserSearch;
}
</code>```

Title: Spring Security returns 52e

Body:
I am trying to do LDAP authentication by Spring Security.
But it returns an error:

error code 49 - 80090308: LdapErr: DSID-0C0903D9, comment: AcceptSecurityContext error, data 52e, v2580 ]

My code:

auth.ldapAuthentication()
            .contextSource().url("ldap://server:389/dc=main,dc=domain,dc=ru")
            .managerDn("uid=user,ou=Domain Users,dc=mydomain,dc=ru").managerPassword("password")
            .and()
            .userSearchBase("ou=student")
            .userSearchFilter("(cn={0})");
}

What can be the kind of mistake (excluding wrong credentials)?

Body:
It's work ... maybe anybody willbe helpfull
       auth.authenticationProvider(ldapAuthenticationProvider());
       auth.eraseCredentials(true);

@Bean
public DefaultSpringSecurityContextSource contextSource(){

DefaultSpringSecurityContextSource contextSource =
        new DefaultSpringSecurityContextSource(Arrays.asList("ldap://url:389/"),"dc=ttu,dc=ru");
contextSource.setUserDn(userDn);
contextSource.setPassword(passwordForLDAP);
contextSource.setReferral("follow");
return contextSource;
}

@Bean
public LdapAuthenticationProvider ldapAuthenticationProvider(){
return new
LdapAuthenticationProvider(ldapAuthenticator(),ldapAuthoritiesPopulator());
}

@Bean
public LdapAuthenticator ldapAuthenticator(){
BindAuthenticator authenticator = new BindAuthenticator(contextSource());
authenticator.setUserSearch(userSearch());
return authenticator;
}

@Bean
public DefaultLdapAuthoritiesPopulator ldapAuthoritiesPopulator(){
 DefaultLdapAuthoritiesPopulator ldapAuthoritiesPopulator =
        new DefaultLdapAuthoritiesPopulator(contextSource(),"ou=TTU");
ldapAuthoritiesPopulator.setSearchSubtree(true);
ldapAuthoritiesPopulator.setIgnorePartialResultException(true);
//ldapAuthoritiesPopulator.setGroupSearchFilter("member={0}");
ldapAuthoritiesPopulator.setRolePrefix("ROLE_");
ldapAuthoritiesPopulator.setConvertToUpperCase(true);
return ldapAuthoritiesPopulator;
}

@Bean
public FilterBasedLdapUserSearch userSearch(){
FilterBasedLdapUserSearch filterBasedLdapUserSearch =
        new FilterBasedLdapUserSearch("","(sAMAccountName={0})",contextSource());
filterBasedLdapUserSearch.setSearchSubtree(true);
return filterBasedLdapUserSearch;
}


问:
docker build error in Dockerfile
When I try to run 'docker build .' or 'docker build - < Dockerfile', errors appeared as below:

```<code>[root@VM_60_90_centos dtask-ctrip-train-domestic]# docker build .
Sending build context to Docker daemon 38.98 MB
Step 1 : FROM ubuntu:14.04  ---> 132b7427a3b4
Step 2 : MAINTAINER Ke Peng<ke.peng@jingli365.com>  ---> Using cache  --->
         db9529465f77
Step 3: WORKDIR /opt/app  ---> Using cache  ---> 3122f40a8e56
Step 4 :COPY . ./  ---> 4d67a5fbf128 Removing intermediate container
c2d83602f613
Step 5 : RUN npm  install  ---> Running in 67680232cbdf

/bin/sh: 1: npm: not found The command '/bin/sh -c npm  install'
returned a non-zero code: 127
</code>```

and my Dockerfile like this:

```<code>FROM ubuntu:14.04
MAINTAINER Ke Peng <ke.peng@jingli365.com>
WORKDIR /opt/app
COPY . ./
RUN npm  install
COPY dist/ /opt/app/
CMD node ./index.js < test.json
</code>```

Can anyone have similar experience and give me an solution. Very appreciated!

答:
Try this Dockerfile

```<code>FROM ubuntu:14.04
MAINTAINER Ke Peng <ke.peng@jingli365.com>
RUN sudo apt-get update
RUN sudo -y apt-get install nodejs
RUN sudo -y apt-get install npm
WORKDIR /opt/app
COPY . ./
RUN npm  install
COPY dist/ /opt/app/
CMD node ./index.js < test.json
</code>```

Edited as suggested in comments

Title: docker build error in Dockerfile

Body:
When I try to run 'docker build .' or 'docker build - < Dockerfile', errors appeared as below:

[root@VM_60_90_centos dtask-ctrip-train-domestic]# docker build .
Sending build context to Docker daemon 38.98 MB
Step 1 : FROM ubuntu:14.04  ---> 132b7427a3b4
Step 2 : MAINTAINER Ke Peng<ke.peng@jingli365.com>  ---> Using cache  --->
         db9529465f77
Step 3: WORKDIR /opt/app  ---> Using cache  ---> 3122f40a8e56
Step 4 :COPY . ./  ---> 4d67a5fbf128 Removing intermediate container
c2d83602f613
Step 5 : RUN npm  install  ---> Running in 67680232cbdf

/bin/sh: 1: npm: not found The command '/bin/sh -c npm  install'
returned a non-zero code: 127

and my Dockerfile like this:

FROM ubuntu:14.04
MAINTAINER Ke Peng <ke.peng@jingli365.com>
WORKDIR /opt/app
COPY . ./
RUN npm  install
COPY dist/ /opt/app/
CMD node ./index.js < test.json

Can anyone have similar experience and give me an solution. Very appreciated!

Body:
Try this Dockerfile

FROM ubuntu:14.04
MAINTAINER Ke Peng <ke.peng@jingli365.com>
RUN sudo apt-get update
RUN sudo -y apt-get install nodejs
RUN sudo -y apt-get install npm
WORKDIR /opt/app
COPY . ./
RUN npm  install
COPY dist/ /opt/app/
CMD node ./index.js < test.json

Edited as suggested in comments


问:
Find XML file changes in all branches
I have an XML file in my main TFS branch. I have 50 branches of the main folder. Is there a quick way to check in which branches the file is modified before merging it to the main branch?

I have found that it can be done with CodeLens for code files, but I don't know how to do it for XML files.

答:
You can refer to these steps below:

Create a new workspace

Map these branches (Do not include other mapping)

To do work (e.g. modify files)

Open Team Explorer

Switch to this workspace

Click Pending Changes, then all changes in this workspace will be list.

If these changes are already existing in different workspace, you can check in changes through TFS API (install Microsoft Team Foundation Server Extended Client package to your project).

Simple code to iterate all workspaces in a machine and check in specified changes:

```<code>NetworkCredential cred = new NetworkCredential("[username]", "[password]", "[domain]");
            TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri("[collection url"), cred);
            tpc.EnsureAuthenticated();
VersionControlServer versionControl = tpc.GetService<VersionControlServer>();
             var spaces = versionControl.QueryWorkspaces(null, null, "[machine name, can be null]");
            foreach(var currentWorkspace in spaces)
            {
               var libChanges= currentWorkspace.GetPendingChanges("[server or local path]",RecursionType.Full);
                if (libChanges.Count() > 0)
                {
                    currentWorkspace.CheckIn(changes: libChanges, comment: "checkInAPI");
                }
            }
</code>```

Update:

You can compare branches.

Open Source Control Explorer

Right click a branch > Compare

Change Target path to target branch server path

Click OK.

On the other hand, there is an TFS Productivity Pack extension you can use.

Title: Find XML file changes in all branches

Body:
You can refer to these steps below:

Create a new workspace

Map these branches (Do not include other mapping)

To do work (e.g. modify files)

Open Team Explorer

Switch to this workspace

Click Pending Changes, then all changes in this workspace will be list.

If these changes are already existing in different workspace, you can check in changes through TFS API (install Microsoft Team Foundation Server Extended Client package to your project).

Simple code to iterate all workspaces in a machine and check in specified changes:

NetworkCredential cred = new NetworkCredential("[username]", "[password]", "[domain]");
            TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri("[collection url"), cred);
            tpc.EnsureAuthenticated();
VersionControlServer versionControl = tpc.GetService<VersionControlServer>();
             var spaces = versionControl.QueryWorkspaces(null, null, "[machine name, can be null]");
            foreach(var currentWorkspace in spaces)
            {
               var libChanges= currentWorkspace.GetPendingChanges("[server or local path]",RecursionType.Full);
                if (libChanges.Count() > 0)
                {
                    currentWorkspace.CheckIn(changes: libChanges, comment: "checkInAPI");
                }
            }

Update:

You can compare branches.

Open Source Control Explorer

Right click a branch > Compare

Change Target path to target branch server path

Click OK.

On the other hand, there is an TFS Productivity Pack extension you can use.


问:
Glassfish log user that failed permission check
I want to see which user tried to access EJB methods that are not allowed for his respective role (via @RolesAllowed annotation).
It seems I can only see that a Failed Permission Check occured in the log (+ on which Bean, what method and the timestamp), but not WHO tried to call it:

```<code>[2016-12-15T17:48:36.061+0100] [glassfish 4.1] [INFO] [] [javax.enterprise.system.core.security] [tid: _ThreadID=96 _ThreadName=http-listener-1(4)] [timeMillis: 1481820516061] [levelValue: 800] [[
JACC Policy Provider: Failed Permission Check, context(SecuredAccess/SecuredAccess_EJB_jar)- permission(("javax.security.jacc.EJBMethodPermission" "WorkBean" "administrationTask,Local,"))]]

[2016-12-15T17:48:36.061+0100] [glassfish 4.1] [WARNING] [AS-EJB-00056] [javax.enterprise.ejb.container] [tid: _ThreadID=96 _ThreadName=http-listener-1(4)] [timeMillis: 1481820516061] [levelValue: 900] [[
A system exception occurred during an invocation on EJB WorkBean, method: public java.lang.String work.WorkBean.administrationTask()]]
</code>```

Is there any way to configure Glassfish so that it logs the principal of the calling user or at least some kind of session ID I can then map to a specific user? It logs the user for each valid method call, but somehow not for the denied ones.

答:
I met this issue too. It may caused by: you copy jar/class file to glassfish application folder directly. You need re-deploy the application(war/ear), then this issue will disappear.

Good luck!

Body:
I want to see which user tried to access EJB methods that are not allowed for his respective role (via @RolesAllowed annotation).
It seems I can only see that a Failed Permission Check occured in the log (+ on which Bean, what method and the timestamp), but not WHO tried to call it:

[2016-12-15T17:48:36.061+0100] [glassfish 4.1] [INFO] [] [javax.enterprise.system.core.security] [tid: _ThreadID=96 _ThreadName=http-listener-1(4)] [timeMillis: 1481820516061] [levelValue: 800] [[
JACC Policy Provider: Failed Permission Check, context(SecuredAccess/SecuredAccess_EJB_jar)- permission(("javax.security.jacc.EJBMethodPermission" "WorkBean" "administrationTask,Local,"))]]

[2016-12-15T17:48:36.061+0100] [glassfish 4.1] [WARNING] [AS-EJB-00056] [javax.enterprise.ejb.container] [tid: _ThreadID=96 _ThreadName=http-listener-1(4)] [timeMillis: 1481820516061] [levelValue: 900] [[
A system exception occurred during an invocation on EJB WorkBean, method: public java.lang.String work.WorkBean.administrationTask()]]

Is there any way to configure Glassfish so that it logs the principal of the calling user or at least some kind of session ID I can then map to a specific user? It logs the user for each valid method call, but somehow not for the denied ones.


问:
What is gRPC programming surface?
In the GPRC Concept document

http://www.grpc.io/docs/guides/concepts.html

The gRPC programming surface concept is mentioned without a definition. Anyone knows exactly what is gRPC programming surface?

答:
Quoting their documentation:

Starting from a service definition in a .proto file, gRPC provides protocol buffer compiler plugins that generate client- and server-side code. gRPC users typically call these APIs on the client side and implement the corresponding API on the server side.

On the server side, the server implements the methods declared by the service and runs a gRPC server to handle client calls. The gRPC infrastructure decodes incoming requests, executes service methods, and encodes service responses.
On the client side, the client has a local object known as stub (for some languages, the preferred term is client) that implements the same methods as the service. The client can then just call those methods on the local object, wrapping the parameters for the call in the appropriate protocol buffer message type - gRPC looks after sending the request(s) to the server and returning the server’s protocol buffer response(s).

In short, the surface is the contract between the client and the service and its realization as the clientside layer (the stub) and the serverside implementation.

Title: What is gRPC programming surface?


问:
WPF Datagrid Cell with Validation Error Style
I am trying to change the default style of a DataGridCell (within a WPF Toolkit DataGrid) when there is a validation error.  The default is a red border.  How can I put my own template?

Thanks.

答: There's a nice tutorial from Diederik Krols that does exactly what you're asking for the WPF Toolkit DataGrid.</p>


问:
Jenkins: "Execute system groovy script" in a pipeline step (SCM committed)
Is there a way to use the Jenkins "Execute system groovy script" step from a pipeline file which is SCM commited ?

If yes, how would I access the predefined variables (like build) in it ?

If no, would I be able to replicate the functionality otherwise, using for example the Shared Library Plugin ?

Thanks !

答:
You can put groovy code in a pipeline in a (always-source-controlled) Jenkinsfile, like this:

```<code>pipeline {
  agent { label 'docker' }
  stages {
    stage ('build') {
      steps {
        script {

          // i used a script block because you can jam arbitrary groovy in here
          // without being constrained by the declarative Jenkinsfile DSL
          def awesomeVar = 'so_true'
          print "look at this: ${awesomeVar}"

          // accessing a predefined variable:
          echo "currentBuild.number: ${currentBuild.number}"
        }
      }
    }
  }
}
</code>```

Produces console log:

```<code>[Pipeline] echo
look at this: so_true
[Pipeline] echo
currentBuild.number: 84
</code>```

Click on the "Pipeline Syntax" link in the left navigation of any of pipeline job to get a bunch of examples of things you can access in the "Global Variables Reference."

Body:
You can put groovy code in a pipeline in a (always-source-controlled) Jenkinsfile, like this:

pipeline {
  agent { label 'docker' }
  stages {
    stage ('build') {
      steps {
        script {

          // i used a script block because you can jam arbitrary groovy in here
          // without being constrained by the declarative Jenkinsfile DSL
          def awesomeVar = 'so_true'
          print "look at this: ${awesomeVar}"

          // accessing a predefined variable:
          echo "currentBuild.number: ${currentBuild.number}"
        }
      }
    }
  }
}

Produces console log:

[Pipeline] echo
look at this: so_true
[Pipeline] echo
currentBuild.number: 84

Click on the "Pipeline Syntax" link in the left navigation of any of pipeline job to get a bunch of examples of things you can access in the "Global Variables Reference."


问:
javascript classes call function
I am beginner in programming and I am trying the javascript classes, I want to call the boardCastinit function from the override function onConnMessage, but I am getting this error message, Please help in this issue.

boReferenceError: boardCastInit is not defined

websocket.js

```<code>class websocket extends webSocketModel {

constructor() {
    let server = new Server();
    let mongodb = new mongoDB();
    super(server.server);
}

onConnMessage(message) {

    let clients = this.clients;
    boardCastInit(1);
}

 boardCastInit(data){
       console.log(data)
   }

}

module.exports = websocket;
</code>```

websocketModel.js

```<code>const ws = require('websocket').server;

class webSocketModel {

constructor(httpServer) {
    if(!httpServer) throw 'Null Http Server';
    this.websocket = new ws({ httpServer: httpServer, autoAcceptConnections: false });
    this.websocket.on('request', this.onConnOpen.bind(this));
}

onConnOpen(request) {
    var connection = request.accept('echo-protocol', request.origin);
    console.log('Connection Accepted');

    connection.on('message', this.onConnMessage);
    connection.on('close', this.onConnClose);
}

onConnMessage(message) {
    if (message.type === 'utf8') {
        console.log(message.utf8Data);
    } else if (message.type == 'binary') {
        console.log(message.binaryData.length + 'bytes');
    }
}

onConnClose(reasonCode, description) {
    console.log('Connection Closed');
}
}

module.exports = webSocketModel;
</code>```

答:
Try binding the boardCastInit() function inside the constructor like this.

```<code>constructor() {
    let server = new Server();
    let mongodb = new mongoDB();
    super(server.server);
    this.boardCastInit = this.boardCastInit.bind(this);
}
</code>```

Then call it from the this reference.

```<code>onConnMessage(message) {
    let clients = this.clients;
    this.boardCastInit(1);
}
</code>```

Title: javascript classes call function

Body:
I am beginner in programming and I am trying the javascript classes, I want to call the boardCastinit function from the override function onConnMessage, but I am getting this error message, Please help in this issue.

boReferenceError: boardCastInit is not defined

websocket.js

class websocket extends webSocketModel {

constructor() {
    let server = new Server();
    let mongodb = new mongoDB();
    super(server.server);
}

onConnMessage(message) {

    let clients = this.clients;
    boardCastInit(1);
}

 boardCastInit(data){
       console.log(data)
   }

}

module.exports = websocket;

websocketModel.js

const ws = require('websocket').server;

class webSocketModel {

constructor(httpServer) {
    if(!httpServer) throw 'Null Http Server';
    this.websocket = new ws({ httpServer: httpServer, autoAcceptConnections: false });
    this.websocket.on('request', this.onConnOpen.bind(this));
}

onConnOpen(request) {
    var connection = request.accept('echo-protocol', request.origin);
    console.log('Connection Accepted');

    connection.on('message', this.onConnMessage);
    connection.on('close', this.onConnClose);
}

onConnMessage(message) {
    if (message.type === 'utf8') {
        console.log(message.utf8Data);
    } else if (message.type == 'binary') {
        console.log(message.binaryData.length + 'bytes');
    }
}

onConnClose(reasonCode, description) {
    console.log('Connection Closed');
}
}

module.exports = webSocketModel;

Body:
Try binding the boardCastInit() function inside the constructor like this.

constructor() {
    let server = new Server();
    let mongodb = new mongoDB();
    super(server.server);
    this.boardCastInit = this.boardCastInit.bind(this);
}

Then call it from the this reference.

onConnMessage(message) {
    let clients = this.clients;
    this.boardCastInit(1);
}


问:
Regex: how to stop match on certain words that cannot exists
The title is so confusing, I admit it - if you want to change it you are welcome.

I'm working on PHP and preg_match function.

The problem is this string (just an example)

```<code>ON DELETE SET NULL ON UPDATE CASCADE
</code>```

ON DELETE CASCADE ON UPDATE CASCADE (another example..)

i need to find ON DELETE and ON UPDATE values, but they can't be there both.

So sometimes i have this:

```<code>ON DELETE something
</code>```

and other times:

```<code>ON UPDATE something
</code>```

and other times both.

So, this regex doesn't cover all possibilities:

```<code>/ON DELETE (.+) ON UPDATE (.+)/
</code>```

If i put

/ON DELETE (.+)( ON UPDATE (.*))?/ -- to cover the case in which there isn't ON UPDATE

if ON UPDATE is present, first group results in "SET NULL ON UPDATE CASCADE".

How can i do that?

答: use Rubular to check your regexp</p>

Body:
The title is so confusing, I admit it - if you want to change it you are welcome.

I'm working on PHP and preg_match function.

The problem is this string (just an example)

ON DELETE SET NULL ON UPDATE CASCADE

ON DELETE CASCADE ON UPDATE CASCADE (another example..)

i need to find ON DELETE and ON UPDATE values, but they can't be there both.

So sometimes i have this:

ON DELETE something

and other times:

ON UPDATE something

and other times both.

So, this regex doesn't cover all possibilities:

/ON DELETE (.+) ON UPDATE (.+)/

If i put

/ON DELETE (.+)( ON UPDATE (.*))?/ -- to cover the case in which there isn't ON UPDATE

if ON UPDATE is present, first group results in "SET NULL ON UPDATE CASCADE".

How can i do that?

Body: use Rubular to check your regexp


问:
ZF2 already active query prevents execution
I have something like the following, in a function that deletes both the files and db entries:

```<code>$adapter = $this->getAdapter();
$query = $adapter->query("call find_results_by_job_id(?)", array($jobId));
$items = array();
while (($current = $query->current()) !== false)
{
    $id = $current['id'];
    $items[] = $id;
    $query->next();
}
$this->deleteFromDataStore($items);
$result = $adapter->query("call delete_results_by_job_id(?)", array($jobId), \Zend\Db\Adapter\Adapter::QUERY_MODE_EXECUTE);
</code>```

(Some of that might not look like the best way to do it, because I simplified it for this example)

I'm getting this error on the last line: SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active.

I'm assuming that the problem is because the query/adapter hasn't closed the connection from iterating results yet when I try to execute another statement. If that is the case, how can reuse the adapter, or close the query, or whatever I have to do before the last line?

The strange part is that code following almost exactly this same pattern works in another method.

Answer:

When using the PDO driver, $query->getDataSource()->getResource()->closeCursor(); fixes it

答:
Assuming you have the result of a query in your hands and you dont know whether it is a ResultSet or a Result, the following will do the job.
Tested as of Zend Framework 3.</p>

```<code>use Zend\Db\ResultSet\ResultSet;
...

public function closeResult( $result )
{
    if( is_a($result, ResultSet::class) )
    {
        $stmt = $result->getDataSource()->getResource();
    }
    else
    {
        $stmt = $result->getResource();
    }
    $stmt->closeCursor();
}
</code>```

Body:
I have something like the following, in a function that deletes both the files and db entries:

$adapter = $this->getAdapter();
$query = $adapter->query("call find_results_by_job_id(?)", array($jobId));
$items = array();
while (($current = $query->current()) !== false)
{
    $id = $current['id'];
    $items[] = $id;
    $query->next();
}
$this->deleteFromDataStore($items);
$result = $adapter->query("call delete_results_by_job_id(?)", array($jobId), \Zend\Db\Adapter\Adapter::QUERY_MODE_EXECUTE);

(Some of that might not look like the best way to do it, because I simplified it for this example)

I'm getting this error on the last line: SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active.

I'm assuming that the problem is because the query/adapter hasn't closed the connection from iterating results yet when I try to execute another statement. If that is the case, how can reuse the adapter, or close the query, or whatever I have to do before the last line?

The strange part is that code following almost exactly this same pattern works in another method.

Answer:

When using the PDO driver, $query->getDataSource()->getResource()->closeCursor(); fixes it

Body:
Assuming you have the result of a query in your hands and you dont know whether it is a ResultSet or a Result, the following will do the job.
Tested as of Zend Framework 3.

use Zend\Db\ResultSet\ResultSet;
...

public function closeResult( $result )
{
    if( is_a($result, ResultSet::class) )
    {
        $stmt = $result->getDataSource()->getResource();
    }
    else
    {
        $stmt = $result->getResource();
    }
    $stmt->closeCursor();
}


问:
Search query with filtering in oracle database
```<code>SELECT * FROM EMPLOYEES
  WHERE (1 = 1 OR FIRST_NAME = 'renz')
    AND (1 = 1 OR LAST_NAME LIKE '%t%')
    AND (1 = 1 OR EMAIL = 'ASD')
    AND
    (CASE
      WHEN ('06/20/2016'!='' AND '01/23/2017'!='')
        THEN HIRE_DATE BETWEEN TO_DATE('06/20/2016','YYYYMMDD') AND TO_DATE('01/23/2017','YYYYMMDD')
      WHEN ('06/20/2016'!='' AND '01/23/2017'=='')
        THEN HIRE_DATE >=TO_DATE('06/20/2016','YYYYMMDD')
      WHEN ('06/20/2016'=='' AND '01/23/2017'!='')
        THEN HIRE_DATE <=TO_DATE('01/23/2017','YYYYMMDD')
    END)
</code>```

Im trying to create a search query that will search : firstname exactly match, lastname partial match, email exact match, data between from date and to date
 if both from and to are present it will return data between those date
 if from is the only present it will return data with date greater than from
 if to is the only present it will return data with date less than to date
How can i achieve this? The data for my filtering is from my jsp page pass to my DAO class

答:
Use the below query:

```<code>SELECT *
  FROM employees e
 WHERE e.first_name = NVL( :first_name, e.first_name )
   AND e.last_name LIKE NVL( :last_name, e.last_name )
   AND e.email = NVL( :email, e.email )
   AND e.hire_date BETWEEN NVL( :start_date, e.hire_date )
                       AND NVL( :end_date, e.hire_date )
</code>```

The query can be executed using zero or more parameters.

Body:
SELECT * FROM EMPLOYEES
  WHERE (1 = 1 OR FIRST_NAME = 'renz')
    AND (1 = 1 OR LAST_NAME LIKE '%t%')
    AND (1 = 1 OR EMAIL = 'ASD')
    AND
    (CASE
      WHEN ('06/20/2016'!='' AND '01/23/2017'!='')
        THEN HIRE_DATE BETWEEN TO_DATE('06/20/2016','YYYYMMDD') AND TO_DATE('01/23/2017','YYYYMMDD')
      WHEN ('06/20/2016'!='' AND '01/23/2017'=='')
        THEN HIRE_DATE >=TO_DATE('06/20/2016','YYYYMMDD')
      WHEN ('06/20/2016'=='' AND '01/23/2017'!='')
        THEN HIRE_DATE <=TO_DATE('01/23/2017','YYYYMMDD')
    END)

Im trying to create a search query that will search : firstname exactly match, lastname partial match, email exact match, data between from date and to date
 if both from and to are present it will return data between those date
 if from is the only present it will return data with date greater than from
 if to is the only present it will return data with date less than to date
How can i achieve this? The data for my filtering is from my jsp page pass to my DAO class

Body:
Use the below query:

SELECT *
  FROM employees e
 WHERE e.first_name = NVL( :first_name, e.first_name )
   AND e.last_name LIKE NVL( :last_name, e.last_name )
   AND e.email = NVL( :email, e.email )
   AND e.hire_date BETWEEN NVL( :start_date, e.hire_date )
                       AND NVL( :end_date, e.hire_date )

The query can be executed using zero or more parameters.


问:
Building shared library with ffmpeg results in relocation error
I need to create a custom shared library that internally uses ffmpeg functions. The idea is to create one fat shared library, say, myffmpeg.so.

I first build ffmpeg code (3.3.1 as of this post). During configuration, I specify -fPIC via --extra-cflags and --extra-cxxflags. I also specify -enable-pic during the configuration. After running configure and make,  various archive files such as libswscale.a, libavformat.a, etc. are successfully created.

Next, I try to build my shared library:

```<code>gcc -fPIC -Ixxx  mywrapper.cpp
gcc -shared -o myffmpeg.so mywrapper.o -Lxxx -lswscale -lavformat...
</code>```

However, this results in an error:

```<code>Relocation R_X86_64_PC32 against symbol ff_M24A can not be
used when making a shared object;
</code>```

Looks like I am missing some compiler/linker setting. Can someone please point me in the right direction? Regards.

答: If you need shared libraries, build ffmpeg with --enable-shared, which will generate shared objects libswscale.so, libavformat.so, etc. The .a files are static libraries built by default configuration.

Body:
I need to create a custom shared library that internally uses ffmpeg functions. The idea is to create one fat shared library, say, myffmpeg.so.

I first build ffmpeg code (3.3.1 as of this post). During configuration, I specify -fPIC via --extra-cflags and --extra-cxxflags. I also specify -enable-pic during the configuration. After running configure and make,  various archive files such as libswscale.a, libavformat.a, etc. are successfully created.

Next, I try to build my shared library:

gcc -fPIC -Ixxx  mywrapper.cpp
gcc -shared -o myffmpeg.so mywrapper.o -Lxxx -lswscale -lavformat...

However, this results in an error:

Relocation R_X86_64_PC32 against symbol ff_M24A can not be
used when making a shared object;

Looks like I am missing some compiler/linker setting. Can someone please point me in the right direction? Regards.


答:
making the list items floating can fix your problem.

in your #wrap ol#menu li rule,
exchange:

```<code>display: inline-block;
</code>```

with:

```<code>float:left;
</code>```

(keeping the display:inline-block isn't a problem, but it is not needed anymore since the elements are floating)

Title: jQuery slideDown beneath menu button moves all other buttons in FF

Body:
I've been working on a menu and have it perfectly working in Chrome/Safari.
The URL is http://www.penuli.nl/aboutvanwow.html.

But FF is giving me a hard time with the tooltip.
Each time I hover over a button, all the other buttons (which are divs inside a list item) jump down to the bottom of their parent, the list item.
I can't understand why they do that, since all the items are big enough to fit into each other without 'pushing' other items around.

IN THE COMMENT BOX IS A LINK TO AN ILLUSTRATION I MADE ABOUT THE MENU
(i don't have enough reputation points to post images)

The thing that makes it maybe a bit more complicated (but it shouldn't got anything to do with it), is that the buttons animate into the page. This means that their position is relative.

I've found one solution thanks to you guys of Stackoverflow, reading another question, but this would mean I have to alter my animation:
overflow: hidden does work when I apply it to the list item, but I have an animation after a click events which makes all the button 'fall' down the page. When nothing works I can of course cancel that animation, it's more important the site works neatly then an animation more or less, but a solution which works for both would be excellent!
Thanks in advance.

Some CSS (without some lines for the start and end animation):

#wrap ol#menu{
margin-left: 0;
padding-left: 0;
width: 1000px;
height: 160px;
}

#wrap ol#menu li{
display: inline-block;
list-style-type: none;
width: 138px;
height: 160px;
background-image: url("/images/backgroundbutton.png");
background-repeat:no-repeat;
background-color: white;
cursor: pointer;
position: relative;
z-index: 0;
}

#wrap ol#menu li .button{
width: 138px;
height: 82px;
z-index: 2;
position: relative;
background-repeat:no-repeat;
}

ol#menu li:nth-child(7n+1) .button {
background-image: url("/images/button-1.png");
}

#wrap ol#menu li .tooltip{
background-image: url("/images/tooltip.png");
position: relative;
background-repeat:no-repeat;
top: -30px;
width: 138px;
height: 130px;
z-index: 1;
display: none;
}

Body:
making the list items floating can fix your problem.

in your #wrap ol#menu li rule,
exchange:

display: inline-block;

with:

float:left;

(keeping the display:inline-block isn't a problem, but it is not needed anymore since the elements are floating)


问:
How to update field value by determining each digit in field?
Although I saw update statements to update field based on existing values, I could not find anything similar to this scenario:

Suppose you have a table with only one column of number(4) type.  The value in the first record is 1010.

```<code>create table stab(
  nmbr number(4)
);

insert into stab values(1010);

For each digit
   When the digit is 1 -- add 3 to the digit
   When the digit is 0 -- add four to the digit
end
</code>```

This operations needs to be completed in a single statement without using pl/sql.

I think substr function need to be used but don't know how to go about completing this.

Thanks in advance.

答: My answer to the interview question would have been that the DB design violates the rules of normalization (i.e. a bad design) and would not have this kind of "update anomaly" if it were properly designed.  Having said that, it can easily be done with an expression using various combinations of single row functions combined with the required arithmetic operations.</p>

Body:
Although I saw update statements to update field based on existing values, I could not find anything similar to this scenario:

Suppose you have a table with only one column of number(4) type.  The value in the first record is 1010.

create table stab(
  nmbr number(4)
);

insert into stab values(1010);

For each digit
   When the digit is 1 -- add 3 to the digit
   When the digit is 0 -- add four to the digit
end

This operations needs to be completed in a single statement without using pl/sql.

I think substr function need to be used but don't know how to go about completing this.

Thanks in advance.


问:
How to add "share notebook as gist" button to Jupyter notebook server?
I upgraded from Ipython Notebook Server to Jupyter Server using anaconda:

```<code>(ioos)usgs@gam:~/.jupyter/custom$ conda list jupyter

jupyter                   1.0.0                    py27_0    defaults
jupyter-client            4.1.1                     <pip>
jupyter-console           4.0.3                     <pip>
jupyter-core              4.0.6                     <pip>
jupyter_client            4.1.1                    py27_0    defaults
jupyter_console           4.0.3                    py27_0    defaults
jupyter_core              4.0.6                    py27_0    defaults
</code>```

and my "Share Notebook as Gist" button went away.

I imagine that the configuration of extensions changed with the new version.

I can see ~/.local/share/jupyter/nbextensions
with gist.js and a directory called mathjax in it.

Does anyone know how to properly configure the "Share Notebook as Gist" button with this Jupyter version?

答:
To install, simply run:

```<code>pip install jupyter-notebook-gist
jupyter serverextension enable --py jupyter_notebook_gist
jupyter nbextension install --py jupyter_notebook_gist
jupyter nbextension enable --py jupyter_notebook_gist
jupyter nbextension enable --py widgetsnbextension
</code>```

you also need to configure jupyter. for details visit here

Body:
I upgraded from Ipython Notebook Server to Jupyter Server using anaconda:

(ioos)usgs@gam:~/.jupyter/custom$ conda list jupyter

jupyter                   1.0.0                    py27_0    defaults
jupyter-client            4.1.1                     <pip>
jupyter-console           4.0.3                     <pip>
jupyter-core              4.0.6                     <pip>
jupyter_client            4.1.1                    py27_0    defaults
jupyter_console           4.0.3                    py27_0    defaults
jupyter_core              4.0.6                    py27_0    defaults

and my "Share Notebook as Gist" button went away.

I imagine that the configuration of extensions changed with the new version.

I can see ~/.local/share/jupyter/nbextensions
with gist.js and a directory called mathjax in it.

Does anyone know how to properly configure the "Share Notebook as Gist" button with this Jupyter version?

Body:
To install, simply run:

pip install jupyter-notebook-gist
jupyter serverextension enable --py jupyter_notebook_gist
jupyter nbextension install --py jupyter_notebook_gist
jupyter nbextension enable --py jupyter_notebook_gist
jupyter nbextension enable --py widgetsnbextension

you also need to configure jupyter. for details visit here


问:
program windows CE in c# 2012?
is their way to developing an application for windows ce device? I have a barcode scanner device with an OS of windows ce and I only have a visual studio 2012. If we buy the 2008 version its only add to cost of development and its possible we only use that in once. If not possible is there any free PL out there that can be use?</p>

答:
The development environment available depends on the version of Windows CE that runs on the scanner.

So you'll need to determine the Windows CE version, and then take a look at this page: Developing .NET Compact Framework apps in Post-2008 Visual Studio?

Title: program windows CE in c# 2012?


问:
jQuery UI setting absolute dialog position does nothing
I want to set the absolute position (x and y) of a jQuery UI (1.12.1) dialog. By all accounts I should be able to do that like so (although the jQuery docs inexplicably do not mention this syntax, neither here nor here):

```<code>$('#element').dialog('option', 'position', [x, y]);
</code>```

Examples of people successfully using this syntax are in:

jQuery UI dialog positioning

Can I make jquery dialog position independent of window size?

Lots of other places.

Yet, when I do attempt this, nothing happens. Consider the following example (might want to run full screen):

$('#test').dialog({
  width: 200,
  height: 200
});

$('#move').click(function () {
  $('#test').dialog('option', 'position', [30, 30]);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<body>
<button id="move">Move</button>
<div id="test" title="test">This is a test.</div>
</body></code>```

Run it, press the button, the dialog does not move.

Why isn't this working for me and how do I set the x,y position of a dialog?

Note that the dialog must remain both draggable and resizable after the position change.

答:
I think I got it to work .. by using

```<code>position: { my: "left top", at: "left+"+x+" top+"+y+"", of: window }
</code>```

and by reading the .position() documentation

I reached to this

$('#test').dialog({
  width: 200,
  height: 200
});

$('#move').click(function () {
  var x = 30,
      y = 30;
  $('#test').dialog({
    //position: { my: "left top", at: "left bottom", of: window }
    position: { my: "left top", at: "left+" + x + " top+" + y + "", of: window }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<body>
<button id="move">Move</button>
<div id="test" title="test">This is a test.</div>
</body></code>```

Body:
I want to set the absolute position (x and y) of a jQuery UI (1.12.1) dialog. By all accounts I should be able to do that like so (although the jQuery docs inexplicably do not mention this syntax, neither here nor here):

$('#element').dialog('option', 'position', [x, y]);

Examples of people successfully using this syntax are in:

jQuery UI dialog positioning

Can I make jquery dialog position independent of window size?

Lots of other places.

Yet, when I do attempt this, nothing happens. Consider the following example (might want to run full screen):

$('#test').dialog({
  width: 200,
  height: 200
});

$('#move').click(function () {
  $('#test').dialog('option', 'position', [30, 30]);
});

<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">

<button id="move">Move</button>

This is a test.

Run it, press the button, the dialog does not move.

Why isn't this working for me and how do I set the x,y position of a dialog?

Note that the dialog must remain both draggable and resizable after the position change.

Body:
I think I got it to work .. by using

position: { my: "left top", at: "left+"+x+" top+"+y+"", of: window }

and by reading the .position() documentation

I reached to this

$('#test').dialog({
  width: 200,
  height: 200
});

$('#move').click(function () {
  var x = 30,
      y = 30;
  $('#test').dialog({
    //position: { my: "left top", at: "left bottom", of: window }
    position: { my: "left top", at: "left+" + x + " top+" + y + "", of: window }
  });
});

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<body>
<button id="move">Move</button>
<div id="test" title="test">This is a test.</div>
</body>


问:
Copy changes origin/development to origin/master
I have this history graph in Sourcetree:
Sourcetree graph

How can I copy the last commits from origin/development to origin/master branch?

The second question is: what are the meanings of the symbols "origin/development", "master", "origin/master", and "origin/HEAD" in the picture?

答:
To push changes from development branch to master:

git push origin development

This syncs the local development branch with the one on the server.

From GitLab, use to tools to create a Pull Request, and then merge it into master:

Create pull request from development branch

Merge development branch into master

origin/development is a reference to a branch called development which is located on a remote repository called "origin".  When you work locally, you can push changes to your remote repository via:

```<code>git push origin `<branch>`
</code>```

This will work for a new local branch that you create. To setup a remote tracking branch for an existing branch on the server, you would run another command first. For example, if there is an existing remote branch called "development":

```<code>git branch development origin/development
</code>```

If you want to setup origin/development to be an upstream branch from (local)/development, then:

```<code>git branch -u development origin/development
</code>```

This allows you to push and pull from origin, without explicitly specifying 'origin':

i.e.

```<code>git push
git pull
</code>```

Instead of:

```<code>git push origin development
git pull origin development
</code>```

ContentLicense: CC BY-SA 4.0

Body:
To push changes from development branch to master:

git push origin development

This syncs the local development branch with the one on the server.

From GitLab, use to tools to create a Pull Request, and then merge it into master:

Create pull request from development branch

Merge development branch into master

origin/development is a reference to a branch called development which is located on a remote repository called "origin".  When you work locally, you can push changes to your remote repository via:

git push origin `<branch>`

This will work for a new local branch that you create. To setup a remote tracking branch for an existing branch on the server, you would run another command first. For example, if there is an existing remote branch called "development":

git branch development origin/development

If you want to setup origin/development to be an upstream branch from (local)/development, then:

git branch -u development origin/development

This allows you to push and pull from origin, without explicitly specifying 'origin':

i.e.

git push
git pull

Instead of:

git push origin development
git pull origin development


问:
add Javadoc for hibernate in netbeans
How to add javadoc in netbeans

mainly me using it for spring hibernate. Its not showing help and saying Javadoc not found

How to add doc for org.hibernate

When selecting a function it is showing like this

```<code>    Javadoc not found. Either Javadoc documentation for this item does not exist or
  you have not added specified Javadoc in the Java Platform Manager or the Library Manager.
</code>```

答:
Here is article along with pictorial representation how to add javadoc for any lib

Go to sourceforge at http://sourceforge.net/projects/hibernate/files/hibernate3/,

download the  3.2.2.ga hibernate bundle and include the javadocs and sources from there according to article describes [select version as per your lib].

Title: add Javadoc for hibernate in netbeans

Body:
How to add javadoc in netbeans

mainly me using it for spring hibernate. Its not showing help and saying Javadoc not found

How to add doc for org.hibernate

When selecting a function it is showing like this

    Javadoc not found. Either Javadoc documentation for this item does not exist or
  you have not added specified Javadoc in the Java Platform Manager or the Library Manager.


问:
MsBuild Database project Publish Profile
We are using TFS and msbuild to deploy our web application using publish profiles. This is working perfectly, but I am trying to do the same for our database project, and I just can't get by the following error:
Error Deploy72002: Unable to connect to master or target server 'xxx'. You must have a user with the same password in master or target server 'xxx'.

The value xxx is actually the name of the database, not the name of the server. I can't find a place to input the server name, and the server is actually xxx\yyy.
Anybody know how/where you would specify the server name or figure out what is wrong?

I am building the project, and using the following msbuild Arguments:
/t:build /t:Publish /p:SqlPublishProfilePath=PublishProfiles/QA.xxx.publish.xml /p:Configuration=Output

答:
Anybody know how/where you would specify the server name or figure out what is wrong?

Do you have Windows authentication or SQL authentication?

For Windows authentication, you must log on with an account that has certain permissions on that database. The specific permissions that you need vary based on what action you want to perform. This document describe each action that you might want to perform and the specific permission that you need to perform it.

For SQL authentication, you need to modify publish profile file (.xml, TargetConnectString), for example:

```<code><TargetConnectionString>Data Source=XXX;User ID=XXX;Password=XXX;Pooling=False;MultipleActiveResultSets=False;Connect Timeout=60;Encrypt=False;TrustServerCertificate=True</TargetConnectionString>
</code>```

Besides, you can build the project by using the following msbuild:

```<code>MSBUILD "....\TestProject.sqlproj" /t:build "/p:Platform=AnyCPU" /t:deploy /p:TargetConnectionString="Data Source=localhost;Integrated Security=True" /p:TargetDatabase="xxx" /p:Configuration=Release /p:VisualStudioVersion=14.0
</code>```

Body:
Anybody know how/where you would specify the server name or figure out what is wrong?

Do you have Windows authentication or SQL authentication?

For Windows authentication, you must log on with an account that has certain permissions on that database. The specific permissions that you need vary based on what action you want to perform. This document describe each action that you might want to perform and the specific permission that you need to perform it.

For SQL authentication, you need to modify publish profile file (.xml, TargetConnectString), for example:

<TargetConnectionString>Data Source=XXX;User ID=XXX;Password=XXX;Pooling=False;MultipleActiveResultSets=False;Connect Timeout=60;Encrypt=False;TrustServerCertificate=True</TargetConnectionString>

Besides, you can build the project by using the following msbuild:

MSBUILD "....\TestProject.sqlproj" /t:build "/p:Platform=AnyCPU" /t:deploy /p:TargetConnectionString="Data Source=localhost;Integrated Security=True" /p:TargetDatabase="xxx" /p:Configuration=Release /p:VisualStudioVersion=14.0


问:
C++ Checking if a double is an integer does not work in some cases
I am trying to print out the first few numbers that follow a certain rule: the sum of its digits can be raised to an integral power to get the number itself. (Basically if the sum is an nth root of the number).

For example, the sum of the digits in the number 81 is 9, and 9^2 is 81.

This is some of the code I am using:

```<code>#include <iostream>
#include <sstream>
#include <stdlib.h>
#include <math.h>
using namespace std;

int sumOfDigits(int num) {
    int sum = 0;
    string numStr = "";
    stringstream s;
    s << num;
    s >> numStr;
    for (int i = 0; i < numStr.length(); i++) {
        int ad = 0;
        stringstream ss;
        ss << numStr[i]; // take each digit
        ss >> ad;
        sum += ad; // and add to sum
    }
    return sum;
}

int num = 10; // starting number
int numFound = 0; // how many such special numbers have been found

int main() {
    while (numFound < 5) {
        int sum = sumOfDigits(num);
        double exp = log10(num) / log10(sum);

        if (fmod(exp, 1.0) == 0.0 && sum != 1) { // if the exponent is an integer
            cout << num << "\t" << sum << endl; // then print out the number and the sum of its digits
            numFound++;
        }
        num++;
    }

    return 0;
}
</code>```

When I run this, I get the following output:

```<code>81      9
2401    7
4913    17
5832    18
17576   26
</code>```

The second entry should be 512 and 8 because 8^3 is 512. I don't understand why the test works with some numbers but doesn't work with others.

I've tried other methods of testing whether the exponent is an integer as well. I've tested it against the floor() expression, and I've tried casting the entire expression with (int).

I may be wrong and the problem may not be in that spot, but I would really appreciate it if you could help me with this. Thank you.

答:
Checking for equality between floating point numbers like this: fmod(exp, 1.0) == 0.0 is bound to cause you trouble. For example, by simply changing your code like this:

```<code>#include <iostream>
#include <sstream>
#include <stdlib.h>
#include <math.h>
#include <limits>
using namespace std;

int sumOfDigits(int num) {
    int sum = 0;
    string numStr = "";
    stringstream s;
    s << num;
    s >> numStr;
    for (int i = 0; i < numStr.length(); i++) {
        int ad = 0;
        stringstream ss;
        ss << numStr[i]; // take each digit
        ss >> ad;
        sum += ad; // and add to sum
    }
    return sum;
}

int num = 10; // starting number
int numFound = 0; // how many such special numbers have been found

int main() {
    while (numFound < 5) {
        int sum = sumOfDigits(num);
        double exp = log10(num) / log10(sum);

        if (fabs(fmod(exp, 1.0)) < std::numeric_limits<float>::epsilon() && sum != 1) { // if the exponent is an integer
            //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
            cout << num << "\t" << sum << endl; // then print out the number and the sum of its digits
            numFound++;
        }
        num++;
    }

    return 0;
}
</code>```

I can get this output:

```<code>81  9
512 8
2401    7
4913    17
5832    18
</code>```

So, use a suitable epsilon value or just stick to integers.

Read here:

What is the most effective way for float and double comparison?

Body:
I am trying to print out the first few numbers that follow a certain rule: the sum of its digits can be raised to an integral power to get the number itself. (Basically if the sum is an nth root of the number).

For example, the sum of the digits in the number 81 is 9, and 9^2 is 81.

This is some of the code I am using:

#include <iostream>
#include <sstream>
#include <stdlib.h>
#include <math.h>
using namespace std;

int sumOfDigits(int num) {
    int sum = 0;
    string numStr = "";
    stringstream s;
    s << num;
    s >> numStr;
    for (int i = 0; i < numStr.length(); i++) {
        int ad = 0;
        stringstream ss;
        ss << numStr[i]; // take each digit
        ss >> ad;
        sum += ad; // and add to sum
    }
    return sum;
}

int num = 10; // starting number
int numFound = 0; // how many such special numbers have been found

int main() {
    while (numFound < 5) {
        int sum = sumOfDigits(num);
        double exp = log10(num) / log10(sum);

        if (fmod(exp, 1.0) == 0.0 && sum != 1) { // if the exponent is an integer
            cout << num << "\t" << sum << endl; // then print out the number and the sum of its digits
            numFound++;
        }
        num++;
    }

    return 0;
}

When I run this, I get the following output:

81      9
2401    7
4913    17
5832    18
17576   26

The second entry should be 512 and 8 because 8^3 is 512. I don't understand why the test works with some numbers but doesn't work with others.

I've tried other methods of testing whether the exponent is an integer as well. I've tested it against the floor() expression, and I've tried casting the entire expression with (int).

I may be wrong and the problem may not be in that spot, but I would really appreciate it if you could help me with this. Thank you.

Body:
Checking for equality between floating point numbers like this: fmod(exp, 1.0) == 0.0 is bound to cause you trouble. For example, by simply changing your code like this:

#include <iostream>
#include <sstream>
#include <stdlib.h>
#include <math.h>
#include <limits>
using namespace std;

int sumOfDigits(int num) {
    int sum = 0;
    string numStr = "";
    stringstream s;
    s << num;
    s >> numStr;
    for (int i = 0; i < numStr.length(); i++) {
        int ad = 0;
        stringstream ss;
        ss << numStr[i]; // take each digit
        ss >> ad;
        sum += ad; // and add to sum
    }
    return sum;
}

int num = 10; // starting number
int numFound = 0; // how many such special numbers have been found

int main() {
    while (numFound < 5) {
        int sum = sumOfDigits(num);
        double exp = log10(num) / log10(sum);

        if (fabs(fmod(exp, 1.0)) < std::numeric_limits<float>::epsilon() && sum != 1) { // if the exponent is an integer
            //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
            cout << num << "\t" << sum << endl; // then print out the number and the sum of its digits
            numFound++;
        }
        num++;
    }

    return 0;
}

I can get this output:

81  9
512 8
2401    7
4913    17
5832    18

So, use a suitable epsilon value or just stick to integers.

Read here:

What is the most effective way for float and double comparison?


问:
How to make JSON.parse promise? (or asynchronous)
I am trying to make a function which returns result of JSON.parse. Following is example code:

```<code>function test(raw) {
 return JSON.parse(raw);
}

// assume I provide valid raw_input...
console.log(test(raw_input));
// expect json object but it says "undefined"...
</code>```

I think I know why (please correct me if I am wrong). JSON.parse is not asynchronous... it returns its result when it is ready. And console.log doesn't wait for its result... more like console.log thinks it is done, so it says "undefined".

Here is my question... how can you make JSON.parse promise? Or asynchronous? Like how can you make "return" in the function to wait result of JSON.parse?

If you can provide simple promise codes... that would be really helpful. Thank you so much in advance. (I am open to bluebird js or async/await or etc...)

ADDING codes (more about raw)

In the function, I am reading json file, then JSON.parse it, then return the result. (source is the path to the json file)

```<code>function test(source) {
fs.readFile(source, function (err, content) {
return JSON.parse(content));
});
}
console.log(test('test.json'));
// it says
// undefined
</code>```

json file looks like this (test.json)

```<code>{
"a": "apple",
"b": "banana",
"c": "cat"
}
</code>```

答:
JSON.parse() is indeed synchronous, so is console.log(), so is the return statement. Everything in Javscript is synchronous (and single threaded) unless you explicitly make it asynchronous.

You're getting an undefined because the whatever you passed in raw to JSON.parse() wasn't valid JSON or it was empty or maybe it wasn't actually a string.

Here is a live example to show it running synchronously.

function test(raw) {
  return JSON.parse(raw);
}

console.log('this happens first');
console.log(test('{"valid1": true}'));
console.log('this happens 3rd');
console.log(test('{"valid2": true}'));
console.log('this happens last');```

Body:
I am trying to make a function which returns result of JSON.parse. Following is example code:

function test(raw) {
 return JSON.parse(raw);
}

// assume I provide valid raw_input...
console.log(test(raw_input));
// expect json object but it says "undefined"...

I think I know why (please correct me if I am wrong). JSON.parse is not asynchronous... it returns its result when it is ready. And console.log doesn't wait for its result... more like console.log thinks it is done, so it says "undefined".

Here is my question... how can you make JSON.parse promise? Or asynchronous? Like how can you make "return" in the function to wait result of JSON.parse?

If you can provide simple promise codes... that would be really helpful. Thank you so much in advance. (I am open to bluebird js or async/await or etc...)

ADDING codes (more about raw)

In the function, I am reading json file, then JSON.parse it, then return the result. (source is the path to the json file)

function test(source) {
fs.readFile(source, function (err, content) {
return JSON.parse(content));
});
}
console.log(test('test.json'));
// it says
// undefined

json file looks like this (test.json)

{
"a": "apple",
"b": "banana",
"c": "cat"
}


问:
save dataframe as external hive table
I have used one way to save dataframe as external table using parquet file format but is there some other way to save dataframes directly as external table in hive like we have saveAsTable for managed table</p>

答:
You can also save dataframe with manual create table

```<code>dataframe.registerTempTable("temp_table");
hiveSqlContext.sql("create external table
   table_name if not exist as select * from temp_table");
</code>```

Below mentioned link has a good explanation for create table  https://docs.databricks.com/spark/latest/spark-sql/language-manual/create-table.html

Title: save dataframe as external hive table

Body:
You can also save dataframe with manual create table

dataframe.registerTempTable("temp_table");
hiveSqlContext.sql("create external table
   table_name if not exist as select * from temp_table");

Below mentioned link has a good explanation for create table  https://docs.databricks.com/spark/latest/spark-sql/language-manual/create-table.html


问:
Node.Js in Erlang style?
I am a complete noob when it comes to both Node.Js and Erlang.
But wouldn't it be possible to build a Node.js app that emulates Erlang behavior?

e.g. you pass json messages across an distributed node.js server park and even pass new code to those servers w/o going offline, just like erlang.

If you have a message handler callback that is activated when a message is received, then this message handler could check if the message is a code update message and thus replace itself(the current handler) with the new code.

So it should be possible to have Node.Js servers with no downtime for code updates w/o too much fuss, right?

答:
Not completely right.

Yes you could distribute JSON messages

The part with hot code replacement is a bit more complicated let me explain...

OK, first you obviously need to have validation etc. in place, that shouldn't be a big problem. The first small problem arises from JSON, which does not allow for any JS code/functions in it, well you can work around that by sending the data as a string.

Next problem, when you want to replace function/method you need to make sure that it keeps it's scope, so that the newly compiled functions has access to the same things.

With some dark eval magic this is certainly possible, but don't expect it to be anywhere near as natural as it's in Erlang:

```<code>var Script = process.binding('evals').Script;

var hello = 'Hello World';
var test = 42;
function Swappable(initCode) {
    this.execute = function() {}
    this.swap = function(code) {
        this.execute = eval('func = ' + code);
    }
    this.swap(initCode);
}

// Note: Swappable's scope is limited, it won't inherit the local scope in which it was created...
var foo = new Swappable('function(){console.log(hello);return function(){console.log(test)}}')
var cb = foo.execute();
cb();

foo.swap('function(){console.log("Huh, old world?");return function(){console.log(test * test)}}');
var cb = foo.execute();
cb();
console.log(bar.execute());
foo.execute();
</code>```

Output

```<code>Hello World
42
Huh, old world?
1764
</code>```

This is not guaranteed to work in 100% of all cases and scopes. Also, the syntax is horrible, so I'd suggest if you want hot swapping, stay with Erlang.

Remember: Right tool for the right job.

Update

There won't be anything better than that in the near future see:

https://github.com/ry/node/issues/issue/46#issue/46/comment/610779

Title: Node.Js in Erlang style?

Body:
Not completely right.

Yes you could distribute JSON messages

The part with hot code replacement is a bit more complicated let me explain...

OK, first you obviously need to have validation etc. in place, that shouldn't be a big problem. The first small problem arises from JSON, which does not allow for any JS code/functions in it, well you can work around that by sending the data as a string.

Next problem, when you want to replace function/method you need to make sure that it keeps it's scope, so that the newly compiled functions has access to the same things.

With some dark eval magic this is certainly possible, but don't expect it to be anywhere near as natural as it's in Erlang:

var Script = process.binding('evals').Script;

var hello = 'Hello World';
var test = 42;
function Swappable(initCode) {
    this.execute = function() {}
    this.swap = function(code) {
        this.execute = eval('func = ' + code);
    }
    this.swap(initCode);
}

// Note: Swappable's scope is limited, it won't inherit the local scope in which it was created...
var foo = new Swappable('function(){console.log(hello);return function(){console.log(test)}}')
var cb = foo.execute();
cb();

foo.swap('function(){console.log("Huh, old world?");return function(){console.log(test * test)}}');
var cb = foo.execute();
cb();
console.log(bar.execute());
foo.execute();

Output

Hello World
42
Huh, old world?
1764

This is not guaranteed to work in 100% of all cases and scopes. Also, the syntax is horrible, so I'd suggest if you want hot swapping, stay with Erlang.

Remember: Right tool for the right job.

Update

There won't be anything better than that in the near future see:

https://github.com/ry/node/issues/issue/46#issue/46/comment/610779


问:
Storyboarddoesn't contain a view controller with identifier
Hello I did some research regarding this error but unfortunately the solutions provided did not work for me. I have a project where I first started working on redViewController. Then, on the same storyboard, I added a pageviewcontroller and on the swift file added redViewController as one of its views. I changed the entry point to be the pageViewController. When I run the application the error is still looking for the redViewController. I cleaned my code and this issue still happens, do I need to update anything else? I tried using instantiateViewController(withIdentifier) but it does not find my pageViewController. Thank you for your help!

Code:

AppDelegate-

```<code>let storyboard = UIStoryboard(name: "Main", bundle: nil)
        //self.window?.rootViewController = storyboard.instantiateInitialViewController() //Looking for redviewController is it saved somewhere?
        self.window?.rootViewController = storyboard.instantiateViewController(withIdentifier: "PageViewController")
self.window?.makeKeyAndVisible()
</code>```

答: Make sure following field of the PageViewController is filled with identifier "PageViewController":

Body:
Hello I did some research regarding this error but unfortunately the solutions provided did not work for me. I have a project where I first started working on redViewController. Then, on the same storyboard, I added a pageviewcontroller and on the swift file added redViewController as one of its views. I changed the entry point to be the pageViewController. When I run the application the error is still looking for the redViewController. I cleaned my code and this issue still happens, do I need to update anything else? I tried using instantiateViewController(withIdentifier) but it does not find my pageViewController. Thank you for your help!

Code:

AppDelegate-

let storyboard = UIStoryboard(name: "Main", bundle: nil)
        //self.window?.rootViewController = storyboard.instantiateInitialViewController() //Looking for redviewController is it saved somewhere?
        self.window?.rootViewController = storyboard.instantiateViewController(withIdentifier: "PageViewController")
self.window?.makeKeyAndVisible()


问:
Unable to iterate a list and compare strings python
I am new to python programming and I really need help in comparing values in a list.

I have two lists(drink,food) .I'm not doing a comparison between two lists. What i am trying to do is comparing all the values within a list by itself.

So, I have to first compare all the values in drink list first using a for loop and an if-else statement. If there's a match in drink, I will do another for loop for food list and compare the values in food list using an if-else statement.

These are my code:

```<code>drinks = []
food = []

drinks.append("lemontea")
drinks.append("coke")
drinks.append("sprite")
drinks.append("orangejuice")
drinks.append("fantagrape")

food.append("nugget")
food.append("pizza")
food.append("chickenwing")
food.append("fries")
food.append("pizza")

for i in drinks:
    if i == drinks:
        for j in food:
            if j == food:
                print("fail")
    else:
         print("success")
</code>```

My issue is that I am supposed to be getting an 'failed' output as I have the same item in the food list that is pizza. Also, i'm not sure why am i getting 5 success output when im expected to get either only 1 'failed' or 'success' output.

This is my output i got:

```<code>success
success
success
success
success
</code>```

I would appreciate if any help was given. Thank you.

Update:
Thanks for the reply but however, it seem that people are confused with my question, hence im providing more information.

The reason why i have to compare each item in a list is because the items are generated randomly and are of string type which are then appended to the list. For example, the first item generated is '00100ABC'and so on. So in case, there are duplicate values/item in the list, i have to give an error message.

答:
If you want check the pizza value exist in food list or not, you just need do like this:

```<code>def insertValue2List(list, value):
    if value not in list:
        list.append(value)
    else:
        print("fail")

drinks = []
food = []

insertValue2List(food, "nugget")
insertValue2List(food, "pizza")
insertValue2List(food, "chickenwing")
insertValue2List(food, "fries")
insertValue2List(food, "pizza")
</code>```

the output is :

```<code>fail
</code>```

If you just want delete the duplicate value in list, you can used the sample code:

```<code>print(list(set(food)))
</code>```

The output is :

```<code>['pizza', 'nugget', 'chickenwing', 'fries']
</code>```

Body:
I am new to python programming and I really need help in comparing values in a list.

I have two lists(drink,food) .I'm not doing a comparison between two lists. What i am trying to do is comparing all the values within a list by itself.

So, I have to first compare all the values in drink list first using a for loop and an if-else statement. If there's a match in drink, I will do another for loop for food list and compare the values in food list using an if-else statement.

These are my code:

drinks = []
food = []

drinks.append("lemontea")
drinks.append("coke")
drinks.append("sprite")
drinks.append("orangejuice")
drinks.append("fantagrape")

food.append("nugget")
food.append("pizza")
food.append("chickenwing")
food.append("fries")
food.append("pizza")

for i in drinks:
    if i == drinks:
        for j in food:
            if j == food:
                print("fail")
    else:
         print("success")

My issue is that I am supposed to be getting an 'failed' output as I have the same item in the food list that is pizza. Also, i'm not sure why am i getting 5 success output when im expected to get either only 1 'failed' or 'success' output.

This is my output i got:

success
success
success
success
success

I would appreciate if any help was given. Thank you.

Update:
Thanks for the reply but however, it seem that people are confused with my question, hence im providing more information.

The reason why i have to compare each item in a list is because the items are generated randomly and are of string type which are then appended to the list. For example, the first item generated is '00100ABC'and so on. So in case, there are duplicate values/item in the list, i have to give an error message.

Body:
If you want check the pizza value exist in food list or not, you just need do like this:

def insertValue2List(list, value):
    if value not in list:
        list.append(value)
    else:
        print("fail")

drinks = []
food = []

insertValue2List(food, "nugget")
insertValue2List(food, "pizza")
insertValue2List(food, "chickenwing")
insertValue2List(food, "fries")
insertValue2List(food, "pizza")

the output is :

fail

If you just want delete the duplicate value in list, you can used the sample code:

print(list(set(food)))

The output is :

['pizza', 'nugget', 'chickenwing', 'fries']


问:
iOS FMDB multithreading operation failure
yep,i try to operation database in multi-thread with fmdb.
i create a timer to work to query database with 1.5s interval in child thread.
in the same time , it may operation the database in main-thread with delete,add,edit operation.
i find the delete add edit operation may fail if the query is operating.it say the database is locked.
i dont know how fmdb work in multi-thread,this is my code:

```<code>-(NSArray *)list{

NSString *path = [[PathHelper cachePath] stringByAppendingString:@"/MessagesCache.db"];
FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:path];
NSMutableArray *list = [NSMutableArray array];
[queue inDatabase:^(FMDatabase *db) {
    [db open];
    FMResultSet *set = [db executeQuery:@"SELECT * FROM t_messagesCache ORDER BY triggerTime ASC;"];

    while (set.next) {

        MXNIMMessageModel *message = [MXNIMMessageModel new];
        message.msgType = [set intForColumn:@"msgType"];
        message.uid = [set stringForColumn:@"uid"];
        message.msg = [set stringForColumn:@"msg"];
        message.nickname = [set stringForColumn:@"nickname"]; ;
        message.name = [set stringForColumn:@"name"];
        message.url = [set stringForColumn:@"url"];
        message.ext = [set stringForColumn:@"ext"];
        message.dur = [set intForColumn:@"dur"];
        message.w = [set intForColumn:@"w"];
        message.h = [set intForColumn:@"h"];
        message.size = [set intForColumn:@"size"];
        message.lastInterval = [set intForColumn:@"lastInterval"];
        message.md5 = [set stringForColumn:@"md5"];
        message.sort = [set intForColumn:@"sort"];
        message.triggerTime = [set stringForColumn:@"triggerTime"];
        message.teamId = [set stringForColumn:@"teamId"];

        [list addObject:message];

    }
    [db close];

}];
return list;
</code>```

}

```<code>- (BOOL)deleteMessageModelByUid:(NSString *)uid
</code>```

{

```<code>__block BOOL result;
NSString *path = [[PathHelper cachePath] stringByAppendingString:@"/MessagesCache.db"];
FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:path];
[queue inDatabase:^(FMDatabase *db) {
    [db open];
    result = [db executeUpdateWithFormat:@"DELETE FROM t_messagesCache WHERE uid = %@",uid];
    [db close];
}];

return result;
</code>```

}

答:
We can perform any action when database is open. So in fmdb you can't do mutithread because for every query fmdb first open the db fire query &return
the result set and then close it again.

If you need to perform then you keep you db open for both task..

Body:
yep,i try to operation database in multi-thread with fmdb.
i create a timer to work to query database with 1.5s interval in child thread.
in the same time , it may operation the database in main-thread with delete,add,edit operation.
i find the delete add edit operation may fail if the query is operating.it say the database is locked.
i dont know how fmdb work in multi-thread,this is my code:

-(NSArray *)list{

NSString *path = [[PathHelper cachePath] stringByAppendingString:@"/MessagesCache.db"];
FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:path];
NSMutableArray *list = [NSMutableArray array];
[queue inDatabase:^(FMDatabase *db) {
    [db open];
    FMResultSet *set = [db executeQuery:@"SELECT * FROM t_messagesCache ORDER BY triggerTime ASC;"];

    while (set.next) {

        MXNIMMessageModel *message = [MXNIMMessageModel new];
        message.msgType = [set intForColumn:@"msgType"];
        message.uid = [set stringForColumn:@"uid"];
        message.msg = [set stringForColumn:@"msg"];
        message.nickname = [set stringForColumn:@"nickname"]; ;
        message.name = [set stringForColumn:@"name"];
        message.url = [set stringForColumn:@"url"];
        message.ext = [set stringForColumn:@"ext"];
        message.dur = [set intForColumn:@"dur"];
        message.w = [set intForColumn:@"w"];
        message.h = [set intForColumn:@"h"];
        message.size = [set intForColumn:@"size"];
        message.lastInterval = [set intForColumn:@"lastInterval"];
        message.md5 = [set stringForColumn:@"md5"];
        message.sort = [set intForColumn:@"sort"];
        message.triggerTime = [set stringForColumn:@"triggerTime"];
        message.teamId = [set stringForColumn:@"teamId"];

        [list addObject:message];

    }
    [db close];

}];
return list;

}

- (BOOL)deleteMessageModelByUid:(NSString *)uid

{

__block BOOL result;
NSString *path = [[PathHelper cachePath] stringByAppendingString:@"/MessagesCache.db"];
FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:path];
[queue inDatabase:^(FMDatabase *db) {
    [db open];
    result = [db executeUpdateWithFormat:@"DELETE FROM t_messagesCache WHERE uid = %@",uid];
    [db close];
}];

return result;

}


问:
I am creating an email spammer, for an outstanding cause
In Cuba, web access is extremely censored, so I created a tool that allows more than 50,000 people to browse the Internet through email. Cubans send me an email with an URL in the subject line, and I email them back with the response. Read more at https://apretaste.com.

It was working like a charm, till the communist government of Cuba started blocking my emails. My solution was rotation.

I started with Amazon SES, and I was changing the domain each time it was blocked, but Amazon adds a header to all emails, and once they blocked the header no email from SES was able to reach Cuba any more. The same happened with Mailgun and others, they all add headers.

Currently I am creating Gmail accounts and sending via SMTP, but Google blocks me for no reason and only allows to send 100 emails a day per account. Also I can only create few emails using the same IP address/phone, so I was forced to use anonymous proxies and fake Chinese phones. Now I am fighting a war on two fronts.

An email can be blocked by three parameters: IP address, domain, and email address.

It will be terrific if I can set up my own Postfix server at a VPS that auto-rotates the IP address. Even better if I can simulate "gmail.com", to avoid purchasing a new domain every day.

All the intents to create what I call "the ultimate sender" just either reach the spam folder or add unwanted headers making it too easy to block. I feel exhausted. I hit a knowledge barrier here.

I know I am crossing to the dark side, but this is for a very good cause. Thousands count on this service as their only source of unbiased news, social network and to feel part of the 21st century.

Can you please help me implementing "the ultimate sender", or pointing to another solution that I may be missing?

答:
I have a few suggestions for you.

The first one relies on The Onion Router also known as Tor.

Since you are crossing to the dark side, why not also take a look into the darknet?

Take a look at this list of Tor email providers. If you have your own email server that can be accessed through Tor, it becomes much harder for anybody to stop people from using this service. After all, Tor was developed to offer people uncensored access to the web.

You can read about Tor in detail here, it uses Onion Routing and this is how you would set up your server to use Tor.

Here is an example how you could use it:

The steps that involve the setup, receiving an URL request and sending back the reply are as follows:

Set up an email server.

Configure your email server to use Tor.

Publish the public service name. (e.g. "duskgytldkxiuqc6.onion")

Deploy a client that takes the service name and a URL, and let it send an email with a request to your server.

The client now waits for a reply.

You send a reply and the client receives it.

You can change your service name on a regular basis, but you need to make it accessible to those who will use this service.

Having an own email server means being able to control the email header.

Here is one example how you could make use of it:

Configure your email server so that it receives and recognizes
emails which contain the requested URLs.

Before you send a reply modify the email header so that it shows a random IP address and a random sender email address including a random domain name.

Send your reply.

Sending an email that way means that you cannot be replied back to. But since your reply already contains the requested information there is no need to.

I hope this helps.


问:
Command line: piping find results to rm
I'm trying to work out a command which deletes sql files older than 15 days.

The find part is working but not the rm.

```<code>rm -f | find -L /usr/www2/bar/htdocs/foo/rsync/httpdocs/db_backups -type f  \( -name '*.sql' \) -mtime +15
</code>```

It kicks out a list of exactly the files I want deleted but is not deleting them.  The paths are correct.

```<code>usage: rm [-f | -i] [-dIPRrvW] file ...
       unlink file
/usr/www2/bar/htdocs/foo/rsync/httpdocs/db_backups/20120601.backup.sql
...
/usr/www2/bar/htdocs/foo/rsync/httpdocs/db_backups/20120610.backup.sql
</code>```

What am I doing wrong?

答:
Assuming you aren't in the directory containing the *.sql backup files:

```<code>find /usr/www2/bar/htdocs/foo/rsync/httpdocs/db_backups/*.sql -mtime +15 -exec rm -v {} \;
</code>```

The -v option above is handy it will verbosely output which files are being deleted as they are removed.

I like to list the files that will be deleted first to be sure. E.g:

```<code>find /usr/www2/bar/htdocs/foo/rsync/httpdocs/db_backups/*.sql -mtime +15 -exec ls -lrth {} \;
</code>```

Title: Command line: piping find results to rm

Body:
I'm trying to work out a command which deletes sql files older than 15 days.

The find part is working but not the rm.

rm -f | find -L /usr/www2/bar/htdocs/foo/rsync/httpdocs/db_backups -type f  \( -name '*.sql' \) -mtime +15

It kicks out a list of exactly the files I want deleted but is not deleting them.  The paths are correct.

usage: rm [-f | -i] [-dIPRrvW] file ...
       unlink file
/usr/www2/bar/htdocs/foo/rsync/httpdocs/db_backups/20120601.backup.sql
...
/usr/www2/bar/htdocs/foo/rsync/httpdocs/db_backups/20120610.backup.sql

What am I doing wrong?

Body:
Assuming you aren't in the directory containing the *.sql backup files:

find /usr/www2/bar/htdocs/foo/rsync/httpdocs/db_backups/*.sql -mtime +15 -exec rm -v {} \;

The -v option above is handy it will verbosely output which files are being deleted as they are removed.

I like to list the files that will be deleted first to be sure. E.g:

find /usr/www2/bar/htdocs/foo/rsync/httpdocs/db_backups/*.sql -mtime +15 -exec ls -lrth {} \;


问:
Passing a parameter that could be null to a method
I have the following method call and for some reason the syntax in C# is not working correctly. If the pkg.Library.description is null then set it to a string.."No Folder Selected". Is there another way to do this?</p>

```<code>SendEmail (pkg.libraryfolder.description == null ? "No Folder Selected" :pkg.libraryfolder.description)

public void SendEmail(string folderdescription)
{
////
}
</code>```

答:
You don't explain why your code isn't working, it should, my guess is either pkgs is null or libraryfolder is null.    Currently you are just checking if description is null, which will be an error if any of the other things are null.  So to fix that, try :-

```<code>SendEmail (pkg?.libraryfolder?.description == null ? "No Folder Selected" :pkg.libraryfolder.description)

public void SendEmail(string folderdescription)
{
////
}
</code>```

or make it simpler by using

```<code> SendEmail (pkg?.libraryfolder?.description ?? "No Folder Selected");
</code>```

Body:
I have the following method call and for some reason the syntax in C# is not working correctly. If the pkg.Library.description is null then set it to a string.."No Folder Selected". Is there another way to do this?

SendEmail (pkg.libraryfolder.description == null ? "No Folder Selected" :pkg.libraryfolder.description)

public void SendEmail(string folderdescription)
{
////
}

Body:
You don't explain why your code isn't working, it should, my guess is either pkgs is null or libraryfolder is null.    Currently you are just checking if description is null, which will be an error if any of the other things are null.  So to fix that, try :-

SendEmail (pkg?.libraryfolder?.description == null ? "No Folder Selected" :pkg.libraryfolder.description)

public void SendEmail(string folderdescription)
{
////
}

or make it simpler by using

 SendEmail (pkg?.libraryfolder?.description ?? "No Folder Selected");