text:
Q: cocos2d-x runs on windows platform fine, but on android crashes I've been paid so much time debuging it, but I can't find any solution for the bug,
the following code always crashing on my galaxy S2 ( runs on android 4.1.2),
I develop with cocos2d-x 2.1.5,I avoid using autorelease,release,retain.. in onHttpRequestCompleted() functions, but it still not work on my device.
help me,please!
Here is my code:
#include "WuXiaUpdateScene.h"
#include "base64.h";
#include "FileOperation.h";
#include <algorithm>
#include "WuXiaLoginScene.h";
#include "WuXiaProgressBar.h"
#include "WuXiaServer.h"
#include "WuXiaMsgBox.h"
#include "StringHelper.h"

USING_NS_CC;

CCScene* WuXiaUpdateScene::scene()
{
    // 'layer' is an autorelease object
    WuXiaUpdateScene *layer = WuXiaUpdateScene::create();

    // return the scene
    return (CCScene*)layer;
}

// on "init" you need to initialize your instance
bool WuXiaUpdateScene::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !CCLayer::init())
    {
        return false;
    }

    CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
    CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();

    this->setFlag(UPDATE);

    /////////////////////////////
    // 3. add your codes below...
    fileCount = 0;
    fileUpdated = 0;
    CCLabelTTF * checkupdatesTTF = CCLabelTTF::create("Checking updates","Arial",22);
    checkupdatesTTF->setTag(1);
    checkupdatesTTF->setPosition(CCPoint(visibleSize.width/2,visibleSize.height/2));
    this->addChild(checkupdatesTTF);

    // 建立 progress bar
    WuXiaProgressBar * progressBar = WuXiaProgressBar::create();
    progressBar->setTag(2);
    progressBar->setPercentage(0);

    status = Updating;

    connect();

    return true;
}

void WuXiaUpdateScene::onEnter()
{
    CCLayer::onEnter();
    this->schedule(schedule_selector(WuXiaUpdateScene::onUpdateCompleted),0.5);
}

void WuXiaUpdateScene::onHttpRequestCompleted(cocos2d::extension::CCHttpClient* client, cocos2d::extension::CCHttpResponse* response)
{
    std::vector<char> *buffer = response->getResponseData();
    char* cString = new char[buffer->size()];
    for (unsigned int i=0;i<buffer->size();i++)
    {
        sprintf(cString+i,"%c",(*buffer)[i]);
    }

    std::string sString = cString;
    if (response->isSucceed() && sString.find("SUCCESS") != string::npos &&  sString.find("#SUCCESS") != string::npos)
    {
        if (sString.find("NO_UPDATES") != string::npos)
        {
            CCLabelTTF * checkupdatesTTF = (CCLabelTTF*)this->getChildByTag(1);
            if (checkupdatesTTF)
            {
                checkupdatesTTF->setString("No updates");
                status = Updated;
            }
            return;
        }

        vector<string> fileParts = StringHelper::Split(cString,"#");
        std::string writablePath = cocos2d::CCFileUtils::sharedFileUtils()->getWritablePath();
        std::vector<std::string> vPaths = std::vector<std::string>();
        vPaths.push_back(writablePath);
        cocos2d::CCFileUtils::sharedFileUtils()->setSearchPaths(vPaths);

        vector<string> fileList = StringHelper::Split(fileParts.at(3).c_str(),",");
        CCLabelTTF * checkupdatesTTF = (CCLabelTTF*)this->getChildByTag(1);
        char* cFileCount = new char[5];
        sprintf(cFileCount,"0/%d",fileList.size());
        string count(cFileCount, cFileCount+strlen(cFileCount));
        string wstr;
        wstr.append("There're ");
        wstr.append(count);
        wstr.append(" files need to be updated.");
        checkupdatesTTF->setString(wstr.c_str());

        version = fileParts.at(1);
        fileCount = fileList.size();
        for (int i=0;i<fileList.size();i++)
        {
            cocos2d::extension::CCHttpRequest* request = new cocos2d::extension::CCHttpRequest();
            std::string version="0";
            char* url= new char[1024];
            sprintf(url,"%s",fileList.at(i).c_str());
            request->setUrl(url);
            request->setRequestType(cocos2d::extension::CCHttpRequest::kHttpGet);
            request->setResponseCallback(this, httpresponse_selector(WuXiaUpdateScene::onFileDownloaded));
            cocos2d::extension::CCHttpClient::getInstance()->send(request);
            request->release();
            delete url;
        }

        CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
        CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();

        WuXiaProgressBar * progressBar = (WuXiaProgressBar*)this->getChildByTag(2);
        progressBar->setPosition(CCPoint(visibleSize.width/2,visibleSize.height/2-50));
        this->addChild(progressBar);
    }
}

void WuXiaUpdateScene::onFileDownloaded(cocos2d::extension::CCHttpClient* client, cocos2d::extension::CCHttpResponse* response)
{
    WuXiaProgressBar * progressBar = (WuXiaProgressBar *)this->getChildByTag(2);
    std::vector<char> *buffer = response->getResponseData();

    cocos2d::extension::CCHttpRequest *hr = response->getHttpRequest();
    const char * url = hr->getUrl();

    int len = strlen("7a30a48c-bd38-46b2-bb38-4afb79ac89abi.png");
    char * fileName = new char[len+1];
    memcpy( fileName, &url[strlen(url)-len], len );
    fileName[41] = '\0';
    FileOperation::saveFile(fileName,buffer);

    progressBar->setPercentage((++fileUpdated)/fileCount*100);

    if (fileUpdated == fileCount)
    {
        // 取得版本
        char* versionFile = "version.cfg";

        // 儲存版本資訊
        FileOperation::saveFile(versionFile,(char*)version.c_str());

        CCLabelTTF * checkupdatesTTF = (CCLabelTTF*)this->getChildByTag(1);
        checkupdatesTTF->setString("Update finished.");

        status = Updated;
        return;
    }
    else
    {
        CCLabelTTF * checkupdatesTTF = (CCLabelTTF*)this->getChildByTag(1);
        char* cFileCount = new char[5];
        sprintf(cFileCount,"%.0f/%.0f",fileUpdated,fileCount);
        string count(cFileCount, cFileCount+strlen(cFileCount));
        string wstr;
        wstr.append("there're ");
        wstr.append(count);
        wstr.append(" files need to be updated.");
        checkupdatesTTF->setString(wstr.c_str());
    }
}
// connect to server and get file list to update
void WuXiaUpdateScene::connect()
{
    cocos2d::extension::CCHttpRequest* request = new cocos2d::extension::CCHttpRequest();
    std::string version="0";
    char* url= new char[1024];

    std::string versionFile = "version.cfg";
    if (FileOperation::isFileAvaiable(versionFile))
        sprintf(url,"%sgetUpdateFiles.aspx?text=%s",WuXiaServer::PrimaryServer,base64_encode(FileOperation::readFile(versionFile)).c_str());
    else
        sprintf(url,"%sgetUpdateFiles.aspx?text=%s",WuXiaServer::PrimaryServer,base64_encode("0").c_str());
    request->setUrl(url);
    request->setRequestType(cocos2d::extension::CCHttpRequest::kHttpGet);
    request->setResponseCallback(this, httpresponse_selector(WuXiaUpdateScene::onHttpRequestCompleted));
    cocos2d::extension::CCHttpClient::getInstance()->send(request);
    request->release();
    delete url;
}

// switch screen whem update completed
void WuXiaUpdateScene::onUpdateCompleted(float dtTime)
{
    if (status != Updated)
        return;

    this->unschedule(schedule_selector(WuXiaUpdateScene::onUpdateCompleted));

    CCScene * scene  = WuXiaLoginScene::scene();
    CCDirector::sharedDirector()->replaceScene(CCTransitionFade::create(1,scene));
}@

A: Have you checked that all the resources loaded while loading from android? Windows platform and android platform might have different resolution, and if you have loaded your resources according to resolutions, then check if all the resources are availble.

A: Thank you for replying me.
I've resolve this problem, the problem may cause by Visual Studio IDE, I remove some remarks it now works fine. I don't know why when I just add new .cpp and .h files to my project same problem may occur again, but to remove or add some codes to some pages, it works, very weird.

A: I correct my answer, it's a memory issue.
char* cString = new char[buffer->size()]; can not store enough char for "buffer",
char* cString = new char[buffer->size()+1]; is correct,
I did not consider the empty char at the end of the buffer.


text:
Q: Simple regex in python I'm trying to simply get everything after the colon in the following:
hfarnsworth:204b319de6f41bbfdbcb28da724dda23

And then everything before the space in the following:
29ca0a80180e9346295920344d64d1ce ::: 25basement

Here's what I have:
for line in f:
    line = line.rstrip() #to remove \n
    line = re.compile('.* ',line) #everything before space.
    print line

Any tips to point me in the corrent direction? Thanks!
Also, is re.compile the correct function to use if I want the matched string returned? I'm pretty new at python too.
Thanks!!

A: string = "hfarnsworth:204b319de6f41bbfdbcb28da724dda23"
print(string.split(":")[1:])
string = "29ca0a80180e9346295920344d64d1ce ::: 25basement"
print(string.split(" ")[0])

A: At first you should probably take a careful look at the doc for re.compile.  It doesn't expect for second parameter to be a string to lookup.  Try to use re.search or re.findall. E.g.:
>>> s = "29ca0a80180e9346295920344d64d1ce ::: 25basement"
>>> re.findall('(\S*) ', s)[0]
'29ca0a80180e9346295920344d64d1ce'
>>> re.search('(\S*) ', s).groups()
('29ca0a80180e9346295920344d64d1ce',)

BTW, this is not the task for regular expressions.  Consider using some simple string operations (like split).

A: this regular expression seems to work
r"^(?:[^:]*\:)?([^:]*)(?::::.*)?$"

redpajama_set_name: RedPajamaStackExchange


text:
Q: Single process accessed by multiple apps I have a single C++ process that performs some extraction. I have 4 Java apps that are dependent on that extraction. How can I make sure that only one app is using that process at a time? Also, I don't want other apps to wait for a long time.

A: Using socketed I/O would allow you to queue up requests.

A: You can use something like ZeroMQ to setup a worker queue on your C++ process. Then your java apps can post to that queue and you C++ process can do as many or as few extractions as it wants.
There are other queues out there, such as HornetQ that can do the same as ZeroMQ and might be a bit simpler.
If you want to make it only do 1 extraction at a time, make your C++ thing spawn only one worker, then no matter how much stuff is posted to the Queue by your java apps, only one thing will happen at a time.


text:
Q: Electrons direction in cathode ray tube This image below show the movement of an electron in a magnetic field, it's taken from the video [Histoire des sciences] La découverte de l'électron explaining the experience of J.J. Thompson when he discovered the electron.

I don't understand why electrons are going the way indicated the red dotted line. Below is how I understand this image with the right-hand rule:

Because the force $\vec{F}$ is oriented toward the top, a positively charged ion (or cation) should go toward the top as shown on the picture. But here, it's an electron, a negatively charged particle, so it should be going toward the bottom. So why is it going toward the top? What's wrong in my understanding?
Also, is it correct to mark a plus (+) and a minus (-) on the magnet?

