问:
freemarker + spring configuration and simplest example
Despite there are a lot of discussion around freemarker + spring but it is hard to find neat working example to copy and run.

Could you please provide simplest working configuration of freemarker in spring xml context and java code snippet to load template from resource file and process it.

答:
Other than maven dependency in pom.xml to use it with java configuration in spring you can do -

```<code>public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[] { MyRootContextConfig.class };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[] { MyServletContextConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/test/*" };
    }

}
</code>```

and then MyRootContextConfig can have

```<code>@Bean(name = "myFreeMarkerConfigruation")
public FreeMarkerConfigurationFactoryBean getFreeMarkerConfiguration() {
    FreeMarkerConfigurationFactoryBean bean = new FreeMarkerConfigurationFactoryBean();
    bean.setTemplateLoaderPath("classpath:/templates/");
    return bean;
}
</code>```

Body:
Other than maven dependency in pom.xml to use it with java configuration in spring you can do -

public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[] { MyRootContextConfig.class };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[] { MyServletContextConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/test/*" };
    }

}

and then MyRootContextConfig can have

@Bean(name = "myFreeMarkerConfigruation")
public FreeMarkerConfigurationFactoryBean getFreeMarkerConfiguration() {
    FreeMarkerConfigurationFactoryBean bean = new FreeMarkerConfigurationFactoryBean();
    bean.setTemplateLoaderPath("classpath:/templates/");
    return bean;
}


来源: stackexchange

问:
Recycler View Horizontal Scroll with 2 columns
Here is I have I have tried so far

```<code>LinearLayoutManager layoutManager =
        new GridLayoutManager(getActivity(), 2, GridLayoutManager.HORIZONTAL, false);
</code>```

but It showed 2 rows instead of two columns.

How can I show two items with horizontal scroll with recycler view?

答:
Alright here is a funda,

When you are using GridLayoutManager.HORIZONTAL, second parameter will be considered as number of rows

while, when you write GridLayoutManager.VERTICAL second parameter will be considered as number of columns

Also, this

```<code>LinearLayoutManager layoutManager =
        new GridLayoutManager(getActivity(), 2, GridLayoutManager.HORIZONTAL, false);
</code>```

supposed to be,

```<code>GridLayoutManager layoutManager =
            new GridLayoutManager(getActivity(), 2, GridLayoutManager.HORIZONTAL, false);
</code>```

in above code, 2 is considered as number of rows to be generated.

ContentLicense: CC BY-SA 4.0

Body:
Here is I have I have tried so far

LinearLayoutManager layoutManager =
        new GridLayoutManager(getActivity(), 2, GridLayoutManager.HORIZONTAL, false);

but It showed 2 rows instead of two columns.

How can I show two items with horizontal scroll with recycler view?

Body:
Alright here is a funda,

When you are using GridLayoutManager.HORIZONTAL, second parameter will be considered as number of rows

while, when you write GridLayoutManager.VERTICAL second parameter will be considered as number of columns

Also, this

LinearLayoutManager layoutManager =
        new GridLayoutManager(getActivity(), 2, GridLayoutManager.HORIZONTAL, false);

supposed to be,

GridLayoutManager layoutManager =
            new GridLayoutManager(getActivity(), 2, GridLayoutManager.HORIZONTAL, false);

in above code, 2 is considered as number of rows to be generated.

ContentLicense: CC BY-SA 3.0


问:
Why isn't .reverse() working?
I am trying to take a sentence and split that sentence, reverse it, and print it to the screen.

I am having trouble understanding how .reverse() works?
When I do something like:

```<code>test = ['This','is','a','test']
new_test = test.reverse()
print(new_test)
</code>```

When I run this I am getting None, why is this? How can I make .reverse() work?

Here is my final code:

```<code>sentence = input("What is your sentence? ")
split_sentence = sentence.split().reverse()
for word in sentence:
    print(word,end='')
</code>```

答:
reverse() operates in place, and doesn't return a new array. If you want to use a copy, you'll need to do the following:

```<code>arr = [1, 2, 3, 4, 5]
copy = arr.copy() # omit this if you don't want a new list
copy.reverse()
# copy now contains [5, 4, 3, 2, 1]
# arr still contains [1, 2, 3, 4, 5]
</code>```

Title: Why isn't .reverse() working?

Body:
I am trying to take a sentence and split that sentence, reverse it, and print it to the screen.

I am having trouble understanding how .reverse() works?
When I do something like:

test = ['This','is','a','test']
new_test = test.reverse()
print(new_test)

When I run this I am getting None, why is this? How can I make .reverse() work?

Here is my final code:

sentence = input("What is your sentence? ")
split_sentence = sentence.split().reverse()
for word in sentence:
    print(word,end='')

Body:
reverse() operates in place, and doesn't return a new array. If you want to use a copy, you'll need to do the following:

arr = [1, 2, 3, 4, 5]
copy = arr.copy() # omit this if you don't want a new list
copy.reverse()
# copy now contains [5, 4, 3, 2, 1]
# arr still contains [1, 2, 3, 4, 5]


问:
Get URI of RSM Diagram Elements
I would like to be able to programmatically retrieve the same URI that is available through BIRT (getURI). I am developing an Rational Software Modeler plug-let and need to get the unique identifier for the diagram elements. This would enable the elements to be recognized in later database ETL processes.

I have found a URI available through EObject.eResource().getURI(), except it only returns half of what is returned in the BIRT reports. BIRT reports something like "platform:/resource/Common/S.efx#_c0KLYFImEd-iIqDctBy_JQ" while EObject.eResource().getURI() only returns "platform:/resource/Common/S.efx"

Any help would be appreciated.

答:
You should be able to get the whole URI with ECoreUtil.getURI(EObject) function, it should also include the fragment part.

EObject.eResource().getURI() returns you the resource's URI where this object is located, so it will not include the Objects own unique ID there.

That fragment ending hash there is EObjects XMI-ID, that can be returned using ECoreUtil.getID(EObject) if needed. But that ECoreUtil.getURI(EObject) should be just ok.

ContentLicense: CC BY-SA 2.5

Title: Get URI of RSM Diagram Elements


问:
How to use windows speech synthesizer in ASP.NET MVC
I tried to use the System.Speech class to generate speech in ASP.NET mvc application.

```<code>[HttpPost]
public  ActionResult TTS(string text)
{
   SpeechSynthesizer speechSynthesizer = new SpeechSynthesizer();
   speechSynthesizer.Speak(text);
   return View();
}
</code>```

But it gives the following error.

```<code> System.InvalidOperationException: 'An asynchronous operation cannot be
 Started at this time. Asynchronous operations may only be started within an
 asynchronous handler or module or during certain events in the Page lifecycle.
 If this exception occurred while executing a Page, ensure that the Page is
 marked <%@ Page Async="true" %>.
 This exception may also indicate an attempt to call an "async void" method,
 which is generally unsupported within ASP.NET request processing. Instead,
the asynchronous method should return a Task, and the caller should await it.
</code>```

I used the System.Speech class and async methods in wpf applications.

Can the System.Speech class be used in a ASP.NET mvc application?

How to do it?

Where should be the <%@ Page Async="true" %> be
    placed?

答:
The answer is: yes, you can use System.Speech class in MVC.

I think you can try using async controller action method and use SpeechSynthesizer.Speak with Task.Run method like this:

```<code>[HttpPost]
public async Task<ActionResult> TTS(string text)
{
    Task<ViewResult> task = Task.Run(() =>
    {
        using (SpeechSynthesizer speechSynthesizer = new SpeechSynthesizer())
        {
            speechSynthesizer.Speak(text);
            return View();
        }
    });
    return await task;
}
</code>```

However, as in example above the generated sound plays on server, because the code above runs server-side instead of client-side. To enable playing on client-side, you can use SetOutputToWaveFile method and use audio tag to play audio content when returning view page shown in example below (assumed you're using HTML 5 in CSHTML view):

Controller

```<code>[HttpPost]
public async Task<ActionResult> TTS(string text)
{
    // you can set output file name as method argument or generated from text
    string fileName = "fileName";
    Task<ViewResult> task = Task.Run(() =>
    {
        using (SpeechSynthesizer speechSynthesizer = new SpeechSynthesizer())
        {
            speechSynthesizer.SetOutputToWaveFile(Server.MapPath("~/path/to/file/") + fileName + ".wav");
            speechSynthesizer.Speak(text);

            ViewBag.FileName = fileName + ".wav";
            return View();
        }
    });
    return await task;
}
</code>```

View

```<code><audio autoplay="autoplay" src="@Url.Content("~/path/to/file/" + ViewBag.FileName)">
</audio>
</code>```

Or you can change action type to FileContentResult and use MemoryStream with SetOutputToWaveStream to let user play audio file himself:

```<code>Task<FileContentResult> task = Task.Run(() =>
{
    using (SpeechSynthesizer speechSynthesizer = new SpeechSynthesizer())
    {
        using (MemoryStream stream = new MemoryStream())
        {
            speechSynthesizer.SetOutputToWaveStream(stream);
            speechSynthesizer.Speak(text);
            var bytes = stream.GetBuffer();
            return File(bytes, "audio/x-wav");
        }
    }
});
</code>```

Reference:

Using Asynchronous Methods in ASP.NET MVC

Similar issues:

How to use speech in mvc

System.Speech.Synthesis hangs with high CPU on 2012 R2

Body:
I tried to use the System.Speech class to generate speech in ASP.NET mvc application.

[HttpPost]
public  ActionResult TTS(string text)
{
   SpeechSynthesizer speechSynthesizer = new SpeechSynthesizer();
   speechSynthesizer.Speak(text);
   return View();
}

But it gives the following error.

 System.InvalidOperationException: 'An asynchronous operation cannot be
 Started at this time. Asynchronous operations may only be started within an
 asynchronous handler or module or during certain events in the Page lifecycle.
 If this exception occurred while executing a Page, ensure that the Page is
 marked <%@ Page Async="true" %>.
 This exception may also indicate an attempt to call an "async void" method,
 which is generally unsupported within ASP.NET request processing. Instead,
the asynchronous method should return a Task, and the caller should await it.

I used the System.Speech class and async methods in wpf applications.

Can the System.Speech class be used in a ASP.NET mvc application?

How to do it?

Where should be the <%@ Page Async="true" %> be
    placed?

Body:
The answer is: yes, you can use System.Speech class in MVC.

I think you can try using async controller action method and use SpeechSynthesizer.Speak with Task.Run method like this:

[HttpPost]
public async Task<ActionResult> TTS(string text)
{
    Task<ViewResult> task = Task.Run(() =>
    {
        using (SpeechSynthesizer speechSynthesizer = new SpeechSynthesizer())
        {
            speechSynthesizer.Speak(text);
            return View();
        }
    });
    return await task;
}

However, as in example above the generated sound plays on server, because the code above runs server-side instead of client-side. To enable playing on client-side, you can use SetOutputToWaveFile method and use audio tag to play audio content when returning view page shown in example below (assumed you're using HTML 5 in CSHTML view):

Controller

[HttpPost]
public async Task<ActionResult> TTS(string text)
{
    // you can set output file name as method argument or generated from text
    string fileName = "fileName";
    Task<ViewResult> task = Task.Run(() =>
    {
        using (SpeechSynthesizer speechSynthesizer = new SpeechSynthesizer())
        {
            speechSynthesizer.SetOutputToWaveFile(Server.MapPath("~/path/to/file/") + fileName + ".wav");
            speechSynthesizer.Speak(text);

            ViewBag.FileName = fileName + ".wav";
            return View();
        }
    });
    return await task;
}

View

<audio autoplay="autoplay" src="@Url.Content("~/path/to/file/" + ViewBag.FileName)">
</audio>

Or you can change action type to FileContentResult and use MemoryStream with SetOutputToWaveStream to let user play audio file himself:

Task<FileContentResult> task = Task.Run(() =>
{
    using (SpeechSynthesizer speechSynthesizer = new SpeechSynthesizer())
    {
        using (MemoryStream stream = new MemoryStream())
        {
            speechSynthesizer.SetOutputToWaveStream(stream);
            speechSynthesizer.Speak(text);
            var bytes = stream.GetBuffer();
            return File(bytes, "audio/x-wav");
        }
    }
});

Reference:

Using Asynchronous Methods in ASP.NET MVC

Similar issues:

How to use speech in mvc

System.Speech.Synthesis hangs with high CPU on 2012 R2


问:
Why doesn't this crash?
I'm attempting to narrow down a bug to a minimum reproducible case and found something odd.

Consider this code:

```<code>static NSString *staticString = nil;
int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    if (staticString == nil) {
        staticString = [[NSArray arrayWithObjects:@"1", @"2", @"3", nil] componentsJoinedByString:@","];
    }

    [pool drain];

    NSLog(@"static: %@", staticString);
    return 0;
}
</code>```

I'm expecting this code to crash.  Instead, it logs:

```<code>2011-01-18 14:41:06.311 EmptyFoundation[61419:a0f] static: static:
</code>```

However, if I change the NSLog() to:

```<code>NSLog(@"static: %s", [staticString UTF8String]);
</code>```

Then it does crash.

edit a bit more info:

After draining the pool:

```<code>NSLog(@"static: %@", staticString);  //this logs "static: static: "
NSLog(@"static: %@", [staticString description]); //this crashes
</code>```

So apparently invoking a method on the string is good enough to get it to crash.  In that case, why doesn't logging the string directly cause it to crash?  Shouldn't NSLog() be invoking the -description method?

Where is the second "static: " coming from?  Why isn't this crashing?

Results:

Both Kevin Ballard and Graham Lee are correct.  Graham's correct in realizing that NSLog() is not invoking -description (as I was erroneously assuming), and Kevin is almost definitely correct that this is a weird stack-related issue with copying a format string and a va_list around.

NSLogging and NSString does not invoke -description.  Graham elegantly showed this, and if you trace through the Core Foundation sources that do the logging, you'll see that this is the case.  Any backtrace originating inside NSLog shows that it invokes NSLogv => _CFLogvEx => _CFStringCreateWithFormatAndArgumentsAux => _CFStringAppendFormatAndArgumentsAux.  _CFStringAppendFormatAndArgumentsAux() (line 5365) is where all of the magic is going on.  You can see that it's manually going through to find all the % substitutions.  It only ends up invoking the description copy function if the type of the substitution is a CFFormatObjectType, the description function is non-nil, and the substitution hasn't already been handled by another type.  Since we've shown that the description is not getting copied, it's reasonable to assume that an NSString gets handled earlier (in which case it's probably going to be doing a raw byte copy), which leads us to believe...

There's a stack error going on here, as Kevin surmises.  Somehow the pointer that was pointing to the autoreleased string is getting substituted to a different object, which happens to be an NSString.  So, it doesn't crash.  Weird.  However, if we change the type of the static variable to something else, like an NSArray, then the -description method does get called, and the program does crash as expected.

How truly and utterly strange.  Points go to Kevin for being the most correct about the root cause of the behavior, and kudos to Graham for correcting my fallacious thinking.  I wish I could accept two answers...

答:
Your assumption that NSLog() calls -description on an NSString instance is faulty. I just added this category:

```<code>@implementation NSString (GLDescription)

- (NSString *)description {
  NSLog(@"-description called on %@", self);
  return self;
}

@end
</code>```

It doesn't cause a stack overflow, because it doesn't get called recursively. Not only that, but if I insert that category into the code in your question, I find this output:

```<code>2011-01-18 23:04:11.653 LogString[3769:a0f] -description called on 1
2011-01-18 23:04:11.656 LogString[3769:a0f] -description called on 2
2011-01-18 23:04:11.657 LogString[3769:a0f] -description called on 3
2011-01-18 23:04:11.658 LogString[3769:a0f] static: static:
</code>```

so we conclude that NSLog() doesn't call -description on an NSString it comes across in its args. Why you get the static string twice is likely a quirk of the data on the stack when you erroneously access the released staticString variable.

Title: Why doesn't this crash?

Body:
I'm attempting to narrow down a bug to a minimum reproducible case and found something odd.

Consider this code:

static NSString *staticString = nil;
int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    if (staticString == nil) {
        staticString = [[NSArray arrayWithObjects:@"1", @"2", @"3", nil] componentsJoinedByString:@","];
    }

    [pool drain];

    NSLog(@"static: %@", staticString);
    return 0;
}

I'm expecting this code to crash.  Instead, it logs:

2011-01-18 14:41:06.311 EmptyFoundation[61419:a0f] static: static:

However, if I change the NSLog() to:

NSLog(@"static: %s", [staticString UTF8String]);

Then it does crash.

edit a bit more info:

After draining the pool:

NSLog(@"static: %@", staticString);  //this logs "static: static: "
NSLog(@"static: %@", [staticString description]); //this crashes

So apparently invoking a method on the string is good enough to get it to crash.  In that case, why doesn't logging the string directly cause it to crash?  Shouldn't NSLog() be invoking the -description method?

Where is the second "static: " coming from?  Why isn't this crashing?

Results:

Both Kevin Ballard and Graham Lee are correct.  Graham's correct in realizing that NSLog() is not invoking -description (as I was erroneously assuming), and Kevin is almost definitely correct that this is a weird stack-related issue with copying a format string and a va_list around.

NSLogging and NSString does not invoke -description.  Graham elegantly showed this, and if you trace through the Core Foundation sources that do the logging, you'll see that this is the case.  Any backtrace originating inside NSLog shows that it invokes NSLogv => _CFLogvEx => _CFStringCreateWithFormatAndArgumentsAux => _CFStringAppendFormatAndArgumentsAux.  _CFStringAppendFormatAndArgumentsAux() (line 5365) is where all of the magic is going on.  You can see that it's manually going through to find all the % substitutions.  It only ends up invoking the description copy function if the type of the substitution is a CFFormatObjectType, the description function is non-nil, and the substitution hasn't already been handled by another type.  Since we've shown that the description is not getting copied, it's reasonable to assume that an NSString gets handled earlier (in which case it's probably going to be doing a raw byte copy), which leads us to believe...

There's a stack error going on here, as Kevin surmises.  Somehow the pointer that was pointing to the autoreleased string is getting substituted to a different object, which happens to be an NSString.  So, it doesn't crash.  Weird.  However, if we change the type of the static variable to something else, like an NSArray, then the -description method does get called, and the program does crash as expected.

How truly and utterly strange.  Points go to Kevin for being the most correct about the root cause of the behavior, and kudos to Graham for correcting my fallacious thinking.  I wish I could accept two answers...

Body:
Your assumption that NSLog() calls -description on an NSString instance is faulty. I just added this category:

@implementation NSString (GLDescription)

- (NSString *)description {
  NSLog(@"-description called on %@", self);
  return self;
}

@end

It doesn't cause a stack overflow, because it doesn't get called recursively. Not only that, but if I insert that category into the code in your question, I find this output:

2011-01-18 23:04:11.653 LogString[3769:a0f] -description called on 1
2011-01-18 23:04:11.656 LogString[3769:a0f] -description called on 2
2011-01-18 23:04:11.657 LogString[3769:a0f] -description called on 3
2011-01-18 23:04:11.658 LogString[3769:a0f] static: static:

so we conclude that NSLog() doesn't call -description on an NSString it comes across in its args. Why you get the static string twice is likely a quirk of the data on the stack when you erroneously access the released staticString variable.


答:
reverse() function performs in place reversal of a list and that's reason you're getting None in new_test list. You can use following snippet to have reversed list.

```<code>from copy import deepcopy

test = ['This','is','a','test']
new_test = deepcopy(test)
print(new_test)
new_test.reverse()
print(new_test)
</code>```

output:

```<code>['This', 'is', 'a', 'test']
['test', 'a', 'is', 'This']
</code>```

Title: Why isn't .reverse() working?

Body:
reverse() function performs in place reversal of a list and that's reason you're getting None in new_test list. You can use following snippet to have reversed list.

from copy import deepcopy

test = ['This','is','a','test']
new_test = deepcopy(test)
print(new_test)
new_test.reverse()
print(new_test)

output:

['This', 'is', 'a', 'test']
['test', 'a', 'is', 'This']


问:
In my broadcast receiver 's onreceive() method, how can I tell the origin of the Intent
In the broadcast receiver's onReceive() method, how can I tell which app send me the Intent?</p>

答: This is not the intent of how android uses Intents (no pun intended.).  However, if you are sending the intent and your broadcaster is receiving the intent, you can use setExtra ( String, String) on the Intent to attach the name of the class sending the intent.  Inside your onReceive, check to see if that extra is set and, if it is, check to see if the value matches your expected class.  </p>


问:
How to get a number at the end of a string followed by this character `:` using regex
I need to get a number (integer) at the end of a string followed by this character :.

Basically:

qwe-tyu-iop[-zxc:10  //result  should be 10

::qwe-ty:u-iop[-zxc:10  //result  should be 10

::qwe-ty:u-iop[-zxc:10.10  //result  should be undefined

::qwe-ty:u-iop[-zxc:abc  //result  should be undefined

::qwe-ty:u-iop[-zxc:afdf10  //result  should be undefined

答:
Simply

```<code>inputStr.split(":").pop();
</code>```

Example

function getValue( input )
{
    var value = input.split(":").pop();
    return parseInt( value ) == value ? value : "undefined";
}

console.log( getValue( "qwe-tyu-iop[-zxc:10" ) );
console.log( getValue( "::qwe-ty:u-iop[-zxc:10" ) );
console.log( getValue( "::qwe-ty:u-iop[-zxc:10.10" ) );
console.log( getValue( "::qwe-ty:u-iop[-zxc:abc" ) );
console.log( getValue( "::qwe-ty:u-iop[-zxc:afdf10" ) );```

Body:
Simply

inputStr.split(":").pop();

Example

function getValue( input )
{
    var value = input.split(":").pop();
    return parseInt( value ) == value ? value : "undefined";
}

console.log( getValue( "qwe-tyu-iop[-zxc:10" ) );
console.log( getValue( "::qwe-ty:u-iop[-zxc:10" ) );
console.log( getValue( "::qwe-ty:u-iop[-zxc:10.10" ) );
console.log( getValue( "::qwe-ty:u-iop[-zxc:abc" ) );
console.log( getValue( "::qwe-ty:u-iop[-zxc:afdf10" ) );


问:
Call method on downcasted class
I have a certain SomeInterface and I have a number of classes implementing this interface. All these classes have someMethod() that is not defined by the interface.

Say I have a variable someVariable of type SomeInterface and I want to call someMethod() on it. One way to do it is to downcast SomeInterface to SomeClass that implements SomeInterface and call the someMethod on it like this:

```<code>((SomeClass) someVariable).someMethod()
</code>```

But I do not know which one of the classes that implement SomeInterface is stored in someVariable. What is the alternative clean way to call a method that is implemented by an underlying class but not defined by the interface I am coding against.

答:
You can check whether someVariable is storing a SomeClass instance before calling someMethod

```<code>if (someVariable instanceof SomeClass) {
    ((SomeClass)someVariable).someMethod();
} else {
    // do something else
}
</code>```

Title: Call method on downcasted class

Body:
I have a certain SomeInterface and I have a number of classes implementing this interface. All these classes have someMethod() that is not defined by the interface.

Say I have a variable someVariable of type SomeInterface and I want to call someMethod() on it. One way to do it is to downcast SomeInterface to SomeClass that implements SomeInterface and call the someMethod on it like this:

((SomeClass) someVariable).someMethod()

But I do not know which one of the classes that implement SomeInterface is stored in someVariable. What is the alternative clean way to call a method that is implemented by an underlying class but not defined by the interface I am coding against.

Body:
You can check whether someVariable is storing a SomeClass instance before calling someMethod

if (someVariable instanceof SomeClass) {
    ((SomeClass)someVariable).someMethod();
} else {
    // do something else
}


问:
Why does spark mllib define DoubleParam, IntParam, FloatParam, etc?
In Spark params.scala, there are definitions for DoubleParam, IntParam, FloatParam, etc.  I want to know why the developers define those classes?

答:
As can be seen in the param.scala file, Param is a class used by Spark. There are two comments in the code explaining the need of primitive-typed params is needed to make them more Java friendly:

... Primitive-typed param should use the specialized versions, which are more friendly to Java users.

and:

// specialize primitive-typed params because Java doesn't recognize scala.Double, scala.Int, ...

Hence, Double, Int, Float, Long, Boolean and some Array types all ahve their own, specific implementation. These use the Java classes as can be seen here (for Array[Array[Double]]):

```<code>/** Creates a param pair with a `java.util.List` of values (for Java and Python). */
  def w(value: java.util.List[java.util.List[java.lang.Double]]): ParamPair[Array[Array[Double]]] =
    w(value.asScala.map(_.asScala.map(_.asInstanceOf[Double]).toArray).toArray)
</code>```

Body:
As can be seen in the param.scala file, Param is a class used by Spark. There are two comments in the code explaining the need of primitive-typed params is needed to make them more Java friendly:

... Primitive-typed param should use the specialized versions, which are more friendly to Java users.

and:

// specialize primitive-typed params because Java doesn't recognize scala.Double, scala.Int, ...

Hence, Double, Int, Float, Long, Boolean and some Array types all ahve their own, specific implementation. These use the Java classes as can be seen here (for Array[Array[Double]]):

/** Creates a param pair with a `java.util.List` of values (for Java and Python). */
  def w(value: java.util.List[java.util.List[java.lang.Double]]): ParamPair[Array[Array[Double]]] =
    w(value.asScala.map(_.asScala.map(_.asInstanceOf[Double]).toArray).toArray)


问:
Swift String escaping when serializing to JSON using Codable
I'm trying to serialize my object as following:

```<code>import Foundation

struct User: Codable {
    let username: String
    let profileURL: String
}

let user = User(username: "John", profileURL: "http://google.com")

let json = try? JSONEncoder().encode(user)

if let data = json, let str = String(data: data, encoding: .utf8) {
    print(str)
}
</code>```

However on macOS I'm getting the following:

```<code>{"profileURL":"http:\/\/google.com","username":"John"}
</code>```

(note escaped '/' character).

While on Linux machines I'm getting:

```<code>{"username":"John","profileURL":"http://google.com"}
</code>```

How can I make JSONEncoder return the unescaped?

I need the string in JSON to be strictly unescaped.

答:
I got it. The thing was that it didn't contain any \ character. It is just the property of swift that it will always return such a string on a console. The workaround is to j-son parse it.

Still, you can be used below solution of replacing '\/' with "/" string

```<code> let newString = str.replacingOccurrences(of: "\\/", with: "/")
 print(newString)
</code>```

Body:
I'm trying to serialize my object as following:

import Foundation

struct User: Codable {
    let username: String
    let profileURL: String
}

let user = User(username: "John", profileURL: "http://google.com")

let json = try? JSONEncoder().encode(user)

if let data = json, let str = String(data: data, encoding: .utf8) {
    print(str)
}

However on macOS I'm getting the following:

{"profileURL":"http:\/\/google.com","username":"John"}

(note escaped '/' character).

While on Linux machines I'm getting:

{"username":"John","profileURL":"http://google.com"}

How can I make JSONEncoder return the unescaped?

I need the string in JSON to be strictly unescaped.

Body:
I got it. The thing was that it didn't contain any \ character. It is just the property of swift that it will always return such a string on a console. The workaround is to j-son parse it.

Still, you can be used below solution of replacing '\/' with "/" string

 let newString = str.replacingOccurrences(of: "\\/", with: "/")
 print(newString)


问:
How do I return the previous Sunday from 7 days ago using PHP date()?
Here is what I have so far:

```<code>$date = date('Y-m-d h:i:s', strtotime('-7 days'));
$start = date('Y-m-d h:i:s', strtotime($date,'previous Sunday'));
</code>```

When outputting $start, it returns: 1969-12-31 06:00:00

What am I doing wrong?

答:
You have the arguments the wrong way round:

```<code>date('Y-m-d h:i:s', strtotime('previous Sunday', $date));
</code>```

Edit: Furthermore, you have made $date a formatted string. It needs to be a timestamp, so your code should look something like this:

```<code>$date = strtotime('-7 days');
$start = date('Y-m-d h:i:s', strtotime('previous Sunday', $date));
</code>```

Body:
Here is what I have so far:

$date = date('Y-m-d h:i:s', strtotime('-7 days'));
$start = date('Y-m-d h:i:s', strtotime($date,'previous Sunday'));

When outputting $start, it returns: 1969-12-31 06:00:00

What am I doing wrong?

Body:
You have the arguments the wrong way round:

date('Y-m-d h:i:s', strtotime('previous Sunday', $date));

Edit: Furthermore, you have made $date a formatted string. It needs to be a timestamp, so your code should look something like this:

$date = strtotime('-7 days');
$start = date('Y-m-d h:i:s', strtotime('previous Sunday', $date));


答:
Use this approach. Get the index of the last : and get that part from the string. If it is not a number, parseInt will give you NaN

const str = '::qwe-tyu-iop[-zxc:10';
const number = str.substring(str.lastIndexOf(':') + 1);
console.log(Number.parseInt(number));```

Title: How to get a number at the end of a string followed by this character `:` using regex

Body:
I need to get a number (integer) at the end of a string followed by this character :.

Basically:

qwe-tyu-iop[-zxc:10  //result  should be 10

::qwe-ty:u-iop[-zxc:10  //result  should be 10

::qwe-ty:u-iop[-zxc:10.10  //result  should be undefined

::qwe-ty:u-iop[-zxc:abc  //result  should be undefined

::qwe-ty:u-iop[-zxc:afdf10  //result  should be undefined


问:
How to get a quoted printable string in golang
How to get a quoted printable string created according to » RFC2045, section 6.7. in golang

PHP equivalent is "quoted_printable_encode ( string $str )"

答:
Use the standard quotedprintable package to encode the string:</p>

```<code>...

import (
    "bytes"
    "mime/quotedprintable"
    "github.com/pkg/errors"
)

...

func toQuotedPrintable(s string) (string, error) {
    var ac bytes.Buffer
    w := quotedprintable.NewWriter(&ac)
    _, err := w.Write([]byte(s))
    if err != nil {
        return "", errors.Wrap(err, "write")
    }
    err = w.Close()
    if err != nil {
        return "", errors.Wrap(err, "close")
    }
    return ac.String(), nil
}
</code>```

Body:
Use the standard quotedprintable package to encode the string:

...

import (
    "bytes"
    "mime/quotedprintable"
    "github.com/pkg/errors"
)

...

func toQuotedPrintable(s string) (string, error) {
    var ac bytes.Buffer
    w := quotedprintable.NewWriter(&ac)
    _, err := w.Write([]byte(s))
    if err != nil {
        return "", errors.Wrap(err, "write")
    }
    err = w.Close()
    if err != nil {
        return "", errors.Wrap(err, "close")
    }
    return ac.String(), nil
}


问:
Difference between char* and const char*?
What's the difference between </p>

```<code>char* name
</code>```

<p>which points to a constant string literal, and </p>

```<code>const char* name
</code>```

答:
CASE 1:

```<code>char *str = "Hello";
str[0] = 'M'  //Warning may be issued by compiler, and will cause segmentation fault upon running the programme
</code>```

The above sets str to point to the literal value "Hello" which is hard-coded in the program's binary image, which is flagged as read-only in memory, means any change in this String literal is illegal and that would throw segmentation faults.

CASE 2:

```<code>const char *str = "Hello";
str[0] = 'M'  //Compile time error
</code>```

CASE 3:

```<code>char str[] = "Hello";
str[0] = 'M'; // legal and change the str = "Mello".
</code>```

Body:
What's the difference between

char* name

which points to a constant string literal, and

const char* name

Body:
CASE 1:

char *str = "Hello";
str[0] = 'M'  //Warning may be issued by compiler, and will cause segmentation fault upon running the programme

The above sets str to point to the literal value "Hello" which is hard-coded in the program's binary image, which is flagged as read-only in memory, means any change in this String literal is illegal and that would throw segmentation faults.

CASE 2:

const char *str = "Hello";
str[0] = 'M'  //Compile time error

CASE 3:

char str[] = "Hello";
str[0] = 'M'; // legal and change the str = "Mello".


问:
React Native: Creating custom tabs with animation
I have this use case which is a bit confusing compared to the norm , and Im not sure how to structure it. I have a screen (tabs) with 4 tabs .

The thing is that the contents of each tab (their screens) are actually in One big page, when scrolling down the page and it reaches the contents of Tab2 ,  the tab should change too to Tab2 (its not actually a screen change) .

Now initially I have used react-navigation and it's tab navigator. But here Im not sure if this should use tab navigator. The questions that arise to me (from the top of my head):

Q1) If we wrap the components (each tab's screen) in a parent one. How do we go about detecting where the scroll reached! (or something that notifies we are viewing contents of tab2 and so on...)

Q2) How can I handle the animation of the tabs (especially the line under them as shown in the image) to transition back and forth?

Q3) Is there a better way to do this! (better than my initial thoughts above)

答:
Q1. You must use the TabNavigator to avoid the problem as you asking in Q1. So you don't need to worry about the Scroll.

Q2. I recommend using StyleSheet, create a CSS style for line bar then maybe you just need to call a function to set the CSS of current tab or use the navigation options.

Q3. TabNavigator is a good option here and it belongs to react-navigation.

TabNavigator

Animation example with custom function

--- Update ------
I have created an example project for you to solve the problem, I'm not sure if you're doing the same.

Check the Scroll.js, I added a function Callme that changes tabs when scroll reaches to end.

To detect the Scroll reaches to end or not, I have used the isCloseToBottom from another StackOverflow answer.

Follow the following link to Github project.

Change-Tabs-When-Scroll-End

Thanks

_Pradeep


问:
Any idea on change the Apple push service certificate in rails?
I went to my production console and changed the certificate as follows

```<code>prod_app = Rpush::Apns::App.find_by_name(APP_NAME_PRODUCTION)
prod_app.certificate = File.read("path/to/new/certificate.pem")
prod_app.save!
</code>```

But It didn't work for me, even I restarted the server and Rpush service.

Now I see this error in Rpush.log

```<code>[2017-11-09 15:32:57] [ERROR] Rpush::CertificateExpiredError, ios_production certificate expired at 2017-11-09 14:29:24 UTC.
</code>```

答:
I found that there may be threads which is attached or using the old certificate in the server. so Kill them.

to see all the processors using Rpush, run

```<code>ps aux | grep rpush
</code>```

And kill the process

```<code>kill -9 the-pid-number
</code>```

Restart the server

```<code>bundle exec rpush start -p /home/deploy/pml_prod/shared/tmp/pids/rpush.pid -c /home/deploy/pml_prod/shared/config/rpush.rb -e production
</code>```

Body:
I went to my production console and changed the certificate as follows

prod_app = Rpush::Apns::App.find_by_name(APP_NAME_PRODUCTION)
prod_app.certificate = File.read("path/to/new/certificate.pem")
prod_app.save!

But It didn't work for me, even I restarted the server and Rpush service.

Now I see this error in Rpush.log

[2017-11-09 15:32:57] [ERROR] Rpush::CertificateExpiredError, ios_production certificate expired at 2017-11-09 14:29:24 UTC.

Body:
I found that there may be threads which is attached or using the old certificate in the server. so Kill them.

to see all the processors using Rpush, run

ps aux | grep rpush

And kill the process

kill -9 the-pid-number

Restart the server

bundle exec rpush start -p /home/deploy/pml_prod/shared/tmp/pids/rpush.pid -c /home/deploy/pml_prod/shared/config/rpush.rb -e production


问:
In jQuery is there way for slideDown() method to scroll the page down too?
The slideDown() applied to a div element does the slide down, but doesn't scroll the page down and the div slided down div remains hidden from view.

Is there a way to scroll the page down as well so the user can view the div?

答:
```<code>$.extend($.expr[':'],{
    inView: function(a) {
        var st = (document.documentElement.scrollTop || document.body.scrollTop),
            ot = $(a).offset().top,
            wh = (window.innerHeight && window.innerHeight < $(window).height()) ? window.innerHeight : $(window).height();
        return ot > st && ($(a).height() + ot) < (st + wh);
    }
});

if ($('#whatever').is(':not(:inView)')) {
    $('html,body').animate({
         scrollTop: $('#whatever').offset().top
    }, 3000);
}
</code>```

OwnerDisplayName: Xardas

LastEditorDisplayName: Rob

OwnerDisplayName: JimmyP


问:
How to make UIView on top of all tab in UITabBarController
To make uiview on top of all tabs of uitabbar controller .
I planned to make one baseviewcontroller  named "uiView.swift" .In "uiView.swift" i added my uiview. After that i want to inherit each tab ViewController (say "resturent.swift") from that uiView.swift. So, in each tab of UITabBarController you will get that "uiView.swift" view resued.uiView.swift is connected to  ViewController in Storyboard that has button that show the view on button click  .Here is my "uiView.swift"

```<code>class uiView: UIViewController {
var menuView: UIView?

    override func viewDidLoad() {
        super.viewDidLoad()
        menuView = UIView(frame: CGRect(x: 0, y: -200, width: 420, height: 200))
        menuView?.backgroundColor = UIColor.green
        view.addSubview(menuView!)
    }
    @objc func MyBag(){

    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    @IBAction func collectionmenuone(_ sender: Any) {
       menuView=UIView(frame: CGRect(x: 0, y: 0, width: 420, height: 200))
        menuView?.backgroundColor=UIColor.lightGray
        self.view.addSubview(menuView!)

        var btnbag = UIButton(type: .roundedRect)
        btnbag.addTarget(self, action: #selector(self.MyBag), for: .touchUpInside)
        btnbag.frame = CGRect(x: 104, y:130 , width: 150, height: 60)
        btnbag.setTitle("Done", for: .normal)
        btnbag.backgroundColor=UIColor.green
        menuView?.addSubview(btnbag)

    }

}
</code>```

how i can make possible reuse of view from "uiView.swift" in each tab of tabbar controller (i.e "resturent.swif")

```<code>class resturent:UICollectionViewController,UICollectionViewDelegateFlowLayout {

    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.title="Seafood"
        collectionView?.backgroundColor=UIColor.white
        // view.backgroundColor=UIColor.redColor
        collectionView?.register(VideoCell.self, forCellWithReuseIdentifier: "cellid")
    }
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 5
    }
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell=collectionView.dequeueReusableCell(withReuseIdentifier: "cellid", for: indexPath)
        // cell.backgroundColor=UIColor.red
        return cell
    }
    /* override func collectionView(collectionView: UICollectionView, cellForItemAtIndexpath indexPath: NSIndexPath) -> UICollectionViewCell {
     let cell=collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath as IndexPath)

     return cell
     }*/
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let height=(view.frame.width - 16 - 16) * 9/16
        return  CGSize(width: view.frame.width, height: height + 16 + 68)
    }
}
class VideoCell:UICollectionViewCell{
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
    }
    let thumbnailImageView:UIImageView = {
        let imageView=UIImageView()
        imageView.backgroundColor=UIColor.blue
        imageView.image=UIImage(named: "food24")
        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds=true
        return imageView
    }()
    let userProfileImageView:UIImageView={
        let imageView=UIImageView()
        //imageView.backgroundColor=UIColor.green
        return imageView
    }()
    let separatorView:UIView = {
        let view = UIView ()
        view.backgroundColor=UIColor(red: 230/255, green: 230/255, blue: 230/255, alpha: 1)
        return view
    }()
    let titleLabel:UILabel={
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints=false
        label.text="Resturant name here"
        return label
    }()
    let subtitleTextView:UITextView = {
        let textView=UITextView()
        textView.translatesAutoresizingMaskIntoConstraints=false
        textView.textContainerInset=UIEdgeInsetsMake(0, -4, 0, 0)
        textView.textColor=UIColor.lightGray
        textView.text = "SeaFood"
        return textView
    }()
    func setupView()  {
        //backgroundColor=UIColor.blue
        addSubview(thumbnailImageView)
        addSubview(separatorView)
        addSubview(userProfileImageView)
        addSubview(titleLabel)
        addSubview(subtitleTextView)
        addConstraintsWithFormat(format: "H:|-16-[v0]-16-|", view: thumbnailImageView)
        addConstraintsWithFormat(format: "H:|-16-[v0(44)]", view: userProfileImageView)
        //vertial constratints
        addConstraintsWithFormat(format: "V:|-16-[v0]-8-[v1(44)]-16-[v2(1)]|", view: thumbnailImageView,userProfileImageView,separatorView)
        addConstraintsWithFormat(format: "H:|[v0]|", view: separatorView)
        //top constraints
        addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .top, relatedBy: .equal, toItem:thumbnailImageView , attribute: .bottom, multiplier: 1, constant: 8))
        //left constaints
        addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .left, relatedBy: .equal, toItem: userProfileImageView, attribute: .right, multiplier: 1, constant: 8))
        //right constraint
        addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .right, relatedBy: .equal, toItem: thumbnailImageView, attribute: .right, multiplier: 8, constant: 0))
        //height constraint
        addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .height, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 0, constant: 20))

        //top constraints
        addConstraint(NSLayoutConstraint(item: subtitleTextView, attribute: .top, relatedBy: .equal, toItem:titleLabel , attribute: .bottom, multiplier: 1, constant: 4))
        //left constaints
        addConstraint(NSLayoutConstraint(item: subtitleTextView, attribute: .left, relatedBy: .equal, toItem: userProfileImageView, attribute: .right, multiplier: 1, constant: 8))
        //right constraint
        addConstraint(NSLayoutConstraint(item: subtitleTextView, attribute: .right, relatedBy: .equal, toItem: thumbnailImageView, attribute: .right, multiplier: 8, constant: 0))
        //height constraint
        addConstraint(NSLayoutConstraint(item: subtitleTextView, attribute: .height, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 0, constant: 20))

        // addConstraintsWithFormat(format: "V:[v0(20)]", view: titleLabel)
        //  addConstraintsWithFormat(format: "H:|[v0]|", view: titleLabel)

    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
extension UIView{
    func addConstraintsWithFormat(format:String,view:UIView...){
        var viewDictionary=[String:UIView]()
        for (index,view) in view.enumerated(){
            let key="v\(index)"
            view.translatesAutoresizingMaskIntoConstraints=false
            viewDictionary[key]=view
        }
        NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: format , options: NSLayoutFormatOptions(), metrics: nil, views: viewDictionary))
    }

}
</code>```

uiView.swift is of type UIViewController and resturent.swif is of type UICollectionViewController.You can change the entry point of app from uiView.swift to login View controller(Viewcontroller.swift) to run app.How by inheritance i can reuse the view in uiView.swift ?you can download the project from this link .https://drive.google.com/file/d/1XSwOZcfvglB_7Zt_E8W8W3Dym3i1_lrB/view?usp=sharing

答:
You should not add your menu View on any of your view. Instead of this you can direct add it on your window from AppDelegate.
Adding a view on window will place it above all the views that is been currently visible.</p>

Body:
To make uiview on top of all tabs of uitabbar controller .
I planned to make one baseviewcontroller  named "uiView.swift" .In "uiView.swift" i added my uiview. After that i want to inherit each tab ViewController (say "resturent.swift") from that uiView.swift. So, in each tab of UITabBarController you will get that "uiView.swift" view resued.uiView.swift is connected to  ViewController in Storyboard that has button that show the view on button click  .Here is my "uiView.swift"

class uiView: UIViewController {
var menuView: UIView?

    override func viewDidLoad() {
        super.viewDidLoad()
        menuView = UIView(frame: CGRect(x: 0, y: -200, width: 420, height: 200))
        menuView?.backgroundColor = UIColor.green
        view.addSubview(menuView!)
    }
    @objc func MyBag(){

    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    @IBAction func collectionmenuone(_ sender: Any) {
       menuView=UIView(frame: CGRect(x: 0, y: 0, width: 420, height: 200))
        menuView?.backgroundColor=UIColor.lightGray
        self.view.addSubview(menuView!)

        var btnbag = UIButton(type: .roundedRect)
        btnbag.addTarget(self, action: #selector(self.MyBag), for: .touchUpInside)
        btnbag.frame = CGRect(x: 104, y:130 , width: 150, height: 60)
        btnbag.setTitle("Done", for: .normal)
        btnbag.backgroundColor=UIColor.green
        menuView?.addSubview(btnbag)

    }

}

how i can make possible reuse of view from "uiView.swift" in each tab of tabbar controller (i.e "resturent.swif")

class resturent:UICollectionViewController,UICollectionViewDelegateFlowLayout {

    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.title="Seafood"
        collectionView?.backgroundColor=UIColor.white
        // view.backgroundColor=UIColor.redColor
        collectionView?.register(VideoCell.self, forCellWithReuseIdentifier: "cellid")
    }
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 5
    }
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell=collectionView.dequeueReusableCell(withReuseIdentifier: "cellid", for: indexPath)
        // cell.backgroundColor=UIColor.red
        return cell
    }
    /* override func collectionView(collectionView: UICollectionView, cellForItemAtIndexpath indexPath: NSIndexPath) -> UICollectionViewCell {
     let cell=collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath as IndexPath)

     return cell
     }*/
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let height=(view.frame.width - 16 - 16) * 9/16
        return  CGSize(width: view.frame.width, height: height + 16 + 68)
    }
}
class VideoCell:UICollectionViewCell{
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
    }
    let thumbnailImageView:UIImageView = {
        let imageView=UIImageView()
        imageView.backgroundColor=UIColor.blue
        imageView.image=UIImage(named: "food24")
        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds=true
        return imageView
    }()
    let userProfileImageView:UIImageView={
        let imageView=UIImageView()
        //imageView.backgroundColor=UIColor.green
        return imageView
    }()
    let separatorView:UIView = {
        let view = UIView ()
        view.backgroundColor=UIColor(red: 230/255, green: 230/255, blue: 230/255, alpha: 1)
        return view
    }()
    let titleLabel:UILabel={
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints=false
        label.text="Resturant name here"
        return label
    }()
    let subtitleTextView:UITextView = {
        let textView=UITextView()
        textView.translatesAutoresizingMaskIntoConstraints=false
        textView.textContainerInset=UIEdgeInsetsMake(0, -4, 0, 0)
        textView.textColor=UIColor.lightGray
        textView.text = "SeaFood"
        return textView
    }()
    func setupView()  {
        //backgroundColor=UIColor.blue
        addSubview(thumbnailImageView)
        addSubview(separatorView)
        addSubview(userProfileImageView)
        addSubview(titleLabel)
        addSubview(subtitleTextView)
        addConstraintsWithFormat(format: "H:|-16-[v0]-16-|", view: thumbnailImageView)
        addConstraintsWithFormat(format: "H:|-16-[v0(44)]", view: userProfileImageView)
        //vertial constratints
        addConstraintsWithFormat(format: "V:|-16-[v0]-8-[v1(44)]-16-[v2(1)]|", view: thumbnailImageView,userProfileImageView,separatorView)
        addConstraintsWithFormat(format: "H:|[v0]|", view: separatorView)
        //top constraints
        addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .top, relatedBy: .equal, toItem:thumbnailImageView , attribute: .bottom, multiplier: 1, constant: 8))
        //left constaints
        addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .left, relatedBy: .equal, toItem: userProfileImageView, attribute: .right, multiplier: 1, constant: 8))
        //right constraint
        addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .right, relatedBy: .equal, toItem: thumbnailImageView, attribute: .right, multiplier: 8, constant: 0))
        //height constraint
        addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .height, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 0, constant: 20))

        //top constraints
        addConstraint(NSLayoutConstraint(item: subtitleTextView, attribute: .top, relatedBy: .equal, toItem:titleLabel , attribute: .bottom, multiplier: 1, constant: 4))
        //left constaints
        addConstraint(NSLayoutConstraint(item: subtitleTextView, attribute: .left, relatedBy: .equal, toItem: userProfileImageView, attribute: .right, multiplier: 1, constant: 8))
        //right constraint
        addConstraint(NSLayoutConstraint(item: subtitleTextView, attribute: .right, relatedBy: .equal, toItem: thumbnailImageView, attribute: .right, multiplier: 8, constant: 0))
        //height constraint
        addConstraint(NSLayoutConstraint(item: subtitleTextView, attribute: .height, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 0, constant: 20))

        // addConstraintsWithFormat(format: "V:[v0(20)]", view: titleLabel)
        //  addConstraintsWithFormat(format: "H:|[v0]|", view: titleLabel)

    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
