问:
Find if two strings are same in an array?
I have an array of objects. Each object has an property called title , I want to know if two object has the same title. How to do that in swift?</p>

答:
```<code>var duplicateArray: [String] = []
var storedArray: [String] = []
    for text in array {

        if storedArray.contains(text) {
             dump(text + " is a duplicate")
             dupliateArray.append(text)
        }
        storedArray.append(text)
    }
</code>```


来源: stackexchange

问:
how to solve this gradle project refresh failed

Error:Could not find com.android.tools.build:gradle:2.4.2.

答:
Set 2.3.2 instead of 2.4.2 and sync</p>

```<code>com.android.tools.build:gradle:2.3.2
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Set 2.3.2 instead of 2.4.2 and sync

com.android.tools.build:gradle:2.3.2


问:
Display simple markup in a Label in Delphi
I am currently displaying some text in a TLabel. I would now like to emphasise certain words within the text by displaying them in bold or perhaps italic. What is the recommended way to do this in Delphi? Is there a TLabel-like component that can display simple HTML or markup?
I am imagining some code like this:

```<code>label.text:='This information is <b>important</b>';
</code>```

I am using Delphi 2010

答: JvHTLabel in the JVCL will do the trick very nicely. Download the whole library from http://jvcl.delphi-jedi.org/</p>

ContentLicense: CC BY-SA 2.5

Body:
I am currently displaying some text in a TLabel. I would now like to emphasise certain words within the text by displaying them in bold or perhaps italic. What is the recommended way to do this in Delphi? Is there a TLabel-like component that can display simple HTML or markup?
I am imagining some code like this:

label.text:='This information is important';

I am using Delphi 2010


问:
How can fix this AWS Lambda Function for Google reCaptcha?
I have a lambda function that I am trying to use to verify google recaptcha. I know I am sending the correct data from the client which is the response but I keep getting the verification failed console message.
Here is my code:

//Lambda Function I am using
var AWS = require('aws-sdk');
const https = require('https');
const googleRecapchaSecret = "<site-secret-key>";
/*
  Sample response query string
  https://www.google.com/recaptcha/api/siteverify?secret=your_secret&response=response_string
*/
function validateRecaptcha(recaptchaResponse,  callback, error){
    var querystring = require('querystring');
    var postData = querystring.stringify({secret : googleRecapchaSecret,response : recaptchaResponse});
    var options = {
       hostname: 'www.google.com',
       path: '/recaptcha/api/siteverify',
       method: 'POST',
       port: 443,
       headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': Buffer.byteLength(postData)
        }

    };

   var req = https.request(options, (res) => {
        res.on('data', (d) => {
             if (d === undefined){ error('undefined'); return}

             var response = JSON.parse(d);
             console.log(response);
             if(response.success === true){
                 callback('true');
             }else{
                 callback(response);
             }
        });
   });

   req.write(postData);
   req.end();

   req.on('error', (e) => {
       //console.log(e);
       callback('false');
   });

}
module.exports.grouveReCaptcha =  (event, context, callback) => {
    data = event;
    if(data.body === undefined) { context.fail('Must provide parameters!'); return; }
    console.log('Received Event:',data.body);

   if(recaptchaResponse === undefined){
        context.fail('Recaptcha cannot be validated!');
        return;
    }
    var recaptchaResponse = event.body.data;

    validateRecaptcha(recaptchaResponse, function(err, data){
        if (err) {
          console.log("ReCAPTCHA verification failed!");
         callback(null, {'success': false, 'message': "You appear to be a robot!"});
       context.done(err, null);
        } else {
            console.log("ReCAPTCHA verification succeeded!");
            context.done(null, data);
        }
    });

};```
</div>
</div>
</p>

<p>Here is my html that I am using on the client side:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><script type="text/javascript">
  var onloadCallback = function() {
    grecaptcha.render('quote-g-recaptcha', {
      'sitekey': 'XXXXXXXXXXXXXXXXXXXX',
      'callback': verifyCallback
    });
  };
</script>

<div class="g-recaptcha" id="quote-g-recaptcha" style="transform:scale(0.77);-webkit-transform:scale(0.77);transform-origin:0 0;-webkit-transform-origin:0 0;"></div>
<script type="text/javascript">
  var verifyCallback = function(response) {
    AWS.config.update({
      region: 'us-east-1'
    });
    AWS.config.credentials = new AWS.Credentials('XXXXXXXXX', 'XXXXXXXXX');
    var lambda = new AWS.Lambda({
      region: 'us-east-1',
      apiVersion: '2015-03-31'
    })
    var pullReCaptchaParams = {
      FunctionName: 'ReCaptchaGrouve',
      InvocationType: 'RequestResponse',
      LogType: 'Tail',
      Payload: JSON.stringify({
        response
      })
    };
    lambda.invoke(pullReCaptchaParams, function(error, data) {
      if (error) {
        prompt(error);
      } else {
        pullReCaptchaResults = JSON.parse(data.Payload);
        console.log('User Verified');
      }
    });
    var pullReCaptchaResults;
  };
</script></code>```

答:
Not sure if this will solve your entire problem but I noticed that your callback is not working correctly in the validateRecaptcha function:

```<code> if(response.success === true){
     callback('true');
 }else{
     callback(response);
 }
</code>```

In your case the function you are passing through is function(err, response){...}

In the if block on success you are calling the callback with response as the first argument where the first argument is assigned to err.

```<code>function(err, response) {
  // err is set to the first argument
  // response will be undefined
}
</code>```

You will need to change this to

```<code>if(response.success === true){
    callback(null, response);
}else{
    callback(response);
}
</code>```

Hopefully this gets you a bit further

ContentLicense: CC BY-SA 4.0

Body:
I have a lambda function that I am trying to use to verify google recaptcha. I know I am sending the correct data from the client which is the response but I keep getting the verification failed console message.
Here is my code:

//Lambda Function I am using
var AWS = require('aws-sdk');
const https = require('https');
const googleRecapchaSecret = "<site-secret-key>";
/*
  Sample response query string
  https://www.google.com/recaptcha/api/siteverify?secret=your_secret&response=response_string
*/
function validateRecaptcha(recaptchaResponse,  callback, error){
    var querystring = require('querystring');
    var postData = querystring.stringify({secret : googleRecapchaSecret,response : recaptchaResponse});
    var options = {
       hostname: 'www.google.com',
       path: '/recaptcha/api/siteverify',
       method: 'POST',
       port: 443,
       headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': Buffer.byteLength(postData)
        }

    };

   var req = https.request(options, (res) => {
        res.on('data', (d) => {
             if (d === undefined){ error('undefined'); return}

             var response = JSON.parse(d);
             console.log(response);
             if(response.success === true){
                 callback('true');
             }else{
                 callback(response);
             }
        });
   });

   req.write(postData);
   req.end();

   req.on('error', (e) => {
       //console.log(e);
       callback('false');
   });

}
module.exports.grouveReCaptcha =  (event, context, callback) => {
    data = event;
    if(data.body === undefined) { context.fail('Must provide parameters!'); return; }
    console.log('Received Event:',data.body);

   if(recaptchaResponse === undefined){
        context.fail('Recaptcha cannot be validated!');
        return;
    }
    var recaptchaResponse = event.body.data;

    validateRecaptcha(recaptchaResponse, function(err, data){
        if (err) {
          console.log("ReCAPTCHA verification failed!");
         callback(null, {'success': false, 'message': "You appear to be a robot!"});
       context.done(err, null);
        } else {
            console.log("ReCAPTCHA verification succeeded!");
            context.done(null, data);
        }
    });

};

Here is my html that I am using on the client side:

Body:
Not sure if this will solve your entire problem but I noticed that your callback is not working correctly in the validateRecaptcha function:

 if(response.success === true){
     callback('true');
 }else{
     callback(response);
 }

In your case the function you are passing through is function(err, response){...}

In the if block on success you are calling the callback with response as the first argument where the first argument is assigned to err.

function(err, response) {
  // err is set to the first argument
  // response will be undefined
}

You will need to change this to

if(response.success === true){
    callback(null, response);
}else{
    callback(response);
}

Hopefully this gets you a bit further


问:
Select maximum/minimum with another column
Is there is a way to select the maximum of value + another column without the use of TOP and order by?

Assuming that we have a list of people and their ages, we want take the oldest/youngest. I want to select the name + the age. Even If it happens that we want to group them by name, that won't work.

```<code>SELECT   nom,
         max(age)
from     Agents
group by nom

╔════════╦═════╗
║  Name  ║ Age ║
╠════════╬═════╣
║ John   ║ 200 ║
║ Bob    ║ 150 ║
║ GSkill ║ 300 ║
║ Smith  ║ 250 ║
║ John   ║ 400 ║
║ Zid    ║ 300 ║
║ Wick   ║ 250 ║
║ Smith  ║ 140 ║
╚════════╩═════╝
</code>```

答:
You could use ROW_NUMBER or DENSE_RANK. For example, if you have to show those  employees having the MIN and MAX salary then you could use following SQL statement:

```<code>SELECT x.Name, x.Salary,
    IIF(x.RowNumMIN = 1, 1, 0) AS IsMin,
    IIF(x.RowNumMAX = 1, 1, 0) AS IsMax