A: The force on a particle with charge $q$ and velocity $\vec{v}$ due to a magnetic field $\vec{B}$ is given by $\vec{F} = q(\vec{v} \times \vec{B})$. For an electron, $q$ is of course negative. For the geometry in the figures you posted, $\vec{v} \times \vec{B}$ points downward, and hence the force is upward.
In terms of the vectors in the second figure, I suppose $\vec{I}$ indicates the direction of current flow, which is in the opposite direction of electron flow. The right hand rule says that the force is in the direction of $\vec{I}\times\vec{B}$, which again is upward, as you can deduce by aligning your thumb with $\vec{B}$ and your middle finger with $\vec{I}$, whereby your index finger will point upward. For a positively charged particle, $\vec{I}$, and hence $\vec{F}$, would have the opposite orientation.
Marking a whole magnet plus or minus doesn't make much sense. Magnets have two poles: north and south. Outside the magnet, $\vec{B}$ tends to point from north to south. In this case, the magnet you labeled with a plus likely has its north pole facing the tube, while the other magnet has its south pole facing the tube. The two cylinders in the figure could also be (and I suppose usually are in practice) two different poles of the same magnet.


text:
Q: Get an id of UL having specific class i have a div that has a ul elemenet having class="bla" and id="foo"

aa

how can i get id of the ul,, help is appreciable

A: Try this:
var myEl = $('ul.bla').attr('id');

A: $('.new ul.blah').attr('id')

specifc to uls, and the new container div

A: $('ul[class=bla]').prop('id')

Will look up the ul element with the specific class bla.
prop('id') will get it's id.

A: Try this:
$('div.new').find('ul.bla').attr('id');

A: The id is considered a property of the ul, similar to the class and can both be used as selectors, so to use JQuery. you would use the class as the selector for the ul, and then access the ul property id.
$( '.class' ).prop( 'id' );

In this case it would return 'foo'.
EDIT ------
After seeing that you want to use those id's to select them, you could use one of these two methods.
var list = $( '#id' );

or
var list = $( '.class#id' );

The first method will work, but the second method is more explicit. Either one is acceptable though.


text:
Q: How to parallelize I/O operations when there is no async API I'm working on an application that scans servers remotely and collects meta data about them.
I'm trying to be write code that scales nicely on our servers. I'm using TPL to process multiple jobs at the same time. The problem that I have is that each of these 'jobs' spends half its time waiting for I/O operation to complete.
This would be very easy to fix if those operations offered Async or Begin/End interfaces but they don't. Couple samples:

*

*System.IO.Directory.GetAccessControl

*Win32API calls such as FindFirstFile http://msdn.microsoft.com/en-us/library/windows/desktop/aa364418(v=vs.85).aspx and FindNextFile http://msdn.microsoft.com/en-us/library/windows/desktop/aa364428(v=vs.85).aspx
How can I ensure that my application does more in this scenario? Should I create wrappers for these so that Async is supported and that way they will get send for processing in a thread.
Should I try TPL implementation Producer/Consumer so that all those I/O calls are executed at the same time? Will the TPL be smart enough to create more threads since most of them will not be doing anything?
Or maybe inside each of these jobs I should add job to ThreadPool for processing?

A: If you're spending most of your time in IO-bound operations that don't have asynchronous equivalents, then the only way to speed them up is to use multiple threads that are blocked most of the time.
But depending on the nature of that IO, you might not get any speedup at all. For example, if the IO is accessing a local disk, then using a single thread is most likely going to be the most efficient option. On the other hand, if you're accessing remote computers and you're not bound by your network bandwidth, then using many threads might be the best option.
TPL sounds like the right solution, but which part of TPL depends on your code. Maybe processing multiple jobs at the same time using Parallel.ForEach() will be the right solution. Or maybe you'll want to run some parts of a single job in parallel using Tasks. It's hard to say without knowing more details.

Should I create wrappers for these so that Async is supported and that way they will get send for processing in a thread.

No, don't do that. If you start a blocking Task on another thread and then release the current thread using await, then you haven't gained anything (assuming this is a server application). For more information, see Should I expose asynchronous wrappers for synchronous methods?

Will the TPL be smart enough to create more threads since most of them will not be doing anything?

Yes, the TPL tends to use more threads if the current ones are blocked. But at the same time, you most likely want to limit the number of threads (usually by setting something like MaxDegreeOfParallelism), depending on the kind of IO you're doing.


text:
Q: crt_externs.h on iOS? I've compiled the app for iOS Simulator successfully but i failed to do it for iOS device.
I've found that the file is presented for iOS Simulator, but it's absent for device:
$ ls /Applications/Xcode.app/Contents/Developer/Platforms/
MacOSX.platform         iPhoneOS.platform       iPhoneSimulator.platform

$ find /Applications/Xcode.app/Contents/Developer/Platforms/ -name "crt_externs.h"
/Applications/Xcode.app/Contents/Developer/Platforms//iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator6.1.sdk/usr/include/crt_externs.h
/Applications/Xcode.app/Contents/Developer/Platforms//iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator7.1.sdk/usr/include/crt_externs.h
/Applications/Xcode.app/Contents/Developer/Platforms//MacOSX.platform/Developer/SDKs/MacOSX10.8.sdk/usr/include/crt_externs.h
/Applications/Xcode.app/Contents/Developer/Platforms//MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/include/crt_externs.h

What's the reason and how can i workaround it?

A: I'm not sure why Apple didn't include them with the device headers but simply copying them from Simulator to Device folder works fine.
P.S: As far as I remember, this trick is not just to compile the solution. It also works as expected so far ;)

A: I manually copy the source from internet to get it compiled.


text:
Q: Appending the selected value to input field using ionic2 /angular 2 I want to append the selected value to input field using angular2/ionic2. I tried in the following way but it is appending in the following way:

But the actual requirement is like this:
fdfdfdf@hdfc or fdfdfd@icici
view
<ion-item>
        <ion-label floating>Bank Name</ion-label>
        <ion-select [formControl]="bank" (ionChange)="bankChange($event)">
          <ion-option value="HDFC">HDFC</ion-option>
          <ion-option value="ICICI">ICICI</ion-option>
        </ion-select>
</ion-item>

typescript
export class AddAccountPage {
  addAccountForm: ControlGroup;
  vaddr: AbstractControl;

  constructor(public navCtrl: NavController, private fb: FormBuilder) {
    this.addAccountForm = fb.group({
      'vaddr': ['', Validators.compose([Validators.required])]
    });
    this.vaddr = this.addAccountForm.controls['vaddr'];
  }

  bankChange(val){
   (this.vaddr as Control).updateValue(this.vaddr.value +'@'+ val);
  }
}

A: I fixed my problem in the following way,
if(this.vaddr.value.indexOf('@') > -1){
   (this.vaddr as Control).updateValue(this.vaddr.value.split("@")[0]);
}


text:
Q: Prove that for any prime $p>2$ the sum if written as a rational number $a/b$, has the property that $p|a$. Prove that for any prime $p>2$ the sum
$$\frac{1}{1^3}+\frac{1}{2^3}+\dots+\frac{1}{(p-1)^3}$$
if written as a rational number $a/b$, has the property that $p|a$.

A: Generalization
For $p=3$, the claim is trivial.  For a prime integer $p>3$, the sum $$\sum_{x\in\mathbb{F}_p}\,x^k$$
is equal to $0$ for all $k=0,1,2,\ldots,p-2$ (where $0^0:=1$).  In particular, when $k:=p-4<p-2$, we have
$$0=\sum_{x\in\mathbb{F}_p}\,x^{p-4}=\sum_{x\in\mathbb{F}_p^\times}\,\frac{1}{x^3}\,.$$
In general, if a prime number $p$ and an integer $k$ satisfy $p-1>k>0$, then $$\sum_{x\in\mathbb{F}_p^\times}\,\frac{1}{x^k}=0\,.$$

Alternative, Elementary Solution
For $j=1,2,\ldots,\frac{p-1}{2}$ and for an odd integer $k>0$, we have that $$\frac{1}{j^k}+\frac{1}{(p-j)^k}=\frac{p\,a_j}{b_j}$$
for some $a_j,b_j\in\mathbb{Z}_{>0}$ with $\gcd\left(a_j,b_j\right)=1$ and $p\nmid b_j$.


text:
Q: Python Async requests with proxy Is there a way to have async requests in python using an http proxy, which has been set by the PAAS provider (pythonanywhere) on the requests module but not aiohttp which uses the websocket API ?
Thanks.


text:
Q: AS3. Duration of microphone recording less then original sound In my as3 application i capture sound input using Microphone class. But i faced with problem.
Duration of my recording less then original sound. The problem is easily reproduced if put a microphone device near the sound speakers.
I begin to play local mp3 using Sound class and put microphone samples into byte array. After that i save byte array with microphone samples into local file (raw data) and load this file to Audacity. Also i load to Audacity original mp3 file.
The picture shows two sound waves as it shows in the Audacity.

I expect to see in the Audacity two synchronized sound waves - record and original sound. But i see by the end of the recording out of sync increase. And at the end i see different durations.
And one more thing. I have 2 computers for my tests. This problem occurs on first computer if i initialize microphone with rate 44100, but if i set rate 22050 problem there is no.
On the second computer is no problem at all - neither with a rate of 44100, nor with the rate 22050.
Does anyone had this problem? Why this occur?
Hope on your help, thanks!

A: This is an extremely tough thing to get right. There are a lot of variables at play - when the microphone starts recording, when playback begins, when they stop, etc. There's very little you can get back from the AS3 API that reveals start and stop times.
In general, you can usually count on the delay from when you ask playback to start and when sound actually comes out of your speakers to be greater than the delay of when you start listening for recorded samples. In your example above, you can see this. The problem isn't that the microphone recording is late, even though it appears that way. Instead, the problem is that the audio playback began later than the microphone, so the microphone recorded some relative silence at the beginning. Therefore, when you put the mic recording back up against the playback track, you see that silence first, then the recorded playback, giving the false impression that the mic was late.
On the other end, you have to contend with a very substantial delay between when the microphone picks up sound and when the SampleDataEvent arrives with those samples in Flash. When you get that event, you might be getting the samples that were recorded quite a while before - maybe a half second or more even. What this means is that if you stop the recording and the playback at the same time, you're going to chop off any samples from the microphone that haven't arrived yet, even though they were from the actual time that the audio was playing. Your best bet here is to NOT cut the microphone off at the same time as playback, but rather keep checking the length of your total recorded bytes in that SampleDataEvent handler, and when it is finally as long as the sound file (possibly plus an amount allowing for the play delay discussed before), stop it.


text:
Q: Is there a word that means simple but not easy? Often I find myself or others describing a concept that is simple to explain, but difficult to execute. I end up saying "it's really simple, just not easy" way too often for my tastes. Is there a word that expresses this idea well?

A: Something that is simple to explain, but difficult to execute can be called tricky.
M-W:

tricky
adjective
2 a :  giving a deceptive impression of easiness, simplicity, or order :  ticklish : a tricky path through the swamp

A: One word that may be suitable is awkward.

awkward [adjective]

  difficult to use, do, or deal with:

*

*It's an awkward corner, so take it slowly.


text:
Q: I can't correctly calculate the permutations of a number help, I made a code that allows to calculate the permutations of a number. for example if I enter the number 2090, this returns me the solutions:
2090, 0092, 0290, 0209, 9200, 9002, 9020, 0029, 0920, 0902, 2900, 2009, 2090, 0092, 0290, 0209, 9200, 9002, 9020, 0029, 0920, 0902, 2900, 2009.
then filter the solutions so that they are multiple of 11, have no zeros left and do not repeat. this filter gives me if I use the same number (2090) the following solutions:

2090
9020