extension UIView{
    func addConstraintsWithFormat(format:String,view:UIView...){
        var viewDictionary=[String:UIView]()
        for (index,view) in view.enumerated(){
            let key="v\(index)"
            view.translatesAutoresizingMaskIntoConstraints=false
            viewDictionary[key]=view
        }
        NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: format , options: NSLayoutFormatOptions(), metrics: nil, views: viewDictionary))
    }

}

uiView.swift is of type UIViewController and resturent.swif is of type UICollectionViewController.You can change the entry point of app from uiView.swift to login View controller(Viewcontroller.swift) to run app.How by inheritance i can reuse the view in uiView.swift ?you can download the project from this link .https://drive.google.com/file/d/1XSwOZcfvglB_7Zt_E8W8W3Dym3i1_lrB/view?usp=sharing


问:
How to make other styles set as default when we changing class of element using JavaScript
I have created div and place it right margin of the page with position:fixed. I need to place the div to bottom margin when I call the JavaScript function. I tried to use classList.add() and classList.remove() to accomplish my task.

here is the CSS classes I created,

```<code>.example-right{
        position:fixed;
        top:50px;
        right:0px;
    }
.example-bottom{
        position:fixed;
        left:50px;
        bottom:0px;
    }
</code>```

This is JavaScript code what I tried,

