问:
What is causing jQuery UI to slide instead of fade?
I'm using jQueryUI and a Polymer popup dialog, and I'm hiding a div and then loading data of a profile photo from ajax and popuplating the div with an image element and having it fade in. As far as I know, it's doing this the same exact way in another section that fades in fine instead of sliding. I removed a lot of code here as I found it has no influence to the problem. </p>

```<code>function supervisorAccountPopup(e) {

    var button = e.target;

    while (!button.hasAttribute('data-dialog') && button !== document.body) {
        button = button.parentElement;
    }

    if (!button.hasAttribute('data-dialog')) {

        return;

    }

    var dialogID = button.getAttribute('data-dialog');
    var dialog   = document.getElementById(dialogID);

    if (dialog) {

    $('#supervisorPopupProfilePic').hide();

        dialog.open();

        $.ajax({
            type: 'POST',
            url: 'getProfileImage.php',
            data:{'userID':<? echo $createdByID; ?>,
                  'size'  :'big'},
            tryCount:0,
            retryLimit:5,
            cache:false,
            success: function(data) {

                var profileData = JSON.parse(data);

                if(profileData[0].profilePhotoFullpath != ""){

                    $('#supervisorPopupProfilePic').html("<img class='profileImgPopup' id='supervisorPopupProfilePicIMG' src='uploads/profile/" + profileData[0].profilePhotoFullpath + "?" + new Date().getTime() + "'>");

                    var supervisorPopupProfilePic = document.getElementById('supervisorPopupProfilePicIMG');

                    supervisorPopupProfilePic.onload = function () {
                        $('#supervisorPopupProfilePic').show('fade');
                    };

                }else{

                    $('#supervisorPopupProfilePic').html("<img id='supervisorPopupProfilePicIMG' class='profileImgPopup' src='uploads/profile/_default/defaultProfileImage_big_noBorder.png'>");

                    var supervisorPopupProfilePic = document.getElementById('supervisorPopupProfilePicIMG');

                    supervisorPopupProfilePic.onload = function () {
                        $('#supervisorPopupProfilePic').show('fade');
                    };

                }

            },
            error : function(xhr, textStatus, errorThrown ) {

                this.tryCount++;

                if (this.tryCount <= this.retryLimit) {
                    //try again
                    $.ajax(this);
                    return;
                }

                return;

            }
        });

     }

}
</code>```

答:
You are using the fade option here: $('#supervisorPopupProfilePic').show('fade');

To slide the content in and out, you would use slideToggle() or slideDown() if you only need the single action. You wont need show();

```<code>button.click(function() {
  $('#supervisorPopupProfilePic').slideToggle( "slow", function() {

  });
});
</code>```

or

```<code>button.click(function() {
  $('#supervisorPopupProfilePic').slideDown( "slow", function() {

  });
});
</code>```

Body:
I'm using jQueryUI and a Polymer popup dialog, and I'm hiding a div and then loading data of a profile photo from ajax and popuplating the div with an image element and having it fade in. As far as I know, it's doing this the same exact way in another section that fades in fine instead of sliding. I removed a lot of code here as I found it has no influence to the problem.

function supervisorAccountPopup(e) {

    var button = e.target;

    while (!button.hasAttribute('data-dialog') && button !== document.body) {
        button = button.parentElement;
    }

    if (!button.hasAttribute('data-dialog')) {

        return;

    }

    var dialogID = button.getAttribute('data-dialog');
    var dialog   = document.getElementById(dialogID);

    if (dialog) {

    $('#supervisorPopupProfilePic').hide();

        dialog.open();

        $.ajax({
            type: 'POST',
            url: 'getProfileImage.php',
            data:{'userID':<? echo $createdByID; ?>,
                  'size'  :'big'},
            tryCount:0,
            retryLimit:5,
            cache:false,
            success: function(data) {

                var profileData = JSON.parse(data);

                if(profileData[0].profilePhotoFullpath != ""){

                    $('#supervisorPopupProfilePic').html("");

                    var supervisorPopupProfilePic = document.getElementById('supervisorPopupProfilePicIMG');

                    supervisorPopupProfilePic.onload = function () {
                        $('#supervisorPopupProfilePic').show('fade');
                    };

                }else{

                    $('#supervisorPopupProfilePic').html("");

                    var supervisorPopupProfilePic = document.getElementById('supervisorPopupProfilePicIMG');

                    supervisorPopupProfilePic.onload = function () {
                        $('#supervisorPopupProfilePic').show('fade');
                    };

                }

            },
            error : function(xhr, textStatus, errorThrown ) {

                this.tryCount++;

                if (this.tryCount <= this.retryLimit) {
                    //try again
                    $.ajax(this);
                    return;
                }

                return;

            }
        });

     }

}

Body:
You are using the fade option here: $('#supervisorPopupProfilePic').show('fade');

To slide the content in and out, you would use slideToggle() or slideDown() if you only need the single action. You wont need show();

button.click(function() {
  $('#supervisorPopupProfilePic').slideToggle( "slow", function() {

  });
});

or

button.click(function() {
  $('#supervisorPopupProfilePic').slideDown( "slow", function() {

  });
});


来源: stackexchange

问:
Possibility to use 'wchar_t' string pointers in LabVIEW DLLs?
I'm planning a Windows-only measurement system that will be written in C++. This system should offer a DLL based plugin system, so colleagues can create some kind of device drivers for external hardware by programming specific DLL's themselves.

There are many clever guys here having experience in NI LabVIEW and it is very likely that some of them will create those DLLs with that dev system.
From my own (not very up-to-date) experiences with LV I can remember that there was no possibility to create or consume DLLs which make use of wchar_t encoded string pointer parameters back then.

As my measurement system's API will only expose string parameters as wchar_t, would this be a problem for the LabVIEW guys or do I have to provide extra functions with string params to be called by LV DLLs (which I try to avoid)?

答:
LabVIEW does not have good build in support for Unicode (or wchar_t) and using them in the program might be a big hassle. I think you have several options:

Rethink the use of wchar_t, for me it is surprising that for a measurement device you would necessarily need to use wchar_t. Of course that is completely depended on you system.

Write a wrapper dll for you dll for communication with LabVIEW or any language not supporting wchar_t.

Write a conversion function in Labview that retrieves the bare wchar_t array as integer array and convert them to ASCII code. Use this function after calls to your dll to go to ASCII code.

It is good that you think ahead and already try to create DLLs that LabVIEW can communicate with. I think you just need to take it a step further and go talk to the Labview Guys at you company to see what solution they prefer, that makes later integration so much easier.

ContentLicense: CC BY-SA 3.0


问:
Linking object files from different C compilers
Say I have two compilers, or even a single compiler with two different option sets. Each compiler compiles some C code into an object and I try to link the two .o files with a common linker. Will this succeed?

My initial thought is: not always. If the compilers are using the same object file format and have compatible options, then it would succeed. But, if the compilers have conflicting options, or (and this is an easy one) are using two different object file formats, it would not work correctly.

Does anyone have more insight on this? What standards would the object files need to comply with to gain confidence that this will work?

答:
Most flavors of *nix OSes have well defined and open ABI and mostly use ELF object file format, so it is not a problem at all for *nix.