here is where I have the problem, if I enter for example the number 2900 should give me the same solutions as when entering 2090, but I only return a solution that is 9020
How can I fix this error?
this is the code:
public static void main(String[] args) {

        ArrayList<String> list = new ArrayList<String>();
        Scanner read = new Scanner(System.in);

        System.out.println("Enter a Number");
        String n = read.next();

        //Calculate number of permutations
        long nPer = 1;
        for (int i = 1; i <= n.length(); i++) {
            nPer *= i;

        }
        System.out.println("Number of Permutations:" + nPer);
        char nums[] = n.toCharArray();

        //performs the permutation of the number according to the number of permutations
        for (int i = 0; i < nPer; i++) {

            /*
            valid if it is multiple of 11, does not have 0 to the left or if it is repeated and adds it to the ArrayList called list
             */

            if (Long.parseLong(String.valueOf(nums)) % 11 == 0) {
                if (nums[0] != '0') {
                    if (!list.contains(String.valueOf(nums))) {
                        list.add(String.valueOf(nums));
                    }
                }
            }

            char t = nums[i % (nums.length - 1)];
            nums[i % (nums.length - 1)] = nums[nums.length - 1];
            nums[nums.length - 1] = t;

        }
        //Display list with final solutions
        System.out.println("______________");
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
        System.out.println(list.size());

    }

A: Here is why posting mcve is so helpful:
When you eliminate the filters :
public static void main(String[] args) throws IOException {

    String n = "2900";
    ArrayList<String> list = new ArrayList<>();

    //Calculate number of permutations
    long nPer = 1;

    for (int i = 1; i <= n.length(); i++) {
        nPer *= i;
    }

    char nums[] = n.toCharArray();

    //performs the permutation of the number according to the number of permutations
    for (int i = 0; i < nPer; i++) {

        list.add(String.valueOf(nums));

        char t = nums[i % (nums.length - 1)];
        nums[i % (nums.length - 1)] = nums[nums.length - 1];
        nums[nums.length - 1] = t;
    }
    //Display list with final solutions

    System.out.println("______________");
    for (String s:  list) { System.out.println(s); }
}

You get:

2900 0902 0209 0290 0290 0092 0029 9020 9020 9002 2009 2900 2900 0902
  0209 0290 0290 0092 0029 9020 9020 9002 2009 2900

As you can see 2090 combination is not generated. On the other hands, other combinations appear more than once.
So now it is very clear that you need to look into:
        char t = nums[i % (nums.length - 1)];
        nums[i % (nums.length - 1)] = nums[nums.length - 1];
        nums[nums.length - 1] = t;

(Always verify that a piece of code works as expected, before adding complexity)
To properly find permutations, try:
ArrayList<String> list = new ArrayList<>(permutation(n));

private static Set<String>  permutation(String s) {

    if((s == null) || (s.length() < 2) ) {
        return null;
    }

    Set<String> permutations = new HashSet<>();
    permutation(0,s,permutations);
    return permutations;
}

private static void  permutation(int index, String s, Set<String> permutations) {

    permutations.add(s);

    if(index >= (s.length()-1)) {
        return;
    }

    char[] chars = s.toCharArray();

    for(int pos=0; pos < s.length() ; pos++) {

        char[] temp  = s.toCharArray();

        char c = temp[pos];
        temp[pos] = chars[index];
        temp[index] = c;

        permutation(index +1, String.valueOf(temp),  permutations);
    }

}


text: Q: How to Handle Hidden Field value changed event Globally in asp.net In my case i have one hidden field on each content page. which is same on all content pages in my application ( on each page with same Id) Now i want to handle value changed event of this field. but at global level. dont want to go on each page and write code. Is it possible? how ? Please help me..


text:
Q: Stata: Appending multiple files and extracting variables from file names I have 114 files with .dat extension to convert to Stata/SE and append, with substantial number of variables (varying from 81 to 16800). I have reset max number of variables to 32000 (set maxvar 32000), increased the memory (set mem 500m) and I was using the following algorithm to combine large number of files and to generate several variables by extracting parts of file names: http://www.ats.ucla.edu/stat/stata/faq/append_many_files.htm
The code looks as follows:
cd "C:\Users\..."
! dir *.dat /a-d /b >d:\Stata_directory\Products_batchfilelist.txt

file open myfile using "d:\Stata_directory\Products_batchfilelist.txt", read
file read myfile line
drop _all
insheet using `line', comma names

gen n = substr("`line'",10,1)
gen m = substr("`line'",12,1)
gen playersnum = substr("`line'",14,1)

save Products_merged.dta, replace

drop _all
file read myfile line