```<code>function test(){
  document.getElementById('target').classList.remove('example-right');
  document.getElementById('target').classList.add('example-bottom');
}
</code>```

When I trigger the test() function it removes the example-right and replace it with example-bottom. But the div's top value is not going to change after the function is triggered. So, it is not place the div on bottom margin of the window. I can puttop:## px; to example-bottom. But when page is resizing and

Is it possible to Solve this problem using CSS. I know I can use document.getElementById('target').style.top = window.innerHeight- div_Height to change the top value. but I like to know is there any way to do it using css or another method. (otherwise I have to use JavaScript all the times when I need to change the position)

pure CSS and JavaScript only

答:
You . have done right. Only thing is understanding a  bit of css more.

.example-right{
        position:fixed;
        top:50px;
        right:0px;
    }
.example-bottom{
        position:fixed;
        top:inital
        left:50px;
        bottom:0px;
    }```

Body:
I have created div and place it right margin of the page with position:fixed. I need to place the div to bottom margin when I call the JavaScript function. I tried to use classList.add() and classList.remove() to accomplish my task.

here is the CSS classes I created,

.example-right{
        position:fixed;
        top:50px;
        right:0px;
    }
.example-bottom{
        position:fixed;
        left:50px;
        bottom:0px;
    }

This is JavaScript code what I tried,

function test(){
  document.getElementById('target').classList.remove('example-right');
  document.getElementById('target').classList.add('example-bottom');
}

When I trigger the test() function it removes the example-right and replace it with example-bottom. But the div's top value is not going to change after the function is triggered. So, it is not place the div on bottom margin of the window. I can puttop:## px; to example-bottom. But when page is resizing and

Is it possible to Solve this problem using CSS. I know I can use document.getElementById('target').style.top = window.innerHeight- div_Height to change the top value. but I like to know is there any way to do it using css or another method. (otherwise I have to use JavaScript all the times when I need to change the position)

pure CSS and JavaScript only


问:
Auto generate ranges of Examples in Specflow Scenario Outline
In Specflow, although I know about the Scenario Outline / Examples feature, I was wondering if there is a more elegant way to generate ranges and combinations to be used in test cases?

For example, in vanilla NUnit, I can use a TestCaseSource or Theory to build a generator which I can feed in a large number of test cases into a test.

private static readonly IEnumerable<int> Numbers = Enumerable.Range(1, 50);

[TestCaseSource(nameof(Numbers))]
public void TestFoo(int number)
{
    // Test goes here.
}
```

