问:
SonarQube 5.6.2 plugin - custom Extension point does not get executed
I have added an interface 'FileGenerator' as an extension point and implementation class 'JavaFileGenerator' is added implementing to the interface/extension point however the implementation class is not getting executed.
I have below classes in my sonar plugin

MyPlugin class implementing Plugin interface where I have registered
my extension class 'JavaFileGenerator'

FileGenerator is annotated with @ExtensionPoint,
@BatchSide/@ServerSide

In JavaFileGenerator class FileSystem is injected in constructor of
the class

```<code> public class MyPlugin implements Plugin {
  @Override
  public void define(Context context) {
   context.addExtension(JavaFileGenerator.class); }
}
    @BatchSide
    @ExtensionPoint
     public interface FileGenerator {
        void generateFile();
     }
     public class JavaFileGenerator implements FileGenerator{
     private FileSystem fileSystem;

        public JavaFileGenerator(final FileSystem fileSystem){
            this.fileSystem=fileSystem; }
         @Override
         public void generateFile() { ... }
        }
</code>```

JavaFileGenerator class does not get executed. Anybody has any idea about this?

答:
for example, for action at the end of analyse on client side you can write a plugin as  :</p>

```<code>@BatchSide
public class XXXPostJob implements PostJob {

@Override
public void describe(PostJobDescriptor descriptor) {
    descriptor.name("-- post client side analyse sonarqube plugin --");
}

@Override
public void execute(PostJobContext context) {

// your business here ...

    }
</code>```

Body:
I have added an interface 'FileGenerator' as an extension point and implementation class 'JavaFileGenerator' is added implementing to the interface/extension point however the implementation class is not getting executed.
I have below classes in my sonar plugin

MyPlugin class implementing Plugin interface where I have registered
my extension class 'JavaFileGenerator'

FileGenerator is annotated with @ExtensionPoint,
@BatchSide/@ServerSide

In JavaFileGenerator class FileSystem is injected in constructor of
the class

 public class MyPlugin implements Plugin {
  @Override
  public void define(Context context) {
   context.addExtension(JavaFileGenerator.class); }
}
    @BatchSide
    @ExtensionPoint
     public interface FileGenerator {
        void generateFile();
     }
     public class JavaFileGenerator implements FileGenerator{
     private FileSystem fileSystem;

        public JavaFileGenerator(final FileSystem fileSystem){
            this.fileSystem=fileSystem; }
         @Override
         public void generateFile() { ... }
        }

JavaFileGenerator class does not get executed. Anybody has any idea about this?

Body:
for example, for action at the end of analyse on client side you can write a plugin as  :

@BatchSide
public class XXXPostJob implements PostJob {

@Override
public void describe(PostJobDescriptor descriptor) {
    descriptor.name("-- post client side analyse sonarqube plugin --");
}

@Override
public void execute(PostJobContext context) {

// your business here ...

    }


来源: stackexchange

问:
calling external js file from html template
i'm having a problem during the onclick button calling an external js file, i'm getting error on the onclick function is not defined.

```<code><table class="table table-striped table-bordered table-nonfluid" style='width: auto;'>
        <tr>
            <td>Name: </td>
            <td><input type='text' name='ref_name' id='ref_name'></td>
        </tr>
        <tr>
            <td>Description: </td>
            <td><input type='text' name='ref_desc'></td>
        </tr>
        <tr>
            <td colspan='2' align='right'><button type='button' class='btn btn-primary' id="btn_save" onclick="saveMst();">Save</button></td> //this is the line onclick "saveMst()" is not defined when calling external js file.
            <input type='hidden' name='ref_type' value='1'>
        </tr>
    </table>
</code>```

This is the scripts I defined in php:

```<code>$scripts = '<script type="text/javascript" src="js/references.js"></script>';

$smarty->assign('script', $scripts);
</code>```

Here are the references.js code

```<code>function saveMst(){
sessionExpired();
if(mstValidate()==true){
    var url= "ref_deparment.php?do=save&save=mst&ref_name="+encodeURIComponent(ref_name)+
             "&ref_desc="+encodeURIComponent(ref_desc);
    alert (url);return false;
    topMsgDisplay('Saving... Please wait...');
    var myAjax = new Ajax.Request(url, { method: 'get', onComplete: function(oR){
        hideOverlay();
        r = oR.responseText.split('||');
        //alert (oR.responseText);
        if(r[0]==1) {
            $('btn_save').style.display = 'none';
            alert('Record had been save sucessfully!');
            getEdit(r[1]);
        }
        else alert(r[1]);
    } });
}
}

function mstValidate(){
borderpass = '1px solid #ccc';
borderfail = '1px solid #f00';

shortdesc = $('ref_name').value;
longdesc = $('ref_desc').value;

err_msg = 'You\'ve encounter the below error:\n';
pass=true;

if(shortdesc.length==0){
    pass=false;
    err_msg += '* Name field is left empty.\n';
    $('ref_name').style.border = borderfail;
}else {
    $('ref_name').style.border = borderpass;
}

if(longdesc.length==0){
    pass=false;
    err_msg += '* Description field is left empty.\n';
    $('ref_desc').style.border = borderfail;
}else {
    $('ref_desc').style.border = borderpass;
}

if(pass==false){
    alert(err_msg);
    return false;
}else return true;
}
</code>```

答:
You can move the event handler from the inline html to your javascript file. You should put that in a block that executes when the DOM is loaded so that you can be sure all elements you are attaching handlers to, exist.

As you seem to be using jquery, that would look something like:

```<code>$(function(){
    // Document ready
    $('#btn_save').on('click', function() {
        saveMst();
    });
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i'm having a problem during the onclick button calling an external js file, i'm getting error on the onclick function is not defined.

            Name:
            <input type='text' name='ref_name' id='ref_name'>

            Description:
            <input type='text' name='ref_desc'>

            <button type='button' class='btn btn-primary' id="btn_save" onclick="saveMst();">Save</button>	 //this is the line onclick "saveMst()" is not defined when calling external js file.
            <input type='hidden' name='ref_type' value='1'>

This is the scripts I defined in php:

$scripts = '';

$smarty->assign('script', $scripts);

Here are the references.js code

function saveMst(){
sessionExpired();
if(mstValidate()==true){
    var url= "ref_deparment.php?do=save&save=mst&ref_name="+encodeURIComponent(ref_name)+
             "&ref_desc="+encodeURIComponent(ref_desc);
    alert (url);return false;
    topMsgDisplay('Saving... Please wait...');
    var myAjax = new Ajax.Request(url, { method: 'get', onComplete: function(oR){
        hideOverlay();
        r = oR.responseText.split('||');
        //alert (oR.responseText);
        if(r[0]==1) {
            $('btn_save').style.display = 'none';
            alert('Record had been save sucessfully!');
            getEdit(r[1]);
        }
        else alert(r[1]);
    } });
}
}

function mstValidate(){
borderpass = '1px solid #ccc';
borderfail = '1px solid #f00';

shortdesc = $('ref_name').value;
longdesc = $('ref_desc').value;

err_msg = 'You\'ve encounter the below error:\n';
pass=true;

if(shortdesc.length==0){
    pass=false;
    err_msg += '* Name field is left empty.\n';
    $('ref_name').style.border = borderfail;
}else {
    $('ref_name').style.border = borderpass;
}

if(longdesc.length==0){
    pass=false;
    err_msg += '* Description field is left empty.\n';
    $('ref_desc').style.border = borderfail;
}else {
    $('ref_desc').style.border = borderpass;
}

if(pass==false){
    alert(err_msg);
    return false;
}else return true;
}

Body:
You can move the event handler from the inline html to your javascript file. You should put that in a block that executes when the DOM is loaded so that you can be sure all elements you are attaching handlers to, exist.

As you seem to be using jquery, that would look something like:

$(function(){
    // Document ready
    $('#btn_save').on('click', function() {
        saveMst();
    });
});


问:
what is difference between sbt/scala-seed.g8 and scala/scala-seed.g8?
The sbt-hello uses sbt new command to quickly setup a project:

```<code>sbt new sbt/scala-seed.g8
</code>```

However, I cannot find sbt/scala-seed.g8 in giter8-templates.

what is difference between sbt/scala-seed.g8 and scala/scala-seed.g8? Is it an alias?

答:
giter8 templates use github to create a project:

you can see the raw templates:

for scala/scala-seed.g8

for sbt/scala-seed.g8

Body:
The sbt-hello uses sbt new command to quickly setup a project:

sbt new sbt/scala-seed.g8

However, I cannot find sbt/scala-seed.g8 in giter8-templates.

what is difference between sbt/scala-seed.g8 and scala/scala-seed.g8? Is it an alias?


问:
Is it possible to ignore an exception?
In Java, is it possible to make a method that has a throws statement to be not checked.

For example:

```<code>public class TestClass {
    public static void throwAnException() throws Exception {
        throw new Exception();
    }
    public static void makeNullPointer() {
        Object o = null;
        o.equals(0);//NullPointerException
    }
    public static void exceptionTest() {
        makeNullPointer(); //The compiler allows me not to check this
        throwAnException(); //I'm forced to handle the exception, but I don't want to
    }
}
</code>```

答:
It is not advisable to avoid an exception with an empty catch block even though you are completely sure that is not going to fail under any circumstance. Sometimes, we are not aware of the human factor.

If you are sure that an exception is very unlikely to happen (if not impossible) you should create your own Exception and and wrap the unexpected exception in it.

For example:

```<code>private class UnlikelyException extends RuntimeException {
    public UnlikelyException (Exception e){
        super (e);
    }
}
</code>```

Then wrap your code with a try-catch block and throw your exception, which you don't have to catch

```<code>try {
    // Your code
} catch  (Exception e) {
    throw new UnlikelyException(e);
}
</code>```

Title: Is it possible to ignore an exception?

Body:
In Java, is it possible to make a method that has a throws statement to be not checked.

For example:

public class TestClass {
    public static void throwAnException() throws Exception {
        throw new Exception();
    }
    public static void makeNullPointer() {
        Object o = null;
        o.equals(0);//NullPointerException
    }
    public static void exceptionTest() {
        makeNullPointer(); //The compiler allows me not to check this
        throwAnException(); //I'm forced to handle the exception, but I don't want to
    }
}

Body:
It is not advisable to avoid an exception with an empty catch block even though you are completely sure that is not going to fail under any circumstance. Sometimes, we are not aware of the human factor.

If you are sure that an exception is very unlikely to happen (if not impossible) you should create your own Exception and and wrap the unexpected exception in it.

For example:

private class UnlikelyException extends RuntimeException {
    public UnlikelyException (Exception e){
        super (e);
    }
}

Then wrap your code with a try-catch block and throw your exception, which you don't have to catch

try {
    // Your code
} catch  (Exception e) {
    throw new UnlikelyException(e);
}


问:
Why does dreamweaver show an error on this line when the code is valid
Why does Dreamweaver show a red error on this line

```<code><?php $pt=$test->Terms()['Terms'];?>
</code>```

The line is perfectly valid and runs, and does what it is supposed to do, and yet dreamweaver insists that it is an error.

I have a function returning a named array you see, and it works fine on the page.

答: You should check array key existence before referencing to it</p>

Body:
Why does Dreamweaver show a red error on this line

<?php $pt=$test->Terms()['Terms'];?>

The line is perfectly valid and runs, and does what it is supposed to do, and yet dreamweaver insists that it is an error.

I have a function returning a named array you see, and it works fine on the page.


问:
Kodi jsonrpc know if an episode has been see
I trying to retrieve a list of episode of a TV Show on my Kodi jsonrpc api, it return the list of episode but only id and name instead of all attributs show in the doc http://kodi.wiki/view/JSON-RPC_API/v8#Video.Details.Episode

Here is my request :

{"jsonrpc":"2.0","id":1,"method":"VideoLibrary.GetEpisodes","params":{"tvshowid":11}}

And here is the response :

{
  "id": 1,
  "jsonrpc": "2.0",
  "result": {
    "episodes": [
      {
        "episodeid": 303,
        "label": "4x01. Success Failure"
      },
      {
        "episodeid": 318,
        "label": "4x02. Terms of Service"
      },
      {
        "episodeid": 339,
        "label": "4x03. Intellectual Property"
      },
      {
        "episodeid": 354,
        "label": "4x04. Teambuilding Exercise"
      },
      {
        "episodeid": 393,
        "label": "4x05. The Blood Boy"
      },
      {
        "episodeid": 414,
        "label": "4x06. Customer Service"
      },
      {
        "episodeid": 487,
        "label": "4x07. The Patent Troll"
      }
    ],
    "limits": {
      "end": 7,
      "start": 0,
      "total": 7
    }
  }
}

答:
In the params array add this 'properties': ['season', 'episode', 'playcount'] for example

{"jsonrpc":"2.0","id":1,"method":"VideoLibrary.GetEpisodes","params":{"tvshowid":11, "properties": ["season", "episode", "playcount"]}}

This will add the three properties to the response.

ContentLicense: CC BY-SA 4.0


问:
Can I use a variable's value as a new variable in swift?
Is it possible to set a content of a variable as a variable itself? Like for example

```<code>let variable1 = "variable2"
let variable2 = "Hello"
</code>```

What I want is to print the content of variable2 using variable1? i.e I want to print "Hello" using variable1 which has a content named "variable2".

答:
You can, but it might not be the best idea if you already know it's going to be a variable name. It still would work though, just have to be sensible with the naming convention.

This link might help,
https://github.com/raywenderlich/swift-style-guide

Body:
Is it possible to set a content of a variable as a variable itself? Like for example

let variable1 = "variable2"
let variable2 = "Hello"

What I want is to print the content of variable2 using variable1? i.e I want to print "Hello" using variable1 which has a content named "variable2".


问:
Need to know the right way to scan infected website files
My website index.php and htaccess. file got infected and another PHP file of plugin and the website is down now. See the snapshot in this link [https://drive.google.com/open?id=0B6wLmLAtHwZCZnhmV0QzdDMyTW8][1]

could you tell my the way to scan these files? I have scanned with some free antivirus but it is not showing any virus infection. Help to solve this issue.

答:
You need to use Clamav antivirus scanner which can be done via command line.

Download and install it via command line tools. Document for clamav : https://www.clamav.net/documents/installing-clamav


问:
Is It Possible To Migrate From Realm To Sqlite?
For some reasons(mainly large apk size even with ABI splits, anyway) i need to remove Realm completely and use Sqlite without losing data.

I couldn't find a way. It seems the app must continue using Realm, or users will lost their data completely.

Any idea will be appreciated

答:
As i know (not sure) if you are using default RealmConfig, Context.getFilesDir() can return the folder of where default.realm is located. You dont need permission to modify them. You can iterate files under this folder to delete them. Hope it works.

PS : Apache-commons has a great FileUtils.java

Good luck

Emre


问:
Difference between init() and main() method in java
I want to know the difference between init and main method of java </p>

答: The main method is used as an entry point for applications, the init method is used as an entry point for applets and servlets.</p>

ContentLicense: CC BY-SA 2.5


答:
You are directly accessing an array key of a function result. Array dereferencing of function results was implemented in PHP 5.4. See http://php.net/manual/en/language.types.array.php

I'd guess that the syntax checking of Dreamweaver uses a version of PHP < 5.4.

Title: Why does dreamweaver show an error on this line when the code is valid


问:
Amazon Alexa Custom skill: Respond to intent using standard short sound
I'm developing a custom skill. For communication with Alexa, I use Amazon Echo Dot device. Sometimes Alexa answers with a standard short sound in the end. For example, if a session is closed because there was no answer on a question (EXCEEDED_MAX_REPROMPTS) or when some error occurred.

Is it possible to use standard short sounds in response on my custom intents and, if so, how?

答:
yes if you are using 'alexa-app' module you can use the following code:</p>

```<code>  yourSkill.error= function(exception, request, response) {

  response.say('Sorry an error occured ' + error.message);
  };
</code>```

Body:
yes if you are using 'alexa-app' module you can use the following code:

  yourSkill.error= function(exception, request, response) {

  response.say('Sorry an error occured ' + error.message);
  };


问:
How to disable sliding animation in Android TabBar with Xamarin.Forms?
I'm using a TabbedPage, and whenever I select a new Tab, there is a sliding animation. I would like to disable the sliding animation.

There is a Xamarin Sample that does this, without the sliding animation. How can I replicate this?

I'm using a custom ToolBar and a TabBar, and also a FormsAppCompatActivity in my AppActivity.

The Sample provided by Xamarin isn't, so I'm not sure how I can disable these animations.

Thank you

答:
Similar to the Native approach described here. This can be done with a custom renderer:</p>

```<code>[assembly: ExportRenderer(typeof(TabsPage), typeof(TabsPageRenderer))]
namespace App.Droid.Renderers
{
    public class TabsPageRenderer : BadgedTabbedPageRenderer
    {
        ViewPager _viewPager;
        TabLayout _tabLayout;