Windows is less strictly defined and different compilers may vary in some calling conventions (for example __fastcall may not be supported by some compilers or may have different behavior, see https://en.wikipedia.org/wiki/X86_calling_conventions). But main set of calling conventions (__stdcall, _cdecl, etc) is standard enough to ensure successfull call of function compiled by one compiler from another compiler, otherwise the program won't work at all, since unlike Linux every system call in Windows is wrapped by function from DLL which you need to successfully call.

The other problem is that there is no standard common format for object files. Although most tools (MS, Intel, GCC (MinGW), Clang) use COFF format, some may use OMF (Watcom) or ELF (TinyC).

Another problem is so called "name mangling". Although it was introduced to support overloading C++ functions with the same name, it was adopted by C compilers to prevent linkage of functions defined with different calling conventions. For example, function int _cdecl fun(void); will get compiled name _fun whilst int __stdcall fun(void); will get name _fun@0. More information on name mangling see here: https://en.wikipedia.org/wiki/Name_mangling.

At last, default behavior may differ for some compilers, so yes, options may prevent successful linking of object files produced by different compilers or even by the same compiler. For example, TinyC use default convention _cdecl, whilst CLang use __stdcall. TinyC with default options may not produce code that may be linked with other because it doesn't prepend name by underscore sign. To make it cross-linkable it needs -fleading-underscore option.

But keeping in mind all said above the code may successfully be intermixed. For example, I successfully linked together code produced by Visual Studio, Intel Parallel Studio, GCC (MinGW), Clang, TinyC, NASM.


问:
Bigquery API: How to provide schema to load_table_from_storage call
What is the best way to specify schema when uploading json hosted on Google Cloud Storage to Bigquery using load_table_from_storage?

The list of fields is quite bi and complex and i already have it in a format like this:
https://cloud.google.com/bigquery/docs/personsDataSchema.json

Is there any way i can provide the schema in this format in Python? And if yes what syntax should i be foollowing? I tried various options none of thos worked so far.

答:
Notice that load_table_from_storage receives in the destination input an object of the class google.cloud.bigquery.table.Table. This is where you should have your schema specified.

As an example, if "bqc" is your BigQuery Client object, then this creates a Table object:

```<code>ds = bqc.dataset('dataset_name')
table = ds.table('table_name')
</code>```

Now let's say you have this data in your json file to work with:

```<code>{"user_id": "1", "visitid": 1, "hits": [{"hitNumber": 1, "type": "PAGE"}, {"hitNumber": 2, "type": "PAGE"}]}
{"user_id": "2", "visitid": 1, "hits": [{"hitNumber": 1, "type": "EVENT"}, {"hitNumber": 2, "type": "PAGE"}]}
</code>```

Then defining its schema would be done like so:

```<code>from google.cloud.bigquery.schema import SchemaField
f1 = SchemaField('user_id', 'STRING')
f2 = SchemaField('visitid', 'INTEGER')
f3 = SchemaField('hits', 'RECORD', mode='REPEATED', fields=[SchemaField('hitNumber', 'INTEGER'), SchemaField('type', 'STRING')])

table.schema = [f1, f2, f3]
table.create()
</code>```

Body:
Notice that load_table_from_storage receives in the destination input an object of the class google.cloud.bigquery.table.Table. This is where you should have your schema specified.

As an example, if "bqc" is your BigQuery Client object, then this creates a Table object:

ds = bqc.dataset('dataset_name')
table = ds.table('table_name')

Now let's say you have this data in your json file to work with:

{"user_id": "1", "visitid": 1, "hits": [{"hitNumber": 1, "type": "PAGE"}, {"hitNumber": 2, "type": "PAGE"}]}
{"user_id": "2", "visitid": 1, "hits": [{"hitNumber": 1, "type": "EVENT"}, {"hitNumber": 2, "type": "PAGE"}]}

Then defining its schema would be done like so:

from google.cloud.bigquery.schema import SchemaField
f1 = SchemaField('user_id', 'STRING')
f2 = SchemaField('visitid', 'INTEGER')
f3 = SchemaField('hits', 'RECORD', mode='REPEATED', fields=[SchemaField('hitNumber', 'INTEGER'), SchemaField('type', 'STRING')])

table.schema = [f1, f2, f3]
table.create()


问:
Sentiment Analysis R Naive Bayes in german
I've got a problem with the naive bayes algorithm and I'm not able to find out why. I tried out an online tutorial and so in the beginning I started to create some training data. In the code below I use just very few training data, but it's the same problem.

```<code>pos_tweets =  rbind(
  c('Ich liebe das auto', 'positive'),
  c('Diese Aussicht ist großartig', 'positive'),
  c('toller morgen', 'positive'),
  c('ich freue mich so', 'positive'),
  c('du bist aber lieb, danke', 'positive')
)

neg_tweets = rbind(
  c('ich hasse autos', 'negative'),
  c('der blick ist horror', 'negative'),
  c('voll müde heute', 'negative'),
  c('schreckliche stille', 'negative'),
  c('er ist ein feind', 'negative')
)

test_tweets = rbind(
    c('Schöne Momente erlebt', 'positive'),
    c('zusammen macht es gleich doppelt spass', 'positive'),
    c('Yeah, toller Tag', 'positive'),
    c('Super schöne Umgebung', 'positive'),
    c('es zieht ein leichter wind auf, sehr angenehm', 'positive')
)

tweetsbind = rbind(pos_tweets, neg_tweets, test_tweets)

matrix1= create_matrix(tweetsbind[,1], language="german",
                      removeStopwords=FALSE, removeNumbers=TRUE,
                      stemWords=FALSE)
mat1 = as.matrix(matrix1)
</code>```

Now I train my model:

```<code>classifier1 = naiveBayes(mat1[1:10,], as.factor(tweetsbind[1:10,2]) )
</code>```

And now I want to use it:

```<code>predicted = predict(classifier1, mat1[11:15,]); predicted
</code>```

When I look into my model it look pretty good, because the negative words are marked as negative and the positive ones as positive.

But while using the model to analyse the testing data, it only outputs negative, even when the statement are obviously positive and the used word also exist in the training set.

My new code is:

```<code># search for some twitter data
happy <- searchTwitter(":)",n = 10000, lang ='de')
happy_text <- sapply(happy, function (x) x$getText())
sad <- searchTwitter(":(",n = 10000, lang ='de')
sad_text <- sapply(sad, function (x) x$getText())

# create the matrix
tweets <- rbind(sad_text[1:2500,], happy_text[1:2500,]) # if I use more training data, I get a storage error
tweet <- as.matrix(tweets)
matrix= create_matrix(tweet[,2], language= "german", removeStopwords=FALSE, removeNumbers=TRUE,  stemWords=FALSE)
matrixdoc = as.matrix(matrix)

# transform to factor and train the model
X <- as.data.frame(matrixdoc[1:5000,])
X$out <- as.factor(tweet[1:5000,3])
X <- as.data.frame(lapply(X, factor))
classifierstack <- naiveBayes(out ~ ., data=X)

# predict
predicted = predict(classifierstack, mat1[11:15,],type = "raw" )
</code>```

And this is the result: everything ist negativ, even if all my inputs are very positiv (I changed them).

```<code>     negativ       positiv
[1,]       1 5.828223e-176
[2,]       1 4.110223e-244
[3,]       1 3.274458e-244
[4,]       1 3.534996e-176
[5,]       1  0.000000e+00
</code>```

And if I try this:

```<code>> predict(classifierstack, "zeigt", type = "raw" )
     negativ positiv
[1,]     0.5     0.5
</code>```

-> it always outputs 0.5 0.5 and is finally always negativ :/

答:
You are lacking training data. If I run your code I get

```<code>> predicted = predict(classifier1, mat1[11:15,]); predicted
[1] negative negative negative positive negative
Levels: negative positive
</code>```

So only the first two elements are wrong - the last three should indeed be negative, postive and negative. If we look at the classifier information for the words found in, say, feinde sind doof we find

```<code>                             feinde
as.factor(tweetsbind[1:10, 2]) [,1] [,2]
                      negative    0    0
                      positive    0    0

                              sind
as.factor(tweetsbind[1:10, 2]) [,1] [,2]
                      negative    0    0
                      positive    0    0

                              doof
as.factor(tweetsbind[1:10, 2]) [,1] [,2]
                      negative    0    0
                      positive    0    0
</code>```

so there really is no information to classify and it defaults to the first level category, negative. Try to feed it more information where there is an overlap between the words you want to predict and it should work.

Update If you run

```<code>> predicted = predict(classifier1, mat1[11:15,], type="raw"); predicted
         negative     positive
[1,] 9.999959e-01 4.093637e-06
[2,] 7.329224e-01 2.670776e-01
[3,] 1.000000e+00 4.598781e-11
[4,] 9.898881e-05 9.999010e-01
[5,] 1.000000e+00 1.608783e-16
</code>```

then you can see the individual probabilities. The "problem" with your fit is that the input is read as being numeric (and not as binary factors) so you will not see conditional probabilities that (row-wise) add up to one. As per the man page for naiveBayes you get Gaussian means and sds. You can get the conditional probabilities like this:

```<code>X <- as.data.frame(mat1[1:10,])
X$out <- as.factor(tweetsbind[1:10,2])
X <- as.data.frame(lapply(X, factor))
naiveBayes(out ~ ., data=X)
</code>```

This will give you

```<code>          hab
Y          0
  negative 1
  positive 1
          dich
Y          0
  negative 1
  positive 1
          lieb
Y            0   1
  negative 1.0 0.0
  positive 0.8 0.2
</code>```

Those are the P(lieb|positive) probabilities and you need to you Bayes formula to invert the probabilities.

Google "zero problem" and "naive bayes" to get directions for making slight improvements when the words aren't present in both training and test parts (see the laplace argument).

Body:
I've got a problem with the naive bayes algorithm and I'm not able to find out why. I tried out an online tutorial and so in the beginning I started to create some training data. In the code below I use just very few training data, but it's the same problem.

pos_tweets =  rbind(
  c('Ich liebe das auto', 'positive'),
  c('Diese Aussicht ist großartig', 'positive'),
  c('toller morgen', 'positive'),
  c('ich freue mich so', 'positive'),
  c('du bist aber lieb, danke', 'positive')
)

neg_tweets = rbind(
  c('ich hasse autos', 'negative'),
  c('der blick ist horror', 'negative'),
  c('voll müde heute', 'negative'),
  c('schreckliche stille', 'negative'),
  c('er ist ein feind', 'negative')
)

test_tweets = rbind(
    c('Schöne Momente erlebt', 'positive'),
    c('zusammen macht es gleich doppelt spass', 'positive'),
    c('Yeah, toller Tag', 'positive'),
    c('Super schöne Umgebung', 'positive'),
    c('es zieht ein leichter wind auf, sehr angenehm', 'positive')
)

tweetsbind = rbind(pos_tweets, neg_tweets, test_tweets)

matrix1= create_matrix(tweetsbind[,1], language="german",
                      removeStopwords=FALSE, removeNumbers=TRUE,
                      stemWords=FALSE)
mat1 = as.matrix(matrix1)

Now I train my model:

classifier1 = naiveBayes(mat1[1:10,], as.factor(tweetsbind[1:10,2]) )

And now I want to use it:

predicted = predict(classifier1, mat1[11:15,]); predicted

When I look into my model it look pretty good, because the negative words are marked as negative and the positive ones as positive.

But while using the model to analyse the testing data, it only outputs negative, even when the statement are obviously positive and the used word also exist in the training set.

My new code is:

# search for some twitter data
happy <- searchTwitter(":)",n = 10000, lang ='de')
happy_text <- sapply(happy, function (x) x$getText())
sad <- searchTwitter(":(",n = 10000, lang ='de')
sad_text <- sapply(sad, function (x) x$getText())

# create the matrix
tweets <- rbind(sad_text[1:2500,], happy_text[1:2500,]) # if I use more training data, I get a storage error
tweet <- as.matrix(tweets)
matrix= create_matrix(tweet[,2], language= "german", removeStopwords=FALSE, removeNumbers=TRUE,  stemWords=FALSE)
matrixdoc = as.matrix(matrix)

# transform to factor and train the model
X <- as.data.frame(matrixdoc[1:5000,])
X$out <- as.factor(tweet[1:5000,3])
X <- as.data.frame(lapply(X, factor))
classifierstack <- naiveBayes(out ~ ., data=X)

# predict
predicted = predict(classifierstack, mat1[11:15,],type = "raw" )

And this is the result: everything ist negativ, even if all my inputs are very positiv (I changed them).

     negativ       positiv
[1,]       1 5.828223e-176
[2,]       1 4.110223e-244
[3,]       1 3.274458e-244
[4,]       1 3.534996e-176
[5,]       1  0.000000e+00

And if I try this:

> predict(classifierstack, "zeigt", type = "raw" )
     negativ positiv
[1,]     0.5     0.5

-> it always outputs 0.5 0.5 and is finally always negativ :/

Body:
You are lacking training data. If I run your code I get

> predicted = predict(classifier1, mat1[11:15,]); predicted
[1] negative negative negative positive negative
Levels: negative positive

So only the first two elements are wrong - the last three should indeed be negative, postive and negative. If we look at the classifier information for the words found in, say, feinde sind doof we find

                             feinde
as.factor(tweetsbind[1:10, 2]) [,1] [,2]
                      negative    0    0
                      positive    0    0

                              sind
as.factor(tweetsbind[1:10, 2]) [,1] [,2]
                      negative    0    0
                      positive    0    0

                              doof
as.factor(tweetsbind[1:10, 2]) [,1] [,2]
                      negative    0    0
                      positive    0    0

so there really is no information to classify and it defaults to the first level category, negative. Try to feed it more information where there is an overlap between the words you want to predict and it should work.

Update If you run

> predicted = predict(classifier1, mat1[11:15,], type="raw"); predicted
         negative     positive
[1,] 9.999959e-01 4.093637e-06
[2,] 7.329224e-01 2.670776e-01
[3,] 1.000000e+00 4.598781e-11
[4,] 9.898881e-05 9.999010e-01
[5,] 1.000000e+00 1.608783e-16

then you can see the individual probabilities. The "problem" with your fit is that the input is read as being numeric (and not as binary factors) so you will not see conditional probabilities that (row-wise) add up to one. As per the man page for naiveBayes you get Gaussian means and sds. You can get the conditional probabilities like this:

X <- as.data.frame(mat1[1:10,])
X$out <- as.factor(tweetsbind[1:10,2])
X <- as.data.frame(lapply(X, factor))
naiveBayes(out ~ ., data=X)

This will give you

          hab
Y          0
  negative 1
  positive 1
          dich
Y          0
  negative 1
  positive 1
          lieb
Y            0   1
  negative 1.0 0.0
  positive 0.8 0.2

Those are the P(lieb|positive) probabilities and you need to you Bayes formula to invert the probabilities.

Google "zero problem" and "naive bayes" to get directions for making slight improvements when the words aren't present in both training and test parts (see the laplace argument).


问:
create Advanced and Custom Dynamics CRM online report
I know how to create the report using ADVANCED FIND but I want to create a Custom Report in CRM online using fetchxml. </p>

答:
Here you go: This post will teach you many things like Getting FetchXML from Advanced Find query & customize it, build a report from scratch, design it, etc.

Try to learn Some SQL stuffs & CRM videos which will help you.

For SQL to fetchxml query converter use: http://www.sql2fetchxml.com/

ContentLicense: CC BY-SA 4.0


问:
How to make div come under another div
How can I make DIV "sideBottom" go under "SideTop" and "console " go under "Main"?

This is how it looks at the moment:

HTML/CSS:

*{
    padding : 0;
    margin : 0;
    border : 0;
}
body{
    background-image : url(' bi-background-cubes.png ');
    background-attachment : fixed;
    background-size : 100% auto;
}
.blended_grid{
    display : block;
    width : 1370px;
    overflow : auto;
    margin : 50px auto 0 auto;
}
.pageHeader{
    background-color : rgba(6,67,0,0.4);
    float : left;
    clear : none;
    height : 70px;
    width : 1370px;
}
.sideTop{
    background-color : rgba(0,2,227,0.4);
    float : left;
    clear : none;
    height : 430px;
    width : 260px;
}
.main{
    background-color : rgba(171,0,161,0.4);
    float : left;
    clear : none;
    height : 600px;
    width : 680px;
}
.tableInput{
    background-color : rgba(156,141,0,0.4);
    float : left;
    clear : none;
    height : 350px;
    width : 400px;
}
.tableOutput{
    clear : none;
    float : left;
    position : relative;
    width : 400px;
    height : 350px;
    background-color : rgba(0,115,97,0.4);
}
.sideBottom{
    clear : none;
    float : left;
    position : relative;
    width : 260px;
    height : 270px;
    background-color : rgba(255,0,10,0.4);
}
.console{
    background-color : lightgreen;
    float : left;
    clear : none;
    height : 100px;
    width : 680px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="blended_grid">
  <div class="pageHeader">`
    <h1> pageHeader</h1>
  </div>
  <div class="sideTop">
    <h1> SideTop </h1>
  </div>

  <div class="main">
    <h1> Main </h1>
  </div>
  <div class="tableInput">
    <h1>tableInput</h1>
  </div>

  <div class="tableOutput">
    <h1> tableOutput</h1>
  </div>
  <div class="sideBottom">
    <h1> SideBottom</h1>
  </div>
  <div class="console">
    <h1>  Console</h1>
  </div>
</div></code>```

答:
try using z-index.
it determines what div / object is rendered first.
:)</p>

Title: How to make div come under another div

Body:
How can I make DIV "sideBottom" go under "SideTop" and "console " go under "Main"?

This is how it looks at the moment:

HTML/CSS:

*{
    padding : 0;
    margin : 0;
    border : 0;
}
body{
    background-image : url(' bi-background-cubes.png ');
    background-attachment : fixed;
    background-size : 100% auto;
}
.blended_grid{
    display : block;
    width : 1370px;
    overflow : auto;
    margin : 50px auto 0 auto;
}
.pageHeader{
    background-color : rgba(6,67,0,0.4);
    float : left;
    clear : none;
    height : 70px;
    width : 1370px;
}
.sideTop{
    background-color : rgba(0,2,227,0.4);
    float : left;
    clear : none;
    height : 430px;
    width : 260px;
}
.main{
    background-color : rgba(171,0,161,0.4);
    float : left;
    clear : none;
    height : 600px;
    width : 680px;
}
.tableInput{
    background-color : rgba(156,141,0,0.4);
    float : left;
    clear : none;
    height : 350px;
    width : 400px;
}
.tableOutput{
    clear : none;
    float : left;
    position : relative;
    width : 400px;
    height : 350px;
    background-color : rgba(0,115,97,0.4);
}
.sideBottom{
    clear : none;
    float : left;
    position : relative;
    width : 260px;
    height : 270px;
    background-color : rgba(255,0,10,0.4);
}
.console{
    background-color : lightgreen;
    float : left;
    clear : none;
    height : 100px;
    width : 680px;
}

`

 pageHeader

 SideTop

 Main

tableInput

 tableOutput

 SideBottom

  Console


问:
HTML and enable div's horizontal scrolling but hide the horizontal scrollbar
I need my div to be scrollable. Now it works fine, but I would like to hide the horizontal scrollbar. I do not want to disable it, just hide it.

All I want to see is one vertical scrollbar on the browser window. No horizontal scrollbars on the screen.

No JavaScript/jQuery allowed. I need a cross-browser solution.

#kaaviopohja {
  width: 100%;
  overflow: hidden;
  background-color: yellow;
}

#kaaviotaulukko {
  width: 100%;
  overflow-x: scroll;
  padding-bottom: 17px;
  background-color: pink;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh<br />
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh<br />
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh<br />
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh<br />
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh<br />

<DIV id="kaaviopohja">

  <div id="kaaviotaulukko" style="white-space: nowrap; position: relative; text-align: center;">
    <div style="display:inline-block">
      <!--
        -->
      <DIV STYLE="DISPLAY:INLINE-BLOCK">
        <div style="float:left;width:0">
          <div id="navi7">
            <div style="z-index:100;position:fixed;left:0;top:0;bottom:0;max-height:1em;margin:auto;">A</div>
            <div style="z-index:100;position:fixed;right:0;top:0;bottom:0;max-height:1em;margin:auto;">B</div>
          </div>
        </div>
        <div class="krs" style="display: inline-block; vertical-align: top; width: 300px;">
          <div>
            <h3>LQsssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss</h3>
          </div>
          1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />
        </div>
      </DIV>
      <!--
        -->
      <div style="float: right; width: 0;">
        <div id="navi100">
          <div style="z-index: 100; position: fixed; left: 0; top: 500px">C</div>
        </div>
      </div>
      <!--

      -->
      <div style="z-index:99;width:70px;position:fixed;left:0;top:0;bottom:0;margin:auto;background-color:red;"><br />
      </div>

      <div style="z-index:99;width:70px;position:fixed;right:0;top:0;bottom:0;margin:auto;background-color:red;"><br />
      </div>
    </div>
  </div>

</DIV></code>```

答:
I just modified my CSS code. This seems to help:</p>

```<code>#kaaviotaulukko {
  width: 100%;
  overflow-x: scroll;
  padding-bottom: 17px;
  background-color: pink;

  margin-top: -17px; /* this was added */
  top: 17px; /* this was added */
}
</code>```

Body:
I need my div to be scrollable. Now it works fine, but I would like to hide the horizontal scrollbar. I do not want to disable it, just hide it.

All I want to see is one vertical scrollbar on the browser window. No horizontal scrollbars on the screen.

No JavaScript/jQuery allowed. I need a cross-browser solution.

#kaaviopohja {
  width: 100%;
  overflow: hidden;
  background-color: yellow;
}