<p>At present, in my tests, I need to manually create all permutations in my <code>Examples</code>, which can be hard to read, and potentially error prone.</p>

```Scenario Outline: Count things
    Given I'm playing a game of counting
    When I count to <number>
    Then the highest number I should have counted to should be <number>

    Examples:
        | number|
        | 1    |
        | 2    |
        | 3    |
        ...
        | 50    |
```

<p>What I would really like to be able to do would be</p>

```Examples:
    | number| : Range 1 to 20
```

<p>And even better, create the cartesian product of two sets, i.e.:</p>

```Examples:
    | number1| : Range 1 to 20
    | number2| : Range 5 to 10

// i.e. 20 x 5 = 100 combinations of the tuple (number1, number2)
```

Is there anyway for me to approach this more elegantly in Specflow?

答:
You can dynamically generate the range of numbers from two inputs as a step.

For example:

```<code>Scenario Outline: Count things
    Given I'm playing a game of counting
    When I count from <First Number> to <Last Number>
    Then the highest number I should have counted to should be <Last Number>

    Examples:
        | Description        | First Number| Last Number |
        | Count from 1 to 20 | 1           | 20          |
        | Count from 5 to 10 | 5           | 10          |
</code>```

And then the When step can be defined as something like this:

```<code>[When("I count from (\d+) to (\d+)")]
public void ICountFromFirstNumberToLastNumber(int firstNumber, int lastNumber)
{
    IEnumerable<int> numbers = Enumerable.Range(firstNumber, lastNumber);
    this.countResult = this.Count(numbers);
}
</code>```