        protected override void OnElementChanged(ElementChangedEventArgs<TabbedPage> e)
        {
            base.OnElementChanged(e);

            for (int i = 0; i < ChildCount; i++)
            {
                var v = GetChildAt(i);
                if (v is ViewPager)
                    _viewPager = (ViewPager)v;
                else if (v is TabLayout)
                    _tabLayout = (TabLayout)v;
            }

            _viewPager.SetPageTransformer(true, new NoAnimationPageTransformer());

        }

    }

    public class NoAnimationPageTransformer : Java.Lang.Object, Android.Support.V4.View.ViewPager.IPageTransformer
    {
        public void TransformPage(Android.Views.View view, float position)
        {
            if (position < 0)
            {
                view.ScrollX = (int)((float)(view.Width) * position);
            }
            else if (position > 0)
            {
              view.ScrollX = -(int)((float)(view.Width) * -position);
            }
            else
            {
              view.ScrollX = 0;
            }

        }

    }

}
</code>```

Body:
Similar to the Native approach described here. This can be done with a custom renderer:

[assembly: ExportRenderer(typeof(TabsPage), typeof(TabsPageRenderer))]
namespace App.Droid.Renderers
{
    public class TabsPageRenderer : BadgedTabbedPageRenderer
    {
        ViewPager _viewPager;
        TabLayout _tabLayout;

        protected override void OnElementChanged(ElementChangedEventArgs<TabbedPage> e)
        {
            base.OnElementChanged(e);

            for (int i = 0; i < ChildCount; i++)
            {
                var v = GetChildAt(i);
                if (v is ViewPager)
                    _viewPager = (ViewPager)v;
                else if (v is TabLayout)
                    _tabLayout = (TabLayout)v;
            }

            _viewPager.SetPageTransformer(true, new NoAnimationPageTransformer());

        }

    }

    public class NoAnimationPageTransformer : Java.Lang.Object, Android.Support.V4.View.ViewPager.IPageTransformer
    {
        public void TransformPage(Android.Views.View view, float position)
        {
            if (position < 0)
            {
                view.ScrollX = (int)((float)(view.Width) * position);
            }
            else if (position > 0)
            {
              view.ScrollX = -(int)((float)(view.Width) * -position);
            }
            else
            {
              view.ScrollX = 0;
            }

        }

    }

}


问:
How to search for any word in a json file with java
my goal is to program a function (Ri) that returns the number of rows that contain the term i in json file, for that I started by looking for a word that I initialized, but subsequently I don't know how to generalize.
This is my start code:

```<code>public class rit {
private static final String filePath = "D:\\c4\\11\\test.json";
    public static void main(String[] args) throws FileNotFoundException, ParseException, IOException {
        try{
             InputStream ips=new FileInputStream(filePath);
             InputStreamReader ipsr=new InputStreamReader(ips);
             BufferedReader br=new BufferedReader(ipsr);
             String ligne;
                 String mot="feel";
                 int i=1;
                // nombre de lignes  totales contenant le terme
                int nbre=0;
             while ((ligne=br.readLine())!=null){

          try {
            // read the json file
                JSONParser jsonParser = new JSONParser();
            JSONObject jsonObject = (JSONObject) jsonParser.parse(ligne);

               // get a number from the JSON object
            String text =  (String) jsonObject.get("text");

                        if ( text.contains(mot)){
                        nbre++;
                        System.out.println("Mot trouvé a la ligne " + i );
                        i++;

                        }

        } catch (ParseException ex) {
            ex.printStackTrace();
        } catch (NullPointerException ex) {
            ex.printStackTrace();
        }}

               System.out.println("number of lines Which contain the term: " +nbre);
    br.close();
 }
 catch (Exception e){
    System.out.println(e.toString());
 }}}
</code>```

And the output is :

```<code>Mot trouvé a la ligne 1
Mot trouvé a la ligne 2
number of lines Which contain the term: 2
</code>```

If it is possible to generalize, how to do this ?

答:
The String args[] in public static void main(String[] args) are input parameters. Thus, for running java rit.class feel, args would be [feel].

You could make your program expect word (and even filePath) in those input argument :

```<code>public static void main(String[] args) {
    if(args.length != 2){
        // crash the application with an error message
        throw new IllegalArgumentException("Please enter $filePath and $wordToFind as input parameters");
    }
    String filePath = args[0];
    String mot = args[1];
    System.out.println("filePath : "+filePath);
    System.out.println("mot : "+mot);
}
</code>```

Another way to do so is to wait for user input. It's neat because you can wrap it in a loop and reuse it:

```<code>public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in); // used for scanning user input
    while(true){
        System.out.println("please enter a word : ");
        String mot = scanner.nextLine();  // wait for user to input a word and enter
        System.out.println("mot is : "+mot);
    }
}
</code>```

Body:
my goal is to program a function (Ri) that returns the number of rows that contain the term i in json file, for that I started by looking for a word that I initialized, but subsequently I don't know how to generalize.
This is my start code:

public class rit {
private static final String filePath = "D:\\c4\\11\\test.json";
    public static void main(String[] args) throws FileNotFoundException, ParseException, IOException {
        try{
             InputStream ips=new FileInputStream(filePath);
             InputStreamReader ipsr=new InputStreamReader(ips);
             BufferedReader br=new BufferedReader(ipsr);
             String ligne;
                 String mot="feel";
                 int i=1;
                // nombre de lignes  totales contenant le terme
                int nbre=0;
             while ((ligne=br.readLine())!=null){

          try {
            // read the json file
                JSONParser jsonParser = new JSONParser();
            JSONObject jsonObject = (JSONObject) jsonParser.parse(ligne);

               // get a number from the JSON object
            String text =  (String) jsonObject.get("text");

                        if ( text.contains(mot)){
                        nbre++;
                        System.out.println("Mot trouvé a la ligne " + i );
                        i++;

                        }

        } catch (ParseException ex) {
            ex.printStackTrace();
        } catch (NullPointerException ex) {
            ex.printStackTrace();
        }}

               System.out.println("number of lines Which contain the term: " +nbre);
    br.close();
 }
 catch (Exception e){
    System.out.println(e.toString());
 }}}

And the output is :

Mot trouvé a la ligne 1
Mot trouvé a la ligne 2
number of lines Which contain the term: 2

If it is possible to generalize, how to do this ?

Body:
The String args[] in public static void main(String[] args) are input parameters. Thus, for running java rit.class feel, args would be [feel].

You could make your program expect word (and even filePath) in those input argument :

public static void main(String[] args) {
    if(args.length != 2){
        // crash the application with an error message
        throw new IllegalArgumentException("Please enter $filePath and $wordToFind as input parameters");
    }
    String filePath = args[0];
    String mot = args[1];
    System.out.println("filePath : "+filePath);
    System.out.println("mot : "+mot);
}

Another way to do so is to wait for user input. It's neat because you can wrap it in a loop and reuse it:

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in); // used for scanning user input
    while(true){
        System.out.println("please enter a word : ");
        String mot = scanner.nextLine();  // wait for user to input a word and enter
        System.out.println("mot is : "+mot);
    }
}


问:
Postgresql query a weeks worth of data based on a calendar day regardless which one
In PostgreSQL, how could I get the dates of all days in a week, using the date of a single day as input?  For example, imagine a user clicks on on a day in a calendar user interface widget.  That highlights the entire week.

I want to write a query that pulls all rows from a table where a date column matches the date from any day in the highlighted week, regardless of whether the user selected Monday, Wednesday, etc.

答:
Your best option would be date_trunc('week', ts), like in

```<code>WHERE date_trunc('week', ts_col) = date_trunc('week', ?)
</code>```

However, this won't use indexes on ts_col. And date_trunc('week', ts_col) is only index-able if ts_col is timestamp [without time zone]. timestamptz (or timestamp with time zone) is not able to use date_trunc() based expression indexes. But you can make this sargable with:

```<code>WHERE ts_col BETWEEN date_trunc('week', ?) AND date_trunc('week', ?) + interval '1 week'
</code>```

Note that date_trunc('week', ...) uses the ISO concept of a week, i.e. all of its weeks start on Monday. If that's not good enough for you, you can tweak the following expression: date_trunc('day', ts) - interval '1 day' * extract(dow from ts). This will calculate f.ex. the week start when weeks start on Sunday. If you're aiming other than Sunday, just use some math on the expression above, like:

```<code>select date_trunc('day', ts) - interval '1 day' * extract(dow from ts) "sunday",
       date_trunc('week', ts) "monday",
       date_trunc('day', ts) - interval '1 day' * ((extract(dow from ts) + 5)::int % 7) "tuesday",
       date_trunc('day', ts) - interval '1 day' * ((extract(dow from ts) + 4)::int % 7) "wednesday"