FROM (
    SELECT x.Name, x.Salary,
        ROW_NUMBER() OVER(ORDER BY x.Salary ASC) AS RowNumMIN,
        ROW_NUMBER() OVER(ORDER BY x.Salary DESC) AS RowNumMAX
    FROM dbo.SourceTable AS x
) AS x
WHERE x.RowNumMIN = 1 OR x.RowNumMAX = 1
</code>```

If there are two or more people having the same min or max salary and you have to show all of then you could use DENSE_RANK function instead of ROW_NUMBER.

Body:
Is there is a way to select the maximum of value + another column without the use of TOP and order by?

Assuming that we have a list of people and their ages, we want take the oldest/youngest. I want to select the name + the age. Even If it happens that we want to group them by name, that won't work.

SELECT   nom,
         max(age)
from     Agents
group by nom

╔════════╦═════╗
║  Name  ║ Age ║
╠════════╬═════╣
║ John   ║ 200 ║
║ Bob    ║ 150 ║
║ GSkill ║ 300 ║
║ Smith  ║ 250 ║
║ John   ║ 400 ║
║ Zid    ║ 300 ║
║ Wick   ║ 250 ║
║ Smith  ║ 140 ║
╚════════╩═════╝

Body:
You could use ROW_NUMBER or DENSE_RANK. For example, if you have to show those  employees having the MIN and MAX salary then you could use following SQL statement:

SELECT x.Name, x.Salary,
    IIF(x.RowNumMIN = 1, 1, 0) AS IsMin,
    IIF(x.RowNumMAX = 1, 1, 0) AS IsMax
FROM (
    SELECT x.Name, x.Salary,
        ROW_NUMBER() OVER(ORDER BY x.Salary ASC) AS RowNumMIN,
        ROW_NUMBER() OVER(ORDER BY x.Salary DESC) AS RowNumMAX
    FROM dbo.SourceTable AS x
) AS x
WHERE x.RowNumMIN = 1 OR x.RowNumMAX = 1

If there are two or more people having the same min or max salary and you have to show all of then you could use DENSE_RANK function instead of ROW_NUMBER.


问:
Integrate JQuery steps with ZK framework
I am trying to integrate the jQuery plugin "steps" with ZK framework. I am using textboxes and data binding like so:

<textbox value="@bind(vm.Model.prop.propOfProp)/>"

I use jQuery steps like so:

```<code>$("#form").steps({
    bodyTag: "fieldset",
    transitionEffect: "slideLeft",
   onFinishing : function(event,currentIndex) {
            $('.z-button')[0].click();
            return true;
           }
});
</code>```

What I have been trying is to trigger the click event on the ZK button and the event is fired but all the data bindings are ignored. It appears that the "steps" plugin sends the form in a way that zk doesn't like.

I have already tried the exact same form without the plugin and it works.

How would that be possible if possible ?

I looked for information about how the plugin sends the forms and if it has influence over the inputs but without success.

答: JQuery steps plugin can't be integrated to zk in its current state due to the influance it has on the inputs and the formdata itself.If you really need it you will have to change the plugin code or simulate it manually with JavaScript on the client side like I did because its easier. You can find my code here ! My manual solution!</p>

Body:
I am trying to integrate the jQuery plugin "steps" with ZK framework. I am using textboxes and data binding like so:

<textbox value="@bind(vm.Model.prop.propOfProp)/>"

I use jQuery steps like so:

$("#form").steps({
    bodyTag: "fieldset",
    transitionEffect: "slideLeft",
   onFinishing : function(event,currentIndex) {
            $('.z-button')[0].click();
            return true;
           }
});

What I have been trying is to trigger the click event on the ZK button and the event is fired but all the data bindings are ignored. It appears that the "steps" plugin sends the form in a way that zk doesn't like.

I have already tried the exact same form without the plugin and it works.

How would that be possible if possible ?

I looked for information about how the plugin sends the forms and if it has influence over the inputs but without success.


问:
Isolating reactive expression
I want to call a particular reactive expression for someobserveEvent and isolate it for other observeEvent. Below I have minimal code for what I want to achieve( my actual app contains many observeEventcalling the reactive expression).

```<code>library(shiny)

ui <- fluidPage(

  numericInput("Num1", "First number:", 0),

  numericInput("Num2", "Second number:", 0),

  textOutput("Answer"),

  actionButton("Button_1", "Call reactive"),

  actionButton("Button_2", "Don't Call reactive")

)

server <- function(input, output){

  Ans <- reactive({
    a <-input$Num1 + input$Num2
    a
  })

  observeEvent(input$Button_1, {

    output$Answer <- renderText({Ans()})

  })

  observeEvent(input$Button_2, {

    output$Answer <- renderText({isolate(Ans())})

  })

}

shinyApp(ui = ui, server = server)
</code>```

In the above app I have two actionButtons Button_1(Call reactive) and Button_2(Don't Call reactive). As the label suggest for the first button (Button_1) I want the reactive expression to be called every time the button is clicked but for the second button (Button_2)I want the reactive expression not to be called (even when the inputs change). To prevent the Button_2 form calling the reactive expression I added isolate but that does not prevent the reactive expression from being called.

Is there any way in which a reactive expression can be isolated even when the inputs change?

答:
You could use ?eventReactive().

So replace the reactive() function with

```<code>  Ans <- eventReactive(input$Button_1,{
    input$Num1 + input$Num2
  })
</code>```

(Then you can also remove the isolate() function).

As you mentioned that you have several observeEvent() and potentially more conditions, it is worth mentioning that the also works for multiple conditions:

```<code>  Ans <- eventReactive({input$Button_1;input$Button_2;...},{
    input$Num1 + input$Num2
  })
</code>```

Title: Isolating reactive expression

Body:
I want to call a particular reactive expression for someobserveEvent and isolate it for other observeEvent. Below I have minimal code for what I want to achieve( my actual app contains many observeEventcalling the reactive expression).

library(shiny)

ui <- fluidPage(

  numericInput("Num1", "First number:", 0),

  numericInput("Num2", "Second number:", 0),

  textOutput("Answer"),

  actionButton("Button_1", "Call reactive"),

  actionButton("Button_2", "Don't Call reactive")

)

server <- function(input, output){

  Ans <- reactive({
    a <-input$Num1 + input$Num2
    a
  })

  observeEvent(input$Button_1, {

    output$Answer <- renderText({Ans()})

  })

  observeEvent(input$Button_2, {

    output$Answer <- renderText({isolate(Ans())})

  })

}

shinyApp(ui = ui, server = server)

In the above app I have two actionButtons Button_1(Call reactive) and Button_2(Don't Call reactive). As the label suggest for the first button (Button_1) I want the reactive expression to be called every time the button is clicked but for the second button (Button_2)I want the reactive expression not to be called (even when the inputs change). To prevent the Button_2 form calling the reactive expression I added isolate but that does not prevent the reactive expression from being called.

Is there any way in which a reactive expression can be isolated even when the inputs change?

Body:
You could use ?eventReactive().

So replace the reactive() function with

  Ans <- eventReactive(input$Button_1,{
    input$Num1 + input$Num2
  })

(Then you can also remove the isolate() function).

As you mentioned that you have several observeEvent() and potentially more conditions, it is worth mentioning that the also works for multiple conditions:

  Ans <- eventReactive({input$Button_1;input$Button_2;...},{
    input$Num1 + input$Num2
  })


问:
Function is returning Undefined
I need small help in a small code. The function is returning undefined and i want to return the console.log of the sum. The code is here http://jsbin.com/jedigigigo/edit?js,console

var addDigits = function a(num) {
  var length = num.toString().length;
  var value = num.toString();
  var sum = 0;
  for (var i = 0; i < value.length; i++) {
    sum += Number(value[i]);
  }
  if (sum > 9) {
    a(sum);
  } else {
    console.log(sum);
    return sum;
  }
};

console.log(addDigits(38));```

答:
I have edited your code. I don't know why are calling sum recursively here. If I understood it correct then you are only trying to return sum of digits of a number (non-negative). I modified your code like below

```<code>var addDigits = function a(num) {
     var length=num.toString().length;
     var value=num.toString();
     var sum=0;
     for(var i=0;i<value.length;i++) {
         sum+=Number(value[i]);
     }
     return sum;
};
console.log(addDigits(23456));
</code>```

I updated your bin also you can check here

Title: Function is returning Undefined

Body:
I have edited your code. I don't know why are calling sum recursively here. If I understood it correct then you are only trying to return sum of digits of a number (non-negative). I modified your code like below

var addDigits = function a(num) {
     var length=num.toString().length;
     var value=num.toString();
     var sum=0;
     for(var i=0;i<value.length;i++) {
         sum+=Number(value[i]);
     }
     return sum;
};
console.log(addDigits(23456));

I updated your bin also you can check here


问:
Django - TinyMCE - admin - How to change editor size?
I can't seem to find any way to hange editor size in TinyMCE.
I edit posts on my site in Django administration and to make it easier I looked for a better editor than just a textfield. I succesfully installed TinyMCE, but the editor is tiny, which makes editing very annoying.

Here's how it looks like.

Here is my models.py

```<code>from django.db import models
from tinymce.models import HTMLField

class Post(models.Model):
    title = models.CharField(max_length=140)
    # body = models.TextField()
    date = models.DateTimeField()
    body = HTMLField()

    def __str__(self):
        return self.title
</code>```

Here is my admin.py:

```<code>from django.contrib import admin
from blog.models import Post

admin.site.register(Post)
</code>```

And here is my urls.py:

```<code>from django.conf.urls import url, include
from django.views.generic import ListView, DetailView
from .models import Post

urlpatterns = [
    url(r'^$', ListView.as_view(
        queryset=Post.objects.all().order_by("-date")[:25],
        template_name='blog/blog.html')),
    url(r'^(?P<pk>\d+)$',
        DetailView.as_view(model=Post,
                           template_name='blog/post.html')),
]
</code>```

I've been trying and googling for the past 2 hours, but I can't figure it out.

Can anyone help me?
Thanks.

答:
TINYMCE_DEFAULT_CONFIG dictionary needs to set in the settings.py file.

```<code>TINYMCE_DEFAULT_CONFIG = {
    'theme': "advanced",
    'width' : 758,
    'height' : 118,
}
</code>```

This will change width and height of the tinymce editor.

Body:
I can't seem to find any way to hange editor size in TinyMCE.
I edit posts on my site in Django administration and to make it easier I looked for a better editor than just a textfield. I succesfully installed TinyMCE, but the editor is tiny, which makes editing very annoying.

Here's how it looks like.

Here is my models.py

from django.db import models
from tinymce.models import HTMLField

class Post(models.Model):
    title = models.CharField(max_length=140)
    # body = models.TextField()
    date = models.DateTimeField()
    body = HTMLField()

    def __str__(self):
        return self.title

Here is my admin.py:

from django.contrib import admin
from blog.models import Post

admin.site.register(Post)

And here is my urls.py:

from django.conf.urls import url, include
from django.views.generic import ListView, DetailView
from .models import Post

urlpatterns = [
    url(r'^$', ListView.as_view(
        queryset=Post.objects.all().order_by("-date")[:25],
        template_name='blog/blog.html')),
    url(r'^(?P<pk>\d+)$',
        DetailView.as_view(model=Post,
                           template_name='blog/post.html')),
]