while r(eof)==0 {
    insheet using `line', comma names
    gen n = substr("`line'",10,1)
    gen m = substr("`line'",12,1)
    generate playersnum = substr("`line'",14,1)

    save `line'.dta, replace
    append using Products_merged.dta
    save Products_merged.dta,replace
    drop _all
    file read myfile line
}

The problem is that although variables n,m,playersnumextracted from file names are present in each individual file, they disappear in the final "Products_merged.dta" file. Could anyone tell me what could be the problem and if it is possible to solve with Stata/SE?

A: I don't see an obvious problem with the code that would be causing this. It may have something to do with the limits in SE, but that is still unlikely in my mind (you would see an error if a command does something to exceed maxvar).
My only suggestion would be to put a couple commands inside the append loop that will help you debug:
save `line'.dta, replace
append using Products_merged.dta
assert m!="" & n!="" & playersnum!=""
save Products_merged.dta,replace

This will do two things: ensure your variables exist after each new append (your first-order concern), and check that they are never blank (not your stated concern but a good check anyway).
If you post a couple of the files I could probably give a better answer.


text:
Q: libpcap timestamp resolution I am using python module pypcap (simplified object-oriented Python wrapper for libpcap). I am having troubles with timestamp resolution. In my pcap file I can see my packets have nanosecond precision, but when I parse the pcap file in python and extact the timestamp from a particular packet, it only has microsecond precision?
import pcap
for ts, pkt in pcap.pcap():
    print ts, `pkt`

ts has microsecond precision. I want nanosecond precision, any ideas? Thanks


text:
Q: PowerShell condition - result length > 0 or something like that I have a simple one line command that list contents of some remote share
Get-ChildItem -Path "\\some_path\" -Recurse | Where-Object{ $_.LastWriteTime -lt (Get-Date).AddDays(-1) }

I need to send an email in case there are no files in this folder.
So I found code that should send an email:
if ($Condition) {
    Send-MailMessage -From "sender@example.com" -To "receiver@example.com" -Subject "Condition met" -Body "The condition you specified has been met." -SmtpServer "smtp.example.com"
}

However, I'm not sure how should I define this $Condition in case there is nothing in this folder.
Maybe something like this:
$Condition = Get-ChildItem -Path "\\some_path\" -Recurse | Where-Object{ $_.LastWriteTime -lt (Get-Date).AddDays(-1) } | length>0

Thanks.


text:
Q: "who are"instead of "as"? I am plagued by a sentence from journal Nature. Though understanding the meaning it conveyed, certainly I could not write in that way. Here is the sentence.

Focusing evaluation on such inflexible terms leads us (a), as scientists at the beginning of our careers (b), to adopt utilitarian rather than academic motives.

I view b as an infinite attribute to modify us in a, and I would replace as in b with who are. So I hope you would explain the structure in the original sentence.

A: I suppose you are talking about this post.
"as", here, is used for "being currently" and begins a nominal clause, separated from the main clause by commas.
You can move the different clauses of the sentence to understand better :

Focusing evaluation on such inflexible terms leads us to adopt utilitarian rather than academic motives, as scientists at the beginning of our careers.

or

As scientists at the beginning of our careers, focusing evaluation on such inflexible terms leads us to adopt utilitarian rather than academic motives.

or with "being currently"

Being currently scientists at the beginning of our careers, focusing evaluation on such inflexible terms leads us to adopt utilitarian rather than academic motives.


text:
Q: Contact Form 7 to Wordpress User Database I have written the following function to add the contact form into the user database fields when it is sent. The issue is it sends the final email but isn't entering anything to the database so I must have an error somewhere, anyhelp would be much appreciated.
add_action('wpcf7_before_send_mail', 'my_conversion');
function my_conversion($cf7) {
 global $wpdb;
 parse_str($_POST['values'], $cf7->posted_data);
 $user_id = get_current_user_id();
 update_user_meta( $user_id, 'prefix', $cf7->posted_data['prefix'] );
 update_user_meta( $user_id, 'first_name', $cf7->posted_data['first-name'] );
 update_user_meta( $user_id, 'middle_name', $cf7->posted_data['middle-name'] );
 update_user_meta( $user_id, 'last_name', $cf7->posted_data['last-name'] );
 update_user_meta( $user_id, 'suffix', $cf7->posted_data['suffix'] );
 update_user_meta( $user_id, 'former_name', $cf7->posted_data['former-name'] );
 update_user_meta( $user_id, 'dob', $cf7->posted_data['date-of-birth'] );
 update_user_meta( $user_id, 'country_of_birth', $cf7->posted_data['country-of-birth'] );
 update_user_meta( $user_id, 'native_language', $cf7->posted_data['native-language'] );
 update_user_meta( $user_id, 'city_of_birth', $cf7->posted_data['city-of-birth'] );
 update_user_meta( $user_id, 'citizenship', $cf7->posted_data['citizenship'] );
 update_user_meta( $user_id, 'citizenship_status', $cf7->posted_data['citizenship-status'] );
 update_user_meta( $user_id, 'gender', $cf7->posted_data['gender'] );
 update_user_meta( $user_id, 'expiration_date', $cf7->posted_data['expiration-date'] );
 update_user_meta( $user_id, 'current_country', $cf7->posted_data['current-country'] );
 update_user_meta( $user_id, 'current_city', $cf7->posted_data['current-city'] );
 update_user_meta( $user_id, 'primary_address', $cf7->posted_data['primary-address'] );
 update_user_meta( $user_id, 'secondary_address', $cf7->posted_data['secondary-address'] );
 update_user_meta( $user_id, 'current_state', $cf7->posted_data['current-state'] );
 update_user_meta( $user_id, 'zipcode', $cf7->posted_data['zipcode'] );
 update_user_meta( $user_id, 'current_resident_country', $cf7->posted_data['current_resident_country'] );
 update_user_meta( $user_id, 'current_contact_residence_phone', $cf7->posted_data['current-contact-residence-phone'] );
 update_user_meta( $user_id, 'current_contact_business_phone', $cf7->posted_data['current-contact-business-phone'] );
 update_user_meta( $user_id, 'current_contact_cell_phone', $cf7->posted_data['current-contact-cell-phone'] );
 update_user_meta( $user_id, 'permanent_addr_expiration_date', $cf7->posted_data['permanent-addr-expiration-date'] );
 update_user_meta( $user_id, 'permanent_addr_country', $cf7->posted_data['permanent-addr-country'] );
 update_user_meta( $user_id, 'permanent_addr_city', $cf7->posted_data['permanent-addr-city'] );
 update_user_meta( $user_id, 'permanent_address', $cf7->posted_data['permanent-address'] );
 update_user_meta( $user_id, 'permanent_secondary_address', $cf7->posted_data['permanent-secondary-address'] );
 update_user_meta( $user_id, 'permanent_current_state', $cf7->posted_data['permanent-current-state'] );
 update_user_meta( $user_id, 'permanent_zipcode', $cf7->posted_data['permanent-zipcode'] );
 update_user_meta( $user_id, 'permanent_addr_res_county', $cf7->posted_data['permanent_addr_res_county'] );
 update_user_meta( $user_id, 'permanent_contact_residence_phone', $cf7->posted_data['permanent-contact-residence-phone'] );
 update_user_meta( $user_id, 'permanent_contact_business_phone', $cf7->posted_data['permanent-contact-business-phone'] );
 update_user_meta( $user_id, 'permanent_contact_cell_phone', $cf7->posted_data['permanent-contact-cell-phone'] );
 update_user_meta( $user_id, 'highest_degree', $cf7->posted_data['highest-degree'] );

 update_user_meta( $user_id, 'school_name_num_1', $cf7->posted_data['school-name-num-1'] );
 update_user_meta( $user_id, 'school_location_num_1', $cf7->posted_data['school-location-num-1'] );
 update_user_meta( $user_id, 'school_attended_from_num_1', $cf7->posted_data['school-attended-from-num-1'] );
 update_user_meta( $user_id, 'school_attended_to_num_1', $cf7->posted_data['school-attended-to-num-1'] );
 update_user_meta( $user_id, 'school_attended_as_num_1', $cf7->posted_data['school-attended-as-num-1'] );
 update_user_meta( $user_id, 'school_major_num_1', $cf7->posted_data['school-major-num-1'] );
 update_user_meta( $user_id, 'school_degree_num_1', $cf7->posted_data['school-degree-num-1'] );
 update_user_meta( $user_id, 'school_recieved_degree_when_num_1', $cf7->posted_data['school-recieved-degree-when-num-1'] );
 update_user_meta( $user_id, 'school_gpa_num_1', $cf7->posted_data['school-gpa-num-1'] );
 update_user_meta( $user_id, 'school_transcript_num_1', $cf7->posted_data['school-transcript-num-1'] );

 update_user_meta( $user_id, 'school_name_num_2', $cf7->posted_data['school-name-num-2'] );
 update_user_meta( $user_id, 'school_location_num_2', $cf7->posted_data['school-location-num-2'] );
 update_user_meta( $user_id, 'school_attended_from_num_2', $cf7->posted_data['school-attended-from-num-2'] );
 update_user_meta( $user_id, 'school_attended_to_num_2', $cf7->posted_data['school-attended-to-num-2'] );
 update_user_meta( $user_id, 'school_attended_as_num_2', $cf7->posted_data['school-attended-as-num-2'] );
 update_user_meta( $user_id, 'school_major_num_2', $cf7->posted_data['school-major-num-2'] );
 update_user_meta( $user_id, 'school_degree_num_2', $cf7->posted_data['school-degree-num-2'] );
 update_user_meta( $user_id, 'school_recieved_degree_when_num_2', $cf7->posted_data['school-recieved-degree-when-num-2'] );
 update_user_meta( $user_id, 'school_gpa_num_2', $cf7->posted_data['school-gpa-num-2'] );
 update_user_meta( $user_id, 'school_transcript_num_2', $cf7->posted_data['school-transcript-num-2'] );

 update_user_meta( $user_id, 'school_name_num_3', $cf7->posted_data['school-name-num-3'] );
 update_user_meta( $user_id, 'school_location_num_3', $cf7->posted_data['school-location-num-3'] );
 update_user_meta( $user_id, 'school_attended_from_num_3', $cf7->posted_data['school-attended-from-num-3'] );
 update_user_meta( $user_id, 'school_attended_to_num_3', $cf7->posted_data['school-attended-to-num-3'] );
 update_user_meta( $user_id, 'school_attended_as_num_3', $cf7->posted_data['school-attended-as-num-3'] );
 update_user_meta( $user_id, 'school_major_num_3', $cf7->posted_data['school-major-num-3'] );
 update_user_meta( $user_id, 'school_degree_num_3', $cf7->posted_data['school-degree-num-3'] );
 update_user_meta( $user_id, 'school_recieved_degree_when_num_3', $cf7->posted_data['school-recieved-degree-when-num-3'] );
 update_user_meta( $user_id, 'school_gpa_num_3', $cf7->posted_data['school-gpa-num-3'] );
 update_user_meta( $user_id, 'school_transcript_num_3', $cf7->posted_data['school-transcript-num-3'] );

 update_user_meta( $user_id, 'school_name_num_4', $cf7->posted_data['school-name-num-4'] );
 update_user_meta( $user_id, 'school_location_num_4', $cf7->posted_data['school-location-num-4'] );
 update_user_meta( $user_id, 'school_attended_from_num_4', $cf7->posted_data['school-attended-from-num-4'] );
 update_user_meta( $user_id, 'school_attended_to_num_4', $cf7->posted_data['school-attended-to-num-4'] );
 update_user_meta( $user_id, 'school_attended_as_num_4', $cf7->posted_data['school-attended-as-num-4'] );
 update_user_meta( $user_id, 'school_major_num_4', $cf7->posted_data['school-major-num-4'] );
 update_user_meta( $user_id, 'school_degree_num_4', $cf7->posted_data['school-degree-num-4'] );
 update_user_meta( $user_id, 'school_recieved_degree_when_num_4', $cf7->posted_data['school-recieved-degree-when-num-4'] );
 update_user_meta( $user_id, 'school_gpa_num_4', $cf7->posted_data['school-gpa-num-3'] );
 update_user_meta( $user_id, 'school_transcript_num_4', $cf7->posted_data['school-transcript-num-4'] );

 update_user_meta( $user_id, 'school_name_num_5', $cf7->posted_data['school-name-num-5'] );
 update_user_meta( $user_id, 'school_location_num_5', $cf7->posted_data['school-location-num-5'] );
 update_user_meta( $user_id, 'school_attended_from_num_5', $cf7->posted_data['school-attended-from-num-5'] );
 update_user_meta( $user_id, 'school_attended_to_num_5', $cf7->posted_data['school-attended-to-num-5'] );
 update_user_meta( $user_id, 'school_attended_as_num_5', $cf7->posted_data['school-attended-as-num-5'] );
 update_user_meta( $user_id, 'school_major_num_5', $cf7->posted_data['school-major-num-5'] );
 update_user_meta( $user_id, 'school_degree_num_5', $cf7->posted_data['school-degree-num-5'] );
 update_user_meta( $user_id, 'school_recieved_degree_when_num_5', $cf7->posted_data['school-recieved-degree-when-num-5'] );
 update_user_meta( $user_id, 'school_gpa_num_5', $cf7->posted_data['school-gpa-num-5'] );
 update_user_meta( $user_id, 'school_transcript_num_5', $cf7->posted_data['school-transcript-num-5'] );

 update_user_meta( $user_id, 'school_name_num_6', $cf7->posted_data['school-name-num-6'] );
 update_user_meta( $user_id, 'school_location_num_6', $cf7->posted_data['school-location-num-6'] );
 update_user_meta( $user_id, 'school_attended_from_num_6', $cf7->posted_data['school-attended-from-num-6'] );
 update_user_meta( $user_id, 'school_attended_to_num_6', $cf7->posted_data['school-attended-to-num-6'] );
 update_user_meta( $user_id, 'school_attended_as_num_6', $cf7->posted_data['school-attended-as-num-6'] );
 update_user_meta( $user_id, 'school_major_num_6', $cf7->posted_data['school-major-num-6'] );
 update_user_meta( $user_id, 'school_degree_num_6', $cf7->posted_data['school-degree-num-6'] );
 update_user_meta( $user_id, 'school_recieved_degree_when_num_6', $cf7->posted_data['school-recieved-degree-when-num-6'] );
 update_user_meta( $user_id, 'school_gpa_num_6', $cf7->posted_data['school-gpa-num-6'] );
 update_user_meta( $user_id, 'school_transcript_num_6', $cf7->posted_data['school-transcript-num-6'] );

 update_user_meta( $user_id, 'school_name_num_7', $cf7->posted_data['school-name-num-7'] );
 update_user_meta( $user_id, 'school_location_num_7', $cf7->posted_data['school-location-num-7'] );
 update_user_meta( $user_id, 'school_attended_from_num_7', $cf7->posted_data['school-attended-from-num-7'] );
 update_user_meta( $user_id, 'school_attended_to_num_7', $cf7->posted_data['school-attended-to-num-7'] );
 update_user_meta( $user_id, 'school_attended_as_num_7', $cf7->posted_data['school-attended-as-num-7'] );
 update_user_meta( $user_id, 'school_major_num_7', $cf7->posted_data['school-major-num-7'] );
 update_user_meta( $user_id, 'school_degree_num_7', $cf7->posted_data['school-degree-num-7'] );
 update_user_meta( $user_id, 'school_recieved_degree_when_num_7', $cf7->posted_data['school-recieved-degree-when-num-7'] );
 update_user_meta( $user_id, 'school_gpa_num_7', $cf7->posted_data['school-gpa-num-7'] );
 update_user_meta( $user_id, 'school_transcript_num_7', $cf7->posted_data['school-transcript-num-7'] );

 update_user_meta( $user_id, 'school_name_num_8', $cf7->posted_data['school-name-num-8'] );
 update_user_meta( $user_id, 'school_location_num_8', $cf7->posted_data['school-location-num-8'] );
 update_user_meta( $user_id, 'school_attended_from_num_8', $cf7->posted_data['school-attended-from-num-8'] );
 update_user_meta( $user_id, 'school_attended_to_num_8', $cf7->posted_data['school-attended-to-num-8'] );
 update_user_meta( $user_id, 'school_attended_as_num_8', $cf7->posted_data['school-attended-as-num-8'] );
 update_user_meta( $user_id, 'school_major_num_8', $cf7->posted_data['school-major-num-8'] );
 update_user_meta( $user_id, 'school_degree_num_8', $cf7->posted_data['school-degree-num-8'] );
 update_user_meta( $user_id, 'school_recieved_degree_when_num_8', $cf7->posted_data['school-recieved-degree-when-num-8'] );
 update_user_meta( $user_id, 'school_gpa_num_8', $cf7->posted_data['school-gpa-num-8'] );
 update_user_meta( $user_id, 'school_transcript_num_8', $cf7->posted_data['school-transcript-num-8'] );

 update_user_meta( $user_id, 'carreer_field', $cf7->posted_data['carreer-field'] );
 update_user_meta( $user_id, 'carreer_field_spec', $cf7->posted_data['carreer-field-spec'] );

 update_user_meta( $user_id, 'exper_1_position_title', $cf7->posted_data['exper-1-position-title'] );
 update_user_meta( $user_id, 'exper_1_organization_name', $cf7->posted_data['exper-1-organization-name'] );
 update_user_meta( $user_id, 'exper_1_country', $cf7->posted_data['exper-1-country'] );
 update_user_meta( $user_id, 'exper_1_city', $cf7->posted_data['exper-1-city'] );
 update_user_meta( $user_id, 'exper_1_from', $cf7->posted_data['exper-1-from'] );
 update_user_meta( $user_id, 'exper_1_to', $cf7->posted_data['exper-1-to'] );

 update_user_meta( $user_id, 'exper_2_position_title', $cf7->posted_data['exper-2-position-title'] );
 update_user_meta( $user_id, 'exper_2_organization_name', $cf7->posted_data['exper-2-organization-name'] );
 update_user_meta( $user_id, 'exper_2_country', $cf7->posted_data['exper-2-country'] );
 update_user_meta( $user_id, 'exper_2_city', $cf7->posted_data['exper-2-city'] );
 update_user_meta( $user_id, 'exper_2_from', $cf7->posted_data['exper-2-from'] );
 update_user_meta( $user_id, 'exper_2_to', $cf7->posted_data['exper-2-to'] );

 update_user_meta( $user_id, 'exper_3_position_title', $cf7->posted_data['exper-3-position-title'] );
 update_user_meta( $user_id, 'exper_3_organization_name', $cf7->posted_data['exper-3-organization-name'] );
 update_user_meta( $user_id, 'exper_3_country', $cf7->posted_data['exper-3-country'] );
 update_user_meta( $user_id, 'exper_3_city', $cf7->posted_data['exper-3-city'] );
 update_user_meta( $user_id, 'exper_3_from', $cf7->posted_data['exper-3-from'] );
 update_user_meta( $user_id, 'exper_3_to', $cf7->posted_data['exper-3-to'] );

 update_user_meta( $user_id, 'exper_4_position_title', $cf7->posted_data['exper-4-position-title'] );
 update_user_meta( $user_id, 'exper_4_organization_name', $cf7->posted_data['exper-4-organization-name'] );
 update_user_meta( $user_id, 'exper_4_country', $cf7->posted_data['exper-4-country'] );
 update_user_meta( $user_id, 'exper_4_city', $cf7->posted_data['exper-4-city'] );
 update_user_meta( $user_id, 'exper_4_from', $cf7->posted_data['exper-4-from'] );
 update_user_meta( $user_id, 'exper_4_to', $cf7->posted_data['exper-4-to'] );

 update_user_meta( $user_id, 'exper_5_position_title', $cf7->posted_data['exper-5-position-title'] );
 update_user_meta( $user_id, 'exper_5_organization_name', $cf7->posted_data['exper-5-organization-name'] );
 update_user_meta( $user_id, 'exper_5_country', $cf7->posted_data['exper-5-country'] );
 update_user_meta( $user_id, 'exper_5_city', $cf7->posted_data['exper-5-city'] );
 update_user_meta( $user_id, 'exper_5_from', $cf7->posted_data['exper-5-from'] );
 update_user_meta( $user_id, 'exper_5_to', $cf7->posted_data['exper-5-to'] );

 update_user_meta( $user_id, 'exper_6_position_title', $cf7->posted_data['exper-6-position-title'] );
 update_user_meta( $user_id, 'exper_6_organization_name', $cf7->posted_data['exper-6-organization-name'] );
 update_user_meta( $user_id, 'exper_6_country', $cf7->posted_data['exper-6-country'] );
 update_user_meta( $user_id, 'exper_6_city', $cf7->posted_data['exper-6-city'] );
 update_user_meta( $user_id, 'exper_6_from', $cf7->posted_data['exper-6-from'] );
 update_user_meta( $user_id, 'exper_6_to', $cf7->posted_data['exper-6-to'] );

 update_user_meta( $user_id, 'exper_7_position_title', $cf7->posted_data['exper-7-position-title'] );
 update_user_meta( $user_id, 'exper_7_organization_name', $cf7->posted_data['exper-7-organization-name'] );
 update_user_meta( $user_id, 'exper_7_country', $cf7->posted_data['exper-7-country'] );
 update_user_meta( $user_id, 'exper_7_city', $cf7->posted_data['exper-7-city'] );
 update_user_meta( $user_id, 'exper_7_from', $cf7->posted_data['exper-7-from'] );
 update_user_meta( $user_id, 'exper_7_to', $cf7->posted_data['exper-7-to'] );

 update_user_meta( $user_id, 'exper_8_position_title', $cf7->posted_data['exper-8-position-title'] );
 update_user_meta( $user_id, 'exper_8_organization_name', $cf7->posted_data['exper-8-organization-name'] );
 update_user_meta( $user_id, 'exper_8_country', $cf7->posted_data['exper-8-country'] );
 update_user_meta( $user_id, 'exper_8_city', $cf7->posted_data['exper-8-city'] );
 update_user_meta( $user_id, 'exper_8_from', $cf7->posted_data['exper-8-from'] );
 update_user_meta( $user_id, 'exper_8_to', $cf7->posted_data['exper-8-to'] );

 update_user_meta( $user_id, 'conv_area1', $cf7->posted_data['conv-area1'] );
 update_user_meta( $user_id, 'conv_area2', $cf7->posted_data['conv-area2'] );
 update_user_meta( $user_id, 'research_area1', $cf7->posted_data['research-area1'] );
 update_user_meta( $user_id, 'research_area2', $cf7->posted_data['research-area2'] );
 update_user_meta( $user_id, 'research_area3', $cf7->posted_data['research-area3'] );
 update_user_meta( $user_id, 'research_area4', $cf7->posted_data['research-area4'] );
 update_user_meta( $user_id, 'application_status', 'I' );

 global $current_user;
 get_currentuserinfo();
 $email_address = 'email@address.com';
 // write the email content
$header .= "MIME-Version: 1.0\n";
$header .= "Content-Type: text/html; charset=utf-8\n";
$header .= "From:" . $email_address;
$subject = 'W Application Form';
$message = "Hi,

".$cf7->posted_data['first-name'].' '.$cf7->posted_data['last-name']."

";
$message .= "Your application has been submitted successfully";
wp_mail($current_user->user_email, $subject, $message, $header);
 //$current_user->user_email
 }

I've also tried another way to do it which is below based on other examples and WP codex and this doesn't work either?
   add_action('wpcf7_before_send_mail', 'updateuser');
 function updateuser($cf7)
{
$first_name = $cf7->posted_data["first-name"];
$middle_name = $cf7->posted_data["middle-name"];
$last_name = $cf7->posted_data["last-name"];

global $wpdb, $wpcf7;
global $current_user;
get_currentuserinfo();
$wpdb->update(
'usermeta',
array (
    'first_name' => $first_name,
    'middle_name' => $middle_name,
    'last_name' =>  $last_name
),
array( 'ID' => $userid ),
array(
    '%s',
    '%s',
    '%s'
),
array( '%d' )
);

 global $current_user;
 get_currentuserinfo();
 $email_address = 'contact@domain.com';
 // write the email content
$header .= "MIME-Version: 1.0\n";
$header .= "Content-Type: text/html; charset=utf-8\n";
$header .= "From:" . $email_address;
$subject = 'New Application Form';
$message = "Hi,

".$cf7->posted_data['first-name'].' '.$cf7->posted_data['last-name']."

";
$message .= "Your application has been submitted successfully";
wp_mail($current_user->user_email, $subject, $message, $header);
   //$current_user->user_email
}
 ?>

A: I finally got there after much experimenting and googling and following Howli's advice, this code works to update the usermeta table, hopefully it helps someone save hours of time:
add_action('wpcf7_before_send_mail', 'cf7import',1);
function cf7import() {
$title = $contact_form->title;
$submission = WPCF7_Submission::get_instance();
if ( $submission )
{
$posted_data = $submission->get_posted_data();
$formtitle = $cfdata->title; }
if ( $formtitle == 'Form Name') {
}
 global $wpdb;
 $user_id = get_current_user_id();
 update_user_meta( $user_id, 'prefix', $posted_data['prefix'] );
 update_user_meta( $user_id, 'first_name', $posted_data['first-name'] );
 update_user_meta( $user_id, 'middle_name', $posted_data['middle-name'] );
 update_user_meta( $user_id, 'last_name', $posted_data['last-name'] );

A: Try this:
add_action('wpcf7_before_send_mail', 'my_conversion');
function my_conversion()
{
    $submission = WPCF7_Submission::get_instance();
    if ( $submission )
    {
        $posted_data = $submission->get_posted_data();
    }

update_user_meta( $user_id, 'prefix', $posted_data['prefix'] );

The $cf7 trick doesn't work after contact form 7 3.8


text: Q: Why probability of detection of optimum unambiguous discrimination between linearly independent symmetric states is less than random guess? Considering the analysis and result of this paper, http://arxiv.org/pdf/quant-ph/9807023v1.pdf, I have used equation (3.15) and (4.3) to calculate the optimum probability of success for mean photon number = 10000 and number of measurement basis= 2000, and got probability of success for detecting correct state is $6.19*10^-13$, which is much smaller than random guess($1/2000$).What is the reason behind this of getting such a small probability of success following a particular measurement scheme,which is even smaller than random guess(1/2000), and random guess means no measurement at all.


text:
Q: How does fastapi/uvicorn parallelize requests? I ran an experiment with fastapi and uvicorn that I don't understand the outcome of.
On the code
@app.get('/loadtest')
def root():
    time.sleep(1)
    return {'message': 'hello'}

running in docker with
CMD ["uvicorn", "app.main:app", "--proxy-headers", "--host", "0.0.0.0", "--port", "80"]

I ran the following test:
ab -c 100 -n 1000 localhost/loadtest

which gives me the results:
bersling-2:cas bersling$ ab -c 100 -n 1000 localhost/loadtest
This is ApacheBench, Version 2.3 <$Revision: 1879490 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking localhost (be patient)
Completed 100 requests
Completed 200 requests
Completed 300 requests
Completed 400 requests
Completed 500 requests
Completed 600 requests
Completed 700 requests
Completed 800 requests
Completed 900 requests
Completed 1000 requests
Finished 1000 requests

Server Software:        uvicorn
Server Hostname:        localhost
Server Port:            80

Document Path:          /loadtest
Document Length:        19 bytes

Concurrency Level:      100
Time taken for tests:   85.052 seconds
Complete requests:      1000
Failed requests:        0
Total transferred:      163000 bytes
HTML transferred:       19000 bytes
Requests per second:    11.76 [#/sec] (mean)
Time per request:       8505.191 [ms] (mean)
Time per request:       85.052 [ms] (mean, across all concurrent requests)
Transfer rate:          1.87 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.7      0       4
Processing:  1008 7964 1419.3   8010    9022
Waiting:     1004 7963 1419.3   8008    9020
Total:       1008 7965 1418.7   8010    9024

Percentage of the requests served within a certain time (ms)
  50%   8010
  66%   8016
  75%   8988
  80%   8989
  90%   8993
  95%   8998
  98%   9003
  99%   9006
 100%   9024 (longest request)

So we see this takes around 100s to complete. However, I would have expected 1000s, since I'd assume the requests need to be worked sequentially and each request takes one second. I assumed the sequential queue since I thought python can only ever handle one request at a time (in synchronous mode) and I'm not aware that uvicorn would spawn multiple processes or threads. So I don't understand how the 100s result instead of the 1000s result is possible. Can somebody please explain?

A: To quote the docs:

When you declare a path operation function with normal def instead of async def, it is run in an external threadpool that is then awaited, instead of being called directly (as it would block the server).

Or to quote the answer from the github discussion which is a bit simpler to read:

For endpoints defined with def (not async def), FastAPI will run them in a threadpool, exactly as to avoid blocking the server and allow multiple requests to be served in parallel.

Which then raises the question of the number of concurrent threads and how this can be controlled. This question is addressed here.
For convenience again the quote:

fastAPI is based on starlette that use to control the
ThreadPoolExecutor , but starlette is now using anyio , so I don't see
a better way than your proposition :
RunVar("_default_thread_limiter").set(CapacityLimiter(2))


text:
Q: Firebase storage security rule parameter hash I work in an industry where there is an incredible amount of image hotlinking that takes place.
To help with this issue, it is very common to pass a hash when generating image URLs which allows the authenticity of querystring parameters to be verified, and which allows the storage location to do things like limit by IP, or a usage window (Supplied in the querystring parameters)
Is it possible to generate some type of hash in the security rules for firebase storage which can be used with a secret to ensure that the parameters supplied were generated by a trusted source?

A: If you want to store a hash you'll need to compute it client-side, but it's easy to validate correctness of hashes using Rules!
rules_version="2"
service firebase.storage {
  match path/{docId} {
    // also available in md5, crc32 and crc32c flavors
    allow read, write: if docId == hashing.sha256(/* stuff */).toBase64();
  }
}


text:
Q: iBeacon possible to wake up an app? We have requirement to integrate ibeacon in our iphone app.When user reached nearest to a beacon ,
1)App need to wake up and open automatically.Is it possible?
or
2)We need a local notification first and click on it will open the app?
First one is possible , help is highly appreciable
Thanks,

A: You cannot open an app on iOS automatically on beacon detection.   The most you can do is send a local notification, and if the user taps on that, the app will launch.
See here for details:  Can I launch an app in Foreground when I enter an iBeacon range?


text:
Q: Veracode Insecure Temporary File error when using java.io.File.createTempFile I need to create a temporary file and store some data into it. I have written the following code to do so:
import org.apache.commons.lang.RandomStringUtils;
import java.security.SecureRandom;

[...]

String random = RandomStringUtils.random(10, 0, 0, true, true, null, new SecureRandom());
File tempFile = File.createTempFile("PREFIX-" + random, ".pdf");

[...]

It does work perfectly, but when I submit this code to Veracode, I get an "Insecure Temporary File (CWE ID 377)" error.
I thought that using SecureRandom will make the temporary file name impossible to predict by attackers.
What is the right way to generate a temporary file without making Veracode unhappy?

A: While creating File using CreateTemp file (in lower version java) it will first create a filename with given suffix and prefix and a random number. format--> Prefix+randam number+Suffix. If the generated name already present it just increment the randam number. here comes the issue in algorithum where v can guess what will be the next filename.
The issue is resolved in Java 6. But still if u do Static scan in veracode they will show it as bug since they cause vulnerable issue in java version lower than 6. If you are using higher version then no problem. Just Skip it..
Reference from veracode: https://www.veracode.com/blog/2009/01/how-boring-flaws-become-interesting

A: I think the issue is resolved in Java 6 Update 11 release. Use latest version of Java.


text:
Q: Azure Service Bus topic subscription throws FilterException about System.DBNull All messages in a subscription to an Azure Service Bus topic are sent to the dead letter queue with a FilterException saying

Operator '==' cannot be applied to operands of type 'string' and 'System.DBNull'

The filter is of type SqlFilter and the expression is:
TriggerEvent in ("A01", "A04", "A28", "A47") OR (TriggerEvent = "A31" AND EventReasonCode = "REG_MANUAL")

This has been running for months without any FilterException, and it currently runs fine in a different environment for production.
A collegue found the reason for this error, and since I didn't find anything relevant when googling this error, I'll post this question and the answer to it right away.

A: For some reason the test environment has been updated with double quotes instead of single quotes around the trigger events and reason code stings like this:
TriggerEvent = "A31" AND EventReasonCode = "REG_MANUAL"

When we changed that back to single quotes, everything was fine:
TriggerEvent in ('A01', 'A04', 'A28', 'A47') OR (TriggerEvent = 'A31' AND EventReasonCode = 'REG_MANUAL')

The error message is misleading and it's hard to see what the reason might be, because I couldn't find any System.DBNull value anyhere.


text:
Q: При перетаскивании элементов списка порядок остается прежним Пишу свой ToDo List на Android (Kotlin) с сохранением в базе данных. Реализовал возможность перетаскивать элементы, меняя их местами. Однако, есть проблема. Для удобства сделал гифку:

*

*есть список с названиями: 1, 2, 3.

*меняю 1 и 2 местами.

*кликаю на 1, чтобы отредактировать.

*возвращаюсь к списку, но порядок вернулся к тому, который был до перетаскивания.

Если кто-то сталкивался с таким, буду рад помощи.

A: Я думаю, что ваша проблема состоит в том, что вы неправильно храните сам список. Я конечно могу ошибаться т.к. вы не приложили кода, но смею предположить, что ваш список храниться (или получается) где-то или в самом адаптере или Activity.
Если вы хотите иметь актуальное состояние вашего экрана, то вам нужно позаботиться об актуальности данных. Самый простой способ это создать какую-то сущность (Presenter/ViewModel и т.п.) в которой будет храниться состояние экрана, в вашем случае это ваш список в нужном порядке.
Условно вы вошли на экран:

*

*Загрузили данные и передали их в ваша Adapter.

*После чего вы поменяли их местами. И тут важный момент, вы должны сделать замену не в адаптере, а в вашем Presenter/ViewModel и после чего заново обновить адаптер. Тут стоит реализовать DiffUtils, чтоб всякий раз не обновлять весь список.

*После того как вы вернулись на предыдущий экран вы просто снова подгружаете состояние из Presenter.

В целом это же можно сделать и через базу данных, а если вы используете RX Java то вы вообще можете просто подписать ваш адаптер на изменения в БД. И все изменения гонять через БД, так вы будете получать актуальное состояние даже после выгрузки приложения из памяти.
Но суть в том, что ваш UI не должен ничего знать о логике получения данных, он должен быть максимально тупым и единственной его ответственностью должно быть: "Рисование самого себя".
В то же время слой с логикой и данными не должен зависеть от вашего UI, и хранить в себе актуальное состояние независимо от того что и где открылось.


text:
Q: При запуске проекта yii2-advance в логах nginx выпадают ошибки ядра, в чем может быть проблема?
FastCGI sent in stderr: "PHP message: PHP Warning:  Invalid argument
  supplied for foreach() in
  /var/www/yii/crmtest/vendor/yiisoft/yii2/helpers/BaseArrayHelper.php
  on line 123 PHP message: PHP Fatal error:  Uncaught exception
  'yii\base\InvalidConfigException' with message 'The "id" configuration
  for the Application is required.' in
  /var/www/yii/crmtest/vendor/yiisoft/yii2/base/Application.php:219
  Stack trace:
  0 /var/www/yii/crmtest/vendor/yiisoft/yii2/base/Application.php(201): yii\base\Application->preInit(Array)
  1 /var/www/yii/crmtest/frontend/web/index.php(17): yii\base\Application->__construct(Array)
  2 {main}   thrown in /var/www/yii/crmtest/vendor/yiisoft/yii2/base/Application.php on line
  219" while reading response header from upstream, client: 127.0.0.1,
  server: mysite.test, request: "GET / HTTP/1.1", upstream:
  "fastcgi://unix:/run/php/php5.6-fpm.sock:", host: "127.0.0.1"

Конфиг nginx etc/nginx/site-available
server {
charset utf-8;
client_max_body_size 128M;

listen 80; ## listen for ipv4
#listen [::]:80 default_server ipv6only=on; ## слушаем ipv6

server_name mysite.test;
#root /var/www/yii/crm_2.3/backend/web;
root /var/www/yii/crm_2.3/frontend/web;
#root /var/www/yii/crm/backend/web;
index index.php;

access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;

location / {
# Перенаправляем все запросы к несуществующим директориям и файлам на index.php
try_files $uri $uri/ /index.php?$args;
}

# раскомментируйте строки ниже во избежание обработки Yii обращений к несуществующим статическим файлам
location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ {
try_files $uri =404;
access_log off;
log_not_found off;
expires off;
}
#error_page 404 /404.html;

location ~ \.php$ {
include fastcgi_params;
#fastcgi_pass 127.0.0.1:9000;
#fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_pass unix:/run/php/php5.6-fpm.sock;
fastcgi_read_timeout 3000;

fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_buffers 16 16k;
fastcgi_buffer_size 32k;
}

location ~ /\.(ht|svn|git) {
access_log off;
log_not_found off;
deny all;
}
}

A: Я бы даже сказал, что это не ошибки ядра, а ошибки взаимодействия nginx и fpm.
Необходимо правильно настроить конфиги nginx и php и перегрузить эти сервисы.
В конфигах виртуального хоста надо найти что-то типа fastcgi_pass 127.0.0.1:9000; (это настройка через порт), а в конфиге /etc/php/7.0/fpm/pool.d/www.conf (в зависимости от версии пхп) listen = 127.0.0.1:9000
Для настройки сокетов аналогично должно быть. Или можно настроить на порты. Вот тут один из вариантов настройки виртуального хоста nginx и диагностика ошибок. Главное не забыть сделать рестарт, релоад не поможет.


text:
Q: How to remove margin around cards in android prelollipop? Everything is fine in Android Lollipop, but there is extra space around card view in Android 4.
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/card_member"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardCornerRadius="0dp"
app:cardUseCompatPadding="true"
android:foreground="?android:attr/selectableItemBackground">

image here


text:
Q: optgroup in dropdown using struts Can anyone please help in implementing the same functionality of optgroup using struts.

A: As far as I know, there is no way of creating select groups using Struts tags.
You will have to resort to using the plain HTML tag <optgroup> tag and create your select options by using either the JSTL <c:forEach> tag or the Struts <logic:iterate> tag.
Such a tag was added in Struts 2 but for Struts 1 there isn't one.


text:
Q: AngleSharp error while making the async calls I am trying to load many pages using the AngleSharp. The idea is that it loads a page, and if this page has a link to the next, loads the next page and so forth, the methods are described like bellow. But I am getting the inner exception:
Specified argument was out of the range of valid values.
Parameter name: index"

I believe is something related with Thread and syncrhronization.
    public static bool ContainsNextPage(IDocument document)
    {
        String href = document.QuerySelectorAll(".prevnext a")[0].GetAttribute("href");
        if (href == String.Empty)
            return false;
        else
            return true;
    }

    public static string GetNextPageUrl(IDocument document)
    {
        return document.QuerySelectorAll(".prevnext a")[0].GetAttribute("href");

    }

    public static async Task<IDocument> ParseUrlSynch(string Url)
    {
            var config = new Configuration().WithDefaultLoader();
            IDocument document = await BrowsingContext.New(config).OpenAsync(Url);

            return document;
    }

    public static async Task<ConcurrentBag<IDocument>> GetAllPagesDOMs(IDocument initialDocument)
    {

        ConcurrentBag< IDocument> AllPagesDOM = new ConcurrentBag< IDocument>();
        IDocument nextPageDOM;
        IDocument currentDocument = initialDocument;

        if (initialDocument != null)
        {
            AllPagesDOM.Add(initialDocument);
        }

        while (ContainsNextPage(currentDocument))
        {
            String nextPageUrl = GetNextPageUrl(currentDocument);

            nextPageDOM = ParseUrlSynch(nextPageUrl).Result;
            if (nextPageDOM != null)
                AllPagesDOM.Add(nextPageDOM);

            currentDocument = nextPageDOM;
        }

        return AllPagesDOM;
    }

      static void Main(string[] args)
    {

        List<IDocument> allPageDOMs = new List<IDocument>();
        IDocument initialDocument = ParseUrlSynch(InitialUrl).Result;
        List<String> urls = new List<string>();
        List<Subject> subjects = new List<Subject>();
        IHtmlCollection<IElement> subjectAnchors = initialDocument.QuerySelectorAll(".course_title a");

        String[] TitleAndCode;
        String Title;
        String Code;
        String Description;
        IDocument currentDocument = initialDocument;

        ConcurrentBag<IDocument> documents =

        GetAllPagesDOMs(initialDocument).Result; //Exception in here
        ...
}

A: Your instincts are correct, if you are using this from an application with a non-default SynchronizationContext such as WPF, Win Forms, or ASP.NET then you will have a deadlock because you are synchronously blocking on an async Task returning function (this is bad and should be avoided). When the first await is reaching inside of the blocking call, it will try to post the continuation to the current SyncronizationContext, which will be already locked by the blocking call (if you use .ConfigureAwait(false) you avoid this, but that is a hack in this case).
A quick fix would be to use async all the way through by changing:
nextPageDOM = ParseUrlSynch(nextPageUrl).Result;

with:
nextPageDOM = await ParseUrlSynch(nextPageUrl);

After you get stung by this a few times, you'll learn to have alarm bells go off in your head every time you block an asynchronous method.

A: Error message is caused by this code:
document.QuerySelectorAll(".prevnext a")[0]

One of your documents doesn't have any anchors inside prevnext. Maybe it's first page, maybe the last, either way you need to check the array for it's length.
Also blocking call on async method is a bad practice and should be avoided. You'll get the deadlock in any UI app. The only reason you don't get it now is that you're in console app.


text:
Q: printing all function calls in a php script I am wondering if it is possible to print on screen all functions that are called in a php script.
This might imply the possibility to override the default behaviour associated to all function calls, which means defining some additional behaviour to what happens when a function is called.
For example, if I have the following functions:
function foo() {
  echo "hi";
}

function additional_behaviour($function_name) {
  echo "function $function_name has been called";
}

Somehow I would like enrich the behaviour associated to all function calls in order to obtain something like this:
> foo();
function foo has been called
hi

A:
I am wondering if it is possible to print on screen all functions that are called in a php script

You can use a tool such as xDebug to provide you with a profiler trace. Then you can use KCacheGrind to view the profiler data, which will tell you about every function call that was made during a program run, including a detailed analysis of the time taken, etc.


text:
Q: Why is JAXB generateElementProperty=false not having the desired effect? I'm running a wsimport task with the following bindings file:
<jaxb:bindings version="2.1"
               xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" xmlns:xs="http://www.w3.org/2001/XMLSchema" >
    <jaxb:bindings>
        <jaxb:globalBindings generateElementProperty="false" typesafeEnumMaxMembers="2000" />
    </jaxb:bindings>
</jaxb:bindings>

However, this is resulting in classes with JAXBElement<String> instead of String as shown in the getUserSummaryOrTypeOrLogLevel() below
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ConfigSLMAction", propOrder = {
    "userSummaryOrTypeOrLogLevel"
})
public class ConfigSLMAction
    extends ConfigConfigBase
{

    @XmlElementRefs({
        @XmlElementRef(name = "UserSummary", type = JAXBElement.class, required = false),
        @XmlElementRef(name = "LogLevel", type = JAXBElement.class, required = false),
        @XmlElementRef(name = "Type", type = JAXBElement.class, required = false)
    })
    protected List<JAXBElement<String>> userSummaryOrTypeOrLogLevel;
    @XmlAttribute(name = "name")
    protected String name;
    @XmlAttribute(name = "local")
    protected Boolean local;
    @XmlAttribute(name = "intrinsic")
    protected Boolean intrinsic;
    @XmlAttribute(name = "read-only")
    protected Boolean readOnly;
    @XmlAttribute(name = "external")
    protected Boolean external;

    /**
     * Gets the value of the userSummaryOrTypeOrLogLevel property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the userSummaryOrTypeOrLogLevel property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getUserSummaryOrTypeOrLogLevel().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link JAXBElement }{@code <}{@link String }{@code >}
     * {@link JAXBElement }{@code <}{@link String }{@code >}
     * {@link JAXBElement }{@code <}{@link String }{@code >}
     *
     *
     */
    public List<JAXBElement<String>> getUserSummaryOrTypeOrLogLevel() {
        if (userSummaryOrTypeOrLogLevel == null) {
            userSummaryOrTypeOrLogLevel = new ArrayList<JAXBElement<String>>();
        }
        return this.userSummaryOrTypeOrLogLevel;
    }
    ...
    ...
    ...
}