#kaaviotaulukko {
  width: 100%;
  overflow-x: scroll;
  padding-bottom: 17px;
  background-color: pink;
}

hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh

hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh

hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh

hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh

hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh

A

B

LQsssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss

          1
2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10

C

Body:
I just modified my CSS code. This seems to help:

#kaaviotaulukko {
  width: 100%;
  overflow-x: scroll;
  padding-bottom: 17px;
  background-color: pink;

  margin-top: -17px; /* this was added */
  top: 17px; /* this was added */
}


问:
How do I compute the frequency/table of categorical variables by group with R data.table?
I have the following data.table with R

```<code>library(data.table)
dt = data.table(ID = c("person1", "person1", "person1", "person2", "person2", "person2", "person2", "person2", ...), category = c("red", "red", "blue", "red", "red", "blue", "green", "green", ...))

dt
ID         category
person1    red
person1    red
person1    blue
person2    red
person2    red
person2    blue
person2    green
person2    green
person3    blue
....
</code>```

I am looking how to create a "frequency" of the categorical variables red, blue, green for each unique ID, and then expand these columns to record the counts for each. The resulting data.table would look like this:

```<code>dt
ID        red    blue    green
person1   2      1       0
person2   2      1       2
...
</code>```

I incorrectly thought the correct way to start this with data.table would be to compute the table() by group, e.g.