I've been trying and googling for the past 2 hours, but I can't figure it out.

Can anyone help me?
Thanks.

Body:
TINYMCE_DEFAULT_CONFIG dictionary needs to set in the settings.py file.

TINYMCE_DEFAULT_CONFIG = {
    'theme': "advanced",
    'width' : 758,
    'height' : 118,
}

This will change width and height of the tinymce editor.


问:
How to read text file from File object in java
I have this code which load the File from class path
a=its text file and i want to read it to string
what im using is :

```<code> File file = new File(classLoader.getResource("sample.json").getFile());
</code>```

i don't want to use:

```<code>file.getAbsolutePath();
</code>```

how can i read this text file into String ?

UPDATE
i found the solution , what do you think?

```<code> ClassLoader classLoader = getClass().getClassLoader();
is = classLoader.getResourceAsStream("sample.json");
String txt = IOUtils.toString(is);
</code>```

答:
You can use the following code to read the file object.</p>

```<code>public static void main(String[] args) {

        try (BufferedReader br = new BufferedReader(file)) {
            String sCurrentLine;
            while ((sCurrentLine = br.readLine()) != null) {
                System.out.println(sCurrentLine);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
</code>```

Body:
I have this code which load the File from class path
a=its text file and i want to read it to string
what im using is :

 File file = new File(classLoader.getResource("sample.json").getFile());

i don't want to use:

file.getAbsolutePath();

how can i read this text file into String ?

UPDATE
i found the solution , what do you think?

 ClassLoader classLoader = getClass().getClassLoader();
is = classLoader.getResourceAsStream("sample.json");
String txt = IOUtils.toString(is);

Body:
You can use the following code to read the file object.