Body:
In Specflow, although I know about the Scenario Outline / Examples feature, I was wondering if there is a more elegant way to generate ranges and combinations to be used in test cases?

For example, in vanilla NUnit, I can use a TestCaseSource or Theory to build a generator which I can feed in a large number of test cases into a test.

private static readonly IEnumerable<int> Numbers = Enumerable.Range(1, 50);

[TestCaseSource(nameof(Numbers))]
public void TestFoo(int number)
{
    // Test goes here.
}

At present, in my tests, I need to manually create all permutations in my Examples, which can be hard to read, and potentially error prone.

Scenario Outline: Count things
    Given I'm playing a game of counting
    When I count to <number>
    Then the highest number I should have counted to should be <number>

    Examples:
        | number|
        | 1    |
        | 2    |
        | 3    |
        ...
        | 50    |

What I would really like to be able to do would be

Examples:
    | number| : Range 1 to 20

And even better, create the cartesian product of two sets, i.e.:

Examples:
    | number1| : Range 1 to 20
    | number2| : Range 5 to 10

// i.e. 20 x 5 = 100 combinations of the tuple (number1, number2)

Is there anyway for me to approach this more elegantly in Specflow?

Body:
You can dynamically generate the range of numbers from two inputs as a step.

For example:

Scenario Outline: Count things
    Given I'm playing a game of counting
    When I count from <First Number> to <Last Number>
    Then the highest number I should have counted to should be <Last Number>

    Examples:
        | Description        | First Number| Last Number |
        | Count from 1 to 20 | 1           | 20          |
        | Count from 5 to 10 | 5           | 10          |