```<code>dt[, counts :=table(category), by=ID]
</code>```

But this appears to count the total number of categorical values by group ID. This also doesn't solve my problem of "expanding" the data.table.

What is the correct way to do this?

答:
You can use the reshape library with one line.

```<code>library(reshape2)
dcast(data=dt,
      ID ~ category,
      fun.aggregate = length,
      value.var = "category")

       ID blue green red
1 person1    1     0   2
2 person2    1     2   2
</code>```

In addition if you just need a simple 2-way table, you can use the builtin R table function.

table(dt$ID,dt$category)

Body:
I have the following data.table with R

library(data.table)
dt = data.table(ID = c("person1", "person1", "person1", "person2", "person2", "person2", "person2", "person2", ...), category = c("red", "red", "blue", "red", "red", "blue", "green", "green", ...))

dt
ID         category
person1    red
person1    red
person1    blue
person2    red
person2    red
person2    blue
person2    green
person2    green
person3    blue
....

I am looking how to create a "frequency" of the categorical variables red, blue, green for each unique ID, and then expand these columns to record the counts for each. The resulting data.table would look like this:

dt
ID        red    blue    green
person1   2      1       0
person2   2      1       2
...

I incorrectly thought the correct way to start this with data.table would be to compute the table() by group, e.g.

dt[, counts :=table(category), by=ID]

But this appears to count the total number of categorical values by group ID. This also doesn't solve my problem of "expanding" the data.table.

What is the correct way to do this?

Body:
You can use the reshape library with one line.

library(reshape2)
dcast(data=dt,
      ID ~ category,
      fun.aggregate = length,
      value.var = "category")

       ID blue green red
1 person1    1     0   2
2 person2    1     2   2

In addition if you just need a simple 2-way table, you can use the builtin R table function.

table(dt$ID,dt$category)


问:
confused about sum_axis in mxnet in the tutorial
I am reading the mxnet tutorial on NDarray part and I am confused about the use of sum_axis function and the example is :

```<code>>>> a = mx.nd.ones((2,3))
>>> c = mx.nd.sum_axis(a, axis=1)
>>> c.asnumpy()
    array([ 3.,  3.], dtype=float32)
>>> c = mx.nd.sum_axis(a, axis=0)
>>> c.asnumpy()
    array([ 2.,  2.,  2.], dtype=float32)
</code>```

What I am wondering is when the value of paramter axis is 1, I think it should output

```<code>array([ 2.,  2.,  2.], dtype=float32)
</code>```

but not

```<code>array([ 3.,  3.], dtype=float32)
</code>```

As when the value of paramter axis is 1, I think the sum_axis should compute the sum along the column ,but the result shows it compute the sum along the rows.

And it seems that  numpy also compute like this and I really don't understand why this way.
So anyone could explain this ?

Thanks!!

答:
Numpy has described what axis is in 2D array.  A 2-dimensional array has two corresponding axes: the first running vertically downwards across rows (axis 0), and the second running horizontally across columns (axis 1).

Check the link for example
https://docs.scipy.org/doc/numpy-1.12.0/glossary.html
This is also true for MXNet. So, in your example mentioned above:
a = [[ 1.,  1.,  1.],
     [ 1.,  1.,  1.]]

axis 0 means, going vertically downwards. So, it will give you output [2., 2., 2.] and axis 1 means, going horizontally across columns. So, it will give you output [3., 3.]

Body:
I am reading the mxnet tutorial on NDarray part and I am confused about the use of sum_axis function and the example is :

>>> a = mx.nd.ones((2,3))
>>> c = mx.nd.sum_axis(a, axis=1)
>>> c.asnumpy()
    array([ 3.,  3.], dtype=float32)
>>> c = mx.nd.sum_axis(a, axis=0)
>>> c.asnumpy()
    array([ 2.,  2.,  2.], dtype=float32)

What I am wondering is when the value of paramter axis is 1, I think it should output

array([ 2.,  2.,  2.], dtype=float32)

but not

array([ 3.,  3.], dtype=float32)

As when the value of paramter axis is 1, I think the sum_axis should compute the sum along the column ,but the result shows it compute the sum along the rows.

And it seems that  numpy also compute like this and I really don't understand why this way.
So anyone could explain this ?

Thanks!!


问:
Tools used for programming in Linux
I would like to start programming using the Linux operating system and all the free stuff out there.

What is the most common and the best language to use with Linux, C or C++ or C#?

What tools are similar to Turbo C, or Visual Studio in Windows?

答: Well if you already have coded in C#.Net before then you may try C# Mono, incase you want to shorten your learning curve. But must linux users use Python, actually.</p>

ContentLicense: CC BY-SA 2.5

Title: Tools used for programming in Linux


问:
Can I access javascripts from iframe parent on another domain
I control both domains and could set whatever policies necessary. The domain in the iframe uses pretty much the same libraries and I was hoping to leech them off the parent if possible.

To be clear, I'm not asking how to make a cross-domain request. I'm asking how to get scripts from an iframe's parent, when the parent is on another domain.

I'm getting a permission error with this (trying jQuery here but same with my other libraries):

```<code>if (typeof(jQuery) == "undefined") {
  var iframebody = document.getElementsByTagName("body")[0];
  var jQuery = function (selector) { return parent.jQuery(selector, iframebody); };
  var $ = jQuery;
}
$("<h1>Hello World</h1>").appendTo("body");
</code>```

This would work if they were on the same domain.

I know this is cross-domain and is blocked for security reasons, but considering I control both domains and neither are security sensitive, I could set any policies as lax as I want to.

Can this be done?

答:
You can use postMessage to pass information back and forth between frames and their parent window.

https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

You'll have to run the code to modify the element in the domain where it lives, but you can set a post message handlerler in the parent to kick it off.

```<code>// child window (iframe content)
parent.postMessage("hi there", "https://parent.domain.here");

// parent window
window.addEventListener("message", function(message){
    $("<h1>"+message+"</h1>").appendTo("body");
});
</code>```

Body:
I control both domains and could set whatever policies necessary. The domain in the iframe uses pretty much the same libraries and I was hoping to leech them off the parent if possible.

To be clear, I'm not asking how to make a cross-domain request. I'm asking how to get scripts from an iframe's parent, when the parent is on another domain.

I'm getting a permission error with this (trying jQuery here but same with my other libraries):