</code>```

http://rextester.com/KZX2905

Body:
Your best option would be date_trunc('week', ts), like in

WHERE date_trunc('week', ts_col) = date_trunc('week', ?)

However, this won't use indexes on ts_col. And date_trunc('week', ts_col) is only index-able if ts_col is timestamp [without time zone]. timestamptz (or timestamp with time zone) is not able to use date_trunc() based expression indexes. But you can make this sargable with:

WHERE ts_col BETWEEN date_trunc('week', ?) AND date_trunc('week', ?) + interval '1 week'

Note that date_trunc('week', ...) uses the ISO concept of a week, i.e. all of its weeks start on Monday. If that's not good enough for you, you can tweak the following expression: date_trunc('day', ts) - interval '1 day' * extract(dow from ts). This will calculate f.ex. the week start when weeks start on Sunday. If you're aiming other than Sunday, just use some math on the expression above, like:

select date_trunc('day', ts) - interval '1 day' * extract(dow from ts) "sunday",
       date_trunc('week', ts) "monday",
       date_trunc('day', ts) - interval '1 day' * ((extract(dow from ts) + 5)::int % 7) "tuesday",
       date_trunc('day', ts) - interval '1 day' * ((extract(dow from ts) + 4)::int % 7) "wednesday"

http://rextester.com/KZX2905


问:
Unable to load the specified metadata resource
I am having some serious problems with Entity Framework and I can't seem to figure out whats going on.

I tried many options provided on: MetadataException: Unable to load the specified metadata resource and the famous Craig Stuntz's blog posting located at: http://blogs.teamb.com/craigstuntz/2010/08/13/38628/

I have 3 projects for the sake of brevity:

Funscribe.Data (EDMX file located here)

Funscribe.Console (Console app)

Funscribe.Web (MVC 3 app)

Originally it was just the MVC app and I recently added this new console project.

I copied the connection string from web.config and applied it to my app.config:

```<code><add name="FundirectoryEntities" connectionString="metadata=res://*/Fundirectory.csdl|res://*/Fundirectory.ssdl|res://*/Fundirectory.msl;provider=System.Data.SqlClient;provider connection string="data source=localhost\sqlexpress;initial catalog=Funscribe;user id=sys_Funscribe;password=blah;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
</code>```

My mvc app continues to work, but when I run the console app, i get the dreaded:

"Unable to load the specified metadata resource."

I tried changing the connection string to the wild card setting:

```<code><add name="FundirectoryEntities" connectionString="metadata=res://*/;provider=System.Data.SqlClient;provider connection string="data source=localhost\sqlexpress;initial catalog=Funscribe;user id=sys_Funscribe;password=blah;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
</code>```

I get:
The specified default EntityContainer name 'FundirectoryEntities' could not be found in the mapping and metadata information.

I tried changing it to specify the assembly:

```<code><add name="FundirectoryEntities" connectionString="metadata=res://Funscribe.Data.dll/Fundirectory.csdl|res://Funscribe.Data.dll/Fundirectory.ssdl|res://Funscribe.Data.dll/Fundirectory.msl;provider=System.Data.SqlClient;provider connection string="data source=localhost\sqlexpress;initial catalog=Funscribe;user id=sys_Funscribe;password=blah;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
</code>```

I get:
Unable to resolve assembly 'Funscribe.Data.dll'.

I am lost on what I should do here. I just upgraded this project to Visual Studio 2012 (I introduce this new console app after converting to VS 2012).

I also noticed that the Funscribe.Data.dll is located within the console project's bin folder, i manually deleted these files and watch it get recreated. And what puzzles me is the web app continues to work properly!

All projects are on .NET 4.0. The console app uses .NET 4.0 not the client profile verison.

Any help on this matter is greatly appreciated.

答:
in my case, I delete my EDMX file in project and create it again with a new name, eg. before it was Home_Model, later it is Home_Cost.
when I try to invoke the below code, it has "Unable to load the specified metadata resource." error.
/////

```<code>    using (var currentEntities = new masterEntities())
    {
        currentUser = currentEntities.Home_User.FirstOrDefault(
            x => x.UserLoginAccount == userLoginAccount && x.UserPwd == userPwd);

    }
</code>```

////
so in Web.config, I modify the
metadata configuation from Home_Model to Home_Cost.

then it works.
obviously, VS2015(my version) didn't update web.config when I delete/create edmx.

Body:
I am having some serious problems with Entity Framework and I can't seem to figure out whats going on.

I tried many options provided on: MetadataException: Unable to load the specified metadata resource and the famous Craig Stuntz's blog posting located at: http://blogs.teamb.com/craigstuntz/2010/08/13/38628/

I have 3 projects for the sake of brevity:

Funscribe.Data (EDMX file located here)

Funscribe.Console (Console app)

Funscribe.Web (MVC 3 app)

Originally it was just the MVC app and I recently added this new console project.

I copied the connection string from web.config and applied it to my app.config:

<add name="FundirectoryEntities" connectionString="metadata=res://*/Fundirectory.csdl|res://*/Fundirectory.ssdl|res://*/Fundirectory.msl;provider=System.Data.SqlClient;provider connection string="data source=localhost\sqlexpress;initial catalog=Funscribe;user id=sys_Funscribe;password=blah;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />

My mvc app continues to work, but when I run the console app, i get the dreaded:

"Unable to load the specified metadata resource."

I tried changing the connection string to the wild card setting:

<add name="FundirectoryEntities" connectionString="metadata=res://*/;provider=System.Data.SqlClient;provider connection string="data source=localhost\sqlexpress;initial catalog=Funscribe;user id=sys_Funscribe;password=blah;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />

I get:
The specified default EntityContainer name 'FundirectoryEntities' could not be found in the mapping and metadata information.

I tried changing it to specify the assembly:

<add name="FundirectoryEntities" connectionString="metadata=res://Funscribe.Data.dll/Fundirectory.csdl|res://Funscribe.Data.dll/Fundirectory.ssdl|res://Funscribe.Data.dll/Fundirectory.msl;provider=System.Data.SqlClient;provider connection string="data source=localhost\sqlexpress;initial catalog=Funscribe;user id=sys_Funscribe;password=blah;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />

I get:
Unable to resolve assembly 'Funscribe.Data.dll'.

I am lost on what I should do here. I just upgraded this project to Visual Studio 2012 (I introduce this new console app after converting to VS 2012).

I also noticed that the Funscribe.Data.dll is located within the console project's bin folder, i manually deleted these files and watch it get recreated. And what puzzles me is the web app continues to work properly!

All projects are on .NET 4.0. The console app uses .NET 4.0 not the client profile verison.

Any help on this matter is greatly appreciated.

Body:
in my case, I delete my EDMX file in project and create it again with a new name, eg. before it was Home_Model, later it is Home_Cost.
when I try to invoke the below code, it has "Unable to load the specified metadata resource." error.
/////

    using (var currentEntities = new masterEntities())
    {
        currentUser = currentEntities.Home_User.FirstOrDefault(
            x => x.UserLoginAccount == userLoginAccount && x.UserPwd == userPwd);

    }

////
so in Web.config, I modify the
metadata configuation from Home_Model to Home_Cost.

then it works.
obviously, VS2015(my version) didn't update web.config when I delete/create edmx.


问:
Monitoring files in linux
How to build a tool in Ubuntu 16.04 that can monitor a given folder/directory in every 5 minutes (or specified time) and can check if it contains any file or not (file can be of any format)? What things I need to learn for doing this task? Can I do this with the help of python script or am I required to learn shell scripting.</p>

答: Try with incron. Incron is for monitoring filesystem activity. It consists of a daemon and a table manipulator. You can use it a similar way as the regular cron. The difference is that the inotify cron handles filesystem events rather than time periods</p>

Title: Monitoring files in linux


问:
How to schedule PHP script on Job Finish (from CLI)
I am processing a big .gz file using PHP (transfering data from gz to mysql)
it takes about 10 minutes per .gz file.
I have a lot of .gz file to be processed.

After PHP is finished with one file I have to manually change the PHP script to select another .gz file and then run the script again manually.

I want it to be automatically run the next job to process the next file.
the gz file is named as 1, 2 ,3, 4, 5 ...
I can simply make a loop to be something like this ( process file 1 - 5):

```<code>for ($i = 1 ; $i >= 5; $i++)
{
    $file = gzfile($i.'.gz')
    ...gz content processing...
}
</code>```

However, since the gz file is really big, I cannot do that, because if I use this loop, PHP will run multiple big gz files as single script job. (takes a lot of memory)

What I want to do is after PHP is finished with one job I want a new job to process the next file.

maybe its going to be something like this:

```<code>    $file = gzfile($_GET['filename'].'.gz')
    ...gz content processing...