And then the When step can be defined as something like this:

[When("I count from (\d+) to (\d+)")]
public void ICountFromFirstNumberToLastNumber(int firstNumber, int lastNumber)
{
    IEnumerable<int> numbers = Enumerable.Range(firstNumber, lastNumber);
    this.countResult = this.Count(numbers);
}


问:
Memory leak - promises in a loop
My node app's CPU usage is gradually increasing. I have found that memory leaks are happening. Through AppDynamics, I have found that there is a significant amount of retained memory which keeps increasing over time under processImmediate call tree. As I drilled in, I found the problem was with settlePromises function.

I want to get your opinion on one particular usage of promises I have been using. Looping of promises. Below is a sample function structure of such usage.

```<code>var dataArray = []; //list of jsons
var Promise = require('node-promise').Promise;

function doSomething(){
    try{
        var promises = [];
        //create function promises and push
        for(var i in dataArray){
            var usage = {};
            usage["user"] = dataArray[i].user;
            promises.push((function(ob){
                var log = extend({},ob);
                return executeFunction(log)}).bind(null,usage));
        }

        //loop and execute
        var respArray = [];
        return (promises.reduce(function(previous , current , index , array){
            try{
                return previous.then(function(resp){
                    if(resp != null)
                        respArray.push(resp);
                    if(promises.indexOf(current)==promises.length -1){
                        return current();
                    }
                    else{
                        return current();
                    }
                });
            }catch(ex){
                throw { ex : ex.stack};
            }
        },delay())).then(function(){
            return data;
        });
    }
    catch(ex){
        console.log(ex,ex.stack);
        throw { ex : ex.stack};
    }
}

function logTemplate(log){
    return models.Users.create(log).then(function(resp){
        return resp;
    },function(err){
        return err;
    });
}
</code>```

The heap growth over an hour is plotted in the below picture

The above function has to perform a synchronous update with the objects in data array. Is there a chance of memory leak with this?

答:
Not sure whether it would be the cause of memory leaks, but your function definitely has a ton of unnecessary cruft that could be cleaned up with Bluebird's Promise.mapSeries() and other Bluebird helpers.

Doing so may very well help cut down on memory leaks.

doSomething function reduced to 8 lines:

```<code>function doSomething(){
    return Promise.delay(1000)  // <-- specify time
        .return(dataArray)
        .mapSeries(function (el) {
            return executeFunction({ user: el.user });
        })
        .filter(function (result) {
            return result !== null;
        });
}
</code>```

Title: Memory leak - promises in a loop

Body:
My node app's CPU usage is gradually increasing. I have found that memory leaks are happening. Through AppDynamics, I have found that there is a significant amount of retained memory which keeps increasing over time under processImmediate call tree. As I drilled in, I found the problem was with settlePromises function.

I want to get your opinion on one particular usage of promises I have been using. Looping of promises. Below is a sample function structure of such usage.

var dataArray = []; //list of jsons
var Promise = require('node-promise').Promise;

function doSomething(){
    try{
        var promises = [];
        //create function promises and push
        for(var i in dataArray){
            var usage = {};
            usage["user"] = dataArray[i].user;
            promises.push((function(ob){
                var log = extend({},ob);
                return executeFunction(log)}).bind(null,usage));
        }

        //loop and execute
        var respArray = [];
        return (promises.reduce(function(previous , current , index , array){
            try{
                return previous.then(function(resp){
                    if(resp != null)
                        respArray.push(resp);
                    if(promises.indexOf(current)==promises.length -1){
                        return current();
                    }
                    else{
                        return current();
                    }
                });
            }catch(ex){
                throw { ex : ex.stack};
            }
        },delay())).then(function(){
            return data;
        });
    }
    catch(ex){
        console.log(ex,ex.stack);
        throw { ex : ex.stack};
    }
}

function logTemplate(log){
    return models.Users.create(log).then(function(resp){
        return resp;
    },function(err){
        return err;
    });
}

The heap growth over an hour is plotted in the below picture

The above function has to perform a synchronous update with the objects in data array. Is there a chance of memory leak with this?

Body:
Not sure whether it would be the cause of memory leaks, but your function definitely has a ton of unnecessary cruft that could be cleaned up with Bluebird's Promise.mapSeries() and other Bluebird helpers.

Doing so may very well help cut down on memory leaks.

doSomething function reduced to 8 lines:

function doSomething(){
    return Promise.delay(1000)  // <-- specify time
        .return(dataArray)
        .mapSeries(function (el) {
            return executeFunction({ user: el.user });
        })
        .filter(function (result) {
            return result !== null;
        });
}


问:
ExpressJS post route is not working and returning an error
I am working on a Mean stack application, I have defined an expressjs backend post route to store some data on server, but its not working and returning an error message which is provided for handling errors 'An error occurred in form api'.

```<code>router.post('/userform', function (req, res, next) {
    var form = new Form({
        controlType: req.body.controlType,
        label: req.body.label,
        required:req.body.required ,
        placeholder: req.body.placeholder,
        options: req.body.options
    });
    form.save(function(err, result) {
        if (err) {
            return res.status(500).json({
                title: 'An error occurred in form api',
                error: err
            });
        }
        res.status(201).json({
            message: 'Form created',
            obj: result
        });
    });
});
</code>```

Its the mongoose schema that I am using:

```<code>var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var mongooseUniqueValidator = require('mongoose-unique-validator');

var formSchema = new Schema({
    controlType: {type: String, required: true},
    label: {type: String, required: true},
    required: {type: Boolean},
    placeholder: {type: String},
    options: [String],    //to store options for select or radio input
} ,  {collection: 'inputForm'});

formSchema.plugin(mongooseUniqueValidator);

module.exports = mongoose.model('Form', formSchema);
</code>```

It is the app.js file:

```<code>// Get dependencies
const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');

var mongoose = require('mongoose');
// Get our API routes
const api = require('./routes/api');
const formApi = require('./routes/form');

const app = express();
mongoose.connect('localhost:27017/test-mean');

// Parsers for POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// Point static path to dist
app.use(express.static(path.join(__dirname, 'dist')));

//to avoid cross origin requests errors
app.use(function (req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PATCH, DELETE, OPTIONS');
  next();
});

// Set our api routes
app.use('/api', api);
app.use('/form', formApi);

// Catch all other routes and return the index file
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/index.html'));
});

/**
 * Get port from environment and store in Express.
 */
const port = process.env.PORT || '3000';
app.set('port', port);

/**
 * Create HTTP server.
 */
const server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */
server.listen(port, () => console.log(`API running on localhost:${port}`));
</code>```

Please help. Thanks

答:
Add your body-parser code above all router

```<code>// Get dependencies
const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');

var mongoose = require('mongoose');

// Parsers for POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// Get our API routes
const api = require('./routes/api');
const formApi = require('./routes/form');

const app = express();
mongoose.connect('localhost:27017/test-mean');

// Point static path to dist
app.use(express.static(path.join(__dirname, 'dist')));

//to avoid cross origin requests errors
app.use(function (req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PATCH, DELETE, OPTIONS');
  next();
});

// Set our api routes
app.use('/api', api);
app.use('/form', formApi);

// Catch all other routes and return the index file
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/index.html'));
});

/**
 * Get port from environment and store in Express.
 */
const port = process.env.PORT || '3000';
app.set('port', port);

/**
 * Create HTTP server.
 */
const server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */
server.listen(port, () => console.log(`API running on localhost:${port}`));
</code>```

Body:
I am working on a Mean stack application, I have defined an expressjs backend post route to store some data on server, but its not working and returning an error message which is provided for handling errors 'An error occurred in form api'.

router.post('/userform', function (req, res, next) {
    var form = new Form({
        controlType: req.body.controlType,
        label: req.body.label,
        required:req.body.required ,
        placeholder: req.body.placeholder,
        options: req.body.options
    });
    form.save(function(err, result) {
        if (err) {
            return res.status(500).json({
                title: 'An error occurred in form api',
                error: err
            });
        }
        res.status(201).json({
            message: 'Form created',
            obj: result
        });
    });
});

Its the mongoose schema that I am using:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var mongooseUniqueValidator = require('mongoose-unique-validator');

var formSchema = new Schema({
    controlType: {type: String, required: true},
    label: {type: String, required: true},
    required: {type: Boolean},
    placeholder: {type: String},
    options: [String],    //to store options for select or radio input
} ,  {collection: 'inputForm'});

formSchema.plugin(mongooseUniqueValidator);