if (typeof(jQuery) == "undefined") {
  var iframebody = document.getElementsByTagName("body")[0];
  var jQuery = function (selector) { return parent.jQuery(selector, iframebody); };
  var $ = jQuery;
}
$("
Hello World
").appendTo("body");

This would work if they were on the same domain.

I know this is cross-domain and is blocked for security reasons, but considering I control both domains and neither are security sensitive, I could set any policies as lax as I want to.

Can this be done?

Body:
You can use postMessage to pass information back and forth between frames and their parent window.

https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

You'll have to run the code to modify the element in the domain where it lives, but you can set a post message handlerler in the parent to kick it off.

// child window (iframe content)
parent.postMessage("hi there", "https://parent.domain.here");

// parent window
window.addEventListener("message", function(message){
    $("<h1>"+message+"</h1>").appendTo("body");
});


问:
Prolog - remove the non unique elements
I have a predicate to check if the element is member of list and looks the following:

```<code>member(X,[X|_]).
member(X,[_|T]) :- member(X,T).
</code>```

When I called: ?- member(1,[2,3,1,4])
I get: true.

And now I have to use it to write predicate which will remove all non unique elements from list of lists like the following:

```<code>remove([[a,m,t,a],[k,a,w],[i,k,b,b],[z,m,m,c]],X).
X = [[t],[w],[i,b,b],[z,c]]
</code>```

How can I do that?

答:
Using library(reif) for
SICStus|SWI:

```<code>lists_uniques(Xss, Yss) :-
   maplist(tfilter(in_unique_t(Xss)), Xss, Yss).

in_unique_t(Xss, E, T) :-
   tfilter(memberd_t(E), Xss, [_|Rs]),
   =(Rs, [], T).
</code>```

Remark that while there is no restriction how to name a predicate, a non-relational, imperative name often hides the pure relation behind. remove is a real imperative, but we only want a relation. A relation between a list of lists and a list of lists with only unique elements.

An example usage:

```<code>?- lists_uniques([[X,b],[b]], [[X],[]]).
   dif(X, b).
</code>```

So in this case we have left X an uninstantiated variable.  Therefore, Prolog computes the most general answer possible, figuring out what X has to look like.

(Note that the answer you have accepted incorrectly fails in this case)

Title: Prolog - remove the non unique elements

Body:
I have a predicate to check if the element is member of list and looks the following:

member(X,[X|_]).
member(X,[_|T]) :- member(X,T).

When I called: ?- member(1,[2,3,1,4])
I get: true.

And now I have to use it to write predicate which will remove all non unique elements from list of lists like the following:

remove([[a,m,t,a],[k,a,w],[i,k,b,b],[z,m,m,c]],X).
X = [[t],[w],[i,b,b],[z,c]]

How can I do that?

Body:
Using library(reif) for
SICStus|SWI:

lists_uniques(Xss, Yss) :-
   maplist(tfilter(in_unique_t(Xss)), Xss, Yss).

in_unique_t(Xss, E, T) :-
   tfilter(memberd_t(E), Xss, [_|Rs]),
   =(Rs, [], T).

Remark that while there is no restriction how to name a predicate, a non-relational, imperative name often hides the pure relation behind. remove is a real imperative, but we only want a relation. A relation between a list of lists and a list of lists with only unique elements.

An example usage:

?- lists_uniques([[X,b],[b]], [[X],[]]).
   dif(X, b).

So in this case we have left X an uninstantiated variable.  Therefore, Prolog computes the most general answer possible, figuring out what X has to look like.

(Note that the answer you have accepted incorrectly fails in this case)


问:
Wait for completion of a calculation without UI freeze
I am trying to implement a search function in an Android app that takes text from an AutoCompleteTextView, waits if there hasn't been made a change in the last 1.5 seconds and shows the search results. For this I use the TextWatcher class.

However, all my tries to implement this behavior ran into trouble with some functions only being allowed in the UI thread itself (via runOnUIThread) or the thread having Looper.prepare() called before.

In all attempts, the app crashes randomly when entering additional characters or deleting some, does not show any search results or reload to the start activity.

The following is a simplyfied recreation of my most recent try, where I use a Handler.

search.getResults is the long computation and matches is an array that has to be filled before delayableAdapterCreation creates the ArrayAdapterWithSpaceFilter.

```<code>public class SearchFragment extends Fragment {

    public final static int MAX_NUMBER_OF_SUGGESTIONS = 4; // only show a max of 4 suggestions if more were found
    public final static int SEARCH_CHAR_AMOUNT = 3; // only search if at least 3 characters were typed
    public final static long SEARCH_DELAY_MILLIS = (long) 1500; // the time to wait for no text changes in milliseconds
    private Search search;
    private AutoCompleteTextView textView;
    private String[] matches;
    private String userStartRequest;
    private Entry[] suggestions;
    private FragmentListenter sListener;
    private EntryFunctions ef = new EntryFunctions();
    private Runnable delayableSearch;
    private Runnable delayableAdapterCreation;
    private Handler delayableSearchHandler;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        delayableSearchHandler = new Handler();

        delayableSearch = new Runnable() {
            @Override
            public void run() {
                userStartRequest = textView.getText().toString();
                sListener.onFragmentFinish(userStartRequest);
                suggestions = search.getResults(userStartRequest);
                matches = ef.fillMatches(suggestions);
            }
        };

        delayableAdapterCreation = new Runnable() {
            @Override
            public void run() {
                ArrayAdapterWithSpaceFilter<String> adapter =
                        new ArrayAdapterWithSpaceFilter<String>(getActivity(),
                                android.R.layout.simple_list_item_1,
                                matches);
                textView.setAdapter(adapter);
            }
        };

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_search, container, false);
    }

    @Override
    public void onStart() {
        super.onStart();
        textViewHandler();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (!(context instanceof FragmentListenter)) throw new AssertionError();
        sListener = (FragmentListenter) context;
    }

    /**
     * Interface for communicate to activity
     */
    public interface FragmentListenter {
        void onFragmentFinish(String userStartRequest);
    }

    /**
     * Handler for the AutoCompleteTextView
     */
    private void textViewHandler() {
        try {
            textView = (AutoCompleteTextView) getView().findViewById
                    (R.id.startNaviAutoCompleteTextView);
            search = new Search();
            System.out.println("Created Search object");

            textView.addTextChangedListener(new TextWatcher() {

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    System.out.println("TextWatcher beforeTextChanged");
                }

                @Override
                public void onTextChanged(CharSequence s, final int start, int before, int count) {
                    delayableSearchHandler.removeCallbacks(delayableSearch);                        userStartRequest = textView.getText().toString();
                    sListener.onFragmentFinish(userStartRequest);
                    if (textView.getText().length() >=
                            SEARCH_CHAR_AMOUNT) {
                        new Thread(delayableSearch).start();
                        delayableSearchHandler.postDelayed
                            (delayableAdapterCreation, SEARCH_DELAY_MILLIS);
                    }
                }

                @Override
                public void afterTextChanged(Editable s) {
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
</code>```

At this point, it does not matter to me, whether the calculation already starts whenever a new character is typed into the AutoCompleteTextView and an eventual old search is canceled or the search starts after the 1.5 seconds.

The above code does crash if the search term yields no results and there are problems with the results list. Sometimes it shows up for what has been entered a few keystrokes ago (so if I search for abcd slowly I get search results for abc), sometimes it doesn't show up at all. My guess would be a race condition or some problem with calling the textViewHandler or onTextChanged methods multiple times, even though delayableSearchHandler.removeCallbacks(delayableSearch) should prevent this from happening.

Can anyone explain, what the interaction between the worker thread and the UI thread would have to look like, so it is guaranteed that the search delivers it's results?

Thanks in advance,

Joe

答:
Any long running operation (Network call, database search...) can take long time to execute thus blocking the UI. Prior to Ice cream sandwich this kind of behavior was tolerated by the android runtime.

This article might be a good read

Body:
I am trying to implement a search function in an Android app that takes text from an AutoCompleteTextView, waits if there hasn't been made a change in the last 1.5 seconds and shows the search results. For this I use the TextWatcher class.

However, all my tries to implement this behavior ran into trouble with some functions only being allowed in the UI thread itself (via runOnUIThread) or the thread having Looper.prepare() called before.

In all attempts, the app crashes randomly when entering additional characters or deleting some, does not show any search results or reload to the start activity.

The following is a simplyfied recreation of my most recent try, where I use a Handler.

search.getResults is the long computation and matches is an array that has to be filled before delayableAdapterCreation creates the ArrayAdapterWithSpaceFilter.

public class SearchFragment extends Fragment {

    public final static int MAX_NUMBER_OF_SUGGESTIONS = 4; // only show a max of 4 suggestions if more were found
    public final static int SEARCH_CHAR_AMOUNT = 3; // only search if at least 3 characters were typed
    public final static long SEARCH_DELAY_MILLIS = (long) 1500; // the time to wait for no text changes in milliseconds
    private Search search;
    private AutoCompleteTextView textView;
    private String[] matches;
    private String userStartRequest;
    private Entry[] suggestions;
    private FragmentListenter sListener;
    private EntryFunctions ef = new EntryFunctions();
    private Runnable delayableSearch;
    private Runnable delayableAdapterCreation;
    private Handler delayableSearchHandler;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        delayableSearchHandler = new Handler();

        delayableSearch = new Runnable() {
            @Override
            public void run() {
                userStartRequest = textView.getText().toString();
                sListener.onFragmentFinish(userStartRequest);
                suggestions = search.getResults(userStartRequest);
                matches = ef.fillMatches(suggestions);
            }
        };

        delayableAdapterCreation = new Runnable() {
            @Override
            public void run() {
                ArrayAdapterWithSpaceFilter<String> adapter =
                        new ArrayAdapterWithSpaceFilter<String>(getActivity(),
                                android.R.layout.simple_list_item_1,
                                matches);
                textView.setAdapter(adapter);
            }
        };

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_search, container, false);
    }

    @Override
    public void onStart() {
        super.onStart();
        textViewHandler();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (!(context instanceof FragmentListenter)) throw new AssertionError();
        sListener = (FragmentListenter) context;
    }

    /**
     * Interface for communicate to activity
     */
    public interface FragmentListenter {
        void onFragmentFinish(String userStartRequest);
    }

    /**
     * Handler for the AutoCompleteTextView
     */
    private void textViewHandler() {
        try {
            textView = (AutoCompleteTextView) getView().findViewById
                    (R.id.startNaviAutoCompleteTextView);
            search = new Search();
            System.out.println("Created Search object");

            textView.addTextChangedListener(new TextWatcher() {

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    System.out.println("TextWatcher beforeTextChanged");
                }

                @Override
                public void onTextChanged(CharSequence s, final int start, int before, int count) {
                    delayableSearchHandler.removeCallbacks(delayableSearch);                        userStartRequest = textView.getText().toString();
                    sListener.onFragmentFinish(userStartRequest);
                    if (textView.getText().length() >=
                            SEARCH_CHAR_AMOUNT) {
                        new Thread(delayableSearch).start();
                        delayableSearchHandler.postDelayed
                            (delayableAdapterCreation, SEARCH_DELAY_MILLIS);
                    }
                }

                @Override
                public void afterTextChanged(Editable s) {
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

At this point, it does not matter to me, whether the calculation already starts whenever a new character is typed into the AutoCompleteTextView and an eventual old search is canceled or the search starts after the 1.5 seconds.

The above code does crash if the search term yields no results and there are problems with the results list. Sometimes it shows up for what has been entered a few keystrokes ago (so if I search for abcd slowly I get search results for abc), sometimes it doesn't show up at all. My guess would be a race condition or some problem with calling the textViewHandler or onTextChanged methods multiple times, even though delayableSearchHandler.removeCallbacks(delayableSearch) should prevent this from happening.

Can anyone explain, what the interaction between the worker thread and the UI thread would have to look like, so it is guaranteed that the search delivers it's results?

Thanks in advance,

Joe


问:
Is it better to open and close a WCF soap client for each call or make multiple calls with the same client
I have a data provider class that makes a SOAP call in the way that you would expect.  I create the client, make the call, close the client, return the data.  I have listed this as Original Code below.

I am doing some batch processing.  I will be processing 30 to 40 records at a time.  I will be calling the data provider from within a for loop from another class.

I would like to know if I should be opening and closing the SOAP client for each request as I have shown in the Original Code or if I should open the client once, only retrieve the data from within the for loop and then close the SOAP client after I exit the Loop (Modified Code).

If you can provide pros/cons on each implementation, I would appreciate it.  I am not sure if creating and closing the client on each call (as in my original code) is a costly operation or if it is insignificant.  Will I incur too much overhead if I open/close each call?  FYI, the SOAP client I am using is not aware of ChannelFactory.

Original Code

```<code>    public int RetrieveSomeInfo(string someWayToIdentify)
    {
        int result = 0;

        try
        {
            _client = new SomeSoapClient();

            var someResponse = _client.Search(someWayToIdentify);

            if (someResponse.Any())
            {
                result = someResponse.First().SomeIntData;
            }

            _client.Close();
        }
        catch (CommunicationException e)
        {
            _logger.Error(e.Message, e);
            _client.Abort();
        }
        catch (TimeoutException e)
        {
            _logger.Error(e.Message, e);
            _client.Abort();
        }
        catch (Exception e)
        {
            _logger.Error(e.Message, e);
            _client.Abort();
            throw;
        }

        return result;
    }
</code>```

Called Like this

```<code>foreach (var record in records)
{
    var someData = _sometDataProvider.RetrieveSomeInfo(someWayToIdentify);
}
</code>```

Modified Code

```<code>public int RetrieveSomeInfo(string someWayToIdentify)
{
    int result = 0;

    try
    {
        //Client created through DI
        if (_client == null || _client.State != System.ServiceModel.CommunicationState.Opened)
        {
            _client = new SomeService();
        }

        var someResponse = _client.Search(someWayToIdentify);

        if (someResponse.Any())
        {
            result = someResponse.First().SomeIntData;
        }
    }
    catch (Exception e)
    {
        _logger.Error(e.Message, e);
        throw;
    }

    return result;
}

public void Close()
{
    try
    {
        _client.Close();
    }
    catch (CommunicationException e)
    {
        _logger.Error(e.Message, e);
        _client.Abort();
    }
    catch (TimeoutException e)
    {
        _logger.Error(e.Message, e);
        _client.Abort();
    }
    catch (Exception e)
    {
        _logger.Error(e.Message, e);
        _client.Abort();
        throw;
    }
}
</code>```

Called Like this

```<code>foreach (var record in records)
{
    var someData = _sometDataProvider.RetrieveSomeInfo(someWayToIdentify);
}
_someDataProvider.Close();
</code>```

答:
Using the same exact client instance for all your batch calls will be OK here. The only time where it may cause an issue is if the WCF service itself sets up a state-full session.

You could setup a connection pool for your WCF service, in which then it would be best to close the connection (i.e. return it to the pool) after using it. In a connection pool scenario, a connection is never really closed completely. This practice is very similar to how a database connection works typically, where a bunch of connections are managed in a pool and closing a connection just marks the connection as usable by the next request to the pool.

Body:
I have a data provider class that makes a SOAP call in the way that you would expect.  I create the client, make the call, close the client, return the data.  I have listed this as Original Code below.

I am doing some batch processing.  I will be processing 30 to 40 records at a time.  I will be calling the data provider from within a for loop from another class.

I would like to know if I should be opening and closing the SOAP client for each request as I have shown in the Original Code or if I should open the client once, only retrieve the data from within the for loop and then close the SOAP client after I exit the Loop (Modified Code).

If you can provide pros/cons on each implementation, I would appreciate it.  I am not sure if creating and closing the client on each call (as in my original code) is a costly operation or if it is insignificant.  Will I incur too much overhead if I open/close each call?  FYI, the SOAP client I am using is not aware of ChannelFactory.

Original Code

    public int RetrieveSomeInfo(string someWayToIdentify)
    {
        int result = 0;

        try
        {
            _client = new SomeSoapClient();

            var someResponse = _client.Search(someWayToIdentify);

            if (someResponse.Any())
            {
                result = someResponse.First().SomeIntData;
            }

            _client.Close();
        }
        catch (CommunicationException e)
        {
            _logger.Error(e.Message, e);
            _client.Abort();
        }
        catch (TimeoutException e)
        {
            _logger.Error(e.Message, e);
            _client.Abort();
        }
        catch (Exception e)
        {
            _logger.Error(e.Message, e);
            _client.Abort();
            throw;
        }

        return result;
    }

Called Like this

foreach (var record in records)
{
    var someData = _sometDataProvider.RetrieveSomeInfo(someWayToIdentify);
}

Modified Code

public int RetrieveSomeInfo(string someWayToIdentify)
{
    int result = 0;

    try
    {
        //Client created through DI
        if (_client == null || _client.State != System.ServiceModel.CommunicationState.Opened)
        {
            _client = new SomeService();
        }

        var someResponse = _client.Search(someWayToIdentify);

        if (someResponse.Any())
        {
            result = someResponse.First().SomeIntData;
        }
    }
    catch (Exception e)
    {
        _logger.Error(e.Message, e);
        throw;
    }

    return result;
}

public void Close()
{
    try
    {
        _client.Close();
    }
    catch (CommunicationException e)
    {
        _logger.Error(e.Message, e);
        _client.Abort();
    }
    catch (TimeoutException e)
    {
        _logger.Error(e.Message, e);
        _client.Abort();
    }
    catch (Exception e)
    {
        _logger.Error(e.Message, e);
        _client.Abort();
        throw;
    }
}

Called Like this

foreach (var record in records)
{
    var someData = _sometDataProvider.RetrieveSomeInfo(someWayToIdentify);
}
_someDataProvider.Close();


问:
How to fetch different records in same row in sql?
I have a table structure similar to one given below

```<code>1001    Jon
1002    Jacob
1003    Cayle
</code>```

I want to fetch records from table in a way that it should look like

```<code>1001 – Jon,   1002 – Jacob,  1003 – Cayle
</code>```

Can anybody suggest some easy way.

答: SELECT listagg(id||' ' || '-'||' ' || name,', ') within GROUP (ORDER BY id) con FROM table;</p>

Body:
I have a table structure similar to one given below

1001    Jon
1002    Jacob
1003    Cayle

I want to fetch records from table in a way that it should look like

1001 – Jon,   1002 – Jacob,  1003 – Cayle

Can anybody suggest some easy way.


问:
Target all users in two OU's and remove Distribution Lists
hoping to get a little help here – I looked around the site but didn’t see anything quite like this (please direct me if there IS and I missed it).

I need to incorporate a new step in our user offboarding process, which would remove them from any AD Distribution Lists.  I would like to set this up as a scheduled task to run once a night against two OU’s where the inactivated user accounts can be found.

I’d like to run this by pointing it at the USERS instead of the OU where the Distro Lists live, because I suspect that we’ll ultimately get the request to remove these users from OTHER types of group as well.

This snippet will remove AD Distro Lists from a single user, but leave all other types of AD groups alone:

```<code>#  GroupCategory 0 = Distro List
#  GroupCategory 1 = Security Group

#  GroupScope 0 = DomainLocal
#  GroupScope 1 = Global
#  GroupScope 2 = Universal

$user = "userlogon"
Get-ADPrincipalGroupMembership -Identity $user|
Where {$_.GroupCategory -eq 0} |
ForEach {Remove-ADPrincipalGroupMembership -Identity $user -MemberOf $_ -Confirm:$false}
</code>```

THIS snippet will look at an OU and return some info (just my example for using a variable with -searchbase):

```<code>$OUs = 'OU=PendingDeletion,OU=Users,DC=Stuff,DC=Place,DC=net','OU=HoldForReview,OU=Users,DC=Stuff,DC=Place,DC=net'

$OU | ForEach {Get-ADGroup -Filter * -Properties ManagedBy -SearchBase $_ } |
 Select Name, ManagedBy |
 Sort -Property Name
 Out-GridView
</code>```

BUT – Does it hold together that in order to complete my objective, I would do something like this?!  I'm a bit out of my depth here, any advice for a re-write is appreciated:

```<code>$OUs = 'OU=PendingDeletion,OU=Users,DC=Stuff,DC=Place,DC=net','OU=HoldForReview,OU=Users,DC=Stuff,DC=Place,DC=net'
 $user = "*"

$OUs | ForEach {
        Get-ADPrincipalGroupMembership -Identity $user|
        Where {$_.GroupCategory -eq 0} |
        ForEach {Remove-ADPrincipalGroupMembership -Identity $user -MemberOf $_ -Confirm:$false}
              }
</code>```

There’s always a couple of ways to do stuff in PoSh, so I’m sure there’s a less-complicated way to do the same thing.  If anyone has a different approach please feel free to suggest an alternative.

Thanks for taking a look!

答:
So it sounds like you need three loops.

First, you will need to loop over the OU list to get the Users. We'll store the user objects in $Users

```<code>$OUs = 'OU=PendingDeletion,OU=Users,DC=Stuff,DC=Place,DC=net','OU=HoldForReview,OU=Users,DC=Stuff,DC=Place,DC=net'
$Users = ForEach ($OU in $OUs) {
    Get-ADUser -Filter * -SearchBase $OU
}
</code>```

Next loop over the users to get the groups that you want to remove. Then loop over the groups to remove each one.

```<code>ForEach ($User in $Users) {
    Get-ADPrincipalGroupMembership -Identity $user |
    Where-Object {$_.GroupCategory -eq 0} |
    ForEach-Object {
        Remove-ADPrincipalGroupMembership -Identity $user -MemberOf $_
    }
}
</code>```

Body:
hoping to get a little help here – I looked around the site but didn’t see anything quite like this (please direct me if there IS and I missed it).

I need to incorporate a new step in our user offboarding process, which would remove them from any AD Distribution Lists.  I would like to set this up as a scheduled task to run once a night against two OU’s where the inactivated user accounts can be found.

I’d like to run this by pointing it at the USERS instead of the OU where the Distro Lists live, because I suspect that we’ll ultimately get the request to remove these users from OTHER types of group as well.

This snippet will remove AD Distro Lists from a single user, but leave all other types of AD groups alone:

#  GroupCategory 0 = Distro List
#  GroupCategory 1 = Security Group

#  GroupScope 0 = DomainLocal
#  GroupScope 1 = Global
#  GroupScope 2 = Universal

$user = "userlogon"
Get-ADPrincipalGroupMembership -Identity $user|
Where {$_.GroupCategory -eq 0} |
ForEach {Remove-ADPrincipalGroupMembership -Identity $user -MemberOf $_ -Confirm:$false}

THIS snippet will look at an OU and return some info (just my example for using a variable with -searchbase):

$OUs = 'OU=PendingDeletion,OU=Users,DC=Stuff,DC=Place,DC=net','OU=HoldForReview,OU=Users,DC=Stuff,DC=Place,DC=net'

$OU | ForEach {Get-ADGroup -Filter * -Properties ManagedBy -SearchBase $_ } |
 Select Name, ManagedBy |
 Sort -Property Name
 Out-GridView

BUT – Does it hold together that in order to complete my objective, I would do something like this?!  I'm a bit out of my depth here, any advice for a re-write is appreciated:

$OUs = 'OU=PendingDeletion,OU=Users,DC=Stuff,DC=Place,DC=net','OU=HoldForReview,OU=Users,DC=Stuff,DC=Place,DC=net'
 $user = "*"

$OUs | ForEach {
        Get-ADPrincipalGroupMembership -Identity $user|
        Where {$_.GroupCategory -eq 0} |
        ForEach {Remove-ADPrincipalGroupMembership -Identity $user -MemberOf $_ -Confirm:$false}
              }

There’s always a couple of ways to do stuff in PoSh, so I’m sure there’s a less-complicated way to do the same thing.  If anyone has a different approach please feel free to suggest an alternative.

Thanks for taking a look!

Body:
So it sounds like you need three loops.

First, you will need to loop over the OU list to get the Users. We'll store the user objects in $Users

$OUs = 'OU=PendingDeletion,OU=Users,DC=Stuff,DC=Place,DC=net','OU=HoldForReview,OU=Users,DC=Stuff,DC=Place,DC=net'
$Users = ForEach ($OU in $OUs) {
    Get-ADUser -Filter * -SearchBase $OU
}

Next loop over the users to get the groups that you want to remove. Then loop over the groups to remove each one.

ForEach ($User in $Users) {
    Get-ADPrincipalGroupMembership -Identity $user |
    Where-Object {$_.GroupCategory -eq 0} |
    ForEach-Object {
        Remove-ADPrincipalGroupMembership -Identity $user -MemberOf $_
    }
}


问:
Convert json to csv and taking just some key value
I have a problem with conversion from json to csv file. I have this data:

```<code>x = ''' [
{u'Plot': u'Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.', u'Rated': u'R', u'Title': u'The Shawshank Redemption', u'Ratings': [{u'Source': u'Internet Movie Database', u'Value': u'9.3/10'}, {u'Source': u'Rotten Tomatoes', u'Value': u'91%'}, {u'Source': u'Metacritic', u'Value': u'80/100'}], u'DVD': u'N/A', u'Writer': u'Stephen King (short story "Rita Hayworth and Shawshank Redemption"), Frank Darabont (screenplay)', u'Production': u'Columbia Pictures', u'Actors': u'Tim Robbins, Morgan Freeman, Bob Gunton, William Sadler', u'Type': u'movie', u'imdbVotes': u'1,814,175', u'Website': u'N/A', u'Director': u'Frank Darabont', u'Released': u'14 Oct 1994', u'Awards': u'Nominated for 7 Oscars. Another 19 wins & 30 nominations.', u'Genre': u'Crime, Drama', u'imdbRating': u'9.3', u'Language': u'English', u'Country': u'USA', u'BoxOffice': u'N/A', u'Runtime': u'142 min', u'imdbID': u'tt0111161', u'Metascore': u'80', u'Response': u'True', u'Year': u'1994'}
{u'Plot': u'The aging patriarch of an organized crime dynasty transfers control of his clandestine empire to his reluctant son.', u'Rated': u'R', u'Title': u'The Godfather', u'Ratings': [{u'Source': u'Internet Movie Database', u'Value': u'9.2/10'}, {u'Source': u'Rotten Tomatoes', u'Value': u'99%'}, {u'Source': u'Metacritic', u'Value': u'100/100'}], u'DVD': u'09 Oct 2001', u'Writer': u'Mario Puzo (screenplay), Francis Ford Coppola (screenplay), Mario Puzo (novel)', u'Production': u'Paramount Pictures', u'Actors': u'Marlon Brando, Al Pacino, James Caan, Richard S. Castellano', u'Type': u'movie', u'imdbVotes': u'1,235,597', u'Website': u'http://www.thegodfather.com', u'Director': u'Francis Ford Coppola', u'Released': u'24 Mar 1972', u'Awards': u'Won 3 Oscars. Another 23 wins & 27 nominations.', u'Genre': u'Crime, Drama', u'imdbRating': u'9.2', u'Language': u'English, Italian, Latin', u'Country': u'USA', u'BoxOffice': u'N/A', u'Runtime': u'175 min', u'imdbID': u'tt0068646', u'Metascore': u'100', u'Response': u'True', u'Year': u'1972'}
]'''
</code>```

and I am trying to convert this to csv to be able to take just title and year from all details. When I am trying to do: json.loads(x), error appears: "ValueError: Expecting property name: line 2 column 2 (char 3)" and I have no idea how to fix it? Any ideas?

答:
Your data isn't in valid JSON format. It's almost valid Python, however. Here's how to leverage that fact and do what you want:

```<code>import ast
import csv

x = ''' [
{u'Plot': u'Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.', u'Rated': u'R', u'Title': u'The Shawshank Redemption', u'Ratings': [{u'Source': u'Internet Movie Database', u'Value': u'9.3/10'}, {u'Source': u'Rotten Tomatoes', u'Value': u'91%'}, {u'Source': u'Metacritic', u'Value': u'80/100'}], u'DVD': u'N/A', u'Writer': u'Stephen King (short story "Rita Hayworth and Shawshank Redemption"), Frank Darabont (screenplay)', u'Production': u'Columbia Pictures', u'Actors': u'Tim Robbins, Morgan Freeman, Bob Gunton, William Sadler', u'Type': u'movie', u'imdbVotes': u'1,814,175', u'Website': u'N/A', u'Director': u'Frank Darabont', u'Released': u'14 Oct 1994', u'Awards': u'Nominated for 7 Oscars. Another 19 wins & 30 nominations.', u'Genre': u'Crime, Drama', u'imdbRating': u'9.3', u'Language': u'English', u'Country': u'USA', u'BoxOffice': u'N/A', u'Runtime': u'142 min', u'imdbID': u'tt0111161', u'Metascore': u'80', u'Response': u'True', u'Year': u'1994'}
{u'Plot': u'The aging patriarch of an organized crime dynasty transfers control of his clandestine empire to his reluctant son.', u'Rated': u'R', u'Title': u'The Godfather', u'Ratings': [{u'Source': u'Internet Movie Database', u'Value': u'9.2/10'}, {u'Source': u'Rotten Tomatoes', u'Value': u'99%'}, {u'Source': u'Metacritic', u'Value': u'100/100'}], u'DVD': u'09 Oct 2001', u'Writer': u'Mario Puzo (screenplay), Francis Ford Coppola (screenplay), Mario Puzo (novel)', u'Production': u'Paramount Pictures', u'Actors': u'Marlon Brando, Al Pacino, James Caan, Richard S. Castellano', u'Type': u'movie', u'imdbVotes': u'1,235,597', u'Website': u'http://www.thegodfather.com', u'Director': u'Francis Ford Coppola', u'Released': u'24 Mar 1972', u'Awards': u'Won 3 Oscars. Another 23 wins & 27 nominations.', u'Genre': u'Crime, Drama', u'imdbRating': u'9.2', u'Language': u'English, Italian, Latin', u'Country': u'USA', u'BoxOffice': u'N/A', u'Runtime': u'175 min', u'imdbID': u'tt0068646', u'Metascore': u'100', u'Response': u'True', u'Year': u'1972'}
]'''

data = [ast.literal_eval(s) for s in x.split('\n') if s.startswith('{')]

with open('movie_data.csv', 'w', newline='') as file:
    fieldnames = list(data[0].keys())
    writer = csv.DictWriter(file, fieldnames, quoting=csv.QUOTE_NONNUMERIC)
    writer.writeheader()  # optional
    for obj in data:
        writer.writerow(obj)
</code>```

Contents of the movie_data.csv created:

Output:

"Plot","Rated","Title","Ratings","DVD","Writer","Production","Actors","Type","imdbVotes","Website","Director","Released","Awards","Genre","imdbRating","Language","Country","BoxOffice","Runtime","imdbID","Metascore","Response","Year"
"Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.","R","The Shawshank Redemption","[{'Source': 'Internet Movie Database', 'Value': '9.3/10'}, {'Source': 'Rotten Tomatoes', 'Value': '91%'}, {'Source': 'Metacritic', 'Value': '80/100'}]","N/A","Stephen King (short story ""Rita Hayworth and Shawshank Redemption""), Frank Darabont (screenplay)","Columbia Pictures","Tim Robbins, Morgan Freeman, Bob Gunton, William Sadler","movie","1,814,175","N/A","Frank Darabont","14 Oct 1994","Nominated for 7 Oscars. Another 19 wins & 30 nominations.","Crime, Drama","9.3","English","USA","N/A","142 min","tt0111161","80","True","1994"
"The aging patriarch of an organized crime dynasty transfers control of his clandestine empire to his reluctant son.","R","The Godfather","[{'Source': 'Internet Movie Database', 'Value': '9.2/10'}, {'Source': 'Rotten Tomatoes', 'Value': '99%'}, {'Source': 'Metacritic', 'Value': '100/100'}]","09 Oct 2001","Mario Puzo (screenplay), Francis Ford Coppola (screenplay), Mario Puzo (novel)","Paramount Pictures","Marlon Brando, Al Pacino, James Caan, Richard S. Castellano","movie","1,235,597","http://www.thegodfather.com","Francis Ford Coppola","24 Mar 1972","Won 3 Oscars. Another 23 wins & 27 nominations.","Crime, Drama","9.2","English, Italian, Latin","USA","N/A","175 min","tt0068646","100","True","1972"
```

Body:
I have a problem with conversion from json to csv file. I have this data:

x = ''' [
{u'Plot': u'Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.', u'Rated': u'R', u'Title': u'The Shawshank Redemption', u'Ratings': [{u'Source': u'Internet Movie Database', u'Value': u'9.3/10'}, {u'Source': u'Rotten Tomatoes', u'Value': u'91%'}, {u'Source': u'Metacritic', u'Value': u'80/100'}], u'DVD': u'N/A', u'Writer': u'Stephen King (short story "Rita Hayworth and Shawshank Redemption"), Frank Darabont (screenplay)', u'Production': u'Columbia Pictures', u'Actors': u'Tim Robbins, Morgan Freeman, Bob Gunton, William Sadler', u'Type': u'movie', u'imdbVotes': u'1,814,175', u'Website': u'N/A', u'Director': u'Frank Darabont', u'Released': u'14 Oct 1994', u'Awards': u'Nominated for 7 Oscars. Another 19 wins & 30 nominations.', u'Genre': u'Crime, Drama', u'imdbRating': u'9.3', u'Language': u'English', u'Country': u'USA', u'BoxOffice': u'N/A', u'Runtime': u'142 min', u'imdbID': u'tt0111161', u'Metascore': u'80', u'Response': u'True', u'Year': u'1994'}
{u'Plot': u'The aging patriarch of an organized crime dynasty transfers control of his clandestine empire to his reluctant son.', u'Rated': u'R', u'Title': u'The Godfather', u'Ratings': [{u'Source': u'Internet Movie Database', u'Value': u'9.2/10'}, {u'Source': u'Rotten Tomatoes', u'Value': u'99%'}, {u'Source': u'Metacritic', u'Value': u'100/100'}], u'DVD': u'09 Oct 2001', u'Writer': u'Mario Puzo (screenplay), Francis Ford Coppola (screenplay), Mario Puzo (novel)', u'Production': u'Paramount Pictures', u'Actors': u'Marlon Brando, Al Pacino, James Caan, Richard S. Castellano', u'Type': u'movie', u'imdbVotes': u'1,235,597', u'Website': u'http://www.thegodfather.com', u'Director': u'Francis Ford Coppola', u'Released': u'24 Mar 1972', u'Awards': u'Won 3 Oscars. Another 23 wins & 27 nominations.', u'Genre': u'Crime, Drama', u'imdbRating': u'9.2', u'Language': u'English, Italian, Latin', u'Country': u'USA', u'BoxOffice': u'N/A', u'Runtime': u'175 min', u'imdbID': u'tt0068646', u'Metascore': u'100', u'Response': u'True', u'Year': u'1972'}
]'''

and I am trying to convert this to csv to be able to take just title and year from all details. When I am trying to do: json.loads(x), error appears: "ValueError: Expecting property name: line 2 column 2 (char 3)" and I have no idea how to fix it? Any ideas?

Body:
Your data isn't in valid JSON format. It's almost valid Python, however. Here's how to leverage that fact and do what you want:

import ast
import csv

x = ''' [
{u'Plot': u'Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.', u'Rated': u'R', u'Title': u'The Shawshank Redemption', u'Ratings': [{u'Source': u'Internet Movie Database', u'Value': u'9.3/10'}, {u'Source': u'Rotten Tomatoes', u'Value': u'91%'}, {u'Source': u'Metacritic', u'Value': u'80/100'}], u'DVD': u'N/A', u'Writer': u'Stephen King (short story "Rita Hayworth and Shawshank Redemption"), Frank Darabont (screenplay)', u'Production': u'Columbia Pictures', u'Actors': u'Tim Robbins, Morgan Freeman, Bob Gunton, William Sadler', u'Type': u'movie', u'imdbVotes': u'1,814,175', u'Website': u'N/A', u'Director': u'Frank Darabont', u'Released': u'14 Oct 1994', u'Awards': u'Nominated for 7 Oscars. Another 19 wins & 30 nominations.', u'Genre': u'Crime, Drama', u'imdbRating': u'9.3', u'Language': u'English', u'Country': u'USA', u'BoxOffice': u'N/A', u'Runtime': u'142 min', u'imdbID': u'tt0111161', u'Metascore': u'80', u'Response': u'True', u'Year': u'1994'}
{u'Plot': u'The aging patriarch of an organized crime dynasty transfers control of his clandestine empire to his reluctant son.', u'Rated': u'R', u'Title': u'The Godfather', u'Ratings': [{u'Source': u'Internet Movie Database', u'Value': u'9.2/10'}, {u'Source': u'Rotten Tomatoes', u'Value': u'99%'}, {u'Source': u'Metacritic', u'Value': u'100/100'}], u'DVD': u'09 Oct 2001', u'Writer': u'Mario Puzo (screenplay), Francis Ford Coppola (screenplay), Mario Puzo (novel)', u'Production': u'Paramount Pictures', u'Actors': u'Marlon Brando, Al Pacino, James Caan, Richard S. Castellano', u'Type': u'movie', u'imdbVotes': u'1,235,597', u'Website': u'http://www.thegodfather.com', u'Director': u'Francis Ford Coppola', u'Released': u'24 Mar 1972', u'Awards': u'Won 3 Oscars. Another 23 wins & 27 nominations.', u'Genre': u'Crime, Drama', u'imdbRating': u'9.2', u'Language': u'English, Italian, Latin', u'Country': u'USA', u'BoxOffice': u'N/A', u'Runtime': u'175 min', u'imdbID': u'tt0068646', u'Metascore': u'100', u'Response': u'True', u'Year': u'1972'}
]'''

data = [ast.literal_eval(s) for s in x.split('\n') if s.startswith('{')]

with open('movie_data.csv', 'w', newline='') as file:
    fieldnames = list(data[0].keys())
    writer = csv.DictWriter(file, fieldnames, quoting=csv.QUOTE_NONNUMERIC)
    writer.writeheader()  # optional
    for obj in data:
        writer.writerow(obj)

Contents of the movie_data.csv created:

Output:

"Plot","Rated","Title","Ratings","DVD","Writer","Production","Actors","Type","imdbVotes","Website","Director","Released","Awards","Genre","imdbRating","Language","Country","BoxOffice","Runtime","imdbID","Metascore","Response","Year"
"Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.","R","The Shawshank Redemption","[{'Source': 'Internet Movie Database', 'Value': '9.3/10'}, {'Source': 'Rotten Tomatoes', 'Value': '91%'}, {'Source': 'Metacritic', 'Value': '80/100'}]","N/A","Stephen King (short story ""Rita Hayworth and Shawshank Redemption""), Frank Darabont (screenplay)","Columbia Pictures","Tim Robbins, Morgan Freeman, Bob Gunton, William Sadler","movie","1,814,175","N/A","Frank Darabont","14 Oct 1994","Nominated for 7 Oscars. Another 19 wins & 30 nominations.","Crime, Drama","9.3","English","USA","N/A","142 min","tt0111161","80","True","1994"
"The aging patriarch of an organized crime dynasty transfers control of his clandestine empire to his reluctant son.","R","The Godfather","[{'Source': 'Internet Movie Database', 'Value': '9.2/10'}, {'Source': 'Rotten Tomatoes', 'Value': '99%'}, {'Source': 'Metacritic', 'Value': '100/100'}]","09 Oct 2001","Mario Puzo (screenplay), Francis Ford Coppola (screenplay), Mario Puzo (novel)","Paramount Pictures","Marlon Brando, Al Pacino, James Caan, Richard S. Castellano","movie","1,235,597","http://www.thegodfather.com","Francis Ford Coppola","24 Mar 1972","Won 3 Oscars. Another 23 wins & 27 nominations.","Crime, Drama","9.2","English, Italian, Latin","USA","N/A","175 min","tt0068646","100","True","1972"