</code>```

Thank You

答:
What you should do is

Schedule a cronjob to run your php script every x minutes

When script is run, check if there is a lock file in place, if not create one and start processing the next unprocessed gz file, if yes abort

Wait for the queue to get cleared

Body:
I am processing a big .gz file using PHP (transfering data from gz to mysql)
it takes about 10 minutes per .gz file.
I have a lot of .gz file to be processed.

After PHP is finished with one file I have to manually change the PHP script to select another .gz file and then run the script again manually.

I want it to be automatically run the next job to process the next file.
the gz file is named as 1, 2 ,3, 4, 5 ...
I can simply make a loop to be something like this ( process file 1 - 5):

for ($i = 1 ; $i >= 5; $i++)
{
    $file = gzfile($i.'.gz')
    ...gz content processing...
}

However, since the gz file is really big, I cannot do that, because if I use this loop, PHP will run multiple big gz files as single script job. (takes a lot of memory)

What I want to do is after PHP is finished with one job I want a new job to process the next file.

maybe its going to be something like this:

    $file = gzfile($_GET['filename'].'.gz')
    ...gz content processing...

Thank You


问:
add sender's name in the from field of the email in python
I am trying to send email with below code.

```<code>import smtplib
from email.mime.text import MIMEText

sender = 'sender@sender.com'

def mail_me(cont, receiver):
    msg = MIMEText(cont, 'html')
    recipients = ",".join(receiver)
    msg['Subject'] = 'Test-email'
    msg['From'] = "XYZ ABC"
    msg['To'] = recipients
    # Send the message via our own SMTP server.
    try:
        s = smtplib.SMTP('localhost')
        s.sendmail(sender, receiver, msg.as_string())
        print "Successfully sent email"
    except SMTPException:
        print "Error: unable to send email"
    finally:
        s.quit()

cont = """\
   <html>
     <head></head>
     <body>
       <p>Hi!<br>
          How are you?<br>
          Here is the <a href="http://www.google.com">link</a> you wanted.
       </p>
     </body>
   </html>
   """