module.exports = mongoose.model('Form', formSchema);

It is the app.js file:

// Get dependencies
const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');

var mongoose = require('mongoose');
// Get our API routes
const api = require('./routes/api');
const formApi = require('./routes/form');

const app = express();
mongoose.connect('localhost:27017/test-mean');

// Parsers for POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// Point static path to dist
app.use(express.static(path.join(__dirname, 'dist')));

//to avoid cross origin requests errors
app.use(function (req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PATCH, DELETE, OPTIONS');
  next();
});

// Set our api routes
app.use('/api', api);
app.use('/form', formApi);

// Catch all other routes and return the index file
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/index.html'));
});

/**
 * Get port from environment and store in Express.
 */
const port = process.env.PORT || '3000';
app.set('port', port);

/**
 * Create HTTP server.
 */
const server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */
server.listen(port, () => console.log(`API running on localhost:${port}`));

Please help. Thanks

Body:
Add your body-parser code above all router

// Get dependencies
const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');

var mongoose = require('mongoose');

// Parsers for POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// Get our API routes
const api = require('./routes/api');
const formApi = require('./routes/form');

const app = express();
mongoose.connect('localhost:27017/test-mean');

// Point static path to dist
app.use(express.static(path.join(__dirname, 'dist')));

//to avoid cross origin requests errors
app.use(function (req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PATCH, DELETE, OPTIONS');
  next();
});

// Set our api routes
app.use('/api', api);
app.use('/form', formApi);

// Catch all other routes and return the index file
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/index.html'));
});

/**
 * Get port from environment and store in Express.
 */
const port = process.env.PORT || '3000';
app.set('port', port);

/**
 * Create HTTP server.
 */
const server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */
server.listen(port, () => console.log(`API running on localhost:${port}`));


问:
decompose color code in react material
I am using react-material and MuiThemeProvider component to use theme.

Here is the code that I copy from the example given below on the website

```<code>const theme = createMuiTheme({
  palette: {
    primary: purple, // Purple and green play nicely together.
    secondary: {
      ...green,
      A400: '#00e677',
    },
    error: red,
  },
});
</code>```

when I changed in the above code primary:'#2ab667' like this it gives an error

So, I don't know where I did wrong or how to use any color code rather using specific color from material

答:
It seems the values must be objects. Try giving like what you did for secondary, defining primary as an object:

```<code>primary: {
  50: '#f3e5f5',    // replace or delete all colors as you wish
  100: '#e1bee7',
  200: '#ce93d8',
  300: '#ba68c8',
  400: '#ab47bc',
  500: '#9c27b0',
  600: '#8e24aa',
  700: '#7b1fa2',
  800: '#6a1b9a',
  900: '#4a148c',
  A100: '#ea80fc',
  A200: '#e040fb',
  A400: '#d500f9',
  A700: '#aa00ff',
  contrastDefaultColor: 'light',
};
</code>```

or to reuse purple with certain shades changed:

```<code>primary: {
  ...purple,
  A700: '#aa00ff',
};
</code>```

UPDATE In your case, you could use a snippet like this (I've used your color code #2ab667 for A400 an different shades of that in other keys):

```<code>primary: {
  A100: '#ADF9CE',
  A200: '#5EE599',
  A400: '#2ab667',
  A700: '#188146',
  contrastDefaultColor: 'light'
},
secondary: ...
</code>```

Title: decompose color code in react material

Body:
I am using react-material and MuiThemeProvider component to use theme.

Here is the code that I copy from the example given below on the website

const theme = createMuiTheme({
  palette: {
    primary: purple, // Purple and green play nicely together.
    secondary: {
      ...green,
      A400: '#00e677',
    },
    error: red,
  },
});

when I changed in the above code primary:'#2ab667' like this it gives an error

So, I don't know where I did wrong or how to use any color code rather using specific color from material

Body:
It seems the values must be objects. Try giving like what you did for secondary, defining primary as an object:

primary: {
  50: '#f3e5f5',    // replace or delete all colors as you wish
  100: '#e1bee7',
  200: '#ce93d8',
  300: '#ba68c8',
  400: '#ab47bc',
  500: '#9c27b0',
  600: '#8e24aa',
  700: '#7b1fa2',
  800: '#6a1b9a',
  900: '#4a148c',
  A100: '#ea80fc',
  A200: '#e040fb',
  A400: '#d500f9',
  A700: '#aa00ff',
  contrastDefaultColor: 'light',
};

or to reuse purple with certain shades changed:

primary: {
  ...purple,
  A700: '#aa00ff',
};

UPDATE In your case, you could use a snippet like this (I've used your color code #2ab667 for A400 an different shades of that in other keys):

primary: {
  A100: '#ADF9CE',
  A200: '#5EE599',
  A400: '#2ab667',
  A700: '#188146',
  contrastDefaultColor: 'light'
},
secondary: ...


问:
Convert struct with pointer to char array
I am currently trying to find the simplest way to convert a struct which contains a char * to a char array for transmitting a serial data frame.

The struct stores the frame headers, checksum, msg size etc along with the data to be transmit. eg

```<code>struct {
    unsigned char header;
    unsigned char msgSizeL;
    unsigned char msgSizeH;
    unsigned char *data;
    unsigned char checksum;
    ....
    ....
    ....
    ....
    unsinged char endFrame;
} Frame;
</code>```

The data is a pointer as the amount of data can change with each frame transmit in the range from 1 to 16 bytes.

I am trying to find the simplest way to convert the struct to an array of unsigned chars without copying out each entry in the struct to the array but don't seem to be able to find a way.

Alternately I don't have to use a struct, as i am generating the frame contents excluding the data contents from scratch, I just want to avoid a case of -

```<code>unsigned char frame[1000];
frame[0] = 0x01; // header
frame[1] = msgSizeL; // msg size low byte
frame[2] = msgSizeH; // msg size high byte
frame[3] = data[0]; // data contents 0    Over simplification
frame[4] = data[1]; // data contents 1    for data copying -
frame[5] = data[2]; // data contents 2    data length is variable.
frame[6] = data[3]; // data contents 3
frame[7] = data[4]; // data contents 4
frame[8] = data[5]; // data contents 5
frame[9] = data[6]; // data contents 6
frame[10] = data[7]; // data contents 7
frame[3 + msgSize]; = getChecksum(data);
....
....
....
....
frame [3 + msgSize + 20] = 0xFF; // end frame
</code>```

where i write data to what reads as a random array index rather than something meaningful like frame.checksum = getChecksum(data);.

Open to suggestions and a little bit of flaming for asking a general question rather than a specific one :-)

答:
You have two options:

1. dynamic frame length

```<code>struct {
    unsigned char header;
    unsigned char msgSizeL; // this will be dynamic from 0x06 (empty) to 0x16 (full)
    unsigned char msgSizeH; // this will be always 0x00
    unsigned char dataSize; // specify the data size here
    unsigned char data[16]; // use a static memory area for the package
    unsigned char checksum;
    unsigned char endFrame;
} Frame;
</code>```

then you can do this:

```<code>Frame xFrame;
unsigned char ucaData[17] = {0}; // your data
unsigned int uiDataLength = 6; // for example
memset(&xFrame, 0, sizeof(Frame)); // just to be sure
xFrame.header = 0x01;
xFrame.msgSizeL = uiDataLength;
xFrame.msgSizeH = 0;
xFrame.dataSize = uiDataLength;
memcpy(xFrame.data, ucaData, uiDataLength);
xFrame.checksum = CRC8(&xFrame, uiDataLength + 4); // crc for filled area
xFrame.endFrame = 0xFF;
</code>```

then when building the package:

```<code>unsigned char xDataFrame[1000];
memcpy(xDataFrame, xFrame, 4 + uiDataLength);
memcpy(xDataFrame + 4 + uiDataLength, &xFrame + 20, 2);
transmit(xDataFrame, 6 + uiDataLength);
</code>```

This way, you will discard empty bytes from sending and from calculating checksum for.

2. static frame length

Then you can use a struct like this:

```<code>struct {
    unsigned char header;
    unsigned char msgSizeL; // this will be always 0x16 (22)
    unsigned char msgSizeH; // this will be always 0x00
    unsigned char dataSize; // specify the data size here
    unsigned char data[16]; // use a static memory area for the package
    unsigned char checksum;
    unsigned char endFrame;
} Frame;
</code>```

This way you can calculate the checksum for the first 20 bytes of this structure, but be aware of that this structure may contain padding areas which may move your data around the defined and padded memory area. sizeof(Frame) may be calculated by hand as 22 bytes but the compiler may decide that it should use 32 bytes or 24 bytes of memory related with the pack setting. You may use

```<code>#pragma pack(1) // disable padding
[structure code]
#pragma pack()  // back to the original setting
</code>```

More info about packing:

#pragma pack effect

Body:
I am currently trying to find the simplest way to convert a struct which contains a char * to a char array for transmitting a serial data frame.

The struct stores the frame headers, checksum, msg size etc along with the data to be transmit. eg

struct {
    unsigned char header;
    unsigned char msgSizeL;
    unsigned char msgSizeH;
    unsigned char *data;
    unsigned char checksum;
    ....
    ....
    ....
    ....
    unsinged char endFrame;
} Frame;

The data is a pointer as the amount of data can change with each frame transmit in the range from 1 to 16 bytes.

I am trying to find the simplest way to convert the struct to an array of unsigned chars without copying out each entry in the struct to the array but don't seem to be able to find a way.

Alternately I don't have to use a struct, as i am generating the frame contents excluding the data contents from scratch, I just want to avoid a case of -

unsigned char frame[1000];
frame[0] = 0x01; // header
frame[1] = msgSizeL; // msg size low byte
frame[2] = msgSizeH; // msg size high byte
frame[3] = data[0]; // data contents 0    Over simplification
frame[4] = data[1]; // data contents 1    for data copying -
frame[5] = data[2]; // data contents 2    data length is variable.
frame[6] = data[3]; // data contents 3
frame[7] = data[4]; // data contents 4
frame[8] = data[5]; // data contents 5
frame[9] = data[6]; // data contents 6
frame[10] = data[7]; // data contents 7
frame[3 + msgSize]; = getChecksum(data);
....
....
....
....
frame [3 + msgSize + 20] = 0xFF; // end frame

where i write data to what reads as a random array index rather than something meaningful like frame.checksum = getChecksum(data);.

Open to suggestions and a little bit of flaming for asking a general question rather than a specific one :-)

Body:
You have two options:

1. dynamic frame length

struct {
    unsigned char header;
    unsigned char msgSizeL; // this will be dynamic from 0x06 (empty) to 0x16 (full)
    unsigned char msgSizeH; // this will be always 0x00
    unsigned char dataSize; // specify the data size here
    unsigned char data[16]; // use a static memory area for the package
    unsigned char checksum;
    unsigned char endFrame;
} Frame;