The entry in the xsd file that this class is being generated from is below:
<xsd:complexType name="ConfigSLMAction">
    <xsd:complexContent>
        <xsd:extension base="tns:ConfigConfigBase">
            <xsd:choice maxOccurs="unbounded">
                <xsd:element name="UserSummary" minOccurs="0" maxOccurs="1">
                    <xsd:simpleType>
                        <xsd:union memberTypes="tns:dmString tns:dmEmptyElement" />
                    </xsd:simpleType>
                </xsd:element>
                <xsd:element name="Type" minOccurs="1" maxOccurs="1">
                    <xsd:simpleType>
                        <xsd:union memberTypes="tns:dmSLMActionType tns:dmEmptyElement" />
                    </xsd:simpleType>
                </xsd:element>
                <xsd:element name="LogLevel" minOccurs="0" maxOccurs="1">
                    <xsd:simpleType>
                        <xsd:union memberTypes="tns:dmLogLevel tns:dmEmptyElement" />
                    </xsd:simpleType>
                </xsd:element>
            </xsd:choice>
            <xsd:attributeGroup ref="tns:ConfigAttributes" />
        </xsd:extension>
    </xsd:complexContent>
</xsd:complexType>

Here's the Maven plugin from my pom file
<plugin>
    <groupId>org.jvnet.jax-ws-commons</groupId>
    <artifactId>jaxws-maven-plugin</artifactId>
    <version>2.3</version>
    <executions>
        <execution>
            <id>wsimport-from-jdk</id>
            <phase>generate-sources</phase>
            <goals>
                <goal>wsimport</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <wsdlFiles>
            <wsdlFile>${basedir}/src/main/resources/wsdl/xml-mgmt.wsdl</wsdlFile>
        </wsdlFiles>
        <bindingFiles>
            <bindingFile>${basedir}/src/main/resources/wsdl/bindings.xml</bindingFile>
        </bindingFiles>
        <keep>true</keep>
        <verbose>true</verbose>
        <extension>true</extension>
        <vmArgs>
            <vmArg>-Djavax.xml.accessExternalDTD=all</vmArg>
            <vmArg>-Djavax.xml.accessExternalSchema=all</vmArg>
        </vmArgs>
    </configuration>