mail_me(cont,['xyz@xyzcom'])
</code>```

I want "XYZ ABC" to appear as the sender's name when the email is received and its email address as 'sender@sender.com'. but when i receive email i am receiving weird details in "from" fields of the email message.

```<code>[![from:    XYZ@<machine-hostname-appearing-here>
reply-to:   XYZ@<machine-hostname-appearing-here>,
ABC@<machine-hostname-appearing-here>][1]][1]
</code>```

I have attached a screenshot of the email that i receive.

how can i fix this according to my need.

答: The name comes from the FROM header. Refer to this answer please Specify a sender when sending mail with Python (smtplib)

Body:
I am trying to send email with below code.

import smtplib
from email.mime.text import MIMEText

sender = 'sender@sender.com'

def mail_me(cont, receiver):
    msg = MIMEText(cont, 'html')
    recipients = ",".join(receiver)
    msg['Subject'] = 'Test-email'
    msg['From'] = "XYZ ABC"
    msg['To'] = recipients
    # Send the message via our own SMTP server.
    try:
        s = smtplib.SMTP('localhost')
        s.sendmail(sender, receiver, msg.as_string())
        print "Successfully sent email"
    except SMTPException:
        print "Error: unable to send email"
    finally:
        s.quit()

cont = """\

Hi!

          How are you?

          Here is the link you wanted.

   """
mail_me(cont,['xyz@xyzcom'])

I want "XYZ ABC" to appear as the sender's name when the email is received and its email address as 'sender@sender.com'. but when i receive email i am receiving weird details in "from" fields of the email message.

[![from:    XYZ@<machine-hostname-appearing-here>
reply-to:   XYZ@<machine-hostname-appearing-here>,
ABC@<machine-hostname-appearing-here>][1]][1]

I have attached a screenshot of the email that i receive.

how can i fix this according to my need.


问:
Error in jags.model
I'm new to R and JAGS, and not even very experienced with programming.

I'm trying to set up a hierarchical model for some data, but I get this error:

```<code>####error in line above:
Error in jags.model(file = "modelControl.txt", data = dataList, inits =
initsList,  :
  RUNTIME ERROR:
Cannot insert node into beta1[1:158]. Dimension mismatch
</code>```

At the end of running the code below.  What am I doing wrong?  How can I avoid the error?

```<code>#declaration
y=as.numeric(PANSS[treat == 0]) #treat == 0 indicates control group
x=as.numeric(time[treat == 0])
meanYcontrol = mean(PANSS[treat == 0])
sdYcontrol = sd(PANSS[treat == 0])
s = pp[treat==0]

#data list
dataList = list(
  y = y,
  x = x,
  Ntotal = length(y),
  Nsubj = length(y)/6 , #each subject had 6 test moments
  s = s
)
#model
modelString = "
model {
for ( i in 1:Ntotal ) {
y[i] ~ dnorm( beta0[s[i]] + beta1[s[i]] * x[i,1], 1/sigma^2 )
}
for ( j in 1:Nsubj ) {
beta0[j] ~ dnorm( beta0mu , 1/(beta0sigma)^2 )
beta1[j] ~ dnorm( beta1mu , 1/(beta1sigma)^2 )
}
#vague priors
beta0 ~ dnorm( 0, 1/(10)^5 )
beta1 ~ dt( 0, 1, 1 ) #Cauchy distribution
beta0sigma ~ dunif( 1.0E-5, 1.0E+5 )
beta1sigma ~ dunif( 1.0E-5, 1.0E+5 )
sigma ~ dunif( 1.0E-5, 1.0E+5 )
nu = nuMinusOne+1
nuMinusOne ~ dexp(1/29)
}
"

 #write model to text file
writeLines(modelString, con="modelControl.txt")

#initialization chains
beta0Init = meanYcontrol
beta1Init = 0
sigmaInit = sdYcontrol
initsList = list(beta0=beta0Init, beta1=beta1Init, sigma=sigmaInit)

#run chains
parameters = c("beta0", "beta1", "sigma") #parameters to be monitored
numSavedSteps = 7500 #number of steps in chain to save
adaptSteps = 1000  #number of steps to tune the samplers
burnInSteps = 500 #number of steps to burn-in the samplers
thinSteps = 1 #number of steps to keep (1=keep every step)
nChains = 3 #number of chains to run
nIter = ceiling(numSavedSteps / nChains) #number of steps per chain

jagsModel = jags.model(file="modelControl.txt", data=dataList, inits =
initsList, n.chains=nChains, n.adapt=adaptSteps)
</code>```

答:
Your comments imply that you have changed a few things in your model, but the model definition in your question has not changed (or perhaps has been partially edited).  Here's what I think you are now using:

```<code>model {
for ( i in 1:Ntotal ) {
y[i] ~ dnorm( beta0[s[i]] + beta1[s[i]] * x[i,1], 1/sigma^2 )
}
for ( j in 1:Nsubj ) {
beta0[j] ~ dnorm( beta0mu , 1/(beta0sigma)^2 )
beta1[j] ~ dnorm( beta1mu , 1/(beta1sigma)^2 )
}
#vague priors
beta0mu ~ dnorm( 0, 1/(10)^5 )
beta1mu ~ dt( 0, 1, 1 ) #Cauchy distribution
beta0sigma ~ dunif( 1.0E-5, 1.0E+5 )
beta1sigma ~ dunif( 1.0E-5, 1.0E+5 )
sigma ~ dunif( 1.0E-5, 1.0E+5 )
nu = nuMinusOne+1
nuMinusOne ~ dexp(1/29)
}

# In R:
meanYcontrol = mean(PANSS[treat == 0])
sdYcontrol = sd(PANSS[treat == 0])
beta0Init = meanYcontrol
beta1Init = 0
sigmaInit = sdYcontrol
initsList = list(beta0=beta0Init, beta1=beta1Init, sigma=sigmaInit)
</code>```

So you give initial values for beta0 and beta1 but I think they are intended to be for beta0mu and beta1mu.  There may be further errors though - it is hard to check because at the moment we can't run the model as we don't have your data.  In the future, it would be a good idea to provide a minimal reproducible example, including any data etc that is required, as it will help to generate faster and more complete answers for you.

One way to avoid errors like this is to use the #inits# and #data# tags with the runjags package, which can help to make the data and initial values being used a bit more obvious e.g.:

```<code>model {
    for ( i in 1:Ntotal ) {   #data# Ntotal
        y[i] ~ dnorm( beta0[s[i]] + beta1[s[i]] * x[i,1], 1/sigma^2 )
            #data# y, x, s
    }
    for ( j in 1:Nsubj ) {  #data# Nsubj
        beta0[j] ~ dnorm( beta0mu , 1/(beta0sigma)^2 )
        beta1[j] ~ dnorm( beta1mu , 1/(beta1sigma)^2 )
            #inits# beta0mu, beta1mu
    }
    #vague priors
    beta0mu ~ dnorm( 0, 1/(10)^5 )
    beta1mu ~ dt( 0, 1, 1 ) #Cauchy distribution
    beta0sigma ~ dunif( 1.0E-5, 1.0E+5 )
    beta1sigma ~ dunif( 1.0E-5, 1.0E+5 )
    sigma ~ dunif( 1.0E-5, 1.0E+5 )
        #inits# sigma
    nu = nuMinusOne+1
    nuMinusOne ~ dexp(1/29)
}
</code>```

[Notice I have also used indenting to make the model easier to read - this often helps to identify mistakes without even needing to post the model]

Then in R you just need the data and inits specified to be in your working environment, and then use:

```<code>results <- runjags::run.jags("modelControl.txt", monitor=...)
</code>```

Hope that helps.

Title: Error in jags.model

Body:
I'm new to R and JAGS, and not even very experienced with programming.

I'm trying to set up a hierarchical model for some data, but I get this error:

####error in line above:
Error in jags.model(file = "modelControl.txt", data = dataList, inits =
initsList,  :
  RUNTIME ERROR:
Cannot insert node into beta1[1:158]. Dimension mismatch

At the end of running the code below.  What am I doing wrong?  How can I avoid the error?

#declaration
y=as.numeric(PANSS[treat == 0]) #treat == 0 indicates control group
x=as.numeric(time[treat == 0])
meanYcontrol = mean(PANSS[treat == 0])
sdYcontrol = sd(PANSS[treat == 0])
s = pp[treat==0]

#data list
dataList = list(
  y = y,
  x = x,
  Ntotal = length(y),
  Nsubj = length(y)/6 , #each subject had 6 test moments
  s = s
)
#model
modelString = "
model {
for ( i in 1:Ntotal ) {
y[i] ~ dnorm( beta0[s[i]] + beta1[s[i]] * x[i,1], 1/sigma^2 )
}
for ( j in 1:Nsubj ) {
beta0[j] ~ dnorm( beta0mu , 1/(beta0sigma)^2 )
beta1[j] ~ dnorm( beta1mu , 1/(beta1sigma)^2 )
}
#vague priors
beta0 ~ dnorm( 0, 1/(10)^5 )
beta1 ~ dt( 0, 1, 1 ) #Cauchy distribution
beta0sigma ~ dunif( 1.0E-5, 1.0E+5 )
beta1sigma ~ dunif( 1.0E-5, 1.0E+5 )
sigma ~ dunif( 1.0E-5, 1.0E+5 )
nu = nuMinusOne+1
nuMinusOne ~ dexp(1/29)
}
"

 #write model to text file
writeLines(modelString, con="modelControl.txt")

#initialization chains
beta0Init = meanYcontrol
beta1Init = 0
sigmaInit = sdYcontrol
initsList = list(beta0=beta0Init, beta1=beta1Init, sigma=sigmaInit)

#run chains
parameters = c("beta0", "beta1", "sigma") #parameters to be monitored
numSavedSteps = 7500 #number of steps in chain to save
adaptSteps = 1000  #number of steps to tune the samplers
burnInSteps = 500 #number of steps to burn-in the samplers
thinSteps = 1 #number of steps to keep (1=keep every step)
nChains = 3 #number of chains to run
nIter = ceiling(numSavedSteps / nChains) #number of steps per chain

jagsModel = jags.model(file="modelControl.txt", data=dataList, inits =
initsList, n.chains=nChains, n.adapt=adaptSteps)

Body:
Your comments imply that you have changed a few things in your model, but the model definition in your question has not changed (or perhaps has been partially edited).  Here's what I think you are now using:

model {
for ( i in 1:Ntotal ) {
y[i] ~ dnorm( beta0[s[i]] + beta1[s[i]] * x[i,1], 1/sigma^2 )
}
for ( j in 1:Nsubj ) {
beta0[j] ~ dnorm( beta0mu , 1/(beta0sigma)^2 )
beta1[j] ~ dnorm( beta1mu , 1/(beta1sigma)^2 )
}
#vague priors
beta0mu ~ dnorm( 0, 1/(10)^5 )
beta1mu ~ dt( 0, 1, 1 ) #Cauchy distribution
beta0sigma ~ dunif( 1.0E-5, 1.0E+5 )
beta1sigma ~ dunif( 1.0E-5, 1.0E+5 )
sigma ~ dunif( 1.0E-5, 1.0E+5 )
nu = nuMinusOne+1
nuMinusOne ~ dexp(1/29)
}

# In R:
meanYcontrol = mean(PANSS[treat == 0])
sdYcontrol = sd(PANSS[treat == 0])
beta0Init = meanYcontrol
beta1Init = 0
sigmaInit = sdYcontrol
initsList = list(beta0=beta0Init, beta1=beta1Init, sigma=sigmaInit)

So you give initial values for beta0 and beta1 but I think they are intended to be for beta0mu and beta1mu.  There may be further errors though - it is hard to check because at the moment we can't run the model as we don't have your data.  In the future, it would be a good idea to provide a minimal reproducible example, including any data etc that is required, as it will help to generate faster and more complete answers for you.

One way to avoid errors like this is to use the #inits# and #data# tags with the runjags package, which can help to make the data and initial values being used a bit more obvious e.g.:

model {
    for ( i in 1:Ntotal ) {   #data# Ntotal
        y[i] ~ dnorm( beta0[s[i]] + beta1[s[i]] * x[i,1], 1/sigma^2 )
            #data# y, x, s
    }
    for ( j in 1:Nsubj ) {  #data# Nsubj
        beta0[j] ~ dnorm( beta0mu , 1/(beta0sigma)^2 )
        beta1[j] ~ dnorm( beta1mu , 1/(beta1sigma)^2 )
            #inits# beta0mu, beta1mu
    }
    #vague priors
    beta0mu ~ dnorm( 0, 1/(10)^5 )
    beta1mu ~ dt( 0, 1, 1 ) #Cauchy distribution
    beta0sigma ~ dunif( 1.0E-5, 1.0E+5 )
    beta1sigma ~ dunif( 1.0E-5, 1.0E+5 )
    sigma ~ dunif( 1.0E-5, 1.0E+5 )
        #inits# sigma
    nu = nuMinusOne+1
    nuMinusOne ~ dexp(1/29)
}

[Notice I have also used indenting to make the model easier to read - this often helps to identify mistakes without even needing to post the model]

Then in R you just need the data and inits specified to be in your working environment, and then use:

results <- runjags::run.jags("modelControl.txt", monitor=...)

Hope that helps.


问:
C# WebApi Json Posting
I have below C# code for WEB API When I post below JSON the Account object is always null. Please, anyone can guide on below code.

```<code>public class Account
{
    public string id { get; set; }
    public string number { get; set; }
}

public object Post([FromBody] Account account)
{
    Message msg = new Message();
    msg.status = "Status";
    return Request.CreateResponse(msg);
}
</code>```

JSON

```<code>{
  "Accounts": {
    "id": "13456454",
    "number": "222",
  }
}
</code>```

答:
Your Account object is null, because the C# code is inconsistent with JSON you provided. That's how MVC defends itself from badly formed requests.

Model suggests, that what you get in JSON are just these 2 pure fields, id and number, so JSON for it should look like this:

```<code>{
    "id": "13456454",
    "number": "222"
}
</code>```

To make C# model adapted for provided JSON it should be built like this:

```<code>public class Accounts
{
    public Account Accounts { get; set; }
}

public class Account
{
    public string id { get; set; }
    public string number { get; set; }
}
</code>```

And API Action prototype should look like this:

```<code>public object Post([FromBody] Accounts account)
</code>```

By this you contain Account into another class with property Accounts resembling what you have in provided JSON.

However your naming scheme suggest that single request might contain more than single account. To achieve this C# Classes should look like this:

```<code>public class Accounts
{
    public Account[] Accounts { get; set; }
}

public class Account
{
    public string id { get; set; }
    public string number { get; set; }
}
</code>```

And your JSON should contain object array:

```<code>{
    "Accounts": [
        {
            "id": "13456454",
            "number": "222",
        },
        {
            "id": "23456",
            "number": "125",
        },
    ]
}
</code>```

Of course that array can contain only single element, if you need so, but it will allow you to put more than one Account at once, as your naming suggests.

For future reference, you should be more precise at what you want to be the result, to make sure we know best how we should help you.

Title: C# WebApi Json Posting

Body:
I have below C# code for WEB API When I post below JSON the Account object is always null. Please, anyone can guide on below code.

public class Account
{
    public string id { get; set; }
    public string number { get; set; }
}

public object Post([FromBody] Account account)
{
    Message msg = new Message();
    msg.status = "Status";
    return Request.CreateResponse(msg);
}

JSON

{
  "Accounts": {
    "id": "13456454",
    "number": "222",
  }
}

Body:
Your Account object is null, because the C# code is inconsistent with JSON you provided. That's how MVC defends itself from badly formed requests.

Model suggests, that what you get in JSON are just these 2 pure fields, id and number, so JSON for it should look like this:

{
    "id": "13456454",
    "number": "222"
}

To make C# model adapted for provided JSON it should be built like this:

public class Accounts
{
    public Account Accounts { get; set; }
}

public class Account
{
    public string id { get; set; }
    public string number { get; set; }
}

And API Action prototype should look like this:

public object Post([FromBody] Accounts account)

By this you contain Account into another class with property Accounts resembling what you have in provided JSON.

However your naming scheme suggest that single request might contain more than single account. To achieve this C# Classes should look like this:

public class Accounts
{
    public Account[] Accounts { get; set; }
}

public class Account
{
    public string id { get; set; }
    public string number { get; set; }
}

And your JSON should contain object array:

{
    "Accounts": [
        {
            "id": "13456454",
            "number": "222",
        },
        {
            "id": "23456",
            "number": "125",
        },
    ]
}

Of course that array can contain only single element, if you need so, but it will allow you to put more than one Account at once, as your naming suggests.

For future reference, you should be more precise at what you want to be the result, to make sure we know best how we should help you.


问:
Can I cast a DynamicObject or ExpandoObject to a specific type?
Let's say I have the following class:

```<code>class Person
{
  public String Name { get; set; }
  public String Address { get; set; }
}
</code>```

And then I create a dynamic object, like this:

```<code>dynamic person = new ExpandoObject();
person.Name = "Henrik";
person.Address = "Home";
person.Age = 100;
</code>```

Now, is it possible in any (preferrably simple) way to convert the created object into an object of (a subclass of) the class Person? Doing this doesn't work:

```<code>var p = (Person)person;
</code>```

since the person object is not related to the class Person in any way, it just happens to contain all the properties of the class Person. But is it possible to make the conversion work anyway, in a simple and generic way? Ideally, I would like to be able to cast my person object into a subclass of Person, which contains (obviously) all the properties of Person, in addition to (in this example) the new property "Age".

答:
No, you can't retroactively apply inheritance or an interface like that. That just isn't how C# or most languages work. See this answer for a discussion on the differences between dynamic, ExpandoObject, and DynamicObject.

You could implement the IDynamicMetaObjectProvider interface, or even inherit from DynamicObject as shown here.

This would allow you to add dynamic-ness to your new type.

Body:
Let's say I have the following class:

class Person
{
  public String Name { get; set; }
  public String Address { get; set; }
}

And then I create a dynamic object, like this:

dynamic person = new ExpandoObject();
person.Name = "Henrik";
person.Address = "Home";
person.Age = 100;

Now, is it possible in any (preferrably simple) way to convert the created object into an object of (a subclass of) the class Person? Doing this doesn't work:

var p = (Person)person;

since the person object is not related to the class Person in any way, it just happens to contain all the properties of the class Person. But is it possible to make the conversion work anyway, in a simple and generic way? Ideally, I would like to be able to cast my person object into a subclass of Person, which contains (obviously) all the properties of Person, in addition to (in this example) the new property "Age".


问:
how to give effect in camanJs canvas with dynamic image?
I am developing mean stack application.

I am stuck in photo editor.

I have use "Camanjs" for give effect to photo and edit it in angularjs 1.
It will works very well with first image for slider, but if i select any other image form slider after edit first image then it display old image.

my file (directive in angularjs)

```<code>.directive('hzPhotoEditor', ['$timeout', function($timeout) {
    return {
        restrict: "E",
        link: function(scope, elem, attrs) {
            var imgCanvas, $save;

            //init photo when click on real photo
            scope.$on("fillCanvas", function(event, data) {
                console.log("fill canvas called");
                console.log(data.photo);
                scope.fillCanvas(data);
            });

            scope.fillCanvas = function(data) {
                var hzMIW = 0,
                    hzMIH = 0,
                    hzImgH = 0,
                    hzImgW = 0,
                    path = '',
                    c, c1, ctx, ctx1;

                angular.element(".hz-photo-editor-wrapper").attr("style", angular.element(".hz-modal-wrapper").attr("style"));
                angular.element(".hz-photo-editor-wrapper .hz-left").attr("style", angular.element(".hz-modal-wrapper .hz-left").attr("style"));
                angular.element(".hz-photo-editor-wrapper .hz-modal-image-wrapper").attr("style", angular.element(".hz-modal-wrapper .hz-modal-image-wrapper").attr("style"));
                angular.element(".hz-photo-editor-wrapper .hz-modal-image").attr("style", angular.element(".hz-modal-wrapper .hz-modal-image").attr("style"));
                angular.element(".hz-photo-editor-wrapper .hz-photo-editor-img").attr("height", angular.element(".hz-modal-slider-image").height());
                angular.element(".hz-photo-editor-wrapper .hz-photo-editor-img").attr("width", angular.element(".hz-modal-slider-image").width());
                hzMIW = angular.element(".hz-modal-wrapper .hz-modal-image").css("width").replace("px", "");
                hzMIH = angular.element(".hz-modal-wrapper .hz-modal-image").css("height").replace("px", "");
                hzImgH = angular.element(".hz-modal-wrapper .hz-modal-image img").css('height').replace("px", "");
                hzImgW = angular.element(".hz-modal-wrapper .hz-modal-image img").css('width').replace("px", "");

                path = '/media/site/photo/' + data.photo.photo_name;

                c = document.getElementById('photoEditorCanvas');
                c.width = hzImgW;
                c.height = hzImgH;

                ctx = c.getContext('2d');
                imgCanvas = new Image();
                imgCanvas.src = path;
                console.log("imgCanvas.src");
                console.log(imgCanvas.src);
                if (imgCanvas !== imgCanvas) {
                    console.log("canvas is load.....");
                }

                angular.element('input[type=range]').val(0);

                imgCanvas.addEventListener('load', function() {
                    /*ctx.clearRect(0, 0, 0, 0);*/
                    console.log(imgCanvas);
                    ctx.drawImage(imgCanvas, 0, 0, hzImgW, hzImgH);
                }, false);

            };

            //give effect by slider like hue, contrast, sepia
            scope.applyImageParameters = function() {
                var hue, cntrst, vibr, sep;
                hue = parseInt(angular.element('#hue').val());
                cntrst = parseInt(angular.element('#contrast').val());
                vibr = parseInt(angular.element('#vibrance').val());
                sep = parseInt(angular.element('#sepia').val());

                Caman('#photoEditorCanvas', imgCanvas, function() {
                    this.revert(false);
                    //this.reloadCanvasData();
                    this.hue(hue).contrast(cntrst).vibrance(vibr).sepia(sep).render();

                });
            };

            angular.element("input[type=range]").change("mouseup", function(e) {
                scope.applyImageParameters();
                console.log("event type: " + e.type);
                var min = e.target.min,
                    max = e.target.max,
                    val = e.target.value;
                angular.element(e.target).css({
                    'backgroundSize': (val - min) * 100 / (max - min) + '% 100%'
                });
                //scope.reloadCanvasData();

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

->if I comment on  "this.revert(false);" line and uncomment "this.reloadCanvasData();" line form "scope.applyImageParameters" function then it works very well, but it will not work in hue 0, contrast 0,etc.

->if I comment on  "this.reloadCanvasData();" line and uncomment "this.revert(false);" line form "scope.applyImageParameters" function then effect works verry well but it display old image not current image with effect

Image attached two screen sort for more details.

First edited image after giving effect

Second image after giving effect

Can any body help me to resolve this issue?

答:
You should remove canvas and the again create a canvas.</p>

```<code>.directive('hzPhotoEditor', ['$timeout', function($timeout) {
return {
    restrict: "E",
    link: function(scope, elem, attrs) {
        var imgCanvas, $save;

        //init photo when click on real photo
        scope.$on("fillCanvas", function(event, data) {
            console.log("fill canvas called");
            console.log(data.photo);
            scope.fillCanvas(data);
        });

        scope.fillCanvas = function(data) {
            var hzMIW = 0,
                hzMIH = 0,
                hzImgH = 0,
                hzImgW = 0,
                path = '',
                c, c1, ctx, ctx1;

            angular.element(".hz-photo-editor-wrapper").attr("style", angular.element(".hz-modal-wrapper").attr("style"));
            angular.element(".hz-photo-editor-wrapper .hz-left").attr("style", angular.element(".hz-modal-wrapper .hz-left").attr("style"));
            angular.element(".hz-photo-editor-wrapper .hz-modal-image-wrapper").attr("style", angular.element(".hz-modal-wrapper .hz-modal-image-wrapper").attr("style"));
            angular.element(".hz-photo-editor-wrapper .hz-modal-image").attr("style", angular.element(".hz-modal-wrapper .hz-modal-image").attr("style"));
            angular.element(".hz-photo-editor-wrapper .hz-photo-editor-img").attr("height", angular.element(".hz-modal-slider-image").height());
            angular.element(".hz-photo-editor-wrapper .hz-photo-editor-img").attr("width", angular.element(".hz-modal-slider-image").width());
            hzMIW = angular.element(".hz-modal-wrapper .hz-modal-image").css("width").replace("px", "");
            hzMIH = angular.element(".hz-modal-wrapper .hz-modal-image").css("height").replace("px", "");
            hzImgH = angular.element(".hz-modal-wrapper .hz-modal-image img").css('height').replace("px", "");
            hzImgW = angular.element(".hz-modal-wrapper .hz-modal-image img").css('width').replace("px", "");

            $(".hz-modal-image").children("canvas").remove();
            var canvas_ = $("<canvas></canvas>").attr({id: 'photoEditorCanvas'});
            $(".hz-modal-image").append(canvas_);

            c = document.getElementById('photoEditorCanvas');
            c.width = hzImgW;
            c.height = hzImgH;

            ctx = c.getContext('2d');
            imgCanvas = new Image();
            imgCanvas.src = path;
            console.log("imgCanvas.src");
            console.log(imgCanvas.src);
            if (imgCanvas !== imgCanvas) {
                console.log("canvas is load.....");
            }

            angular.element('input[type=range]').val(0);

            imgCanvas.addEventListener('load', function() {
                /*ctx.clearRect(0, 0, 0, 0);*/
                console.log(imgCanvas);
                ctx.drawImage(imgCanvas, 0, 0, hzImgW, hzImgH);
            }, false);

        };

        //give effect by slider like hue, contrast, sepia
        scope.applyImageParameters = function() {
            var hue, cntrst, vibr, sep;
            hue = parseInt(angular.element('#hue').val());
            cntrst = parseInt(angular.element('#contrast').val());
            vibr = parseInt(angular.element('#vibrance').val());
            sep = parseInt(angular.element('#sepia').val());

            Caman('#photoEditorCanvas', imgCanvas, function() {
                this.revert(false);
                //this.reloadCanvasData();
                this.hue(hue).contrast(cntrst).vibrance(vibr).sepia(sep).render();

            });
        };

        angular.element("input[type=range]").change("mouseup", function(e) {
            scope.applyImageParameters();
            console.log("event type: " + e.type);
            var min = e.target.min,
                max = e.target.max,
                val = e.target.value;
            angular.element(e.target).css({
                'backgroundSize': (val - min) * 100 / (max - min) + '% 100%'
            });
            //scope.reloadCanvasData();

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

Body:
I am developing mean stack application.

I am stuck in photo editor.

I have use "Camanjs" for give effect to photo and edit it in angularjs 1.
It will works very well with first image for slider, but if i select any other image form slider after edit first image then it display old image.

my file (directive in angularjs)

.directive('hzPhotoEditor', ['$timeout', function($timeout) {
    return {
        restrict: "E",
        link: function(scope, elem, attrs) {
            var imgCanvas, $save;

            //init photo when click on real photo
            scope.$on("fillCanvas", function(event, data) {
                console.log("fill canvas called");
                console.log(data.photo);
                scope.fillCanvas(data);
            });

            scope.fillCanvas = function(data) {
                var hzMIW = 0,
                    hzMIH = 0,
                    hzImgH = 0,
                    hzImgW = 0,
                    path = '',
                    c, c1, ctx, ctx1;

                angular.element(".hz-photo-editor-wrapper").attr("style", angular.element(".hz-modal-wrapper").attr("style"));
                angular.element(".hz-photo-editor-wrapper .hz-left").attr("style", angular.element(".hz-modal-wrapper .hz-left").attr("style"));
                angular.element(".hz-photo-editor-wrapper .hz-modal-image-wrapper").attr("style", angular.element(".hz-modal-wrapper .hz-modal-image-wrapper").attr("style"));
                angular.element(".hz-photo-editor-wrapper .hz-modal-image").attr("style", angular.element(".hz-modal-wrapper .hz-modal-image").attr("style"));
                angular.element(".hz-photo-editor-wrapper .hz-photo-editor-img").attr("height", angular.element(".hz-modal-slider-image").height());
                angular.element(".hz-photo-editor-wrapper .hz-photo-editor-img").attr("width", angular.element(".hz-modal-slider-image").width());
                hzMIW = angular.element(".hz-modal-wrapper .hz-modal-image").css("width").replace("px", "");
                hzMIH = angular.element(".hz-modal-wrapper .hz-modal-image").css("height").replace("px", "");
                hzImgH = angular.element(".hz-modal-wrapper .hz-modal-image img").css('height').replace("px", "");
                hzImgW = angular.element(".hz-modal-wrapper .hz-modal-image img").css('width').replace("px", "");

                path = '/media/site/photo/' + data.photo.photo_name;

                c = document.getElementById('photoEditorCanvas');
                c.width = hzImgW;
                c.height = hzImgH;

                ctx = c.getContext('2d');
                imgCanvas = new Image();
                imgCanvas.src = path;
                console.log("imgCanvas.src");
                console.log(imgCanvas.src);
                if (imgCanvas !== imgCanvas) {
                    console.log("canvas is load.....");
                }

                angular.element('input[type=range]').val(0);

                imgCanvas.addEventListener('load', function() {
                    /*ctx.clearRect(0, 0, 0, 0);*/
                    console.log(imgCanvas);
                    ctx.drawImage(imgCanvas, 0, 0, hzImgW, hzImgH);
                }, false);

            };

            //give effect by slider like hue, contrast, sepia
            scope.applyImageParameters = function() {
                var hue, cntrst, vibr, sep;
                hue = parseInt(angular.element('#hue').val());
                cntrst = parseInt(angular.element('#contrast').val());
                vibr = parseInt(angular.element('#vibrance').val());
                sep = parseInt(angular.element('#sepia').val());

                Caman('#photoEditorCanvas', imgCanvas, function() {
                    this.revert(false);
                    //this.reloadCanvasData();
                    this.hue(hue).contrast(cntrst).vibrance(vibr).sepia(sep).render();

                });
            };

            angular.element("input[type=range]").change("mouseup", function(e) {
                scope.applyImageParameters();
                console.log("event type: " + e.type);
                var min = e.target.min,
                    max = e.target.max,
                    val = e.target.value;
                angular.element(e.target).css({
                    'backgroundSize': (val - min) * 100 / (max - min) + '% 100%'
                });
                //scope.reloadCanvasData();

            });
        }
    };
}])

->if I comment on  "this.revert(false);" line and uncomment "this.reloadCanvasData();" line form "scope.applyImageParameters" function then it works very well, but it will not work in hue 0, contrast 0,etc.

->if I comment on  "this.reloadCanvasData();" line and uncomment "this.revert(false);" line form "scope.applyImageParameters" function then effect works verry well but it display old image not current image with effect

Image attached two screen sort for more details.

First edited image after giving effect

Second image after giving effect

Can any body help me to resolve this issue?

Body:
You should remove canvas and the again create a canvas.

.directive('hzPhotoEditor', ['$timeout', function($timeout) {
return {
    restrict: "E",
    link: function(scope, elem, attrs) {
        var imgCanvas, $save;

        //init photo when click on real photo
        scope.$on("fillCanvas", function(event, data) {
            console.log("fill canvas called");
            console.log(data.photo);
            scope.fillCanvas(data);
        });

        scope.fillCanvas = function(data) {
            var hzMIW = 0,
                hzMIH = 0,
                hzImgH = 0,
                hzImgW = 0,
                path = '',
                c, c1, ctx, ctx1;

            angular.element(".hz-photo-editor-wrapper").attr("style", angular.element(".hz-modal-wrapper").attr("style"));
            angular.element(".hz-photo-editor-wrapper .hz-left").attr("style", angular.element(".hz-modal-wrapper .hz-left").attr("style"));
            angular.element(".hz-photo-editor-wrapper .hz-modal-image-wrapper").attr("style", angular.element(".hz-modal-wrapper .hz-modal-image-wrapper").attr("style"));
            angular.element(".hz-photo-editor-wrapper .hz-modal-image").attr("style", angular.element(".hz-modal-wrapper .hz-modal-image").attr("style"));
            angular.element(".hz-photo-editor-wrapper .hz-photo-editor-img").attr("height", angular.element(".hz-modal-slider-image").height());
            angular.element(".hz-photo-editor-wrapper .hz-photo-editor-img").attr("width", angular.element(".hz-modal-slider-image").width());
            hzMIW = angular.element(".hz-modal-wrapper .hz-modal-image").css("width").replace("px", "");
            hzMIH = angular.element(".hz-modal-wrapper .hz-modal-image").css("height").replace("px", "");
            hzImgH = angular.element(".hz-modal-wrapper .hz-modal-image img").css('height').replace("px", "");
            hzImgW = angular.element(".hz-modal-wrapper .hz-modal-image img").css('width').replace("px", "");

            $(".hz-modal-image").children("canvas").remove();
            var canvas_ = $("<canvas></canvas>").attr({id: 'photoEditorCanvas'});
            $(".hz-modal-image").append(canvas_);

            c = document.getElementById('photoEditorCanvas');
            c.width = hzImgW;
            c.height = hzImgH;

            ctx = c.getContext('2d');
            imgCanvas = new Image();
            imgCanvas.src = path;
            console.log("imgCanvas.src");
            console.log(imgCanvas.src);
            if (imgCanvas !== imgCanvas) {
                console.log("canvas is load.....");
            }

            angular.element('input[type=range]').val(0);

            imgCanvas.addEventListener('load', function() {
                /*ctx.clearRect(0, 0, 0, 0);*/
                console.log(imgCanvas);
                ctx.drawImage(imgCanvas, 0, 0, hzImgW, hzImgH);
            }, false);

        };

        //give effect by slider like hue, contrast, sepia
        scope.applyImageParameters = function() {
            var hue, cntrst, vibr, sep;
            hue = parseInt(angular.element('#hue').val());
            cntrst = parseInt(angular.element('#contrast').val());
            vibr = parseInt(angular.element('#vibrance').val());
            sep = parseInt(angular.element('#sepia').val());

            Caman('#photoEditorCanvas', imgCanvas, function() {
                this.revert(false);
                //this.reloadCanvasData();
                this.hue(hue).contrast(cntrst).vibrance(vibr).sepia(sep).render();

            });
        };

        angular.element("input[type=range]").change("mouseup", function(e) {
            scope.applyImageParameters();
            console.log("event type: " + e.type);
            var min = e.target.min,
                max = e.target.max,
                val = e.target.value;
            angular.element(e.target).css({
                'backgroundSize': (val - min) * 100 / (max - min) + '% 100%'
            });
            //scope.reloadCanvasData();

        });
    }
};
}])


问:
How do you get access to the current System.Web.Routing.RequestContext from within a custom helper method in ASP.NET MVC?
I'm writing a helper method for ASP.NET MVC and I need to call Url.Content to get an appropriate URL for the context.  However, in order to create a new UrlHelper() I need to get the current RequestContext (System.Web.Routing.RequestContext to be precise) and I'm not sure how to grab it. Anyone know?

答:
As mentioned above, just extend the HtmlHelper and the context is exposed in that way.  For example:</p>

```<code>    public static string ExtensionMethodName(this HtmlHelper html,object o)
    {
        html.ViewContext.HttpContext.Request.Uri ... etc
    }
</code>```

OwnerDisplayName: JC Grubbs

LastEditorDisplayName: JC Grubbs

Body:
As mentioned above, just extend the HtmlHelper and the context is exposed in that way.  For example:

    public static string ExtensionMethodName(this HtmlHelper html,object o)
    {
        html.ViewContext.HttpContext.Request.Uri ... etc
    }

OwnerDisplayName: ccook


问:
Is it good practice to unit test properties?
I'm still getting to grips with the whole TDD concept. Should I be writing tests for properties? Should one only write tests on properties containing sufficient logic? Any thoughts or examples on this would be great.</p>

答:
Instead of thinking of them as tests, think of each test as an example of how someone could use your code.

Instead of just testing properties, think about the behaviour which changes when the properties have different values, and give an example of the behaviour of the class in each meaningful context.

If it's really just a data property you can test by inspection, or with automated acceptance tests, or manually, maybe with a tester's help. Otherwise, don't worry about testing each method, or each property - just show how you can use the code and how you expect it to behave.


问:
Bottom Border Width on Swift TextField in TableView
i builded a static tableview with more Rowes than the screen has, so the user has to scroll to see all cell.

Every cell has a textfield with the following class to add a bottom border:

```<code>class TextFieldWithBottomBorder: UITextField {
   let border = CALayer()
   let width = CGFloat(1.0)

   func addBottomBorder(color: UIColor){
       self.border.borderColor = color.cgColor
       self.border.frame = CGRect(x: 0, y: self.frame.size.height - width, width:  self.frame.size.width, height:self.frame.size.height)

       self.border.borderWidth = self.width
       self.layer.addSublayer(self.border)
       self.layer.masksToBounds = true
   }

   func changeBorderColor(color: UIColor){
       self.border.borderColor = color.cgColor
   }
}
</code>```

And i call the method after receiving some data from the server e. g.

```<code>self.firstnameTextField.text = firstNameFromDB
self.firstnameTextField.addBottomBorder(color: .blue)
</code>```

This works fine for every cell is currently displayed. But the cells which are out of the current view the with is shorter than the textfield.
See this screenshot, for "Vorname", means firstName everything looks good, but for email, password etc. the border is to short.
http://share-your-photo.com/34b5e80253

答:
Use this class for bottom line text field</p>

```<code>@IBDesignable class BottomTextField: UITextField {
    var lineView = UIView()

 @IBInspectable var lineViewBgColor:UIColor = UIColor.gray{
        didSet {
            if !isFirstResponder {
                lineView.backgroundColor = lineViewBgColor
            }
        }
    }
required init?(coder aDecoder:NSCoder) {
        super.init(coder:aDecoder)!
        setup()
    }

    override init(frame:CGRect) {
        super.init(frame:frame)
        setup()
    }

    // MARK:- Private Methods
    private func setup() {
        lineView.frame = CGRect(x:CGFloat(0), y:self.frame.size.height-2, width:self.frame.size.width, height:CGFloat(1))
        lineView.backgroundColor = lineViewBgColor

        self.addSubview(lineView)
    }

}
</code>```

Body:
i builded a static tableview with more Rowes than the screen has, so the user has to scroll to see all cell.

Every cell has a textfield with the following class to add a bottom border:

class TextFieldWithBottomBorder: UITextField {
   let border = CALayer()
   let width = CGFloat(1.0)

   func addBottomBorder(color: UIColor){
       self.border.borderColor = color.cgColor
       self.border.frame = CGRect(x: 0, y: self.frame.size.height - width, width:  self.frame.size.width, height:self.frame.size.height)

       self.border.borderWidth = self.width
       self.layer.addSublayer(self.border)
       self.layer.masksToBounds = true
   }

   func changeBorderColor(color: UIColor){
       self.border.borderColor = color.cgColor
   }
}

And i call the method after receiving some data from the server e. g.

self.firstnameTextField.text = firstNameFromDB
self.firstnameTextField.addBottomBorder(color: .blue)

This works fine for every cell is currently displayed. But the cells which are out of the current view the with is shorter than the textfield.
See this screenshot, for "Vorname", means firstName everything looks good, but for email, password etc. the border is to short.
http://share-your-photo.com/34b5e80253

Body:
Use this class for bottom line text field

@IBDesignable class BottomTextField: UITextField {
    var lineView = UIView()

 @IBInspectable var lineViewBgColor:UIColor = UIColor.gray{
        didSet {
            if !isFirstResponder {
                lineView.backgroundColor = lineViewBgColor
            }
        }
    }
required init?(coder aDecoder:NSCoder) {
        super.init(coder:aDecoder)!
        setup()
    }

    override init(frame:CGRect) {
        super.init(frame:frame)
        setup()
    }

    // MARK:- Private Methods
    private func setup() {
        lineView.frame = CGRect(x:CGFloat(0), y:self.frame.size.height-2, width:self.frame.size.width, height:CGFloat(1))
        lineView.backgroundColor = lineViewBgColor

        self.addSubview(lineView)
    }

}


问:
How to parse multi dimension array into Talend
I have array which I need to parse into Talent

```<code>{
    "sEcho": 1,
    "iTotalRecords": 54,
    "iTotalDisplayRecords": 54,
    "aaData": [
        [
            "79",
            "testowy2",
            "testowy samochod",
            "12.00",
            "14.00",
            "2147483647",
            "posciel",
            ""
        ]
    ]
}
</code>```

What would be Xpath Query which I need to pass on the tExtractJSONFields ?

答:
It is not possible to do this,

"Please check right XPathExpression or XML source document." error is occuring...

Your input is a valid json but not a valid XML Document

Body:
I have array which I need to parse into Talent

{
    "sEcho": 1,
    "iTotalRecords": 54,
    "iTotalDisplayRecords": 54,
    "aaData": [
        [
            "79",
            "testowy2",
            "testowy samochod",
            "12.00",
            "14.00",
            "2147483647",
            "posciel",
            ""
        ]
    ]
}

What would be Xpath Query which I need to pass on the tExtractJSONFields ?


答:
I usually write junit tests for accessors. It doesn't add much when they're written, except to keep coverage statistics pretty. But if someone adds "sufficient logic" later to the production code, the tests will already be in place to catch any mistakes.

Also it is the work of moments to write a test to check the value returned by a getter.

Title: Is it good practice to unit test properties?

Body: I'm still getting to grips with the whole TDD concept. Should I be writing tests for properties? Should one only write tests on properties containing sufficient logic? Any thoughts or examples on this would be great.


问:
Replace string where ++ exists SQL
This relates to my previous question

What I now want to do is in my value column, if there are any instance of ++ replace this with 999.

So for e.g. if i have 1+2++3this should be updated to 1+2+999+3

How do i achieve this?

Thanks

答:
Oracle Setup:

```<code>CREATE TABLE your_table ( value ) AS
  SELECT NULL     FROM DUAL UNION ALL
  SELECT '1'      FROM DUAL UNION ALL
  SELECT '1+2'    FROM DUAL UNION ALL
  SELECT '1++2'   FROM DUAL UNION ALL
  SELECT '+1'     FROM DUAL UNION ALL
  SELECT '1+'     FROM DUAL UNION ALL
  SELECT '1+2++3' FROM DUAL;
</code>```

Query:

```<code>SELECT TRIM( BOTH '+' FROM REPLACE( '+' || value || '+', '++', '+999+' ) )
FROM   your_table
</code>```

Output:

```<code>VALUE
---------
999
1
1+2
1+999+2
999+1
1+999
1+2+999+3
</code>```

If you can have more than one missing element to replace in a row then you need a more complicated solution:

Oracle Setup:

```<code>CREATE TABLE your_table ( value ) AS
  SELECT NULL      FROM DUAL UNION ALL
  SELECT '1'       FROM DUAL UNION ALL
  SELECT '1+2'     FROM DUAL UNION ALL
  SELECT '1++2'    FROM DUAL UNION ALL
  SELECT '+1'      FROM DUAL UNION ALL
  SELECT '1+'      FROM DUAL UNION ALL
  SELECT '1+2++3'  FROM DUAL UNION ALL
  SELECT '1+2+++3' FROM DUAL UNION ALL
  SELECT '+'       FROM DUAL;
</code>```

Query:

```<code>SELECT ( SELECT LISTAGG(
                  COALESCE(
                    REGEXP_SUBSTR( t.value, '(.*?)(\+|$)', 1, LEVEL, NULL, 1 ),
                    '999'
                  ),
                  '+'
                ) WITHIN GROUP ( ORDER BY LEVEL )
         FROM   DUAL
         CONNECT BY LEVEL <= REGEXP_COUNT( t.value, '\+' ) + 1
       ) AS value
FROM   your_table t
</code>```

Output:

```<code>VALUE
-------------
999
1
1+2
1+999+2
999+1
1+999
1+2+999+3
1+2+999+999+3
999+999
</code>```

Title: Replace string where ++ exists SQL

Body:
Oracle Setup:

CREATE TABLE your_table ( value ) AS
  SELECT NULL     FROM DUAL UNION ALL
  SELECT '1'      FROM DUAL UNION ALL
  SELECT '1+2'    FROM DUAL UNION ALL
  SELECT '1++2'   FROM DUAL UNION ALL
  SELECT '+1'     FROM DUAL UNION ALL
  SELECT '1+'     FROM DUAL UNION ALL
  SELECT '1+2++3' FROM DUAL;

Query:

SELECT TRIM( BOTH '+' FROM REPLACE( '+' || value || '+', '++', '+999+' ) )
FROM   your_table

Output:

VALUE
---------
999
1
1+2
1+999+2
999+1
1+999
1+2+999+3

If you can have more than one missing element to replace in a row then you need a more complicated solution:

Oracle Setup:

CREATE TABLE your_table ( value ) AS
  SELECT NULL      FROM DUAL UNION ALL
  SELECT '1'       FROM DUAL UNION ALL
  SELECT '1+2'     FROM DUAL UNION ALL
  SELECT '1++2'    FROM DUAL UNION ALL
  SELECT '+1'      FROM DUAL UNION ALL
  SELECT '1+'      FROM DUAL UNION ALL
  SELECT '1+2++3'  FROM DUAL UNION ALL
  SELECT '1+2+++3' FROM DUAL UNION ALL
  SELECT '+'       FROM DUAL;

Query:

SELECT ( SELECT LISTAGG(
                  COALESCE(
                    REGEXP_SUBSTR( t.value, '(.*?)(\+|$)', 1, LEVEL, NULL, 1 ),
                    '999'
                  ),
                  '+'
                ) WITHIN GROUP ( ORDER BY LEVEL )
         FROM   DUAL
         CONNECT BY LEVEL <= REGEXP_COUNT( t.value, '\+' ) + 1
       ) AS value
FROM   your_table t

Output:

VALUE
-------------
999
1
1+2
1+999+2
999+1
1+999
1+2+999+3
1+2+999+999+3
999+999


问:
How to open links in new browser window using ie 11
Can I open links on click in new browser (not a popup) window?

Things I have tried:

```<code><a href='http://osric.net/' onclick='return !window.open(this.href);'>osric.net web hosting</a>
</code>```

A function onclick:

```<code>var windowObjectReference;
var strWindowFeatures = "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes, toolbar=yes";

function openRequestedPopup() {
  windowObjectReference = window.open("http://www.cnn.com/", "CNN_WindowName", strWindowFeatures);
}
</code>```

but with these it opens in new tab only.

答:
Here it goes

```<code><a href="your_link" target="_blank">Visit</a>
</code>```

target="_blank" - is the key

Use this for new window

```<code><a href="print.html"  onclick="window.open('print.html', 'newwindow', 'width=300, height=250'); return false;"> Print</a>
</code>```

Ref: Make a link open a new window (not tab)

Body:
Can I open links on click in new browser (not a popup) window?

Things I have tried:

osric.net web hosting

A function onclick:

var windowObjectReference;
var strWindowFeatures = "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes, toolbar=yes";

function openRequestedPopup() {
  windowObjectReference = window.open("http://www.cnn.com/", "CNN_WindowName", strWindowFeatures);
}

but with these it opens in new tab only.

Body:
Here it goes

<a href="your_link" target="_blank">Visit</a>

target="_blank" - is the key

Use this for new window

<a href="print.html"  onclick="window.open('print.html', 'newwindow', 'width=300, height=250'); return false;"> Print</a>

Ref: Make a link open a new window (not tab)


问:
How to count the documents returned by a Mango query
I have a mango query:

```<code>{
  "selector": {
    "age":{
        "$eq": 22
    }
  }
}
</code>```

I want to know the number of documents that satisfy this criteria.

I know we can use map reduce functions to achieve this, but is there any way to do this by using mango query like using some key like "count" in the query itself as we do for "sort", and "fields".

I am firing mango query through rest client and I want the number of documents as the response of the query.

答:
It is not really possible to retrieve the full number of documents by using the find function.
By default _find is limited to 25 documents to be returned (http://docs.couchdb.org/en/2.0.0/api/database/find.html).

limit (number) – Maximum number of results returned. Default is 25. Optional

By increasing this number, the response time is increasing. Having e.g. 15.000 entries in your couch database and limiting the query to 999999 would result in a long waiting time.

Back to your question: after receiving your result set, simply run something like array.length to count your results.

Body:
I have a mango query:

{
  "selector": {
    "age":{
        "$eq": 22
    }
  }
}

I want to know the number of documents that satisfy this criteria.

I know we can use map reduce functions to achieve this, but is there any way to do this by using mango query like using some key like "count" in the query itself as we do for "sort", and "fields".

I am firing mango query through rest client and I want the number of documents as the response of the query.


问:
Typescript Error: Property 'user' does not exist on type 'Request'
I have the following piece of code in my express app

```<code>router.get('/auth/userInfo', this.validateUser,  (req, res) => {
    res.json(req.user);
});
</code>```

and my IDE seems to be complaining with the error

error TS2339: Property 'user' does not exist on type 'Request'.

When I compile my typescript code it seems to be throwing this error. Any ideas why this is happening?

答:
We have a large API written in Express and Typescript, and this is how we handle such scenarios:

We keep the request definitions in one file:

```<code>import { Request } from "express"
export interface IGetUserAuthInfoRequest extends Request {
  user: string // or any other type
}
</code>```

And then in the file where we are writing the controller functions:

```<code>import { Response } from "express"
import { IGetUserAuthInfoRequest } from "./definitionfile"

app.get('/auth/userInfo', validateUser,  (req: IGetUserAuthInfoRequest, res: Response) => {
  res.status(200).json(req.user); // Start calling status function to be compliant with Express 5.0
});
</code>```

Be advised that "user" is not a property that is available natively in the Request object of Express. Make sure that you are using a middleware that adds such property to the request object.

Body:
I have the following piece of code in my express app

router.get('/auth/userInfo', this.validateUser,  (req, res) => {
    res.json(req.user);
});

and my IDE seems to be complaining with the error

error TS2339: Property 'user' does not exist on type 'Request'.

When I compile my typescript code it seems to be throwing this error. Any ideas why this is happening?

Body:
We have a large API written in Express and Typescript, and this is how we handle such scenarios:

We keep the request definitions in one file:

import { Request } from "express"
export interface IGetUserAuthInfoRequest extends Request {
  user: string // or any other type
}

And then in the file where we are writing the controller functions:

import { Response } from "express"
import { IGetUserAuthInfoRequest } from "./definitionfile"

app.get('/auth/userInfo', validateUser,  (req: IGetUserAuthInfoRequest, res: Response) => {
  res.status(200).json(req.user); // Start calling status function to be compliant with Express 5.0
});

Be advised that "user" is not a property that is available natively in the Request object of Express. Make sure that you are using a middleware that adds such property to the request object.


问:
Iterate through a String Swift 2.0
I am trying to do a very simple piece of code in Swift playgrounds.

```<code>var word = "Zebra"

for i in word {
  print(i)
}
</code>```

However, I always get an error on line 3.

'String' does not have a member named 'Generator'

Any ideas on why this doesn't work? Note: I am working in Xcode 7, with Swift 2.0 (Strings and Characters).

答:
Swift 4

Forin loop:

```<code>let word = "Swift 4"
for i in word {
    print(i)
}
</code>```

map example:

```<code>let word = "Swift 4"
_ = word.map({ print($0) })
</code>```

forEach example:

```<code>let word = "Swift 4"
word.forEach({ print($0) })
</code>```

Title: Iterate through a String Swift 2.0

Body:
I am trying to do a very simple piece of code in Swift playgrounds.

var word = "Zebra"

for i in word {
  print(i)
}

However, I always get an error on line 3.

'String' does not have a member named 'Generator'

Any ideas on why this doesn't work? Note: I am working in Xcode 7, with Swift 2.0 (Strings and Characters).

Body:
Swift 4

Forin loop:

let word = "Swift 4"
for i in word {
    print(i)
}

map example:

let word = "Swift 4"
_ = word.map({ print($0) })

forEach example:

let word = "Swift 4"
word.forEach({ print($0) })


问:
Why button fontsize has no effect when add a TextElement style on Window
```<code><Window.Resources>
    <Style TargetType="{x:Type TextElement}">
        <Setter Property="FontSize" Value="50"/>
    </Style>
</Window.Resources>
<Grid>
    <StackPanel Orientation="Vertical" Grid.Column="0" >

        <Button Click="ButtonBase_OnClick" x:Name="qq">xxx</Button>
        <Button>xxx</Button>
        <Button>xxx</Button>
    </StackPanel>
</Grid>
</code>```

code like above

as I know, FontSize of Button is  a DP from TextElement,but why this code no effect?

```<code> <Window.Resources>
    <Style TargetType="{x:Type Button}">
        <Setter Property="FontSize" Value="50"/>
    </Style>
</Window.Resources>
</code>```

if I change the TextElement to Button everything is ok, why ?

答:
Unlike Button, TextElement is not a Control. It doesn't inherit from the System.Windows.Control class and has no ControlTemplate and because of this the implicit style doesn't get applied. Please refer to the following links for more information about this.

https://blogs.msdn.microsoft.com/wpfsdk/2009/08/27/implicit-styles-templates-controls-and-frameworkelements/
Implicit styles in Application.Resources vs Window.Resources?

If you want to define a global text style, you could add an implicit TextBlock style to your App.xaml:

```<code><Application x:Class="WpfApp1.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfApp2"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <Style TargetType="{x:Type TextBlock}">
            <Setter Property="FontSize" Value="50"/>
        </Style>
    </Application.Resources>
</Application>
</code>```

Body:
<Window.Resources>

</Window.Resources>
<Grid>
    <StackPanel Orientation="Vertical" Grid.Column="0" >

        <Button Click="ButtonBase_OnClick" x:Name="qq">xxx</Button>
        <Button>xxx</Button>
        <Button>xxx</Button>
    </StackPanel>
</Grid>

code like above

as I know, FontSize of Button is  a DP from TextElement,but why this code no effect?

 <Window.Resources>

</Window.Resources>

if I change the TextElement to Button everything is ok, why ?

Body:
Unlike Button, TextElement is not a Control. It doesn't inherit from the System.Windows.Control class and has no ControlTemplate and because of this the implicit style doesn't get applied. Please refer to the following links for more information about this.

https://blogs.msdn.microsoft.com/wpfsdk/2009/08/27/implicit-styles-templates-controls-and-frameworkelements/
Implicit styles in Application.Resources vs Window.Resources?

If you want to define a global text style, you could add an implicit TextBlock style to your App.xaml:

<Application x:Class="WpfApp1.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfApp2"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <Style TargetType="{x:Type TextBlock}">
            <Setter Property="FontSize" Value="50"/>
        </Style>
    </Application.Resources>
</Application>