then you can do this:

Frame xFrame;
unsigned char ucaData[17] = {0}; // your data
unsigned int uiDataLength = 6; // for example
memset(&xFrame, 0, sizeof(Frame)); // just to be sure
xFrame.header = 0x01;
xFrame.msgSizeL = uiDataLength;
xFrame.msgSizeH = 0;
xFrame.dataSize = uiDataLength;
memcpy(xFrame.data, ucaData, uiDataLength);
xFrame.checksum = CRC8(&xFrame, uiDataLength + 4); // crc for filled area
xFrame.endFrame = 0xFF;

then when building the package:

unsigned char xDataFrame[1000];
memcpy(xDataFrame, xFrame, 4 + uiDataLength);
memcpy(xDataFrame + 4 + uiDataLength, &xFrame + 20, 2);
transmit(xDataFrame, 6 + uiDataLength);

This way, you will discard empty bytes from sending and from calculating checksum for.

2. static frame length

Then you can use a struct like this:

struct {
    unsigned char header;
    unsigned char msgSizeL; // this will be always 0x16 (22)
    unsigned char msgSizeH; // this will be always 0x00
    unsigned char dataSize; // specify the data size here
    unsigned char data[16]; // use a static memory area for the package
    unsigned char checksum;
    unsigned char endFrame;
} Frame;

This way you can calculate the checksum for the first 20 bytes of this structure, but be aware of that this structure may contain padding areas which may move your data around the defined and padded memory area. sizeof(Frame) may be calculated by hand as 22 bytes but the compiler may decide that it should use 32 bytes or 24 bytes of memory related with the pack setting. You may use

#pragma pack(1) // disable padding
[structure code]
#pragma pack()  // back to the original setting

More info about packing:

#pragma pack effect


问:
Memory Leak While doing encryption decryption of large audio/video/html files using Java AES
I got a task to perform encryption and decryption of some large amount of files which are consisting of Audio,Video,and some html,swf files. And for this the code I am using works fine in my system. But when I am trying to execute the same code on server using java RMI it throws java.lang.OutOfMemoryError Java heap space.

Please suggest your views how to solve this memory leak issue.

Following is the code that I am using:

```<code>public static void performEncryption(String baseFolderLocation)
{
    String key = "This is a secret";

    System.out.println("Started Doing Encrypting...");
    List<File> filenames = getAllfilesInFolder(baseFolderLocation, new ArrayList<File>());
    int processedFilesCount = 0;

    for (File file : filenames) {
        try {

            Crypto.fileProcessor(Cipher.ENCRYPT_MODE, key, file.getAbsoluteFile(), file.getAbsoluteFile());

        } catch (Exception ex) {
            // ex.printStackTrace();
        }
        processedFilesCount++;
    }

    System.out.println("Ended Encrypting...");
}

static void fileProcessor(int cipherMode, String key, File inputFile, File outputFile) {
    try {
        Key secretKey = new SecretKeySpec(key.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(cipherMode, secretKey);

        FileInputStream inputStream = new FileInputStream(inputFile);
        byte[] inputBytes = new byte[(int) inputFile.length()];
        inputStream.read(inputBytes);

        byte[] outputBytes = cipher.doFinal(inputBytes);

        FileOutputStream outputStream = new FileOutputStream(outputFile);
        outputStream.write(outputBytes);

        inputStream.close();
        outputStream.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

public static List<File> getAllfilesInFolder(String directoryName, ArrayList<File> files) {
    File directory = new File(directoryName);

    // get all the files from a directory
    File[] fList = directory.listFiles();
    for (File file : fList)
    {
        if (file.isFile())
        {
            files.add(file);
        }
        else if (file.isDirectory())
        {
            getAllfilesInFolder(file.getAbsolutePath(), files);
        }
    }

    return files;
}
</code>```

答: Can you try to increase java heap memory of your server using -Xmx option?</p>

Body:
I got a task to perform encryption and decryption of some large amount of files which are consisting of Audio,Video,and some html,swf files. And for this the code I am using works fine in my system. But when I am trying to execute the same code on server using java RMI it throws java.lang.OutOfMemoryError Java heap space.

Please suggest your views how to solve this memory leak issue.

Following is the code that I am using:

public static void performEncryption(String baseFolderLocation)
{
    String key = "This is a secret";

    System.out.println("Started Doing Encrypting...");
    List<File> filenames = getAllfilesInFolder(baseFolderLocation, new ArrayList<File>());
    int processedFilesCount = 0;

    for (File file : filenames) {
        try {

            Crypto.fileProcessor(Cipher.ENCRYPT_MODE, key, file.getAbsoluteFile(), file.getAbsoluteFile());

        } catch (Exception ex) {
            // ex.printStackTrace();
        }
        processedFilesCount++;
    }

    System.out.println("Ended Encrypting...");
}

static void fileProcessor(int cipherMode, String key, File inputFile, File outputFile) {
    try {
        Key secretKey = new SecretKeySpec(key.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(cipherMode, secretKey);

        FileInputStream inputStream = new FileInputStream(inputFile);
        byte[] inputBytes = new byte[(int) inputFile.length()];
        inputStream.read(inputBytes);

        byte[] outputBytes = cipher.doFinal(inputBytes);

        FileOutputStream outputStream = new FileOutputStream(outputFile);
        outputStream.write(outputBytes);

        inputStream.close();
        outputStream.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

public static List<File> getAllfilesInFolder(String directoryName, ArrayList<File> files) {
    File directory = new File(directoryName);

    // get all the files from a directory
    File[] fList = directory.listFiles();
    for (File file : fList)
    {
        if (file.isFile())
        {
            files.add(file);
        }
        else if (file.isDirectory())
        {
            getAllfilesInFolder(file.getAbsolutePath(), files);
        }
    }

    return files;
}


问:
Mocking Apache HTTPClient using Mockito
I'm trying to mock Apache HttpClient Interface in order to mock one of its methods mentioned below to return a stubbed JSON object in response.

```<code>HttpResponse response = defaultHttpClient.execute(postRequest);
</code>```

Could somebody be able to suggest how to achieve this with some sample code? Your help would be greatly appreciated.

Thanks

答:
You can look at HttpClientMock, I wrote it for internal project but later decided to open source. It allows you to define mock behavior with fluent API and later verify a number of made calls. Example:</p>

```<code>HttpClientMock httpClientMock = new
HttpClientMock("http://localhost:8080");
httpClientMock.onGet("/login?user=john").doReturnJSON("{permission:1}");

httpClientMock.verify().get("/login?user=john").called();
</code>```

Title: Mocking Apache HTTPClient using Mockito

Body:
I'm trying to mock Apache HttpClient Interface in order to mock one of its methods mentioned below to return a stubbed JSON object in response.

HttpResponse response = defaultHttpClient.execute(postRequest);

Could somebody be able to suggest how to achieve this with some sample code? Your help would be greatly appreciated.

Thanks

Body:
You can look at HttpClientMock, I wrote it for internal project but later decided to open source. It allows you to define mock behavior with fluent API and later verify a number of made calls. Example:

HttpClientMock httpClientMock = new
HttpClientMock("http://localhost:8080");
httpClientMock.onGet("/login?user=john").doReturnJSON("{permission:1}");

httpClientMock.verify().get("/login?user=john").called();


问:
Scrolling issues with multiple bootstrap modals
I have a page with a modal with a lot of info so you need to scroll. This modal contains a link to a second modal.

When I

open modal 1

click on link to open modal 2 (modal 1 stays in background)

and then close modal 2 so that I am back on modal 1

modal 1 looses scrolling (there is still a scroll bar but it doesn't do anything). Instead the modal stays in the position it was at the time of opening modal 2.

I played around with closing the background modal with js first (but that messes up scrolling on the second modal). It appears that every time I try to open/close more than one modal I always get some issue with the scrolling.

Any suggestions on how to handle this?

答:
Add following to your CSS :

```<code>.modal
{
  overflow: scroll !important;
}
</code>```

Body:
Add following to your CSS :

.modal
{
  overflow: scroll !important;
}


问:
Pivoting the data
This is my SQL statement

```<code>select  id , name, type,  value  from table1 a
INNER JOIN table2 b on a.id = b.id
where  b.type in ('display','contact','ship')
</code>```

which produces below result

```<code>ID  name     type           value
5   test     display        display1
5   test     contact        contact1
5   test     ship           ship1
6   test2    display        display2
6   test2    contact        contact2
6   test2    ship           ship2
</code>```

I need to get result in kind of pivoted format like this

```<code>id  name   display   contact   ship
5   test   display1  contact1 ship1
6   test2  display2  contact2 ship2
</code>```

I tried this solution : https://stackoverflow.com/a/6849706/2645738 ,but its giving me the same result (3 rows for each data). It's like i need to group by id and name,but don't know how to make display,contact,ship as columns.

Would you please help me for the same.

答:
It is necessary to use PIVOT you could also do that by using simple case expression

```<code>SELECT ID,
      Name,
       MAX(CASE([type]) WHEN 'display' THEN value END) [display],
       MAX(CASE([type]) WHEN 'contact' THEN value END) [contact],
       MAX(CASE([type]) WHEN 'ship' THEN value END) [ship]
FROM <table> GROUP BY ID, Name
</code>```

Result :

```<code>ID  Name    display     contact     ship
5   test    display1    contact1    ship1
6   test2   display2    contact2    ship2
</code>```

Title: Pivoting the data

Body:
This is my SQL statement

select  id , name, type,  value  from table1 a
INNER JOIN table2 b on a.id = b.id
where  b.type in ('display','contact','ship')

which produces below result

ID  name     type           value
5   test     display        display1
5   test     contact        contact1
5   test     ship           ship1
6   test2    display        display2
6   test2    contact        contact2
6   test2    ship           ship2

I need to get result in kind of pivoted format like this

id  name   display   contact   ship
5   test   display1  contact1 ship1
6   test2  display2  contact2 ship2

I tried this solution : https://stackoverflow.com/a/6849706/2645738 ,but its giving me the same result (3 rows for each data). It's like i need to group by id and name,but don't know how to make display,contact,ship as columns.

Would you please help me for the same.

Body:
It is necessary to use PIVOT you could also do that by using simple case expression

SELECT ID,
      Name,
       MAX(CASE([type]) WHEN 'display' THEN value END) [display],
       MAX(CASE([type]) WHEN 'contact' THEN value END) [contact],
       MAX(CASE([type]) WHEN 'ship' THEN value END) [ship]
FROM <table> GROUP BY ID, Name

Result :

ID  Name    display     contact     ship
5   test    display1    contact1    ship1
6   test2   display2    contact2    ship2