</plugin>

Can anyone shed some light on why this is happening?
I want String to be used instead of JAXBElement<String> and anything I've found on SO and elsewhere suggests that generateElementProperty=false work but it isn't.

A: The JAXBElement is mandatory if there is a xsd:choice where either foo or bar elements can occur and they are the same type.
A simple String isn't enough to mark which element should be marshalled.
JAXBElement is required also if there are element nillable="true" and minOccurs="0" or if there are two global elements with the same named xsd:complexType.

A: can you try another plugin to make sure error is in JAXB ? In our project we are using:
        <plugin>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-codegen-plugin</artifactId>
            <executions>
                <execution>
                    <id>generate-sources-ais</id>
                    <phase>generate-sources</phase>
                    <configuration>
                        <defaultOptions>
                            <bindingFiles>
                                <bindingFile>${basedir}/src/main/resources/wsdl/binding/bindings.xml</bindingFile>
                            </bindingFiles>
                        </defaultOptions>
                        <sourceRoot>${project.build.directory}/generated-sources/cxf</sourceRoot>
                        <wsdlRoot>${basedir}/src/main/resources/wsdl</wsdlRoot>
                        <includes>
                            <include>**/*.wsdl</include>
                        </includes>
                    </configuration>
                    <goals>
                        <goal>wsdl2java</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

and it works as you expecting
UPDATE:
you are right plugin is ok. It is because choice element. Probably duplicated with this


text:
Q: Source Resistor of JFET Source-Follower I am designing a simple Buffer to get the voltage of a high-impedanze source to an ADC (60k Impedance).
For that I choosed an JFET in the source-follower configuration.

simulate this circuit – Schematic created using CircuitLab
To bias the gate to ground and keep the input-resistance high, there will be an >1Meg Gate-Risistor.
I am a little bit confused about how to select the Source-Risistor, because the Output-Voltage (Voltage at the source) should be nearly independend of the load. So it should not matter, if I am using a 1k or 100k resistor, does it?
Some resources say, with Rs, you bias the JFET.
Could someone please clarify this to me?
A second Question:
To get better linearity, I may use a current Source at the Source (biasing the Gate to Vcc/2 with a single supply-voltage)
What is the approach to choose a current for that?
Thanks for any advice

A: Indeed, with \$R_S\$ you choose the DC operating point of the JFET. An n-type JFET will start conducting as soon as the voltage \$V_{GS}\$ between gate and source is higher than some negative pinch-off voltage \$V_P\$ that depends on the type of the transistor. From this point, the drain current will rise quadratically with \$V_{GS}\$,
\$I_D=I_{DSS} \left( 1-\frac{V_{GS}}{V_P}\right)^2 \$,
where \$I_{DSS}\$ is the drain current at \$V_{GS} =0\$. Therefore \$V_{GS}\$ is usually negative. Since the gate is at ground level (due to \$R_G\$), the source must be positive. This is done by \$R_S\$, since \$V_S = I_D\cdot R_S\$ and finally \$V_{GS} =-I_D\cdot R_S\$.
So \$I_D\$ depends on \$V_{GS} \$ and \$V_{GS}\$ depends on \$I_D\$ and on \$R_S\$. The value of \$R_S\$ for a given \$I_D\$ can be found either graphically or by solving the equation. Small changes in the transistor parameters (\$V_P\$, \$I_{DSS} \$) will not have a huge effect on \$I_D\$.
A simple recipe: Choose an \$I_D\$. For a source follower, a good starting point would be \$I_D\approx I_{DSS}/2\$. From the formula above (or from the characteristic curve of the transistor), determine \$V_{GS} \$. Finally, \$R_S=-\frac{V_{GS}}{I_D} \$ (remember that \$V_{GS} \$ will be negative).
However, with a source follower the gate is usually not set to 0 volts.  Instead, a voltage divider is used to set the gate voltage so that the source terminal is at about half the supply voltage.

A: Negative feedback is in action so it takes a little bit of thought. So, let's talk about things happening in slow motion as a way of explaining how things start and settle down.

*

*Current will pass through the JFET because the way the circuit is biased ensures that.

*As drain/source current starts to flow, the source resistor drops voltage across it and the source voltage rises above 0 volts

*As the source voltage rises, the DC voltage on the gate relative to the rising source can be regarded as becoming more negative relative to the source

*This is because the gate is biased at 0 volts and the source voltage is rising

*As the gate-source voltage becomes more negative the JFET starts to turn off and restricts the current flow into the source resistor

*The J112 typical requires -1 volt between gate and source (\$V_{GS(OFF)}\$) to cut-off the drain-source channel to 1 uA but \$V_{GS(OFF)}\$ can be as high as -5 volt.

So, after all of this, the source settles at a voltage that satisfies the actual JFET used. It will be typically 1 volt higher than 0 volts but can be 2 or more volts if the source resistor is much bigger. Generally we can use formulas to calculate this but, like any type of FET, there is a lot more variation on how much the gate-source voltage needs to be for a particular FET compared to the more reliably predictable BJT. This renders the formulas a bit useless if you want precise predictions.
The current that will be flowing in the J112 will be around 3 mA (based on what the data sheet says) so, if you take a stab at 1 volts at the source, the resistor will be circa 330 ohm.


text:
Q: Integrating SentryLogin & CometChat in Squarespace
1) I am not a programmer; I dabble here and there.
2) I am using Squarespace to build a business website www.prisma-pi.com
3) I want for specific clients to have access to their private page using a subscriber login (fully accomplished w/ SENTRYLOGIN.com)
4) I also want that private page to provide a chat service (partially accomplished w/ CLOUD.COMETCHAT.com)

WHAT I AM MISSING IS: I want SENTRYLOGIN to "talk to" COMETCHAT.
so that user info from SENTRYLOGIN (such as user name)  loads on COMETCHAT.

COMETCHAT provides code that I have "injected" into Squarespace and it is somewhat obvious that the variables need to be updated with input from SENTRYLOGIN. (Which is my gap in knowledge in this problem).

    var chat_name = 'LOGGEDIN_USERNAME' ;
    var chat_id = 'LOGGEDIN_USERNAME_ID';
    var chat_avatar = 'LOGGEDIN_PROFILE_IMAGE';
    var chat_link = 'LOGGEDIN_USERS_PROFILE_LINK' ;
    </script>
    <link type="text/css" href="//fast.cometondemand.net/11205x002c3.css" rel="stylesheet" charset="utf-8">
    <script type="text/javascript"
    src="//fast.cometondemand.net/11205x002c3.js" charset="utf-8"></script>

This is some info available on CometChat's website, they say something along the lines: "Cookie is all you need"
https://support.cometchat.com/documentation/php/installing-cometchat/custom-coded-site/java-or-jsp-site/
SENTRYLOGIN provides access to some JS code that looks promising in accomplishing that task, but I don't know how to complete it.
You can view the source code for Sentrylogin in the sign in page www.prisma-pi.com/sign-in/
Some relevant JS code is found here: http://www.sentrylogin.com/sentry/scripts/SENTRY_AJAX_Style2014.js
Any help would be very much appreciated. If you need more info, let me know.

A: I haven't tested the code, but it looks like SentryLogin stores the login information in cookies. If you have called the SentryLogin code before the CometChat code, then something like this should work:
if (getCookie('Sentry_loginTkn') != '') { // Check if user is logged in

   var chat_name = getCookie('Sentry_firstName')+' '+getCookie('Sentry_lastName');
    var chat_id = getCookie('Sentry_member_ID');
    var chat_avatar = '';
    var chat_link = '' ;
}


text:
Q: Why is axiomatic system needed in propositional logic? I am trying to learn  propositional logic. I have read that axiomatic system is defined since there are some problems which can not be solved using truth tables. I have found such a problem in predicate logic when we use quantifiers. There we should use axioms to derive a formula which contains quantifier, since we can't construct truth table of that formula. But I am interested why we need axiomatic system in propositional logic? We can check if a formula is tautology using its truth table.

A: As you said we can check if a formula is a tautology just looking at it's truth table, anyway studying logical system (i.e. a system with has axioms and inference rules) also for propositional logic can be interesting for different reason:

*

*first of all there's the didactic reason: it's a simple deductive system, indeed it can be seen as just a fragment of the system for first order logic, so it helps to familiarize with deductive systems;

*a second reason it's complexity: sometimes proving the logic validity of a formula through such deductive system can be easier then proving it via truth tables, which involve calculate the truth values of a formula for all possible valuation of the variables which can become easy a troublesome for formula with huge number of variables, while in many cases writing a proof can be much easier involving just few application of inference rules.
Probably there other reasons too that I'm not remembering right now, but I reserve to myself the right to add them later. :)

A: (a) Giorgio Mossa is right. Two reasons for considering deductive systems for standard truth-functional propositional logic are

*

*they can be used as toy examples, as warm-up exercises to the more serious business of considering proof-systems for quantificational,
  modal, and other logics,

*they can (in some cases) deliver proofs-of-classical-validity more efficiently than hacking through a truth-table.

(b) But of course, it all depends which deductive system you look at. The OP mentions axiomatic systems. Well, here's one perfectly good axiomatic system for propositional logic (not just a trick but actually used in some books for the propositional fragment of quantification theory):

For any truth-functional tautology $\varphi$, $\varphi$ is an axiom.

And for pure propositional logic you don't need any additional rule of inference, so all proofs in the axiomatic system are one line! That's just fine, since it is recursively decidable what's an axiom, which makes it a kosher axiomatic logic -- and one which is trivially sound and complete for theorems of classical propositional logic!
(c) But let's set aside such trivialising examples, though they remind us that different deductive systems will have different virtues! And indeed now set aside axiomatic systems in the sense of Frege-Hilbert systems more generally (they usually don't have virtue (2) anyway). Let's concentrate on Natural Deduction proof-systems of one style or another. Now there is an additional reason for being interested in these:

3 Arguably, the ND introduction and elimination rules for connectives fix their sense.

Arguably, what we grasp in pre-formally understanding logical operators is their inferential role, is how we can use them in argument (in a Wittgensteinian slogan, to ask for the meaning [of logical operators] is use for their [inferential] use). Then, in the propositional logic case, a Natural Deduction system can be thought of aiming to directly encapsulate the meaning of the connectives by laying down the inferential rules governing their use, which determine their meaning.
On this sort of view, which we owe to Gentzen, there's a kind of priority to the deduction rules in an ND system -- and it will be a non-trivial discovery that the resulting system is sound and complete with respect to a Boolean truth-functional interpretation.
(d) Or that will be a discovery if, indeed, we accept the "classical" ND rules. But of course there are issues about that. From Gentzen's perspective, there is arguably something anomalous about the classical negation rules (so-called failures in "harmony"). And we can worry too about the classical structural rules that allow unrestricted chaining of proofs in a way that gives us fallacies(?) of irrelevance. But the details don't matter for now, just the following general point:

4 In considering ND systems for classical propositional logic, we can also -- in a smooth and natural way -- investigate neighbouring non-classical logics that arguably avoid some shortcomings of the classical paradigm.

A: Another important use of deductive systems is in proving compactness results. As soon as you have a complete sound deductive system in which proofs are finite, you have a compactness theorem: if a formula $\phi$ follows from some infinite set of premises, then in fact it follows from some finite subset.
Compactness of propositional logic is a much weaker tool than compactness of predicate logic, but it serves as a toy example, and isn't entirely useless in its one right: it is still strong enough, for example, to express many of the compactness arguments used in combinatorics, in which one deduces an infinitary result from its finitary equivalents. For instance, the four-colour theorem for infinite planar graphs can be proved from the finite case in this way.
Of course, with this perspective, you don't really care what proof system you're using, as long as it's complete. This is one reason why unwieldy Hilbert-style systems are used: it's a frustrating amount of work to actually prove any worthwhile result within them, but it's comparatively easy to prove metalogical results like completeness.

A: Truth tables are local to the logical semantics used.  For example, if you use a truth table for a two-valued logical semantics, it shows that the well-formed formula is always true with that two-valued semantics.
On the other hand, axiomatic systems are not local to the logical semantics used.  If you prove something, you've shown that it doesn't hold only for those semantics, but any semantics where the axioms get satisfied.  You've shown that the formula holds for several models.  This is comparable to how if you use the axioms of Boolean algebra to prove an equation, you've shown more than if you had just used the 0-1 Boolean algebra, and didn't have the result that the 0-1 Boolean algebra can get used to show equations true for larger algebras.
So, if the motivation for a logic in part consists to address more than one possible semantics, an axiomatic system can be preferable.
Additionally, if you study non-classical logic and have seen some formal proofs (or can tell a formal proof would be simple enough to produce) in classical logic, you can reuse those proofs for the non-classical logic where all of the axioms and rules of inference in the classical logic proof also hold in the nonclassical logic.  Thus, if the motivation for studying classical logic in part lies in being in a better position to study nonclassical logic, axiomatic systems can be preferable to truth tables.
For example, if you have take a usual proof of CCpCqrCCpqCpr in classical logic, you might find that it only uses the axioms CpCqp and CCpCqrCCpqCpr.  But, that proof implies that CCpCqrCCpqCpr is also a theorem in intuitionist logic, minimal logic, and the pure implicaional calculus.


text:
Q: what is advantage of binderised hidl comparing to passthrough? In android, what's advantage of binderised hidl comparing to passthrough hidl?
As i know, there are two hidl way (binderised way(client/server in seperated process) , passthrough way (client /server in same process).
What is advantage of binderised way comparing to passthrough way?
I think binderised way has more overhead than passthrough because binderised way need to use binder communication(RPC).
Why does vendor use binderised way?

A: binderized means that your service is provided via /dev/hwbinder and hosted in a separate process. This allows it to have exclusive access to a hardware resource and still offer the service to multiple clients at once.
passthrough means that your service is provided via a C++ interface in a shared library. This usually implies that only one client can link to it or the service must be implemented in a way that it does not need exclusive access to hardware. The upside is that you save the communication overhead of using Binder.
You would typically use binderized HALs as the the Binder RPC overhead is really small (smaller than with framework Binder and AIDL).
There is a list of HALs that need to be implemented in passthrough mode (for performance reasons), and a list of HALs that need to be implemented in binderized mode.

A: There's actually more to it than the above answer, which is somewhat inaccurate. "Binderized" indeed means that the service is hosted by a server, accessible over hwbinder, but it has little to do with exclusivity (which passthrough hals do NOT imply, and in fact multiple clients can link with them - the exclusivity is solely at the discretion of the kernel driver).
As part of Project Treble (Android 8.0 refactoring and moving into /vendor, /product, /odm), Google brought in the notion of a Binderized HAL to make sure no vendor HAL code intermixes with AOSP code. Numerous times before this, vulnerable vendor code executed in the context of system_server, and he owns system_server owns Android (i.e. complete and utter system compromise).
Using binderized HALs incurs the same nasty overhead (actually about the same as framework binder and AIDL), but allows complete separation of vendor code. Vendor code can no longer access AOSP services - that is, vendor daemons can open /dev/vndbinder , but not /dev/binder - which means that even if they are compromised there is more chance of containment, preventing malicious code from attacking AOSP services.
Passthrough HALs are definitely better and far more performant - but explicitly deprecated by Google (with the exception of android.hardware.graphics.mapper and maybe one or two more which elude me at the moment). They were allowed in 8.0 as part of the transition period , so as not to "shock" vendors too much. At this point (11.0, 12b3), they are not allowed on Android (per CTS, though vendors can still flout this)


text:
Q: could one emulator send a SMS to itself I've been trying to send message on Android 4.0 emulator via Broadcasting and fetch that message via Broadcast receiver. I'm able to do so with two emulators, say, from 5554 to 5556. However, I can't get the sent message from 5554 to itself. Here's the way I send a message:
  SmsManager sms = SmsManager.getDefault();
  sms.sendTextMessage(number, null, message, sentPI, deliveredPI);

the number here is emulator's port number

A: You can easily demonstrate that using tellnet command :
in windows os if tellnet is off then you can turn on using following steps
Start
Control Panel
Programs And Features
Turn Windows features on or off
Check Telnet Client
Hit OK
then write the command like
telnet localhost 5554
here 5554 is my emulator port number
once the connection has established
write the following command filling appropriated value
sms send 5554  hi
you will see the message has arrived in your emulator .

A: Yes,emulator can send messages to itself.
you can try it on your emulator.
Select messaging Application in your emulator and type your Avd no. of the emulator and send the message.
EDIT :
Reading this answer I have just tried it and Yes It's Taking the message.
I have opened my FirstAVD : 5554 and SecondAVD : 5556
then I go to Messaging :
created message to : 5554(itself) and 5556(to another) and It's showing the message to 5554 in Inbox and In avd 5556 message from FirstAVD in it's inbox.
So,Emulator sends message to itself.
But while sending from one to another it will show notification and sending to itself will not show notification.


text:
Q: selected text background color when i use any site i see that selected text background color show blue or according our OS theme.can i change this selected text background color?

A: You can use this style. this will work on all major browser except IE
<style>
             ::-moz-selection
            {
             background:#0C0;
             color:#f00;
             }
            ::selection
            {
            background:#6374AB;
            color:#F00;
           }
    </style>

A: In Firefox, you can apply CSS styles to ::-moz-selection.
In Safari, you can apply CSS styles to ::selection.
See here.