public static void main(String[] args) {

        try (BufferedReader br = new BufferedReader(file)) {
            String sCurrentLine;
            while ((sCurrentLine = br.readLine()) != null) {
                System.out.println(sCurrentLine);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


问:
PHP SQLite PRAGMA journal_mode = wal and readonly users
I read that WAL mode allows a user users to read while during a write session.
Therefore I should be able to have 3 sessions reading data and one writing data at the same time, This sounds like a good thing for my use, so I figured I should define the session type so the system knows if this session is a reader or a writer using the connection flag.

http://php.net/manual/en/sqlite3.open.php#refsect1-sqlite3.open-parameters

It states here that if the session is not closed cleanly that the -shm and -wal files are not removed

https://www.sqlite.org/tempfiles.html#write_ahead_log_wal_files

After a read session the temporary files are not removed, thus meaning the session was not cleanly closed despite calling the close function and it returning true, so why are the files not being deleted when using the SQLITE3_OPEN_READONLY flag? Should I even use a flag at all?

答:
You've conflated SQLite's concept of 'readers' and 'writers' with the ability of the PHP SQLite3 driver to open a file as read-only.

Using the SQLITE3_OPEN_READONLY flag will cause PHP to block all write operations with a warning:

Warning: SQLite3::exec(): attempt to write a readonly database in ...

This can be useful if you want to ensure no writes can happen from your application (perhaps as a security measure). But it's not related to SQLite's readers and writers.

As pointed out by CL all processes accessing the WAL mode database need write access. This is explicitly documented:

Also, if multiple processes are to access a WAL mode database, then all processes should run under user or group IDs that give them write access to the database files, the WAL file, the shared memory -shm file, and the containing directory.

And mentioned as a disadvantage at the top of that page:

It is not possible to open read-only WAL databases. The opening process must have write privileges for "-shm" wal-index shared memory file associated with the database, if that file exists, or else write access on the directory containing the database file if the "-shm" file does not exist.

SQLite itself decides if a process is a reader or writer when it receives a command to execute. For example, if a single process executes a SELECT, then a INSERT, then a SELECT again it changes from reader to writer to reader. SQLite will handle locking (potentially blocking other processes) automatically. (Note that this is a simplified explanation that can be quite different with different modes of database operation.)

For your purposes you shouldn't use the SQLITE3_OPEN_READONLY flag.


问:
Simple Windows batch to move folders
I'm simply trying to move all files and subdirectories inside d:\temp\test to d:\temp\archive and so I tried these commands:

```<code>move d:\temp\test\* d:\temp\archive\
move d:\temp\test\*.* d:\temp\archive\
</code>```

but I got this error in return:

```<code>The filename, directory name, or volume label syntax is incorrect.
</code>```

Then I dug around on the web and tried this inside a doc bat:

```<code>for %%F in ( d:\temp\test\*.* ) do move /Y %%F d:\temp\archive
</code>```

and this time it shows no error, but everything is standing still and made no changes.

What am i missing here? I'm trying this on Windows 10.

答:
ok, if you want to just move all the files directories from inside \test\ then this will do the files first, then directories in a batch. The for /d will copy the directories and sub directories and files.

```<code>@echo off
move "d:\temp\test\*" "d:\temp\archive"
for /d %%a in ("D:\temp\test\*") do move "%%~fa" "d:\temp\archive\"
</code>```

as a side note, from cmd when running below you get an error.

```<code>move d:\temp\test\* d:\temp\archive
</code>```

That is because it will move all files, but not directories. If you get The filename, directory name, or volume label syntax is incorrect. there are no files and only folders which your move command cannot see.

NOTE from within a batch file, the /Y switch is disabled and folders will not be replaced if exist. So if you plan on overwriting often, perhaps rather use xcopy and update archive instead, then run a delete in d:\temp once the files have successfully copied.

Lastly, always enclose your paths in double ". In this case it will work fine without the double quotes, but if you have something like move d:\program files\temp\* d:\temp\archives it will create an error because of the space between program and files so it is always better to use move "d:\program files\temp\*" "d:\temp\archive

EDIT Understanding the %%~ assignments. In these examples we use %%I instead of %%a

```<code>%~I         : expands %I removing any surrounding quotes (")
%~fI        : expands %I to a fully qualified path name
%~dI        : expands %I to a drive letter only
%~pI        : expands %I to a path only
%~nI        : expands %I to a file name only
%~xI        : expands %I to a file extension only
%~sI        : expanded path contains short names only
%~aI        : expands %I to file attributes of file
%~tI        : expands %I to date/time of file
%~zI        : expands %I to size of file
%~$PATH:I   : searches the directories listed in the PATH
              environment variable and expands %I to the
              fully qualified name of the first one found.
              if the environment variable name is not
              defined or the file is not found by the
              search, then this modifier expands to the
              empty string

The modifiers can be combined to get compound results:

%~dpI       : expands %I to a drive letter and path only
%~nxI       : expands %I to a file name and extension only
%~fsI       : expands %I to a full path name with short names only
%~dp$PATH:I : searches the directories listed in the PATH
              environment variable for %I and expands to the
              drive letter and path of the first one found.
%~ftzaI     : expands %I to a DIR like output line`
</code>```

Title: Simple Windows batch to move folders

Body:
I'm simply trying to move all files and subdirectories inside d:\temp\test to d:\temp\archive and so I tried these commands:

move d:\temp\test\* d:\temp\archive\
move d:\temp\test\*.* d:\temp\archive\

but I got this error in return:

The filename, directory name, or volume label syntax is incorrect.

Then I dug around on the web and tried this inside a doc bat:

for %%F in ( d:\temp\test\*.* ) do move /Y %%F d:\temp\archive

and this time it shows no error, but everything is standing still and made no changes.

What am i missing here? I'm trying this on Windows 10.

Body:
ok, if you want to just move all the files directories from inside \test\ then this will do the files first, then directories in a batch. The for /d will copy the directories and sub directories and files.

@echo off
move "d:\temp\test\*" "d:\temp\archive"
for /d %%a in ("D:\temp\test\*") do move "%%~fa" "d:\temp\archive\"

as a side note, from cmd when running below you get an error.

move d:\temp\test\* d:\temp\archive

That is because it will move all files, but not directories. If you get The filename, directory name, or volume label syntax is incorrect. there are no files and only folders which your move command cannot see.

NOTE from within a batch file, the /Y switch is disabled and folders will not be replaced if exist. So if you plan on overwriting often, perhaps rather use xcopy and update archive instead, then run a delete in d:\temp once the files have successfully copied.

Lastly, always enclose your paths in double ". In this case it will work fine without the double quotes, but if you have something like move d:\program files\temp\* d:\temp\archives it will create an error because of the space between program and files so it is always better to use move "d:\program files\temp\*" "d:\temp\archive

EDIT Understanding the %%~ assignments. In these examples we use %%I instead of %%a

%~I         : expands %I removing any surrounding quotes (")
%~fI        : expands %I to a fully qualified path name
%~dI        : expands %I to a drive letter only
%~pI        : expands %I to a path only
%~nI        : expands %I to a file name only
%~xI        : expands %I to a file extension only
%~sI        : expanded path contains short names only
%~aI        : expands %I to file attributes of file
%~tI        : expands %I to date/time of file
%~zI        : expands %I to size of file
%~$PATH:I   : searches the directories listed in the PATH
              environment variable and expands %I to the
              fully qualified name of the first one found.
              if the environment variable name is not
              defined or the file is not found by the
              search, then this modifier expands to the
              empty string

The modifiers can be combined to get compound results:

%~dpI       : expands %I to a drive letter and path only
%~nxI       : expands %I to a file name and extension only
%~fsI       : expands %I to a full path name with short names only
%~dp$PATH:I : searches the directories listed in the PATH
              environment variable for %I and expands to the
              drive letter and path of the first one found.
%~ftzaI     : expands %I to a DIR like output line`


问:
Which tool/editor can list all the functions directly or indirectly call a function?
For example:

void fooo1()
{
    foo1();
}

void fooo2()
{
    foo2();
}

void foo1()
{
    bar();
}

void foo2()
{
    bar();
}
```

I would like to list all the functions directly/indirectly call function bar, which should be:

foo1 foo2 fooo1 fooo2

答:
In Visual Studio 2015 you can right click a method definition and chose "View Call Hierarchy" from the context menu (shortcut CTRL+K,CTRL+T ):

More info here on MSDN.

Body:
For example:

void fooo1()
{
    foo1();
}

void fooo2()
{
    foo2();
}

void foo1()
{
    bar();
}

void foo2()
{
    bar();
}

I would like to list all the functions directly/indirectly call function bar, which should be:

foo1 foo2 fooo1 fooo2


问:
Sending complex data type to View
I'm aware that this is basic but then again I couldn't figure out answer for this one ...

I would like to send string and int value as one ViewData value to View

```<code>ViewData["TypeOfPaymentSelected"] = new { StringName = Enum.GetName(typeof(PaymentType), payment), IntValue = payment };
</code>```

but I do not know how to cast it inside View.

If I'm still in controller I would simple access is as

```<code>varName.StringName
varName.IntValue
</code>```

I know how to make ViewModel classes and cast it in View, I know I can send this as two ViewData values etc but I thought this can be done simpler
and obvioulsy I lack basic C# knowledge

答:
You can use anonymous types if you want but then you need to use for example Eval-method to access it in the view:

```<code>@ViewData.Eval("TypeOfPaymentSelected.StringName")
</code>```

More info in this question/answer

Preferred way would be to use a model so that everything will be strongly typed.

Example:

```<code>namespace Models
{
    public class MyModel
    {
        public string StringName;
        public int IntValue;
    }
}
</code>```

Controller:

```<code>public ActionResult Index()
{
    ViewData["TypeOfPaymentSelected"] = new MyModel { StringName = "test", IntValue = 5 };
    return View();
}
</code>```

And in View:

```<code>@(((Models.MyModel)ViewData["TypeOfPaymentSelected"]).StringName)
</code>```

Title: Sending complex data type to View

Body:
I'm aware that this is basic but then again I couldn't figure out answer for this one ...

I would like to send string and int value as one ViewData value to View

ViewData["TypeOfPaymentSelected"] = new { StringName = Enum.GetName(typeof(PaymentType), payment), IntValue = payment };

but I do not know how to cast it inside View.

If I'm still in controller I would simple access is as

varName.StringName
varName.IntValue

I know how to make ViewModel classes and cast it in View, I know I can send this as two ViewData values etc but I thought this can be done simpler
and obvioulsy I lack basic C# knowledge

Body:
You can use anonymous types if you want but then you need to use for example Eval-method to access it in the view:

@ViewData.Eval("TypeOfPaymentSelected.StringName")

More info in this question/answer

Preferred way would be to use a model so that everything will be strongly typed.

Example:

namespace Models
{
    public class MyModel
    {
        public string StringName;
        public int IntValue;
    }
}

Controller:

public ActionResult Index()
{
    ViewData["TypeOfPaymentSelected"] = new MyModel { StringName = "test", IntValue = 5 };
    return View();
}

And in View:

@(((Models.MyModel)ViewData["TypeOfPaymentSelected"]).StringName)


问:
Why is this infinite for loop terminating after some time?
I am running this infinite for loop. Why is this for loop terminating after some time?

```<code>for(int i = 10; i > 0; i++) { }
</code>```

But if I print something in this for loop then it is not terminating. Why so?

答:
The int wraps around to -2,147,483,648 when it reaches 2,147,483,647.

That causes the conditional i > 0 to evaluate to false.

This is perfectly well-defined behaviour in Java: you can't do this though in C or C++.

If you are trying to print something in the loop, then the speed of the loop decreases substantially, and you're probably running out of patience. Incorporate the current value of i in your output, and see for yourself: even 1,000 iterations of output per second would take nearly a month to reach the wrap-around point!

Body:
I am running this infinite for loop. Why is this for loop terminating after some time?

for(int i = 10; i > 0; i++) { }

But if I print something in this for loop then it is not terminating. Why so?


问:
Need to create class diagram from C# Class and print it
for a medium project, I need create class diagram from class code (plain text class with public properties), and print it.
This for more develop code and project organization. Which tools I can use? </p>

答:
In Visual Studio,Solution</p>

```<code> Explorer=>
          classFileName=>
                      right Click on it(open Context menu)=>
                                                Select Class Diagram option
</code>```

Body:
In Visual Studio,Solution

 Explorer=>
          classFileName=>
                      right Click on it(open Context menu)=>
                                                Select Class Diagram option


问:
How to post a request to azure ML web service using angular js?
I am trying to build an UI for azure ML model using angular js. I designed an HTML page where user input is captured using ng-model The issue am facing now in this effort is, getting 400 Bad request error as azure expects to send a data in POST request in below mentioned format. I get 200 success message when I test this sample value in Post Request. How should I send a user input for values in POST request. Appreciate any help.

Azure's expected Request body sample:

```<code>{

 "Inputs": {

    "input1": {
      "ColumnNames": [
        "col1",
        "col2",
        "col3"
      ],
      "Values": [
        [
        "value1",
        "value2",
        "value3"
        ]
      ]
    }
  },
  "GlobalParameters": {}
}
</code>```

My Test javascript is

```<code>$http ({

          method  : 'POST',
          url     : 'url',
          data    : '{"Inputs": {"input1": {"ColumnNames": ["col1","col2","col3"],"Values": ["value1","value2","value3"]]}}}',

          headers : {'Content-Type': 'application/json',
                'Authorization' : 'Bearer apikey'
                }
</code>```

答:
It seems that you have a mistake in the angularjs application, when you are generating the data payload.

In the sample,

```<code>"Values": [
        [
        "value1",
        "value2",
        "value3"
        ]
      ]
</code>```

the value is a nested array.

However in your fronted code snippet:

```<code>{"Inputs": {"input1": {"ColumnNames": ["col1","col2","col3"],"Values": ["value1","value2","value3"]]}}}
</code>```

which is an invaild json object. (missing a [ behide "Values").

I suggest you can generate an object as the Request body sample shows, and set id object directly in $http's post body payload, instead of writing a json string it manually.

Body:
I am trying to build an UI for azure ML model using angular js. I designed an HTML page where user input is captured using ng-model The issue am facing now in this effort is, getting 400 Bad request error as azure expects to send a data in POST request in below mentioned format. I get 200 success message when I test this sample value in Post Request. How should I send a user input for values in POST request. Appreciate any help.

Azure's expected Request body sample:

{

 "Inputs": {

    "input1": {
      "ColumnNames": [
        "col1",
        "col2",
        "col3"
      ],
      "Values": [
        [
        "value1",
        "value2",
        "value3"
        ]
      ]
    }
  },
  "GlobalParameters": {}
}

My Test javascript is

$http ({

          method  : 'POST',
          url     : 'url',
          data    : '{"Inputs": {"input1": {"ColumnNames": ["col1","col2","col3"],"Values": ["value1","value2","value3"]]}}}',

          headers : {'Content-Type': 'application/json',
                'Authorization' : 'Bearer apikey'
                }

Body:
It seems that you have a mistake in the angularjs application, when you are generating the data payload.

In the sample,

"Values": [
        [
        "value1",
        "value2",
        "value3"
        ]
      ]

the value is a nested array.

However in your fronted code snippet:

{"Inputs": {"input1": {"ColumnNames": ["col1","col2","col3"],"Values": ["value1","value2","value3"]]}}}

which is an invaild json object. (missing a [ behide "Values").

I suggest you can generate an object as the Request body sample shows, and set id object directly in $http's post body payload, instead of writing a json string it manually.


问:
How can I select an element in jquery?
I'm a beginner in this programming language. I beg your pardon.

How can I select an element in JQuery?  What is wrong with my code? SOmeone help me.

```<code>    <!DOCTYPE html>
    <html>
         <head>
         <title></title>
         <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
         </head>
    <body>
    <input type="password">

    <script type="text/javascript">
         $(document).ready(function(){

         $('input[type=password]').attr({
              name: 'pass'
              style: [
                  color: 'blue',
                  font-size: '20px'
              ],
            });
        )};
    </script>
</code>```

答:
```<code>    <!DOCTYPE html>
            <html>
                 <head>
                 <title></title>
                 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
                 </head>
            <body>
            <input type="password">

            <script type="text/javascript">
                 $(document).ready(function(){

                 $('input[type=password]').attr("name","pass").css({"color":"blue","font-size":"20px"});
               });
            </script>
</body>
</html>
</code>```

Title: How can I select an element in jquery?

Body:
I'm a beginner in this programming language. I beg your pardon.

How can I select an element in JQuery?  What is wrong with my code? SOmeone help me.

    <!DOCTYPE html>

         <title></title>

    <input type="password">


问:
Update column from another table column value
I'm trying to update user_id column on comments table from comment_users table user_id column value whhich comment_id matches on comments table id columns.

comment_users table

```<code>id: 5 comment_id: 1, user_id: 20
</code>```

comments table

before

```<code>id:1 user_id: NULL
</code>```

after

```<code>id: 1 user_id: 20
</code>```

I executed sql below but it doesn't work.

```<code>UPDATE comments
  SET user_id = comment_users.user_id
  INNER JOIN comment_users ON comment_users.comment_id = comments.id
  WHERE comment_users.comment_id = comments.id

Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INNER JOIN comment_users ON comment_users.comment_id = comment' at line 3:       UPDATE comments
      SET user_id = comment_users.user_id
      INNER JOIN comment_users ON comment_users.comment_id = comments.id
      WHERE comment_users.comment_id = comments.id
</code>```

I have no idea about what is wrong.

答:
Your update join syntax is wrong, try following:

```<code>UPDATE comments
INNER JOIN comment_users ON comment_users.comment_id = comments.id
SET comments.user_id = comment_users.user_id
</code>```

Body:
I'm trying to update user_id column on comments table from comment_users table user_id column value whhich comment_id matches on comments table id columns.

comment_users table

id: 5 comment_id: 1, user_id: 20

comments table

before

id:1 user_id: NULL

after

id: 1 user_id: 20

I executed sql below but it doesn't work.

UPDATE comments
  SET user_id = comment_users.user_id
  INNER JOIN comment_users ON comment_users.comment_id = comments.id
  WHERE comment_users.comment_id = comments.id

Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INNER JOIN comment_users ON comment_users.comment_id = comment' at line 3:       UPDATE comments
      SET user_id = comment_users.user_id
      INNER JOIN comment_users ON comment_users.comment_id = comments.id
      WHERE comment_users.comment_id = comments.id

I have no idea about what is wrong.

Body:
Your update join syntax is wrong, try following:

UPDATE comments
INNER JOIN comment_users ON comment_users.comment_id = comments.id
SET comments.user_id = comment_users.user_id


问:
how to solve this gradle project refresh failed

Error:Could not find com.android.tools.build:gradle:2.4.2.

答: Post your  build.gradle file of app</p>

Body: Post your  build.gradle file of app


问:
Find the semester with a stored procedure
I have a query :

```<code>SELECT * FROM `commande`:

id   datecreation            motif          tva    numero   periode
1   27/02/2017 16:16    Achat marchandise   NULL    C001    NULL
9   28/03/2017 14:43    Achat marchandise   NULL    C002    NULL
10  28/03/2017 14:47    Achat marchandise   NULL    C003    NULL
11  28/04/2017 14:53    Achat marchandise   NULL    C004    NULL
12  28/04/2017 14:57    Achat marchandise   NULL    C005    NULL
13  28/05/2017 15:00    Achat marchandise   NULL    C006    NULL
14  28/05/2017 15:36    Achat marchandise   NULL    C007    NULL
15  28/05/2017 16:58    Achat marchandise   NULL    C008    NULL
16  28/05/2017 17:11    Achat marchandise   NULL    C009    NULL
</code>```

I want to create a stored procedure to update a column "periode"  according to "datecreation" month,"periode" column is a semester number,

for example:

```<code> if month(datecreation)=4 then periode = 2

 if month(datecreation)=3 then periode = 1

 if month(datecreation)=5 then periode = 2
</code>```

How I can do this?Thanks

答:
As I mentioned in comment semester system divides year in 2 parts. In that case month 1 - 6 are semester 1 and month 7 - 12 are semester 2. You can achieve it like below

```<code>update commande
set periode =
(floor(month(datecreation)/6) + 1 );
</code>```

If you want month 3 as 1 and month 4 and 5 as 2, then you are talking about quarter system where year is divided in 4 parts. In that case use

```<code>update commande
set periode =
(floor(month(datecreation)/4) + 1 );
</code>```

Body:
I have a query :

SELECT * FROM `commande`:

id   datecreation            motif          tva    numero   periode
1   27/02/2017 16:16    Achat marchandise   NULL    C001    NULL
9   28/03/2017 14:43    Achat marchandise   NULL    C002    NULL
10  28/03/2017 14:47    Achat marchandise   NULL    C003    NULL
11  28/04/2017 14:53    Achat marchandise   NULL    C004    NULL
12  28/04/2017 14:57    Achat marchandise   NULL    C005    NULL
13  28/05/2017 15:00    Achat marchandise   NULL    C006    NULL
14  28/05/2017 15:36    Achat marchandise   NULL    C007    NULL
15  28/05/2017 16:58    Achat marchandise   NULL    C008    NULL
16  28/05/2017 17:11    Achat marchandise   NULL    C009    NULL

I want to create a stored procedure to update a column "periode"  according to "datecreation" month,"periode" column is a semester number,

for example:

 if month(datecreation)=4 then periode = 2

 if month(datecreation)=3 then periode = 1

 if month(datecreation)=5 then periode = 2

How I can do this?Thanks

Body:
As I mentioned in comment semester system divides year in 2 parts. In that case month 1 - 6 are semester 1 and month 7 - 12 are semester 2. You can achieve it like below

update commande
set periode =
(floor(month(datecreation)/6) + 1 );

If you want month 3 as 1 and month 4 and 5 as 2, then you are talking about quarter system where year is divided in 4 parts. In that case use

update commande
set periode =
(floor(month(datecreation)/4) + 1 );


问:
LINQ to NHibernate: could not resolve property
Fluent nHibernate using nHibernate v. 2.1.2.4, nHibernate.Linq v. 1.1.0.1001, and Fluent NHibernate v. 1.1.0.685.

I have a domain object with a DateTime field called DateOfEvent. This is an actual date/time field in the database. I've also added 2 new properties YearOfEvent which grabs the Year from the DateOfEvent field as well as MontOfEvent which grabs the Month from the DateOfEvent field.

```<code>public class Event
{
    public Event() { }
    public virtual Int32 Id { get; set; }
    public virtual String Title { get; set; }
    public virtual DateTime DateOfEvent { get; set; }
    public virtual Int32 YearOfEvent
    {
        get { return DateOfEvent.Year; }
    }
    public virtual Int32 MonthOfEvent
    {
        get { return DateOfEvent.Month; }
    }
    public virtual String Location { get; set; }
    public virtual String City { get; set; }
    public virtual String State { get; set; }
    public virtual String Zip { get; set; }
    public virtual String Description { get; set; }
    public virtual Boolean HasImage { get; set; }
    public virtual Boolean IsActive { get; set; }
}
</code>```

However, when running this method:

```<code>public IList<Event> GetActiveEvents(int pageNumber, int pageSize, out int totalItems)
    {
        Int32 skip = Misc.NumberToSkip(pageNumber, pageSize);
        totalItems = (from e in _session.Linq<Event>()
                      where e.IsActive
                      select e).Count();

        return (from e in _session.Linq<Event>()
                where e.IsActive
                select e)
            .Skip(skip)
            .Take(pageSize)
            .ToList();
    }
</code>```

NHibernate.QueryException: could not resolve property: YearOfEvent of: ....Event

FWIW, I've blurred out the name of the project. ;)

Any idea how to get this query working?

Thanks!
-Steve

EDIT:
Here's my mapping class:

```<code>public class EventMap : ClassMap<Event>
{
    public EventMap()
    {
        Table("tbl_event");
        Id(x => x.Id, "eventId");
        Map(x => x.DateOfEvent, "dateOfEvent");
        Map(x => x.Description, "description");
        Map(x => x.Title, "title");
        Map(x => x.Location, "location");
        Map(x => x.State, "state");
        Map(x => x.City, "city");
        Map(x => x.Zip, "zip");
        Map(x => x.HasImage, "hasImage");
        Map(x => x.IsActive, "isActive");
    }
}
</code>```

...and my config:

```<code>public Configuration GetConfiguration()
    {
        Configuration configuration;
        var assembly = Assembly.Load(".....Data");
        var fluentConfig = Fluently.Configure()
                            .Database(MySQLConfiguration.Standard.ConnectionString(
                                          c => c.FromConnectionStringWithKey("......")
                                          ))
                            .Mappings(m => m.FluentMappings.AddFromAssembly(assembly));
        configuration = fluentConfig.BuildConfiguration();
        configuration.Properties.Add("hbm2ddl.keywords", "none");
        return configuration;
    }
</code>```

I also just tried the Criteria API:

```<code>return _session.CreateCriteria(typeof (Event))
            .Add(Expression.Eq("IsActive", true))
            .Add(Expression.Eq("YearOfEvent", year))
            .List<Event>();
</code>```

No workie either.

答: You can query over properties that really exists in database or introduced in the mappings. As YearOfEvent just exists in your entity, you can not use it in your queries either in LINQ-to-NH or ICriteria.

Body:
Fluent nHibernate using nHibernate v. 2.1.2.4, nHibernate.Linq v. 1.1.0.1001, and Fluent NHibernate v. 1.1.0.685.

I have a domain object with a DateTime field called DateOfEvent. This is an actual date/time field in the database. I've also added 2 new properties YearOfEvent which grabs the Year from the DateOfEvent field as well as MontOfEvent which grabs the Month from the DateOfEvent field.

public class Event
{
    public Event() { }
    public virtual Int32 Id { get; set; }
    public virtual String Title { get; set; }
    public virtual DateTime DateOfEvent { get; set; }
    public virtual Int32 YearOfEvent
    {
        get { return DateOfEvent.Year; }
    }
    public virtual Int32 MonthOfEvent
    {
        get { return DateOfEvent.Month; }
    }
    public virtual String Location { get; set; }
    public virtual String City { get; set; }
    public virtual String State { get; set; }
    public virtual String Zip { get; set; }
    public virtual String Description { get; set; }
    public virtual Boolean HasImage { get; set; }
    public virtual Boolean IsActive { get; set; }
}

However, when running this method:

public IList<Event> GetActiveEvents(int pageNumber, int pageSize, out int totalItems)
    {
        Int32 skip = Misc.NumberToSkip(pageNumber, pageSize);
        totalItems = (from e in _session.Linq<Event>()
                      where e.IsActive
                      select e).Count();

        return (from e in _session.Linq<Event>()
                where e.IsActive
                select e)
            .Skip(skip)
            .Take(pageSize)
            .ToList();
    }

NHibernate.QueryException: could not resolve property: YearOfEvent of: ....Event

FWIW, I've blurred out the name of the project. ;)

Any idea how to get this query working?

Thanks!
-Steve

EDIT:
Here's my mapping class:

public class EventMap : ClassMap<Event>
{
    public EventMap()
    {
        Table("tbl_event");
        Id(x => x.Id, "eventId");
        Map(x => x.DateOfEvent, "dateOfEvent");
        Map(x => x.Description, "description");
        Map(x => x.Title, "title");
        Map(x => x.Location, "location");
        Map(x => x.State, "state");
        Map(x => x.City, "city");
        Map(x => x.Zip, "zip");
        Map(x => x.HasImage, "hasImage");
        Map(x => x.IsActive, "isActive");
    }
}

...and my config:

public Configuration GetConfiguration()
    {
        Configuration configuration;
        var assembly = Assembly.Load(".....Data");
        var fluentConfig = Fluently.Configure()
                            .Database(MySQLConfiguration.Standard.ConnectionString(
                                          c => c.FromConnectionStringWithKey("......")
                                          ))
                            .Mappings(m => m.FluentMappings.AddFromAssembly(assembly));
        configuration = fluentConfig.BuildConfiguration();
        configuration.Properties.Add("hbm2ddl.keywords", "none");
        return configuration;
    }

I also just tried the Criteria API:

return _session.CreateCriteria(typeof (Event))
            .Add(Expression.Eq("IsActive", true))
            .Add(Expression.Eq("YearOfEvent", year))
            .List<Event>();

No workie either.


问:
How to set default_app_config for Django with apps directory structure?
I want to declare default_app_config variable for my app, but I have an error:

django.core.exceptions.ImproperlyConfigured: Cannot import 'accounts'.
  Check that 'apps.accounts.apps.AccountsConfig.name' is correct.

All my apps is located in directory apps:

```<code>project_name/
apps/
   app1/
   app2/
   ....
   accounts/
</code>```

I am using my apps like this:

```<code>INSTALLED_APPS = [
  # Local Apps
  'apps.category',
  'apps.products',
  'apps.cart',
  'apps.orders',
  'apps.accounts',
  'apps.attributes',
  'apps.pages',
  'apps.compare',
  'apps.filters',
  'apps.brands'
]
</code>```

And now when I want to set default_app_config for my app, I get the error above.

__init__.py in app folder:

```<code>default_app_config = 'apps.accounts.apps.AccountsConfig'
</code>```

apps.py in app folder:

```<code>from django.apps import AppConfig

class AccountsConfig(AppConfig):
    name = 'accounts'
    verbose_name = 'Пользователи'
</code>```

Why I get the error?

答:
AppConfig name is full python path to the application. So try...</p>

```<code>name = 'apps.accounts'
</code>```

Body:
I want to declare default_app_config variable for my app, but I have an error:

django.core.exceptions.ImproperlyConfigured: Cannot import 'accounts'.
  Check that 'apps.accounts.apps.AccountsConfig.name' is correct.

All my apps is located in directory apps:

project_name/
apps/
   app1/
   app2/
   ....
   accounts/

I am using my apps like this:

INSTALLED_APPS = [
  # Local Apps
  'apps.category',
  'apps.products',
  'apps.cart',
  'apps.orders',
  'apps.accounts',
  'apps.attributes',
  'apps.pages',
  'apps.compare',
  'apps.filters',
  'apps.brands'
]

And now when I want to set default_app_config for my app, I get the error above.

__init__.py in app folder:

default_app_config = 'apps.accounts.apps.AccountsConfig'

apps.py in app folder:

from django.apps import AppConfig

class AccountsConfig(AppConfig):
    name = 'accounts'
    verbose_name = 'Пользователи'

Why I get the error?

Body:
AppConfig name is full python path to the application. So try...

name = 'apps.accounts'


问:
Build static binary with cgo, LuaJIT and musl
After reading Statically compiled Go programs, always, even with cgo, using musl I'm trying to use described method to statically link LuaJIT.

Using https://github.com/aarzilli/golua go bindings

Assuming musl and golua are already installed

Go code I try to build:

```<code>package main

import "github.com/aarzilli/golua/lua"
import "fmt"

func test(L *lua.State) int {
    fmt.Println("hello world! from go!")
    return 0
}

func test2(L *lua.State) int {
    arg := L.CheckInteger(-1)
    argfrombottom := L.CheckInteger(1)
    fmt.Print("test2 arg: ")
    fmt.Println(arg)
    fmt.Print("from bottom: ")
    fmt.Println(argfrombottom)
    return 0
}

func main() {
    L := lua.NewState()
    defer L.Close()
    L.OpenLibs()

    L.GetField(lua.LUA_GLOBALSINDEX, "print")
    L.PushString("Hello World!")
    L.Call(1, 0)

    L.PushGoFunction(test)
    L.PushGoFunction(test)
    L.PushGoFunction(test)
    L.PushGoFunction(test)

    L.PushGoFunction(test2)
    L.PushInteger(42)
    L.Call(1, 0)

    L.Call(0, 0)
    L.Call(0, 0)
    L.Call(0, 0)

    // this will fail as we didn't register test2 function
    err := L.DoString("test2(42)")

    fmt.Printf("Ciao %v\n", err)
}
</code>```

Build command with parameters and output:

```<code>$ CC="/usr/local/musl/bin/musl-gcc" go build --ldflags '-linkmode external -extldflags "-static"' basic.go
# command-line-arguments
/usr/local/go/pkg/tool/linux_amd64/link: running /usr/local/musl/bin/musl-gcc failed: exit status 1
/usr/bin/ld: cannot find -lluajit-5.1
collect2: error: ld returned 1 exit status
</code>```

Using LD_DEBUG=all I can get more information (8000+ lines).

My question: what is the problem and how to solve it? I think there can be some hint here but I can't quite grasp it.

I took following steps:

1. Build static LuaJIT library with musl.

```<code>$ make STATIC_CC="/usr/local/musl/bin/musl-gcc" CCOPT="-static -fPIC" BUILDMODE="static"
...
==== Successfully built LuaJIT 2.0.4 ====
</code>```

2. Build dynamic LuaJIT library with musl.

```<code>$ make DYNAMIC_CC="/usr/local/musl/bin/musl-gcc" BUILDMODE="dynamic"
...
==== Successfully built LuaJIT 2.0.4 ====
</code>```

3. Check build.

```<code>$ find . -iname *.a -o -iname *.so
./src/libluajit.a
./src/libluajit.so
</code>```

4. Install it.

```<code>$ sudo make install
...
==== Successfully installed LuaJIT 2.0.4 to /usr/local ====
</code>```

5. Check installation.

```<code>$ pkg-config luajit --cflags
-I/usr/include/luajit-2.0
$ pkg-config luajit --libs
-lluajit-5.1
</code>```

6. Modify golua lua.go file to use hardcoded cgo parameters.

I had problems overriding those values so I simply modify source code.

old C comment with cgo parameters:

```<code>/*
#cgo CFLAGS: -I ${SRCDIR}/lua
#cgo llua LDFLAGS: -llua
#cgo luaa LDFLAGS: -llua -lm -ldl
#cgo linux,!llua,!luaa LDFLAGS: -llua5.1
#cgo darwin,!luaa pkg-config: lua5.1
#cgo freebsd,!luaa LDFLAGS: -llua-5.1
#cgo windows,!llua LDFLAGS: -L${SRCDIR} -llua -lmingwex -lmingw32
#include <lua.h>
#include <stdlib.h>
#include "golua.h"
*/
import "C"
</code>```

new:

```<code>/*
#cgo CFLAGS: -I/usr/include/luajit-2.0 -I${SRCDIR}/lua
#cgo LDFLAGS: -lluajit-5.1
#include <lua.h>
#include <stdlib.h>
#include "golua.h"
*/
import "C"
</code>```

7. Build some example

As shown at the beggining of question.

Where LuaJIT got installed:

```<code>$ find / -iname libluajit* 2> /dev/null
/usr/local/lib/libluajit-5.1.so.2
/usr/local/lib/libluajit-5.1.a
/usr/local/lib/libluajit-5.1.so
/usr/local/lib/libluajit-5.1.so.2.0.4
/usr/lib/libluajit-5.1.so.2.0.5
/usr/lib/libluajit-5.1.so.2
/usr/lib/libluajit-5.1.a
/usr/lib/libluajit-5.1.so
/usr/lib/libluajit.s
</code>```

EDIT 1

I've followed @putu's comment and changed #cgo LDFLAGS to

```<code>$ CC="/usr/local/musl/bin/musl-gcc" go build --ldflags '-linkmode external -extldflags "-static"' basic.go
# command-line-arguments
/usr/local/go/pkg/tool/linux_amd64/link: running /usr/local/musl/bin/musl-gcc failed: exit status 1
/usr/bin/ld: cannot find -lluajit-5.1
collect2: error: ld returned 1 exit status
</code>```0

now I have

```<code>$ CC="/usr/local/musl/bin/musl-gcc" go build --ldflags '-linkmode external -extldflags "-static"' basic.go
# command-line-arguments
/usr/local/go/pkg/tool/linux_amd64/link: running /usr/local/musl/bin/musl-gcc failed: exit status 1
/usr/bin/ld: cannot find -lluajit-5.1
collect2: error: ld returned 1 exit status
</code>```1

答:
@putu pointed me to the right direction, all I had to do was tune CFLAGS to include musl.

Cleaned up C comment in lua.go:

```<code>/*
#cgo CFLAGS: -I/usr/include/luajit-2.0 -I/usr/local/musl/include/
#cgo LDFLAGS: -L/usr/local/lib -lluajit-5.1
#include <lua.h>
#include <stdlib.h>
#include "golua.h"
*/
import "C"
</code>```

Looks like everything builds just fine:

```<code>$ CC="/usr/local/musl/bin/musl-gcc" go build --ldflags '-linkmode external -extldflags "-static"' basic.go
$ file basic
basic: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, not stripped
$ ./basic
Hello World!
test2 arg: 42
from bottom: 42
hello world! from go!
hello world! from go!
hello world! from go!
Ciao [string "test2(42)"]:1: attempt to call global 'test2' (a nil value)
</code>```

Body:
After reading Statically compiled Go programs, always, even with cgo, using musl I'm trying to use described method to statically link LuaJIT.

Using https://github.com/aarzilli/golua go bindings

Assuming musl and golua are already installed

Go code I try to build:

package main

import "github.com/aarzilli/golua/lua"
import "fmt"

func test(L *lua.State) int {
    fmt.Println("hello world! from go!")
    return 0
}

func test2(L *lua.State) int {
    arg := L.CheckInteger(-1)
    argfrombottom := L.CheckInteger(1)
    fmt.Print("test2 arg: ")
    fmt.Println(arg)
    fmt.Print("from bottom: ")
    fmt.Println(argfrombottom)
    return 0
}

func main() {
    L := lua.NewState()
    defer L.Close()
    L.OpenLibs()

    L.GetField(lua.LUA_GLOBALSINDEX, "print")
    L.PushString("Hello World!")
    L.Call(1, 0)

    L.PushGoFunction(test)
    L.PushGoFunction(test)
    L.PushGoFunction(test)
    L.PushGoFunction(test)

    L.PushGoFunction(test2)
    L.PushInteger(42)
    L.Call(1, 0)

    L.Call(0, 0)
    L.Call(0, 0)
    L.Call(0, 0)

    // this will fail as we didn't register test2 function
    err := L.DoString("test2(42)")

    fmt.Printf("Ciao %v\n", err)
}

Build command with parameters and output:

$ CC="/usr/local/musl/bin/musl-gcc" go build --ldflags '-linkmode external -extldflags "-static"' basic.go
# command-line-arguments
/usr/local/go/pkg/tool/linux_amd64/link: running /usr/local/musl/bin/musl-gcc failed: exit status 1
/usr/bin/ld: cannot find -lluajit-5.1
collect2: error: ld returned 1 exit status

Using LD_DEBUG=all I can get more information (8000+ lines).

My question: what is the problem and how to solve it? I think there can be some hint here but I can't quite grasp it.

I took following steps:

1. Build static LuaJIT library with musl.

$ make STATIC_CC="/usr/local/musl/bin/musl-gcc" CCOPT="-static -fPIC" BUILDMODE="static"
...
==== Successfully built LuaJIT 2.0.4 ====

2. Build dynamic LuaJIT library with musl.

$ make DYNAMIC_CC="/usr/local/musl/bin/musl-gcc" BUILDMODE="dynamic"
...
==== Successfully built LuaJIT 2.0.4 ====

3. Check build.

$ find . -iname *.a -o -iname *.so
./src/libluajit.a
./src/libluajit.so

4. Install it.

$ sudo make install
...
==== Successfully installed LuaJIT 2.0.4 to /usr/local ====

5. Check installation.

$ pkg-config luajit --cflags
-I/usr/include/luajit-2.0
$ pkg-config luajit --libs
-lluajit-5.1

6. Modify golua lua.go file to use hardcoded cgo parameters.

I had problems overriding those values so I simply modify source code.

old C comment with cgo parameters:

/*
#cgo CFLAGS: -I ${SRCDIR}/lua
#cgo llua LDFLAGS: -llua
#cgo luaa LDFLAGS: -llua -lm -ldl
#cgo linux,!llua,!luaa LDFLAGS: -llua5.1
#cgo darwin,!luaa pkg-config: lua5.1
#cgo freebsd,!luaa LDFLAGS: -llua-5.1
#cgo windows,!llua LDFLAGS: -L${SRCDIR} -llua -lmingwex -lmingw32
#include <lua.h>
#include <stdlib.h>
#include "golua.h"
*/
import "C"

new:

/*
#cgo CFLAGS: -I/usr/include/luajit-2.0 -I${SRCDIR}/lua
#cgo LDFLAGS: -lluajit-5.1
#include <lua.h>
#include <stdlib.h>
#include "golua.h"
*/
import "C"

7. Build some example

As shown at the beggining of question.

Where LuaJIT got installed:

$ find / -iname libluajit* 2> /dev/null
/usr/local/lib/libluajit-5.1.so.2
/usr/local/lib/libluajit-5.1.a
/usr/local/lib/libluajit-5.1.so
/usr/local/lib/libluajit-5.1.so.2.0.4
/usr/lib/libluajit-5.1.so.2.0.5
/usr/lib/libluajit-5.1.so.2
/usr/lib/libluajit-5.1.a
/usr/lib/libluajit-5.1.so
/usr/lib/libluajit.s

EDIT 1

I've followed @putu's comment and changed #cgo LDFLAGS to

#cgo LDFLAGS: -L/usr/local/lib -lluajit-5.1

now I have

$ CC="/usr/local/musl/bin/musl-gcc" go build --ldflags '-linkmode external -extldflags "-static -fPIC"' basic.go
# command-line-arguments
/usr/local/go/pkg/tool/linux_amd64/link: running /usr/local/musl/bin/musl-gcc failed: exit status 1
/tmp/go-link-916770907/000000.o: In function `printf':
/usr/include/x86_64-linux-gnu/bits/stdio2.h:104: undefined reference to `__printf_chk'
collect2: error: ld returned 1 exit status

Body:
@putu pointed me to the right direction, all I had to do was tune CFLAGS to include musl.

Cleaned up C comment in lua.go:

/*
#cgo CFLAGS: -I/usr/include/luajit-2.0 -I/usr/local/musl/include/
#cgo LDFLAGS: -L/usr/local/lib -lluajit-5.1
#include <lua.h>
#include <stdlib.h>
#include "golua.h"
*/
import "C"

Looks like everything builds just fine:

$ CC="/usr/local/musl/bin/musl-gcc" go build --ldflags '-linkmode external -extldflags "-static"' basic.go
$ file basic
basic: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, not stripped
$ ./basic
Hello World!
test2 arg: 42
from bottom: 42
hello world! from go!
hello world! from go!
hello world! from go!
Ciao [string "test2(42)"]:1: attempt to call global 'test2' (a nil value)


问:
What's the difference between the lang attribute and the <meta http-equiv="Content-Language" content="en-US"> tag?
I was wondering what's the significance of using the "lang" attribute and how that differs from using the meta "Content-Language" tag?

Consider the following code:

```<code><html lang="en">
    <head>
        <meta http-equiv="Content-Language" content="en-US">
    </head>...
</code>```

My assumption is that the browser is reading the meta tag's value, but the DOM is concerned with the "lang" attribute. Is this correct? Are there any nuances I'm unaware of?

答:
They mean the same thing — setting the language of the content in question — however the lang attribute has a higher precedence. See 8.1.2 Inheritance of language codes. They handle different use cases — the lang attribute can be set exempla gratis on an individual element, while the Content-Language header can be configured globally by the server to apply to a whole set of documents.

Your examples show two equivalent ways to set the language of the html element, but since the lang attribute takes precedence, the value will be "en" and not "en-US".

Body:
I was wondering what's the significance of using the "lang" attribute and how that differs from using the meta "Content-Language" tag?

Consider the following code:

        <meta http-equiv="Content-Language" content="en-US">
    ...

My assumption is that the browser is reading the meta tag's value, but the DOM is concerned with the "lang" attribute. Is this correct? Are there any nuances I'm unaware of?

Body:
They mean the same thing — setting the language of the content in question — however the lang attribute has a higher precedence. See 8.1.2 Inheritance of language codes. They handle different use cases — the lang attribute can be set <i lang=la>exempla gratis</i> on an individual element, while the Content-Language header can be configured globally by the server to apply to a whole set of documents.

Your examples show two equivalent ways to set the language of the html element, but since the lang attribute takes precedence, the value will be "en" and not "en-US".


问:
LFS: Git credentials for..XXXX..not found. Your user name must be of the form DOMAIN\user
So we are trying to setup GIT LFS with on premises TFS and we are having a couple of errors. The errors and setup are described below:

Setup:

1) On-premises TFS 2017 w/Update 1

2) Visual Studio 2015 w/Update 3

3) Atlassian SourceTree (Git Client)

4) GIT LFS is installed on the developer's system

5) The Git Credential Manager for Windows (GCM)

Errors:

Going to Tools->Options->[Git Tab] in SourceTree and selecting [Use System Git] and trying to checkout a version of the file from history results in the following error:

git-lfs/2.0.1 (GitHub; windows amd64; go 1.8; git 678cdbd4) git
  version 2.12.1.windows.1

$ git-lfs.exe filter-process Error downloading object: Framework4.dll
  (ef57f778c9fd50b27144784cd1df55b1b014d564ad6d8d726b156748219b8e5f)

Smudge error: Error downloading Framework4.dll
  (ef57f778c9fd50b27144784cd1df55b1b014d564ad6d8d726b156748219b8e5f):
  batch response: Your user name must be of the form DOMAIN\user. It is
  currently USR123

Going to Tools->Options->[Git Tab] in SourceTree and selecting [Use Embedded Git] and trying to checkout a version of the file from history results in the following error:

git-lfs/1.5.2 (GitHub; windows 386; go 1.7.3; git 547a06aa) git
  version 2.10.2.windows.1

$ git-lfs.exe smudge -- Framework4.dll Error downloading object:
  Framework4.dll
  (ef57f778c9fd50b27144784cd1df55b1b014d564ad6d8d726b156748219b8e5f)

Smudge error: Error downloading
  ef57f778c9fd50b27144784cd1df55b1b014d564ad6d8d726b156748219b8e5f: LFS:
  Git credentials for
  http://localhost:8080/tfs/DefaultCollection/Common/_git/Common%20References
  not found.: LFS: Git credentials for
  http://localhost:8080/tfs/DefaultCollection/Common/_git/Common%20References
  not found.

What I have researched and tried:

Folks recommended using "The Git Credential Manager for Windows (GCM)" to store and manage credentials. This was installed with the latest git version. But the errors still persists.

Tried it without having installed "The Git Credential Manager for Windows (GCM)" still the error happens.

Updated Git versions to the latest. Tried git-lfs/1.5.2 and git-lfs/2.0.1. But no go.

Additional error info on the Environment:

ENV:

LocalWorkingDir=C:\Users\USR123\Documents\GitCloneTest\Common\References2
  LocalGitDir=C:\Users\USR123\Documents\GitCloneTest\Common\References2.git
  LocalGitStorageDir=C:\Users\USR123\Documents\GitCloneTest\Common\References2.git
  LocalMediaDir=C:\Users\USR123\Documents\GitCloneTest\Common\References2.git\lfs\objects
  LocalReferenceDir=
  TempDir=C:\Users\USR123\Documents\GitCloneTest\Common\References2.git\lfs\tmp
  ConcurrentTransfers=1 TusTransfers=false BasicTransfersOnly=false
  BatchTransfer=true SkipDownloadErrors=false FetchRecentAlways=false
  FetchRecentRefsDays=7 FetchRecentCommitsDays=0
  FetchRecentRefsIncludeRemotes=true PruneOffsetDays=3
  PruneVerifyRemoteAlways=false PruneRemoteName=origin
  AccessDownload=ntlm AccessUpload=ntlm DownloadTransfers=basic
  UploadTransfers=basic GIT_CONFIG_PARAMETERS='color.branch=false'
  'color.diff=false' 'color.status=false' 'diff.mnemonicprefix=false'
  'core.quotepath=false' GIT_DIR=.git GIT_LFS_PATH=C:\Program Files\Git
  LFS GIT_PAGER=cat GIT_PREFIX=

Any ideas on how to fix the credential / authentication errors above?

Thank you.

答:
This error comes from LFS extension if you have logged in to TFS without specifying domain name, and you are trying to push a large file.
Go to Control Panel\User Accounts\Credential Manager, Windows Credentials tab and remove credentials stored for TFS server.
When you git push again from command line, you will be prompted for your credentials. Specify your user name with the domain: DOMAIN\USER</p>


问:
HTTPContext for webservices
HttpContext.Current.Request.ServerVariables["SERVER_PORT"]
HttpContext.Current.Request.ServerVariables["SERVER_PORT_SECURE"]
HttpContext.Current.Request.ServerVariables["SERVER_NAME"]
HttpContext.Current.Request.ApplicationPath

I want to access these value via a webservice -C#, whenever I call these values in webservice I get null for all of the above, where as above works for web pages (aspx).

答:
have you tried to define your method with EnableSession at true?</p>

```<code>[WebMethod(EnableSession = true)]
    public string your_public_method(your_params)
    { [...] }
</code>```

Title: HTTPContext for webservices

Body:
have you tried to define your method with EnableSession at true?

[WebMethod(EnableSession = true)]
    public string your_public_method(your_params)
    { [...] }


问:
Extract the sub string from end offline to a special character in batch file
HI i am trying to get the sub string ZoomIn10X,ZoomIn20X,ZoomIn30X etc, from a file which contain following lines below and out put that to another file

```<code>Job Name : STANALONE/1234/JobId/Date/ZoomIn10X

Job Name : STANALONE/1234/JobId/Date/ZoomIn20X

Job Name : STANALONE/JobId/Date/ZoomIn30X

Job Name : STANALONE/1234/JobId/Date/ZoomIn40X

Job Name : STANALONE/1234/Date/ZoomIn10X
</code>```

i Have tried

```<code>for /F "tokens=*" %%A in (input.txt) do (

   echo %%A r "/" "\n" %%A | tail -1 >> output.txt

)
</code>```

but its not working as properly.Can you please help

答:
on unix, with perl

```<code>perl -pe 's@.*/@@' input.txt
</code>```

see perl -h for options and perlop regex for more details.
habitually substitute expressions are written with a / forward slash delimiter but any other character can be used as in sed. here using @ to avoid escaping /.

or with shell language bash (slower because of bash read)

```<code>while read -r line; do
    echo "${line##*/}"
done <input.txt
</code>```

see bash variable expansion. here ## to remove the longest prefix.

Body:
HI i am trying to get the sub string ZoomIn10X,ZoomIn20X,ZoomIn30X etc, from a file which contain following lines below and out put that to another file

Job Name : STANALONE/1234/JobId/Date/ZoomIn10X

Job Name : STANALONE/1234/JobId/Date/ZoomIn20X

Job Name : STANALONE/JobId/Date/ZoomIn30X

Job Name : STANALONE/1234/JobId/Date/ZoomIn40X

Job Name : STANALONE/1234/Date/ZoomIn10X

i Have tried

for /F "tokens=*" %%A in (input.txt) do (

   echo %%A r "/" "\n" %%A | tail -1 >> output.txt

)

but its not working as properly.Can you please help

Body:
on unix, with perl

perl -pe 's@.*/@@' input.txt

see perl -h for options and perlop regex for more details.
habitually substitute expressions are written with a / forward slash delimiter but any other character can be used as in sed. here using @ to avoid escaping /.

or with shell language bash (slower because of bash read)

while read -r line; do
    echo "${line##*/}"
done <input.txt

see bash variable expansion. here ## to remove the longest prefix.


问:
Spark & Maven: SecurityException: Invalid Signature file digest for Manifest
I am running into an issue with the following error when submitting my Spark application that is copy and pasted below. I did some googling first on the issue and determining it was likely an issue with a signature jar that was being loaded as a dependency on my jar build process.  So I altered my POM to filter and remove it from the dependencies.  However even after I did that the jar still seems to be reporting back Invalid Signature file digest.

I am building my jar via Build > Build Artifacts via IntelliJ IDE.

I created my artifact via File > Project Structure > Artifacts > Extract to the target Jar.

Has anyone compiled a Spark application in Maven & the intellij IDE and provide me steps with how to do this properly?

```<code>java.lang.SecurityException: Invalid signature file digest for Manifest main att                                                                                ributes
    at sun.security.util.SignatureFileVerifier.processImpl(SignatureFileVeri                                                                                fier.java:286)
    at sun.security.util.SignatureFileVerifier.process(SignatureFileVerifier                                                                                .java:239)
    at java.util.jar.JarVerifier.processEntry(JarVerifier.java:307)
    at java.util.jar.JarVerifier.update(JarVerifier.java:218)
    at java.util.jar.JarFile.initializeVerifier(JarFile.java:345)
    at java.util.jar.JarFile.getInputStream(JarFile.java:412)
    at sun.misc.JarIndex.getJarIndex(JarIndex.java:137)
    at sun.misc.URLClassPath$JarLoader$1.run(URLClassPath.java:674)
    at sun.misc.URLClassPath$JarLoader$1.run(URLClassPath.java:666)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.misc.URLClassPath$JarLoader.ensureOpen(URLClassPath.java:665)
    at sun.misc.URLClassPath$JarLoader.<init>(URLClassPath.java:638)
    at sun.misc.URLClassPath$3.run(URLClassPath.java:366)
    at sun.misc.URLClassPath$3.run(URLClassPath.java:356)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.misc.URLClassPath.getLoader(URLClassPath.java:355)
    at sun.misc.URLClassPath.getLoader(URLClassPath.java:332)
    at sun.misc.URLClassPath.getResource(URLClassPath.java:198)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:358)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:270)
    at org.apache.spark.deploy.SparkSubmit$.launch(SparkSubmit.scala:351)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:77)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
</code>```

POM

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.analysis</groupId>
<artifactId>sentiment</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SENTIMENTTWITTER</name>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>2.4</version>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>2.3</version>
            <configuration>
                <createDependencyReducedPom>false</createDependencyReducedPom>
                <filters>
                    <filter>
                        <artifact>*:*</artifact>
                        <excludes>
                            <exclude>META-INF/*.SF</exclude>
                            <exclude>META-INF/*.DSA</exclude>
                            <exclude>META-INF/*.RSA</exclude>
                        </excludes>
                    </filter>
                </filters>
            </configuration>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                    <configuration>
                        <transformers>
                            <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                                <resource>resource.conf</resource>
                            </transformer>
                            <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
                            <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                <mainClass>com.verizon.npi.sentiment.MainApp</mainClass>
                            </transformer>
                        </transformers>
                    </configuration>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.12.4</version>
            <configuration>
                <includes>
                    <include>**/*.class</include>
                </includes>
            </configuration>
        </plugin>
    </plugins>
</build>

<dependencies>
        <dependency>
            <groupId>com.sparkjava</groupId>
            <artifactId>spark-core</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-streaming-kafka_2.10</artifactId>
            <version>1.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-core_2.10</artifactId>
            <version>1.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-streaming_2.10</artifactId>
            <version>1.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-hive_2.10</artifactId>
            <version>1.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-sql_2.10</artifactId>
            <version>1.2.1</version>
        </dependency>

    </dependencies>
</code>```

答: To delete the META-INF* file manually, there is another try: zip -d .jar META-INF/.RSA META-INF/.DSA META-INF/*.SF

Body:
I am running into an issue with the following error when submitting my Spark application that is copy and pasted below. I did some googling first on the issue and determining it was likely an issue with a signature jar that was being loaded as a dependency on my jar build process.  So I altered my POM to filter and remove it from the dependencies.  However even after I did that the jar still seems to be reporting back Invalid Signature file digest.

I am building my jar via Build > Build Artifacts via IntelliJ IDE.

I created my artifact via File > Project Structure > Artifacts > Extract to the target Jar.

Has anyone compiled a Spark application in Maven & the intellij IDE and provide me steps with how to do this properly?

java.lang.SecurityException: Invalid signature file digest for Manifest main att                                                                                ributes
    at sun.security.util.SignatureFileVerifier.processImpl(SignatureFileVeri                                                                                fier.java:286)
    at sun.security.util.SignatureFileVerifier.process(SignatureFileVerifier                                                                                .java:239)
    at java.util.jar.JarVerifier.processEntry(JarVerifier.java:307)
    at java.util.jar.JarVerifier.update(JarVerifier.java:218)
    at java.util.jar.JarFile.initializeVerifier(JarFile.java:345)
    at java.util.jar.JarFile.getInputStream(JarFile.java:412)
    at sun.misc.JarIndex.getJarIndex(JarIndex.java:137)
    at sun.misc.URLClassPath$JarLoader$1.run(URLClassPath.java:674)
    at sun.misc.URLClassPath$JarLoader$1.run(URLClassPath.java:666)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.misc.URLClassPath$JarLoader.ensureOpen(URLClassPath.java:665)
    at sun.misc.URLClassPath$JarLoader.<init>(URLClassPath.java:638)
    at sun.misc.URLClassPath$3.run(URLClassPath.java:366)
    at sun.misc.URLClassPath$3.run(URLClassPath.java:356)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.misc.URLClassPath.getLoader(URLClassPath.java:355)
    at sun.misc.URLClassPath.getLoader(URLClassPath.java:332)
    at sun.misc.URLClassPath.getResource(URLClassPath.java:198)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:358)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:270)
    at org.apache.spark.deploy.SparkSubmit$.launch(SparkSubmit.scala:351)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:77)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)

POM

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.analysis</groupId>
<artifactId>sentiment</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SENTIMENTTWITTER</name>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>2.4</version>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>2.3</version>
            <configuration>
                <createDependencyReducedPom>false</createDependencyReducedPom>
                <filters>
                    <filter>
                        <artifact>*:*</artifact>
                        <excludes>
                            <exclude>META-INF/*.SF</exclude>
                            <exclude>META-INF/*.DSA</exclude>
                            <exclude>META-INF/*.RSA</exclude>
                        </excludes>
                    </filter>
                </filters>
            </configuration>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                    <configuration>
                        <transformers>
                            <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                                <resource>resource.conf</resource>
                            </transformer>
                            <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
                            <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                <mainClass>com.verizon.npi.sentiment.MainApp</mainClass>
                            </transformer>
                        </transformers>
                    </configuration>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.12.4</version>
            <configuration>
                <includes>
                    <include>**/*.class</include>
                </includes>
            </configuration>
        </plugin>
    </plugins>
</build>

<dependencies>
        <dependency>
            <groupId>com.sparkjava</groupId>
            <artifactId>spark-core</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-streaming-kafka_2.10</artifactId>
            <version>1.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-core_2.10</artifactId>
            <version>1.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-streaming_2.10</artifactId>
            <version>1.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-hive_2.10</artifactId>
            <version>1.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-sql_2.10</artifactId>
            <version>1.2.1</version>
        </dependency>

    </dependencies>