问:
initialization error in junit using Eclipse
Running this as Junit causes Initialization error:

import java.io.IOException;
//import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.TimeUnit;

import org.junit.Assert;
import org.junit.Assume;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.events.EventFiringWebDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

import Test.BaseTest;
import Utils.TestUtils;
@RunWith(Parameterized.class)
public class LoginTest extends BaseTest
{
    String UserName;
    String Password;
    String VerifyText;

    public LoginTest(String UserName,String Password,String VerifyText)
    {
        this.UserName=UserName;
        this.Password=Password;
        this.VerifyText=VerifyText;
    }

    @Parameters
    public static Collection<Object[]>readData()
    {
        return Arrays.asList(TestUtils.readTestData("LoginTest"));
    }
    @BeforeClass
    public static void Init()
    {
        System.out.println("Before class called ....");
    }
    @AfterClass
    public static void CloseBrowser()
    {
        System.out.println("Afetr class called....");

    }
    @Before
    public void openSite() throws IOException
    {
        Initialize();
        dr=new FirefoxDriver();
        driver=new EventFiringWebDriver(dr);
        System.out.println("Before called....");
        driver.get("http://www.rediff.com");
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
    }
    @Test
    public void LoginTest()throws IOException,InterruptedException
    {
        System.out.println("Test called");
        //skipping the test case
        if(TestUtils.IsSkipped("LoginTest"))
        {
            Assume.assumeTrue(false);
        }
        String result=TestUtils.Login(UserName,Password,VerifyText);
        if(result.contains("Failed"))
        {
            //Take screen shot
            String filename="LoginFailed_"+UserName;
            TestUtils.takeScreenshot(filename);
            //error
            Assert.assertTrue(result, false);

        }
        //logout
        TestUtils.Logout();
    }

}
```

<p>Stack trace:</p>

```LoginTest (1)
testSuite1.LoginTest
initializationError(testSuite1.LoginTest)
java.lang.Exception: No public static parameters method on class testSuite1.LoginTest
    at org.junit.runners.Parameterized.getParametersMethod(Parameterized.java:309)
    at org.junit.runners.Parameterized.<init>(Parameterized.java:280)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:29)
    at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:21)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:26)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.<init>(JUnit4TestReference.java:28)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestClassReference.<init>(JUnit4TestClassReference.java:24)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:40)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:30)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:445)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
```

答:
Not sure why, but it seams junit doesn't like test names starting with capitals:

```<code>@Test
public void LoginTest()throws IOException,InterruptedException{
 ...
}
</code>```

try changing it to loginTest()

that worked for me.

Body:
Running this as Junit causes Initialization error:

import java.io.IOException;
//import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.TimeUnit;

import org.junit.Assert;
import org.junit.Assume;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.events.EventFiringWebDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

import Test.BaseTest;
import Utils.TestUtils;
@RunWith(Parameterized.class)
public class LoginTest extends BaseTest
{
    String UserName;
    String Password;
    String VerifyText;

    public LoginTest(String UserName,String Password,String VerifyText)
    {
        this.UserName=UserName;
        this.Password=Password;
        this.VerifyText=VerifyText;
    }

    @Parameters
    public static Collection<Object[]>readData()
    {
        return Arrays.asList(TestUtils.readTestData("LoginTest"));
    }
    @BeforeClass
    public static void Init()
    {
        System.out.println("Before class called ....");
    }
    @AfterClass
    public static void CloseBrowser()
    {
        System.out.println("Afetr class called....");

    }
    @Before
    public void openSite() throws IOException
    {
        Initialize();
        dr=new FirefoxDriver();
        driver=new EventFiringWebDriver(dr);
        System.out.println("Before called....");
        driver.get("http://www.rediff.com");
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
    }
    @Test
    public void LoginTest()throws IOException,InterruptedException
    {
        System.out.println("Test called");
        //skipping the test case
        if(TestUtils.IsSkipped("LoginTest"))
        {
            Assume.assumeTrue(false);
        }
        String result=TestUtils.Login(UserName,Password,VerifyText);
        if(result.contains("Failed"))
        {
            //Take screen shot
            String filename="LoginFailed_"+UserName;
            TestUtils.takeScreenshot(filename);
            //error
            Assert.assertTrue(result, false);

        }
        //logout
        TestUtils.Logout();
    }

}

Stack trace:

LoginTest (1)
testSuite1.LoginTest
initializationError(testSuite1.LoginTest)
java.lang.Exception: No public static parameters method on class testSuite1.LoginTest
    at org.junit.runners.Parameterized.getParametersMethod(Parameterized.java:309)
    at org.junit.runners.Parameterized.<init>(Parameterized.java:280)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:29)
    at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:21)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:26)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.<init>(JUnit4TestReference.java:28)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestClassReference.<init>(JUnit4TestClassReference.java:24)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:40)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:30)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:445)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)

Body:
Not sure why, but it seams junit doesn't like test names starting with capitals:

@Test
public void LoginTest()throws IOException,InterruptedException{
 ...
}

try changing it to loginTest()

that worked for me.


来源: stackexchange

问:
Adding an image to UITableViewCell in edit mode isn't aligning properly
I am using the code below to try to get the this look:

but instead it looks like:

```<code>func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let deleteRowAction = UITableViewRowAction(style: UITableViewRowActionStyle.default, title: "Delete") { action, indexPath in

    }
    deleteRowAction.backgroundColor = UIColor.red
    deleteRowAction.backgroundColor = UIColor(patternImage: UIImage(named: "DeleteIcon.png")!)
    return [deleteRowAction]
    }
</code>```

What am I doing wrong?

答:
In below IOS 11 , editActionsForRowAt methods show the patter image on in background, and pattern image is repeated if image is small then cell size.
That's why use the third party for implement this SwipeCellKit

And if you implement this in IOS 11 then use this UITableViewDelegate function, It work perfectly Example:

```<code> func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {

        let deleteAction = UIContextualAction(style: .normal, title:  "", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in
            // Call edit action

            // Reset state
            success(true)
        })
        deleteAction.image = #imageLiteral(resourceName: "Delete")
        deleteAction.backgroundColor = .red
        let value = UISwipeActionsConfiguration(actions: [deleteAction])
        value.performsFirstActionWithFullSwipe = true
        return value
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using the code below to try to get the this look:

but instead it looks like:

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let deleteRowAction = UITableViewRowAction(style: UITableViewRowActionStyle.default, title: "Delete") { action, indexPath in

    }
    deleteRowAction.backgroundColor = UIColor.red
    deleteRowAction.backgroundColor = UIColor(patternImage: UIImage(named: "DeleteIcon.png")!)
    return [deleteRowAction]
    }

What am I doing wrong?

Body:
In below IOS 11 , editActionsForRowAt methods show the patter image on in background, and pattern image is repeated if image is small then cell size.
That's why use the third party for implement this SwipeCellKit

And if you implement this in IOS 11 then use this UITableViewDelegate function, It work perfectly Example:

 func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {

        let deleteAction = UIContextualAction(style: .normal, title:  "", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in
            // Call edit action

            // Reset state
            success(true)
        })
        deleteAction.image = #imageLiteral(resourceName: "Delete")
        deleteAction.backgroundColor = .red
        let value = UISwipeActionsConfiguration(actions: [deleteAction])
        value.performsFirstActionWithFullSwipe = true
        return value
    }


问:
codeigniter rest api returns strange output
I created a rest api with Codeigniter & chriskacerguis/codeigniter-restserver.

It works fine, but when I try with Postman extension or Axios js it returns something strange.
If I open rest api url in another browser normal tab and then I use postman/axios js, then it works as aspected.

Error screen:

答:
Apparently your provider is running anti DoS software.

See here:

https://exceptionshub.com/wordpress-rest-api-not-working-with-postman.html

(Which links to this: https://www.lowendtalk.com/discussion/102642/ddos-protection-for-website-with-vddos-proxy-protection-vddos-layer4-mapping)

And down in this discussion:

https://github.com/SSilence/selfoss/issues/803

The two answers suggest changing providers or asking them to turn it off.


问:
Decrementing for loops
I want to have a for loop like so:

```<code>for counter in range(10,0):
       print counter,
</code>```

and the output should be 10 9 8 7 6 5 4 3 2 1

答:
You need to give the range a -1 step</p>

```<code> for i in range(10,0,-1):
    print i
</code>```

ContentLicense: CC BY-SA 2.5

Title: Decrementing for loops

Body:
I want to have a for loop like so:

for counter in range(10,0):
       print counter,

and the output should be 10 9 8 7 6 5 4 3 2 1

Body:
You need to give the range a -1 step

 for i in range(10,0,-1):
    print i


问:
are these nativecrypto error messages error messages?
When establishing a TLS connection between my android phone and my server I get following nativecrypto error messages in logcat:

```<code>06-30 21:55:06.565: E/NativeCrypto(24826): ssl=0x75e58650 cert_verify_callback x509_store_ctx=0x75e4da40 arg=0x0
06-30 21:55:06.566: E/NativeCrypto(24826): ssl=0x75e58650 cert_verify_callback calling verifyCertificateChain authMethod=RSA
</code>```

I was not able to find an explanation on google or stack for this kind of error logs and somehow I think they are not real errors, more likely informations.

Can someone elaborate what these messages mean?

I am using TLS and I have a serverkey and truststore as well as clientkey- and truststore.

答: This is not an issue from your application this issue is your device, it also appear in my app, Dont worry with SSL on android it is normal log.</p>

Body:
When establishing a TLS connection between my android phone and my server I get following nativecrypto error messages in logcat:

06-30 21:55:06.565: E/NativeCrypto(24826): ssl=0x75e58650 cert_verify_callback x509_store_ctx=0x75e4da40 arg=0x0
06-30 21:55:06.566: E/NativeCrypto(24826): ssl=0x75e58650 cert_verify_callback calling verifyCertificateChain authMethod=RSA

I was not able to find an explanation on google or stack for this kind of error logs and somehow I think they are not real errors, more likely informations.

Can someone elaborate what these messages mean?

I am using TLS and I have a serverkey and truststore as well as clientkey- and truststore.


问:
How to make Webkit webView with Swift with safe area constraints for iPhone X?
This is the configuration of the storyboard: see the image

*Take a look above the link for the image, support from iOS9 to iOS11

Following is the working code solution:

```<code>import UIKit
import WebKit

class ViewController: UIViewController, WKUIDelegate, UIApplicationDelegate, WKNavigationDelegate   {

    @IBOutlet weak var webViewContainer: UIView!

    let requestURLString = "http://google.com/“

    var webView: WKWebView!

    override func viewDidLoad() {

        super.viewDidLoad()
        let webConfiguration = WKWebViewConfiguration()

        let customFrame = CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: 0.0, height: self.webViewContainer.frame.size.height))
        self.webView = WKWebView (frame: customFrame , configuration: webConfiguration)
        webView.translatesAutoresizingMaskIntoConstraints = false
        self.webViewContainer.addSubview(webView)
        webView.topAnchor.constraint(equalTo: webViewContainer.topAnchor).isActive = true
        webView.rightAnchor.constraint(equalTo: webViewContainer.rightAnchor).isActive = true
        webView.leftAnchor.constraint(equalTo: webViewContainer.leftAnchor).isActive = true
        webView.bottomAnchor.constraint(equalTo: webViewContainer.bottomAnchor).isActive = true
        webView.heightAnchor.constraint(equalTo: webViewContainer.heightAnchor).isActive = true

        webView.uiDelegate = self
        webView.navigationDelegate = self
        webView.scrollView.bounces = false
        self.openUrl()
    }

    func openUrl() {
        let url = URL (string: requestURLString)
        let request = URLRequest(url: url!)
        webView.load(request)

    }
}
</code>```

I am sharing the link which contains this project:
https://github.com/kiril6/iPhoneX-webkitWebView

source: http://delovski.net/webkitwebview/

答:
```<code>class ViewController:UIViewController,WKNavigationDelegate,WKUIDelegate
{
@IBOutlet weak var webViewContainer: UIView!
fileprivate var requestURLString: URL?
var webView: WKWebView!

override func viewDidLoad() {
    super.viewDidLoad()
    loadUrl()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func loadUrl() {
    requestURLString = URL(string: "https://www.apple.com/in/")!
    guard let url = requestURLString else { return }

    webView = WKWebView()
    webView.navigationDelegate = self
    webView.allowsLinkPreview = true
    webView.uiDelegate = self

    webViewContainer.addSubview(webView)
    webViewContainer.sendSubview(toBack: webView)
    addConstraints(to: webView, with: webViewContainer)
    webView.load(NSURLRequest(url: url) as URLRequest)
}

func addConstraints(to webView: UIView, with superView: UIView) {
    webView.translatesAutoresizingMaskIntoConstraints = false
    let leadingConstraint = NSLayoutConstraint(item: webView, attribute: .leading, relatedBy: .equal, toItem: superView, attribute: .leading, multiplier: 1, constant: 0)
    let trailingConstraint = NSLayoutConstraint(item: webView, attribute: .trailing, relatedBy: .equal, toItem: superView, attribute: .trailing, multiplier: 1, constant: 0)
    let topConstraint = NSLayoutConstraint(item: webView, attribute: .top, relatedBy: .equal, toItem: superView, attribute: .top, multiplier: 1, constant: 0)
    let bottomConstraint = NSLayoutConstraint(item: webView, attribute: .bottom, relatedBy: .equal, toItem: superView, attribute: .bottom, multiplier: 1, constant: 0)
    superView.addConstraints([leadingConstraint, trailingConstraint, topConstraint, bottomConstraint])
}
}
</code>```

Hope this will work for you, please check. Also, I am sharing the link which contains the project for loading an URL using WKWebView in Swift 4.0: https://github.com/ipran/WebViewTestApp

Body:
This is the configuration of the storyboard: see the image

*Take a look above the link for the image, support from iOS9 to iOS11

Following is the working code solution:

import UIKit
import WebKit

class ViewController: UIViewController, WKUIDelegate, UIApplicationDelegate, WKNavigationDelegate   {

    @IBOutlet weak var webViewContainer: UIView!

    let requestURLString = "http://google.com/“

    var webView: WKWebView!

    override func viewDidLoad() {

        super.viewDidLoad()
        let webConfiguration = WKWebViewConfiguration()

        let customFrame = CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: 0.0, height: self.webViewContainer.frame.size.height))
        self.webView = WKWebView (frame: customFrame , configuration: webConfiguration)
        webView.translatesAutoresizingMaskIntoConstraints = false
        self.webViewContainer.addSubview(webView)
        webView.topAnchor.constraint(equalTo: webViewContainer.topAnchor).isActive = true
        webView.rightAnchor.constraint(equalTo: webViewContainer.rightAnchor).isActive = true
        webView.leftAnchor.constraint(equalTo: webViewContainer.leftAnchor).isActive = true
        webView.bottomAnchor.constraint(equalTo: webViewContainer.bottomAnchor).isActive = true
        webView.heightAnchor.constraint(equalTo: webViewContainer.heightAnchor).isActive = true

        webView.uiDelegate = self
        webView.navigationDelegate = self
        webView.scrollView.bounces = false
        self.openUrl()
    }

    func openUrl() {
        let url = URL (string: requestURLString)
        let request = URLRequest(url: url!)
        webView.load(request)

    }
}

I am sharing the link which contains this project:
https://github.com/kiril6/iPhoneX-webkitWebView

source: http://delovski.net/webkitwebview/

Body:
class ViewController:UIViewController,WKNavigationDelegate,WKUIDelegate
{
@IBOutlet weak var webViewContainer: UIView!
fileprivate var requestURLString: URL?
var webView: WKWebView!

override func viewDidLoad() {
    super.viewDidLoad()
    loadUrl()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func loadUrl() {
    requestURLString = URL(string: "https://www.apple.com/in/")!
    guard let url = requestURLString else { return }

    webView = WKWebView()
    webView.navigationDelegate = self
    webView.allowsLinkPreview = true
    webView.uiDelegate = self

    webViewContainer.addSubview(webView)
    webViewContainer.sendSubview(toBack: webView)
    addConstraints(to: webView, with: webViewContainer)
    webView.load(NSURLRequest(url: url) as URLRequest)
}

func addConstraints(to webView: UIView, with superView: UIView) {
    webView.translatesAutoresizingMaskIntoConstraints = false
    let leadingConstraint = NSLayoutConstraint(item: webView, attribute: .leading, relatedBy: .equal, toItem: superView, attribute: .leading, multiplier: 1, constant: 0)
    let trailingConstraint = NSLayoutConstraint(item: webView, attribute: .trailing, relatedBy: .equal, toItem: superView, attribute: .trailing, multiplier: 1, constant: 0)
    let topConstraint = NSLayoutConstraint(item: webView, attribute: .top, relatedBy: .equal, toItem: superView, attribute: .top, multiplier: 1, constant: 0)
    let bottomConstraint = NSLayoutConstraint(item: webView, attribute: .bottom, relatedBy: .equal, toItem: superView, attribute: .bottom, multiplier: 1, constant: 0)
    superView.addConstraints([leadingConstraint, trailingConstraint, topConstraint, bottomConstraint])
}
}

Hope this will work for you, please check. Also, I am sharing the link which contains the project for loading an URL using WKWebView in Swift 4.0: https://github.com/ipran/WebViewTestApp


问:
What is the diffrence between a function and a module?
I am very new to c++ and confused between what is the difference between modular programming and function oriented programming.I have never done modular programming so I just know modules by definition that it contains functions.So what is the difference between a sequential(function-oriented language)and modular programming?Thanks in advance.

EDIT:
I was reading about C++'s OOP.It started something like what is unstructured programming, than gave a basic idea about structured programming, than modular programming and finally,OOP.

答:
Modular programming is mostly a strategy to reduce coupling in a computer program, mostly by means of encapsulation.

Before modular programming, local coherence of the code was ensured by structured programming, but global coherence was lacking: if you decided that your spell-checking dictionary would be implemented as a red-black tree, then this implementation would be exposed to everyone else in the program, so that the programmer working on, say, text rendering, would be able to access the red-black tree nodes to do meaningful things with them.

Of course, this became hell once you needed to change the implementation of your dictionary, because then you would have to fix the code of other programmers as well.

Even worse, if the implementation detail involved global variables, then you had to be exceedingly careful of who changed them and in what order, or strange bugs would crop up.

Modular programming applied encapsulation to all of this, by separating the implementation (private to the module) from the interface (what the rest of the program can use). So, a dictionary module could expose an abstract type that would only be accessible through module functions such as findWord(word,dictionary). Someone working on the dictionary module would never need to peek outside that module to check if someone might be using an implementation detail.


问:
PHPMailer do not work properly sometimes on gmail port 465 or 587 on localhost
I am using the latest version of PHPMailer 6.0.2 on LOCALHOST with Gmail SMTP Ports [ SSL on 465 and TLS 587 ]. It works well but not stable or works properly, very strange while OpenSSL Extension is also active in PHP Config /PHP.ini file.

It returns the error " SMTP Error: Could not connect to SMTP host ", sometimes on 465 or 587 port.

As right now it's on 587.

Here the exact error on port 587 ;

```<code>2017-12-05 13:00:26 Connection: opening to smtp.gmail.com:587, timeout=300, options=array ( 'ssl' => array ( 'verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true, ),)
2017-12-05 13:00:26 Connection: opened
2017-12-05 13:00:26 SMTP INBOUND: "220 smtp.gmail.com ESMTP f3sm245851pgt.15 - gsmtp"
2017-12-05 13:00:26 SERVER -> CLIENT: 220 smtp.gmail.com ESMTP f3sm245851pgt.15 - gsmtp
2017-12-05 13:00:26 CLIENT -> SERVER: EHLO localhost
2017-12-05 13:00:27 SMTP INBOUND: "250-smtp.gmail.com at your service, [110.36.136.72]"
2017-12-05 13:00:27 SMTP INBOUND: "250-SIZE 35882577"
2017-12-05 13:00:27 SMTP INBOUND: "250-8BITMIME"
2017-12-05 13:00:27 SMTP INBOUND: "250-STARTTLS"
2017-12-05 13:00:27 SMTP INBOUND: "250-ENHANCEDSTATUSCODES"
2017-12-05 13:00:27 SMTP INBOUND: "250-PIPELINING"
2017-12-05 13:00:27 SMTP INBOUND: "250-CHUNKING"
2017-12-05 13:00:27 SMTP INBOUND: "250 SMTPUTF8"
2017-12-05 13:00:27 SERVER -> CLIENT: 250-smtp.gmail.com at your service, [110.36.136.72]250-SIZE 35882577250-8BITMIME250-STARTTLS250-ENHANCEDSTATUSCODES250-PIPELINING250-CHUNKING250 SMTPUTF8
2017-12-05 13:00:27 CLIENT -> SERVER: STARTTLS
2017-12-05 13:00:27 SMTP INBOUND: ""
2017-12-05 13:00:27 SERVER -> CLIENT:
2017-12-05 13:00:27 SMTP ERROR: STARTTLS command failed:
SMTP Error: Could not connect to SMTP host.
2017-12-05 13:00:27 SMTP NOTICE: EOF caught while checking if connected
2017-12-05 13:00:27 Connection: closed
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
</code>```

HERE IS THE RELEVANT CODE:

```<code>use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\OAuth;
use League\OAuth2\Client\Provider\Google;

require '../../vendor/autoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 4;

$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;

$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->SMTPAutoTLS = false;

$mail->SMTPOptions = array(
    'ssl' => array(
        'verify_peer' => false,
        'verify_peer_name' => false,
        'allow_self_signed' => true
    )
);

$mail->Username = $from_address;
$mail->Password = $from_password;
$mail->SetLanguage("tr", "phpmailer/language");
$mail->CharSet = "utf-8";
$mail->Encoding = "base64";
$mail->SetFrom($from_address, $from_name);

foreach ($to_email_list as $to) {
    $mail->AddAddress($to);
}

$mail->AddReplyTo($from_address, $from_name);
$mail->Subject = $email_subject;

//Creating Email Body
$message = "<html>\n";
$message .= "<body>\n";
$message .= '<p>Greetings,</p>';
$message .= '<p>' . $email_message . '</p>';
$message .= "</body>\n";
$message .= "</html>\n";
$mail->isHTML(true);
$mail->MsgHTML($message);

if(!$mail->Send()) {
    echo "On Port: " . $from_smtp_port . " </br> Mailer Error: " . $mail->ErrorInfo;
} else {
    echo "Message sent!  on Port " . $from_smtp_port . "</br>";

   foreach($to_email_list as $list){
        echo $list . "</br>";
    }

}
</code>```

答:
Finally, I found the solution on troubleshooting guide.

I recommend to other users who are facing the same issue; please see following Points carefully on troubleshooting guide;
 - Opportunistic TLS
 - PHP 5.6 certificate verification failure
 - cURL error 60

My Script is working fine with Gmail ss/465 and tls/587.

Thanks! @Synchro.

Body:
I am using the latest version of PHPMailer 6.0.2 on LOCALHOST with Gmail SMTP Ports [ SSL on 465 and TLS 587 ]. It works well but not stable or works properly, very strange while OpenSSL Extension is also active in PHP Config /PHP.ini file.

It returns the error " SMTP Error: Could not connect to SMTP host ", sometimes on 465 or 587 port.

As right now it's on 587.

Here the exact error on port 587 ;

2017-12-05 13:00:26 Connection: opening to smtp.gmail.com:587, timeout=300, options=array ( 'ssl' => array ( 'verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true, ),)
2017-12-05 13:00:26 Connection: opened
2017-12-05 13:00:26 SMTP INBOUND: "220 smtp.gmail.com ESMTP f3sm245851pgt.15 - gsmtp"
2017-12-05 13:00:26 SERVER -> CLIENT: 220 smtp.gmail.com ESMTP f3sm245851pgt.15 - gsmtp
2017-12-05 13:00:26 CLIENT -> SERVER: EHLO localhost
2017-12-05 13:00:27 SMTP INBOUND: "250-smtp.gmail.com at your service, [110.36.136.72]"
2017-12-05 13:00:27 SMTP INBOUND: "250-SIZE 35882577"
2017-12-05 13:00:27 SMTP INBOUND: "250-8BITMIME"
2017-12-05 13:00:27 SMTP INBOUND: "250-STARTTLS"
2017-12-05 13:00:27 SMTP INBOUND: "250-ENHANCEDSTATUSCODES"
2017-12-05 13:00:27 SMTP INBOUND: "250-PIPELINING"
2017-12-05 13:00:27 SMTP INBOUND: "250-CHUNKING"
2017-12-05 13:00:27 SMTP INBOUND: "250 SMTPUTF8"
2017-12-05 13:00:27 SERVER -> CLIENT: 250-smtp.gmail.com at your service, [110.36.136.72]250-SIZE 35882577250-8BITMIME250-STARTTLS250-ENHANCEDSTATUSCODES250-PIPELINING250-CHUNKING250 SMTPUTF8
2017-12-05 13:00:27 CLIENT -> SERVER: STARTTLS
2017-12-05 13:00:27 SMTP INBOUND: ""
2017-12-05 13:00:27 SERVER -> CLIENT:
2017-12-05 13:00:27 SMTP ERROR: STARTTLS command failed:
SMTP Error: Could not connect to SMTP host.
2017-12-05 13:00:27 SMTP NOTICE: EOF caught while checking if connected
2017-12-05 13:00:27 Connection: closed
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

HERE IS THE RELEVANT CODE:

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\OAuth;
use League\OAuth2\Client\Provider\Google;

require '../../vendor/autoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 4;

$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;

$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->SMTPAutoTLS = false;

$mail->SMTPOptions = array(
    'ssl' => array(
        'verify_peer' => false,
        'verify_peer_name' => false,
        'allow_self_signed' => true
    )
);

$mail->Username = $from_address;
$mail->Password = $from_password;
$mail->SetLanguage("tr", "phpmailer/language");
$mail->CharSet = "utf-8";
$mail->Encoding = "base64";
$mail->SetFrom($from_address, $from_name);

foreach ($to_email_list as $to) {
    $mail->AddAddress($to);
}

$mail->AddReplyTo($from_address, $from_name);
$mail->Subject = $email_subject;

//Creating Email Body
$message = "\n";
$message .= "\n";
$message .= '
Greetings,
';
$message .= '
' . $email_message . '
';
$message .= "\n";
$message .= "\n";
$mail->isHTML(true);
$mail->MsgHTML($message);

if(!$mail->Send()) {
    echo "On Port: " . $from_smtp_port . "
 Mailer Error: " . $mail->ErrorInfo;
} else {
    echo "Message sent!  on Port " . $from_smtp_port . "
";

   foreach($to_email_list as $list){
        echo $list . "
";
    }

}


问:
Rails, reading image from url with rmagick
I am trying to read the image from url with Rmagick and carrierwave.

```<code>require 'open-uri'
require 'rubygems'
require 'Rmagick'

image = Magick::ImageList.new
urlimage = open("https://www.jewelinfo4u.com/images/Gallery/ruby.jpg") # Image Remote URL
image.from_blob(urlimage.read)

puts '****************'
puts image
puts '****************'
</code>```

But it gives error;

```<code>no decode delegate for this image format `JPEG' @ error/blob.c/BlobToImage/353
</code>```

EDIT:

I have picture model and I chose mount_uploader as :image;

```<code>class Picture < ActiveRecord::Base
  belongs_to :car
  mount_uploader :image, ImageUploader
end
</code>```

Here is image_uploader.rb to be able to edit the image before saving to S3 Amazon.;

```<code># encoding: utf-8
#require File.join(Rails.root, "lib", "carrier_wave", "delayed_job") # Upload pics with delayed job
class ImageUploader < CarrierWave::Uploader::Base
#include CarrierWave::Delayed::Job # Upload pics with delayed job

  include CarrierWave::RMagick

  storage :fog
  include CarrierWave::MimeTypes
  process :set_content_type

  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  version :slider do
    process :adjust_image
    process :optimize
  end
</code>```

....
    end

答:
If you are using carrierwave, you should try like this -

so let's say, you have Image model(class)

```<code>image = Image.new
image.remote_image_url = "https://www.jewelinfo4u.com/images/Gallery/ruby.jpg"
image.save
</code>```

it will download image from URL and store accordingly.

Here is Github URL(just for reference) - https://github.com/carrierwaveuploader/carrierwave/wiki/How-to:-Upload-remote-image-urls-to-your-seedfile

Body:
I am trying to read the image from url with Rmagick and carrierwave.

require 'open-uri'
require 'rubygems'
require 'Rmagick'

image = Magick::ImageList.new
urlimage = open("https://www.jewelinfo4u.com/images/Gallery/ruby.jpg") # Image Remote URL
image.from_blob(urlimage.read)

puts '****************'
puts image
puts '****************'

But it gives error;

no decode delegate for this image format `JPEG' @ error/blob.c/BlobToImage/353

EDIT:

I have picture model and I chose mount_uploader as :image;

class Picture < ActiveRecord::Base
  belongs_to :car
  mount_uploader :image, ImageUploader
end

Here is image_uploader.rb to be able to edit the image before saving to S3 Amazon.;

# encoding: utf-8
#require File.join(Rails.root, "lib", "carrier_wave", "delayed_job") # Upload pics with delayed job
class ImageUploader < CarrierWave::Uploader::Base
#include CarrierWave::Delayed::Job # Upload pics with delayed job

  include CarrierWave::RMagick

  storage :fog
  include CarrierWave::MimeTypes
  process :set_content_type

  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  version :slider do
    process :adjust_image
    process :optimize
  end

....
    end

Body:
If you are using carrierwave, you should try like this -

so let's say, you have Image model(class)

image = Image.new
image.remote_image_url = "https://www.jewelinfo4u.com/images/Gallery/ruby.jpg"
image.save

it will download image from URL and store accordingly.

Here is Github URL(just for reference) - https://github.com/carrierwaveuploader/carrierwave/wiki/How-to:-Upload-remote-image-urls-to-your-seedfile


问:
Split string by ". " except when after a number
I want to split strings, by phrases, and to do that I'm doing this:

```<code>string.Split(new[] { ". ", "? ", "! " }, StringSplitOptions.None);
</code>```

The thing is my string sometimes catch that after a number, when it has different points, and I want to separate by before the number, and not after, if it is possible.

original:

Com um processo de agendamento de não mais que 60 segundos, um
  pagamento seguro, garantia de qualidade, a Wegho torna-se o meio mais
  simples e conveniente de poder agendar serviços para o seu lar.
  Entenda-se lar como a simbiose perfeita do ativo físico “casa” e do
  ativo “emocional” família. Preparado para ter um parceiro de
  excelência nos serviços que precisa para o seu lar? 1.    Explore os
  nossos serviços em Wegho.om 2.    Selecione o serviço que pretende.
  Através do código postal verificaremos se estamos presentes na área
  que pretende 3.   Escolha uma hora

result:

Com um processo de agendamento de não mais que 60 segundos, um
  pagamento seguro, garantia de qualidade, a Wegho torna-se o meio mais
  simples e conveniente de poder agendar serviços para o seu lar.

Entenda-se lar como a simbiose perfeita do ativo físico “casa” e do
  ativo “emocional” família.

Preparado para ter um parceiro de excelência nos serviços que precisa
  para o seu lar?

Explore os nossos serviços em Wegho.om

Selecione o serviço que pretende. Através do código postal verificaremos se estamos presentes na área que pretende

Escolha uma hora

And also, is it possible to keep the caught separating characters from which the string was split in the strings?

答:
You could try regular expressions:

```<code>string pattern = @"([^\d][.!?][ ])";
string substitution = @"$1\n\n";
string input = @"Com um processo de agendamento de não mais que 60 segundos, um pagamento seguro, garantia de qualidade, a Wegho torna-se o meio mais simples e conveniente de poder agendar serviços para o seu lar. Entenda-se lar como a simbiose perfeita do ativo físico “casa” e do ativo “emocional” família. Preparado para ter um parceiro de excelência nos serviços que precisa para o seu lar? 1. Explore os nossos serviços em Wegho.om. 2. Selecione o serviço que pretende. Através do código postal verificaremos se estamos presentes na área que pretende. 3. Escolha uma hora";
RegexOptions options = RegexOptions.IgnoreCase;

Regex regex = new Regex(pattern, options);
string result = regex.Replace(input, substitution);
</code>```

Check the full code and result.

However, the split will work inside the bullets also. And you will need to end your bullet content with a dot also.

Body:
I want to split strings, by phrases, and to do that I'm doing this:

string.Split(new[] { ". ", "? ", "! " }, StringSplitOptions.None);

The thing is my string sometimes catch that after a number, when it has different points, and I want to separate by before the number, and not after, if it is possible.

original:

Com um processo de agendamento de não mais que 60 segundos, um
  pagamento seguro, garantia de qualidade, a Wegho torna-se o meio mais
  simples e conveniente de poder agendar serviços para o seu lar.
  Entenda-se lar como a simbiose perfeita do ativo físico “casa” e do
  ativo “emocional” família. Preparado para ter um parceiro de
  excelência nos serviços que precisa para o seu lar? 1.    Explore os
  nossos serviços em Wegho.om 2.    Selecione o serviço que pretende.
  Através do código postal verificaremos se estamos presentes na área
  que pretende 3.   Escolha uma hora

result:

Com um processo de agendamento de não mais que 60 segundos, um
  pagamento seguro, garantia de qualidade, a Wegho torna-se o meio mais
  simples e conveniente de poder agendar serviços para o seu lar.

Entenda-se lar como a simbiose perfeita do ativo físico “casa” e do
  ativo “emocional” família.

Preparado para ter um parceiro de excelência nos serviços que precisa
  para o seu lar?

Explore os nossos serviços em Wegho.om

Selecione o serviço que pretende. Através do código postal verificaremos se estamos presentes na área que pretende

Escolha uma hora

And also, is it possible to keep the caught separating characters from which the string was split in the strings?

Body:
You could try regular expressions:

string pattern = @"([^\d][.!?][ ])";
string substitution = @"$1\n\n";
string input = @"Com um processo de agendamento de não mais que 60 segundos, um pagamento seguro, garantia de qualidade, a Wegho torna-se o meio mais simples e conveniente de poder agendar serviços para o seu lar. Entenda-se lar como a simbiose perfeita do ativo físico “casa” e do ativo “emocional” família. Preparado para ter um parceiro de excelência nos serviços que precisa para o seu lar? 1. Explore os nossos serviços em Wegho.om. 2. Selecione o serviço que pretende. Através do código postal verificaremos se estamos presentes na área que pretende. 3. Escolha uma hora";
RegexOptions options = RegexOptions.IgnoreCase;

Regex regex = new Regex(pattern, options);
string result = regex.Replace(input, substitution);

Check the full code and result.

However, the split will work inside the bullets also. And you will need to end your bullet content with a dot also.


问:
Transpose CSV to new format (C#)
I have csv file:

I need to convert it to below format:

I did only this:

```<code>    StreamReader srd = new StreamReader(path: path);
    int rowCount = 0;

    string[] oStreamDataValues = null;
    string[] headerNames = null;

    while (!srd.EndOfStream)
    {
        string oStreamRowData = srd.ReadLine().Trim();
        oStreamDataValues = oStreamRowData.Split(';');

        //headers
        if (rowCount == 0)
        {
            headerNames = oStreamDataValues;
            rowCount++;//second row go to "else"
        }
        //create new csv
        else
        {

        }
        //rowCount++;
    }
    //Console.WriteLine("number of lines " + rowCount);
    srd.Dispose();
</code>```

Can you please help me with transpose to new format?

答:
```<code>using System;
using System.IO;

namespace SharpTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string path = "XXX/test.csv";
            string savePath = "XXX/test2.txt";
            using(StreamReader sr = new StreamReader(path))
            {
                string headerLine = sr.ReadLine();
                string[] headers = headerLine.Split(';');
                using(StreamWriter sw = new StreamWriter(savePath))
                {
                    while (true)
                    {
                        string line = sr.ReadLine();
                        if (line == null) return;
                        string[] ss = line.Split(';');
                        if (ss.Length != headers.Length) continue;
                        for (int i = 1; i < headers.Length; i++)
                        {
                            sw.WriteLine(ss[0] + ";" + headers[i] + ";" + ss[i]);
                        }
                    }
                }
            }
        }
    }
}
</code>```

Test CSV:

ID;Col2;Col3;Col4

  id1;10;def;20

  Id2;30;aaa;40

Title: Transpose CSV to new format (C#)

Body:
I have csv file:

I need to convert it to below format:

I did only this:

    StreamReader srd = new StreamReader(path: path);
    int rowCount = 0;

    string[] oStreamDataValues = null;
    string[] headerNames = null;

    while (!srd.EndOfStream)
    {
        string oStreamRowData = srd.ReadLine().Trim();
        oStreamDataValues = oStreamRowData.Split(';');

        //headers
        if (rowCount == 0)
        {
            headerNames = oStreamDataValues;
            rowCount++;//second row go to "else"
        }
        //create new csv
        else
        {

        }
        //rowCount++;
    }
    //Console.WriteLine("number of lines " + rowCount);
    srd.Dispose();

Can you please help me with transpose to new format?

Body:
using System;
using System.IO;

namespace SharpTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string path = "XXX/test.csv";
            string savePath = "XXX/test2.txt";
            using(StreamReader sr = new StreamReader(path))
            {
                string headerLine = sr.ReadLine();
                string[] headers = headerLine.Split(';');
                using(StreamWriter sw = new StreamWriter(savePath))
                {
                    while (true)
                    {
                        string line = sr.ReadLine();
                        if (line == null) return;
                        string[] ss = line.Split(';');
                        if (ss.Length != headers.Length) continue;
                        for (int i = 1; i < headers.Length; i++)
                        {
                            sw.WriteLine(ss[0] + ";" + headers[i] + ";" + ss[i]);
                        }
                    }
                }
            }
        }
    }
}

Test CSV:

ID;Col2;Col3;Col4

  id1;10;def;20

  Id2;30;aaa;40


问:
Checkbox checked not passing an actual value?
My code checks the value of 2x checkboxes to equal true/false depending on a radio field. I see the checkboxes being ticket on the web page.

However, once they are passed over a HTML POST form, they have no values and always equal false.

If I give the checkboxes a value "TRUE" then of course they have only that value.

What am I missing here?

```<code>    <script>
      $(function() {
  var MAIN= $("input[type='radio']");
  var marketingPhone = $("input[type='checkbox'][name='marketingPhone']");
  var marketingRobo = $("input[type='checkbox'][name='marketingRobo']");

    MAIN.on('change', function()
        {
        if ($(this).val() == "TRUE")  {
          marketingPhone.prop('checked',true);
          marketingRobo.prop('checked',true);
        } else {
          marketingPhone.prop('checked',false);
          marketingRobo.prop('checked',false);
        }

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

The fields are as follows:

```<code>        <input type="checkbox" name="marketingPhone" value=""/>
        <input type="checkbox" name="marketingRobo" value=""/>
</code>```

答:
Checkboxes, if not checked, do not get posted at all with the form.

So if you post a form with checkboxes even if they have some value but they are not checked, you can not get checkbox's values in $_POST or $_GET arrays.

Body:
My code checks the value of 2x checkboxes to equal true/false depending on a radio field. I see the checkboxes being ticket on the web page.

However, once they are passed over a HTML POST form, they have no values and always equal false.

If I give the checkboxes a value "TRUE" then of course they have only that value.

What am I missing here?

The fields are as follows:

        <input type="checkbox" name="marketingPhone" value=""/>
        <input type="checkbox" name="marketingRobo" value=""/>


问:
How to make a dynamic char?
```<code>#include<stdio.h>
#include<string.h>
#include<stdlib.h>

void generarCadena(char *);
void generarDimension(int, void **, int);
void reallocarDimensiones(int , void **, int);

int main(void){
    char *caracter=NULL;
    generarCadena(&caracter);
    printf("%d", sizeof(caracter));
    printf("%s", &caracter);//I want to now why this doesn't print
    return 0;
}

void generarCadena(char *scaneado){
    unsigned int cont;
    char lector;
    generarDimension(1,&scaneado,sizeof(char));
    cont = 0;
    while(!scanf("%s", &scaneado)){
        while((strcpy(lector,getchar())) !='\n' && lector!=EOF){
           reallocarDimensiones(1,&scaneado[cont],sizeof(char));
           cont++;
        }
    }
    printf("%s", &scaneado);/*Inside de function it prints,
    however, it doesn't print outside it*/
}//This function is for the dynamic char

void generarDimension(int bloques, void **ptr, int tamanho){
    *ptr = malloc(bloques * tamanho);
    if(*ptr==NULL){
        printf("No se pudo almacenar memoria\n");
    }
}//This function mallocs any given pointer
void reallocarDimensiones(int bloques, void **ptr, int tamanho){
    *ptr = realloc(*ptr,bloques * tamanho);
    if(*ptr==NULL){
        printf("No se pudo almacenar memoria\n");
    }
}//This function reallocs any given pointer
</code>```

Hi, I want to now how to dynamically store a char while writting it on the keyboard, so I made a function for it. I want to send a char pointer in it, but it doesn't seem to modify it. Another problem I have is that my function only stores a few data, so if the data is to long, my program crashes.

答:
This simplifies the code to one function to capture input until a newline. Memory is allocated on each character.</p>

```<code>#include<stdio.h>
#include<string.h>
#include<stdlib.h>

char *generarCadena(char *);

int main(void){
    char *caracter=NULL;//so realloc will operate as malloc on first call
    caracter = generarCadena ( caracter);
    printf("%zu\n", sizeof(caracter));
    if ( caracter) {//something was input
        printf("%s\n", caracter);
        free ( caracter);
    }
    return 0;
}

char *generarCadena(char *scaneado){
    char *temp = NULL;
    int in = 0;
    size_t size = 0;

    while ( '\n' != ( in = getchar ( ))) {//loop until newline
        if ( NULL == ( temp = realloc ( scaneado, size + 2))) {//realloc for each character input and '\0'
            fprintf ( stderr, "realloc problem\n");
            return scaneado;
        }
        scaneado = temp;
        scaneado[size] = in;//set input
        scaneado[size + 1] = '\0';//terminate
        size++;
    }
    return scaneado;
}
</code>```

Title: How to make a dynamic char?

Body:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

void generarCadena(char *);
void generarDimension(int, void **, int);
void reallocarDimensiones(int , void **, int);

int main(void){
    char *caracter=NULL;
    generarCadena(&caracter);
    printf("%d", sizeof(caracter));
    printf("%s", &caracter);//I want to now why this doesn't print
    return 0;
}

void generarCadena(char *scaneado){
    unsigned int cont;
    char lector;
    generarDimension(1,&scaneado,sizeof(char));
    cont = 0;
    while(!scanf("%s", &scaneado)){
        while((strcpy(lector,getchar())) !='\n' && lector!=EOF){
           reallocarDimensiones(1,&scaneado[cont],sizeof(char));
           cont++;
        }
    }
    printf("%s", &scaneado);/*Inside de function it prints,
    however, it doesn't print outside it*/
}//This function is for the dynamic char

void generarDimension(int bloques, void **ptr, int tamanho){
    *ptr = malloc(bloques * tamanho);
    if(*ptr==NULL){
        printf("No se pudo almacenar memoria\n");
    }
}//This function mallocs any given pointer
void reallocarDimensiones(int bloques, void **ptr, int tamanho){
    *ptr = realloc(*ptr,bloques * tamanho);
    if(*ptr==NULL){
        printf("No se pudo almacenar memoria\n");
    }
}//This function reallocs any given pointer

Hi, I want to now how to dynamically store a char while writting it on the keyboard, so I made a function for it. I want to send a char pointer in it, but it doesn't seem to modify it. Another problem I have is that my function only stores a few data, so if the data is to long, my program crashes.

Body:
This simplifies the code to one function to capture input until a newline. Memory is allocated on each character.

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

char *generarCadena(char *);

int main(void){
    char *caracter=NULL;//so realloc will operate as malloc on first call
    caracter = generarCadena ( caracter);
    printf("%zu\n", sizeof(caracter));
    if ( caracter) {//something was input
        printf("%s\n", caracter);
        free ( caracter);
    }
    return 0;
}

char *generarCadena(char *scaneado){
    char *temp = NULL;
    int in = 0;
    size_t size = 0;

    while ( '\n' != ( in = getchar ( ))) {//loop until newline
        if ( NULL == ( temp = realloc ( scaneado, size + 2))) {//realloc for each character input and '\0'
            fprintf ( stderr, "realloc problem\n");
            return scaneado;
        }
        scaneado = temp;
        scaneado[size] = in;//set input
        scaneado[size + 1] = '\0';//terminate
        size++;
    }
    return scaneado;
}


问:
Robotframework How to uploadfile to the website with RIDE
This is my code

```<code>*** Settings ***
Library           Selenium2Library

*** Variables ***
${Login}          xpath=/html/body/app/main/login/div/div[1]/div/form/div[3]/div/button

*** Test Cases ***
Test
    OPEN
    LOGIN
    Sleep    5s
    ADD TOPIC
    Sleep    2s
    SelectType
    TypePDF
    Sleep    5s
    AddFile

*** Keywords ***
OPEN
    Open Browser    https://********** \ \ \    googlechrome

LOGIN

Input Text    id=inputEmail3    ********

Input Text    id=inputPassword3  *******

 Click Element    xpath=/html/body/app/main/login/div/div[1]/div/form/div[3]/div/button

ADD TOPIC
    Click Element    xpath=/html/body/app/main/pages/div/div/news/div/news-list/button

SelectType
    Click Element    id=selectType

TypePDF
    Click Element    xpath=//*[@id="selectType"]/option[5]

AddFile
    Click Button    xpath=/html/body/app/main/pages/div/div/news/div/news-add/ba-card/div/div[2]/div[2]/div[1]/div[2]/ba-file-uploader/div/span/button
    Sleep    2s
    Choose File    <input type="file" id="myFile">    C:{/}User${/}pr.com${/}Download${/}base.png

Addpicture

Choose File    //input[@type='file']    C:\Users\pr.com\Downloads\b.jpg
</code>```

This is the result

```<code>Test
| FAIL |
File 'C:{/}User\pr.com\Download\base.png' does not exist on the local file system
</code>```

I use:

```<code>Python version 2.7.14
Robotframework ride  1.5.2.1
</code>```

答:
For chrome below code should work

```<code>Choose File    //input[@type='file']    C:/Users/pr.com/Downloads/b.jpg
</code>```

Let me know if you still get issue

Body:
This is my code

*** Settings ***
Library           Selenium2Library

*** Variables ***
${Login}          xpath=/html/body/app/main/login/div/div[1]/div/form/div[3]/div/button

*** Test Cases ***
Test
    OPEN
    LOGIN
    Sleep    5s
    ADD TOPIC
    Sleep    2s
    SelectType
    TypePDF
    Sleep    5s
    AddFile

*** Keywords ***
OPEN
    Open Browser    https://********** \ \ \    googlechrome

LOGIN

Input Text    id=inputEmail3    ********

Input Text    id=inputPassword3  *******

 Click Element    xpath=/html/body/app/main/login/div/div[1]/div/form/div[3]/div/button

ADD TOPIC
    Click Element    xpath=/html/body/app/main/pages/div/div/news/div/news-list/button

SelectType
    Click Element    id=selectType

TypePDF
    Click Element    xpath=//*[@id="selectType"]/option[5]

AddFile
    Click Button    xpath=/html/body/app/main/pages/div/div/news/div/news-add/ba-card/div/div[2]/div[2]/div[1]/div[2]/ba-file-uploader/div/span/button
    Sleep    2s
    Choose File    <input type="file" id="myFile">    C:{/}User${/}pr.com${/}Download${/}base.png

Addpicture

Choose File    //input[@type='file']    C:\Users\pr.com\Downloads\b.jpg

This is the result

Test
| FAIL |
File 'C:{/}User\pr.com\Download\base.png' does not exist on the local file system

I use:

Python version 2.7.14
Robotframework ride  1.5.2.1

Body:
For chrome below code should work

Choose File    //input[@type='file']    C:/Users/pr.com/Downloads/b.jpg

Let me know if you still get issue


问:
How to create DataGrid Matrix from List Chars?
I display a List with chars in a TextBox, but the spacing is not uniform.

A B C D E

F G H I J

K L M N O

P Q R S T

U V W X Y

How can I bind it to a WPF DataGrid so it displays like a uniform 5x5 Matrix?

Or is there another way to make it uniform?

```<code>A B C D E
F G H I J
K L M N O
P Q R S T
U V W X Y
</code>```

C#

```<code>public char A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y;

public List<char> myList = new List<char>()
{
    A, B, C, D, E,
    F, G, H, I, J,
    K, L, M, N, O,
    P, Q, R, S, T,
    U, V, W, X, Y
}

public ObservableCollection<char> myCollection = new ObservableCollection<char>(myList);
</code>```

XAML

```<code><DataGrid x:Name="dataGrid"
          HorizontalAlignment="Left"
          Height="299"
          Margin="191,399,0,0"
          VerticalAlignment="Top"
          Width="360"/>
</code>```

答:
Besides the possibility to use a monospaced font, like

```<code><TextBlock FontFamily="Lucida Console">
    <Run>ABCDE</Run>
    <LineBreak/>
    <Run>FGHIJ</Run>
    <LineBreak/>
    <Run>KLMNO</Run>
    <LineBreak/>
    <Run>PQRST</Run>
    <LineBreak/>
    <Run>UVWXY</Run>
</TextBlock>
</code>```

you could use an ItemsControl with a UniformGrid:

```<code><ItemsControl ItemsSource="ABCDEFGHIJKLMNOPQRSTUVWXY">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid Columns="5"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding}" TextAlignment="Center"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>
</code>```

Although the XAML designer complains about the ItemsSource property, it will work because a string is an IEnumerable and the Text Binding automatically converts char to string.

You may of course also set the ItemsSource in code behind:

```<code>itemsControl.ItemsSource = new List<string>()
{
    "A", "B", "C", "D", "E",
    "F", "G", "H", "I", "J",
    "K", "L", "M", "N", "O",
    "P", "Q", "R", "S", "T",
    "U", "V", "W", "X", "Y"
};
</code>```

or

```<code>itemsControl.ItemsSource = new List<char>()
{
    'A', 'B', 'C', 'D', 'E',
    'F', 'G', 'H', 'I', 'J',
    'K', 'L', 'M', 'N', 'O',
    'P', 'Q', 'R', 'S', 'T',
    'U', 'V', 'W', 'X', 'Y'
};
</code>```

or of course

```<code>itemsControl.ItemsSource = "ABCDEFGHIJKLMNOPQRSTUVWXY";
</code>```

Body:
I display a List with chars in a TextBox, but the spacing is not uniform.

A B C D E

F G H I J

K L M N O

P Q R S T

U V W X Y

How can I bind it to a WPF DataGrid so it displays like a uniform 5x5 Matrix?

Or is there another way to make it uniform?

A B C D E
F G H I J
K L M N O
P Q R S T
U V W X Y

C#

public char A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y;

public List<char> myList = new List<char>()
{
    A, B, C, D, E,
    F, G, H, I, J,
    K, L, M, N, O,
    P, Q, R, S, T,
    U, V, W, X, Y
}

public ObservableCollection<char> myCollection = new ObservableCollection<char>(myList);

XAML

<DataGrid x:Name="dataGrid"
          HorizontalAlignment="Left"
          Height="299"
          Margin="191,399,0,0"
          VerticalAlignment="Top"
          Width="360"/>

Body:
Besides the possibility to use a monospaced font, like

<TextBlock FontFamily="Lucida Console">
    <Run>ABCDE</Run>
    <LineBreak/>
    <Run>FGHIJ</Run>
    <LineBreak/>
    <Run>KLMNO</Run>
    <LineBreak/>
    <Run>PQRST</Run>
    <LineBreak/>
    <Run>UVWXY</Run>
</TextBlock>

you could use an ItemsControl with a UniformGrid:

<ItemsControl ItemsSource="ABCDEFGHIJKLMNOPQRSTUVWXY">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid Columns="5"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding}" TextAlignment="Center"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Although the XAML designer complains about the ItemsSource property, it will work because a string is an IEnumerable and the Text Binding automatically converts char to string.

You may of course also set the ItemsSource in code behind:

itemsControl.ItemsSource = new List<string>()
{
    "A", "B", "C", "D", "E",
    "F", "G", "H", "I", "J",
    "K", "L", "M", "N", "O",
    "P", "Q", "R", "S", "T",
    "U", "V", "W", "X", "Y"
};

or

itemsControl.ItemsSource = new List<char>()
{
    'A', 'B', 'C', 'D', 'E',
    'F', 'G', 'H', 'I', 'J',
    'K', 'L', 'M', 'N', 'O',
    'P', 'Q', 'R', 'S', 'T',
    'U', 'V', 'W', 'X', 'Y'
};

or of course

itemsControl.ItemsSource = "ABCDEFGHIJKLMNOPQRSTUVWXY";


问:
Chrome violation : [Violation] Handler took 83ms of runtime
I'm trying to implement the Facebook's logout functionality in my project. Login works just fine. But I'm facing the getting the following message in JavaScript console with the logout code.

[Violation] Long running JavaScript task took 318ms session.php:51  1
  sdk.js:135

[Violation] Handler took 83ms of runtime (50ms allowed)

I've tried to search for other similar threads and those solutions didn't work out for me. I tried removing parts of my code and see which part is giving problem. Its quite clear that its getting the error due to Facebook's JS SDK as seen in the message. I've also disabled all of my Chrome extensions.

The code works fine in Firefox but not in Chrome, nor in Opera. Is there any method for me to extend this timeout duration? Or any other method to fix this issue in chrome. Here is my code for logout.

```<code><?php
    session_start();
    //echo $_SESSION["current_user"];
    //echo $_COOKIE["current_user"];
    session_destroy();
    unset($_COOKIE["current_user"]);
    setcookie("current_user","",time() -3600, "/","", 0);
    //header("location: login.php");
?>

<!doctype html>

<html>
<head>
</head>
<body>

<script>

    // Default settings
    window.fbAsyncInit = function() {
        FB.init({
            appId      : '<app-id>',
            cookie     : true,
            xfbml      : true,
            version    : 'v2.8'
        });
        FB.AppEvents.logPageView();
    };

    (function(d, s, id){
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) {return;}
        js = d.createElement(s); js.id = id;
        js.src = "//connect.facebook.net/en_US/sdk.js";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));

    window.onload = function(){
        logout();
    }
    function logout(){
        console.log("1");
        FB.getLoginStatus(function(response) {
        if (response.status === 'connected') {
            FB.logout();
            console.log("2");
            window.location="login.php";
            console.log("3");
        }
        else{
            console.log("4");
            window.location="login.php";
            console.log("5");
        }
        });
    }
</script>
</body>
</html>
</code>```

For obvious reasons I've removed the App-Id from the code. Any help is appreciated. :)

答:
It seems you have found your solution, but still it will be helpful to others, on this page on point based on Chrome 59.

4.Note the red triangle in the top-right of the Animation Frame Fired event. Whenever you see a red triangle, it's a warning that there may
be an issue related to this event.

If you hover on these triangle you can see those are the violation handler errors and as per point 4. yes there is some issue related to that event.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to implement the Facebook's logout functionality in my project. Login works just fine. But I'm facing the getting the following message in JavaScript console with the logout code.

[Violation] Long running JavaScript task took 318ms session.php:51  1
  sdk.js:135

[Violation] Handler took 83ms of runtime (50ms allowed)

I've tried to search for other similar threads and those solutions didn't work out for me. I tried removing parts of my code and see which part is giving problem. Its quite clear that its getting the error due to Facebook's JS SDK as seen in the message. I've also disabled all of my Chrome extensions.

The code works fine in Firefox but not in Chrome, nor in Opera. Is there any method for me to extend this timeout duration? Or any other method to fix this issue in chrome. Here is my code for logout.

<?php
    session_start();
    //echo $_SESSION["current_user"];
    //echo $_COOKIE["current_user"];
    session_destroy();
    unset($_COOKIE["current_user"]);
    setcookie("current_user","",time() -3600, "/","", 0);
    //header("location: login.php");
?>

<!doctype html>

For obvious reasons I've removed the App-Id from the code. Any help is appreciated. :)


问:
I have arrays stored in a json object, I send them using ajax call to the server side, how to access the data?

```<code>$scope.addQunatity = function(){

    var url="../php/mainPageFacture.php";

    // store data from user in the js arrays
    var quan_cls_crt=[$("#quan_cls_crt").val(),$("#quan_cls_crt2").val()];
    var quan_piece=[$("#quan_piece").val(),$("#quan_piece2").val()];
    var itemName=[$("#designList").val(),$("#designList2").val()];
    var dechargementNote=[$("#dechargementNote").val(),$("#dechargementNote2").val()];
    var itemIds=[78,75];

    var func="addQunatity";

    var data = {"function": func,
                "quan_cls_crt":quan_cls_crt,
                "itemId":itemIds,
                "dechargementNote":dechargementNote,
                "quan_piece":quan_piece};
    data = JSON.stringify(data);

    var options = {
            type : "get",
            url : url,
            data: {data:data},
            dataType: 'json',
            async : false,
            cache : false,
            success : function(response,status) {
                debugger;
                $scope.getAllItemNames();
                alert("success");
            },
            error:function(request,response,error){
                alert("Error: " + error + ". Please contact developer");
            }
        };
        $.ajax(options);
    }
</code>```

Here is my php code that will receive the Json object

```<code>           function addQunatity(){
              $quan_cls_crt = $_GET["quan_cls_crt"];
              $quan_piece = $_GET["quan_piece"];
              $itemId=$_GET['itemId'];
              $dechargementNote=$_GET['dechargementNote'];
            }
</code>```

I expect to receive the json arrays and store them in php variable in order to use the in the query later on, but i have no idea how to access the arrays in the json object

答:
```<code><?php
$received_data = file_get_contents('php://input');
$data = json_decode($received_data);
//Here now you can access
$variable_name = $data['keyname']; //this means instead of $_GET or $_POST or $_REQUEST
?>
</code>```

You can access received json data to php using the file_get_contents('php://input'); method..

Body:
$scope.addQunatity = function(){

    var url="../php/mainPageFacture.php";

    // store data from user in the js arrays
    var quan_cls_crt=[$("#quan_cls_crt").val(),$("#quan_cls_crt2").val()];
    var quan_piece=[$("#quan_piece").val(),$("#quan_piece2").val()];
    var itemName=[$("#designList").val(),$("#designList2").val()];
    var dechargementNote=[$("#dechargementNote").val(),$("#dechargementNote2").val()];
    var itemIds=[78,75];

    var func="addQunatity";

    var data = {"function": func,
                "quan_cls_crt":quan_cls_crt,
                "itemId":itemIds,
                "dechargementNote":dechargementNote,
                "quan_piece":quan_piece};
    data = JSON.stringify(data);

    var options = {
            type : "get",
            url : url,
            data: {data:data},
            dataType: 'json',
            async : false,
            cache : false,
            success : function(response,status) {
                debugger;
                $scope.getAllItemNames();
                alert("success");
            },
            error:function(request,response,error){
                alert("Error: " + error + ". Please contact developer");
            }
        };
        $.ajax(options);
    }

Here is my php code that will receive the Json object

           function addQunatity(){
              $quan_cls_crt = $_GET["quan_cls_crt"];
              $quan_piece = $_GET["quan_piece"];
              $itemId=$_GET['itemId'];
              $dechargementNote=$_GET['dechargementNote'];
            }

I expect to receive the json arrays and store them in php variable in order to use the in the query later on, but i have no idea how to access the arrays in the json object

Body:
<?php
$received_data = file_get_contents('php://input');
$data = json_decode($received_data);
//Here now you can access
$variable_name = $data['keyname']; //this means instead of $_GET or $_POST or $_REQUEST
?>

You can access received json data to php using the file_get_contents('php://input'); method..


问:
ProGuard obfuscate classes names not working
I know there are some classes which should not be obfuscated but I want the other classes be renamed like adapters ,utilities, etc.  I am not interesting to make the project runnable for now.

Gradle File:

```<code>buildscript {
  repositories {
    maven { url 'https://maven.fabric.io/public' }
  }

  dependencies {
    classpath 'io.fabric.tools:gradle:1.+'
  }
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

repositories {
  jcenter()
  maven { url 'https://maven.fabric.io/public' }
  maven { url "https://jitpack.io" }
}

android {
  compileSdkVersion 23
  buildToolsVersion "23.0.2"
  useLibrary 'org.apache.http.legacy'

  defaultConfig {
    multiDexEnabled true
    applicationId "com.afaqy.gps"
    minSdkVersion 15
    targetSdkVersion 17
    versionCode 39
    versionName "2.10"
    generatedDensities = []
  }
  buildTypes {
    release {
        minifyEnabled true
        debuggable false
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
    debug {
        debuggable false
        minifyEnabled true
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
  }

  lintOptions {
    abortOnError false
    checkReleaseBuilds false
  }

  dexOptions {
    javaMaxHeapSize "4g" //specify the heap size for the dex process
  }

  // This is handled for you by the 2.0+ Gradle Plugin
  aaptOptions {
    additionalParameters "--no-version-vectors"
  }
}

dependencies {
  compile 'com.google.code.gson:gson:2.2.4'
  compile 'com.android.volley:volley:1.0.0'
  compile 'com.jakewharton:disklrucache:2.0.2'
  compile 'com.android.support:appcompat-v7:23.0.0'
  compile 'com.android.support:cardview-v7:23.0.0'
  compile 'com.baoyz.pullrefreshlayout:library:1.2.0'
  compile project(':_LibSlideDateTimePicker')
  compile('io.socket:socket.io-client:0.6.3') {
    exclude group: 'org.json', module: 'json'
  }
  compile 'com.splitwise:tokenautocomplete:2.0.8@aar'
  compile 'com.squareup.picasso:picasso:2.5.2'
  compile 'com.google.firebase:firebase-messaging:9.4.0'
  compile 'com.github.paolorotolo:appintro:4.1.0'
  compile 'com.wang.avi:library:2.1.3'
  compile('com.crashlytics.sdk.android:crashlytics:2.6.8@aar') {
    transitive = true;
  }
  compile 'com.android.support:recyclerview-v7:23.1.1'
  compile 'pl.bclogic:pulsator4droid:1.0.3'
  compile 'com.android.support:multidex:1.0.1'
  compile 'com.kyleduo.switchbutton:library:1.4.6'
  compile 'com.android.support:design:23.0.0'
  compile 'com.github.PhilJay:MPAndroidChart:v3.0.2'
  compile 'com.android.support:support-v4:23.+'
  compile 'com.daimajia.swipelayout:library:1.2.0@aar'
  compile 'me.leolin:ShortcutBadger:1.1.18@aar'
  compile 'su.j2e:rv-joiner:1.0.9'
  compile 'ca.barrenechea.header-decor:header-decor:0.2.8'
}
apply plugin: 'com.google.gms.google-services'
</code>```

Top-level build file

```<code>buildscript {
   repositories {
    jcenter()
    maven { url 'https://maven.fabric.io/public' }
  }
  dependencies {
    classpath 'com.android.tools.build:gradle:1.5.0'
    classpath 'com.google.gms:google-services:3.0.0'
    classpath 'io.fabric.tools:gradle:1.+'
  }
}

allprojects {
  repositories {
    jcenter()
  }
}
</code>```

proguard-rules.pro (#only okio to be able to generate signed apk)

```<code>-dontwarn okio.**
</code>```

Also in the gradle of library i used this in buildTypes.

```<code>consumerProguardFiles 'proguard-rules.pro'
</code>```

All classes is retrieved with the original name.

Any idea what I did wrong ? What I missed in my configuration file which is not obfuscating classes names ?

答:
Fixed by updating app intro library from
compile 'com.github.paolorotolo:appintro:4.1.0'
to
compile 'com.github.apl-devs:appintro:v4.2.2'</p>

Body:
I know there are some classes which should not be obfuscated but I want the other classes be renamed like adapters ,utilities, etc.  I am not interesting to make the project runnable for now.

Gradle File:

buildscript {
  repositories {
    maven { url 'https://maven.fabric.io/public' }
  }

  dependencies {
    classpath 'io.fabric.tools:gradle:1.+'
  }
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

repositories {
  jcenter()
  maven { url 'https://maven.fabric.io/public' }
  maven { url "https://jitpack.io" }
}

android {
  compileSdkVersion 23
  buildToolsVersion "23.0.2"
  useLibrary 'org.apache.http.legacy'

  defaultConfig {
    multiDexEnabled true
    applicationId "com.afaqy.gps"
    minSdkVersion 15
    targetSdkVersion 17
    versionCode 39
    versionName "2.10"
    generatedDensities = []
  }
  buildTypes {
    release {
        minifyEnabled true
        debuggable false
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
    debug {
        debuggable false
        minifyEnabled true
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
  }

  lintOptions {
    abortOnError false
    checkReleaseBuilds false
  }

  dexOptions {
    javaMaxHeapSize "4g" //specify the heap size for the dex process
  }

  // This is handled for you by the 2.0+ Gradle Plugin
  aaptOptions {
    additionalParameters "--no-version-vectors"
  }
}

dependencies {
  compile 'com.google.code.gson:gson:2.2.4'
  compile 'com.android.volley:volley:1.0.0'
  compile 'com.jakewharton:disklrucache:2.0.2'
  compile 'com.android.support:appcompat-v7:23.0.0'
  compile 'com.android.support:cardview-v7:23.0.0'
  compile 'com.baoyz.pullrefreshlayout:library:1.2.0'
  compile project(':_LibSlideDateTimePicker')
  compile('io.socket:socket.io-client:0.6.3') {
    exclude group: 'org.json', module: 'json'
  }
  compile 'com.splitwise:tokenautocomplete:2.0.8@aar'
  compile 'com.squareup.picasso:picasso:2.5.2'
  compile 'com.google.firebase:firebase-messaging:9.4.0'
  compile 'com.github.paolorotolo:appintro:4.1.0'
  compile 'com.wang.avi:library:2.1.3'
  compile('com.crashlytics.sdk.android:crashlytics:2.6.8@aar') {
    transitive = true;
  }
  compile 'com.android.support:recyclerview-v7:23.1.1'
  compile 'pl.bclogic:pulsator4droid:1.0.3'
  compile 'com.android.support:multidex:1.0.1'
  compile 'com.kyleduo.switchbutton:library:1.4.6'
  compile 'com.android.support:design:23.0.0'
  compile 'com.github.PhilJay:MPAndroidChart:v3.0.2'
  compile 'com.android.support:support-v4:23.+'
  compile 'com.daimajia.swipelayout:library:1.2.0@aar'
  compile 'me.leolin:ShortcutBadger:1.1.18@aar'
  compile 'su.j2e:rv-joiner:1.0.9'
  compile 'ca.barrenechea.header-decor:header-decor:0.2.8'
}
apply plugin: 'com.google.gms.google-services'

Top-level build file

buildscript {
   repositories {
    jcenter()
    maven { url 'https://maven.fabric.io/public' }
  }
  dependencies {
    classpath 'com.android.tools.build:gradle:1.5.0'
    classpath 'com.google.gms:google-services:3.0.0'
    classpath 'io.fabric.tools:gradle:1.+'
  }
}

allprojects {
  repositories {
    jcenter()
  }
}

proguard-rules.pro (#only okio to be able to generate signed apk)

-dontwarn okio.**

Also in the gradle of library i used this in buildTypes.

consumerProguardFiles 'proguard-rules.pro'

All classes is retrieved with the original name.

Any idea what I did wrong ? What I missed in my configuration file which is not obfuscating classes names ?


问:
Modifying program using exceptions in python
I need to make a program that initializing class objects throw an exception if the day, month, and year passed as arguments to initialize object variables do not represent a valid date. The exception may only issue an invalid date message.

I do not get much exception in Python, so I did an algorithm that only has an if and else that checks whether it is valid or not. How to transform according to what I need, ie: an exception if the day, month, and year passed as arguments to initialize object variables do not represent a valid date?

```<code>def dois(day, month, year):
    checks = "true"
    i = 0
    while checks == "true" and i == 0:
        if (year%4 == 0 and year%100!= 0) or year%400 == 0:
            leap_year = "sim"
        else:
            leap_year = "nao"

        if month < 1 or month > 12:
            checks = "false"

        if day > 31 or ((month == 4 or month == 6 or month == 9 or month == 11) and day > 30):
            checks = "false"

        if (month == 2 and leap_year == "nao" and day > 28) or ( month == 2 and leap_year == "sim" and day > 29):
            checks = "false"
        i = i + 1

    if checks == "true":
        print("Valid date")
    else:
        print("Invalid date")
</code>```

I can not use ready-made functions like time.strptime, I need to use what I have implemented

答:
```<code># declare a new exception class
class ValidationException(Exception):
    pass

# later
if checks != "true":
    raise ValidationException("Invalid data")
</code>```

Body:
I need to make a program that initializing class objects throw an exception if the day, month, and year passed as arguments to initialize object variables do not represent a valid date. The exception may only issue an invalid date message.

I do not get much exception in Python, so I did an algorithm that only has an if and else that checks whether it is valid or not. How to transform according to what I need, ie: an exception if the day, month, and year passed as arguments to initialize object variables do not represent a valid date?

def dois(day, month, year):
    checks = "true"
    i = 0
    while checks == "true" and i == 0:
        if (year%4 == 0 and year%100!= 0) or year%400 == 0:
            leap_year = "sim"
        else:
            leap_year = "nao"

        if month < 1 or month > 12:
            checks = "false"

        if day > 31 or ((month == 4 or month == 6 or month == 9 or month == 11) and day > 30):
            checks = "false"

        if (month == 2 and leap_year == "nao" and day > 28) or ( month == 2 and leap_year == "sim" and day > 29):
            checks = "false"
        i = i + 1

    if checks == "true":
        print("Valid date")
    else:
        print("Invalid date")

I can not use ready-made functions like time.strptime, I need to use what I have implemented


问:
How can I fix the issue with many-to-many relationship definition
I have a problem like this I ask another question related to this code today.I got solved that problem, but now it giving and another error.

```<code>public function addSubject(Request $request){
        $student=User::find($request->invisible);
        $classsubjects = $request['classsubjects'];
        $student->classSubjects()->attach($classsubjects);
        return redirect()->route('users.index')
            ->with('flash_message',
             'User successfully added.');
}
</code>```

Here i am giving the definition of ClassSubject Model and User model definition.

```<code><?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use Notifiable;
    use HasRoles;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password','language'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function setPasswordAttribute($password)
    {
        $this->attributes['password'] = bcrypt($password);
    }

    public function classSubject()
    {
        return $this->hasMany('App\ClassSubject');
    }

    public function classSubjects()
    {
        return $this->belongsToMany('App\ClassSubject');

    }

}
</code>```

This is my classSubject model.

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ClassSubject extends Model
{
    protected $fillable = [
         'class_room_id','subject_id','teacher_id'
    ];

     public function classRoom()
    {
        return $this->belongsTo('App\ClassRoom','class_room_id','id');
    }

     public function subject()
    {
        return $this->belongsTo('App\Subject','subject_id','id');
    }

     public function teacher()
    {
        return $this->belongsTo('App\User','teacher_id','id');
    }

    public function students()
    {
        return $this->belongsToMany('App\User');

    }

}
</code>```

This is the error that I am getting.

```<code>Illuminate \ Database \ QueryException (42S02)
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'lcurve.class_subject_user' doesn't exist (SQL: insert into `class_subject_user` (`class_subject_id`, `user_id`) values (3, 4), (1, 4))
</code>```

Should i need to create a table like the error message saying.

答:
You need to create a pivot table to handle this. Ex:

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ClassSubjectUser extends Model
{
    protected $fillable = [
         'class_subject_id','user_id'
    ];

    protected $table = 'class_subject_user';
}
</code>```

And then, when defining the relationships, you should set the name of the table and the keys.

In User model:

```<code>public function classSubjects()
{
    return $this->belongsToMany('App\ClassSubject', 'class_subject_user', 'class_subject_id', 'user_id');
}
</code>```

In ClassSubject model:

```<code>public function students()
{
    return $this->belongsToMany('App\User', 'class_subject_user', 'user_id', 'class_subject_id');
}
</code>```

This will set the belongsToMany relationship correctly.

Ref: https://laravel.com/docs/5.5/eloquent-relationships#updating-many-to-many-relationships

Body:
I have a problem like this I ask another question related to this code today.I got solved that problem, but now it giving and another error.

public function addSubject(Request $request){
        $student=User::find($request->invisible);
        $classsubjects = $request['classsubjects'];
        $student->classSubjects()->attach($classsubjects);
        return redirect()->route('users.index')
            ->with('flash_message',
             'User successfully added.');
}

Here i am giving the definition of ClassSubject Model and User model definition.

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use Notifiable;
    use HasRoles;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password','language'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function setPasswordAttribute($password)
    {
        $this->attributes['password'] = bcrypt($password);
    }

    public function classSubject()
    {
        return $this->hasMany('App\ClassSubject');
    }

    public function classSubjects()
    {
        return $this->belongsToMany('App\ClassSubject');

    }

}

This is my classSubject model.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ClassSubject extends Model
{
    protected $fillable = [
         'class_room_id','subject_id','teacher_id'
    ];

     public function classRoom()
    {
        return $this->belongsTo('App\ClassRoom','class_room_id','id');
    }

     public function subject()
    {
        return $this->belongsTo('App\Subject','subject_id','id');
    }

     public function teacher()
    {
        return $this->belongsTo('App\User','teacher_id','id');
    }

    public function students()
    {
        return $this->belongsToMany('App\User');

    }

}

This is the error that I am getting.

Illuminate \ Database \ QueryException (42S02)
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'lcurve.class_subject_user' doesn't exist (SQL: insert into `class_subject_user` (`class_subject_id`, `user_id`) values (3, 4), (1, 4))

Should i need to create a table like the error message saying.

Body:
You need to create a pivot table to handle this. Ex:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ClassSubjectUser extends Model
{
    protected $fillable = [
         'class_subject_id','user_id'
    ];

    protected $table = 'class_subject_user';
}

And then, when defining the relationships, you should set the name of the table and the keys.

In User model:

public function classSubjects()
{
    return $this->belongsToMany('App\ClassSubject', 'class_subject_user', 'class_subject_id', 'user_id');
}

In ClassSubject model:

public function students()
{
    return $this->belongsToMany('App\User', 'class_subject_user', 'user_id', 'class_subject_id');
}

This will set the belongsToMany relationship correctly.

Ref: https://laravel.com/docs/5.5/eloquent-relationships#updating-many-to-many-relationships


问:
Can I pass DATEADD straight into a variable?
In one of the tSQLt tests I am writing I call a method with parameters to fill the expected table like so:

```<code>EXEC Test.Insert_Expected
    @CommencementDt = DATEADD(MONTH, 1, GETDATE)
</code>```

However I am getting an error over the MONTH part of the second line reading:

'Incorrect syntax near MONTH, expecting ( or SELECT'

I'm new to using parameterised methods and was wandering why this wasn't working, and how I might solve it? Thanks

答: Try using GETDATE() instead of GETDATE

Body:
In one of the tSQLt tests I am writing I call a method with parameters to fill the expected table like so:

EXEC Test.Insert_Expected
    @CommencementDt = DATEADD(MONTH, 1, GETDATE)

However I am getting an error over the MONTH part of the second line reading:

'Incorrect syntax near MONTH, expecting ( or SELECT'

I'm new to using parameterised methods and was wandering why this wasn't working, and how I might solve it? Thanks

Body: Try using GETDATE() instead of GETDATE


问:
Is anyone using meta-meta-classes / meta-meta-meta-classes in Python/ other languages?
I recently discovered metaclasses in python.

Basically a metaclass in python is a class that creates a class. There are many useful reasons why you would want to do this - any kind of class initialisation for example. Registering classes on factories, complex validation of attributes, altering how inheritance works, etc. All of this becomes not only possible but simple.

But in python, metaclasses are also plain classes. So, I started wondering if the abstraction could usefully go higher, and it seems to me that it can and that:

a metaclass corresponds to or implements a role in a pattern (as in GOF pattern languages).

a meta-metaclass is the pattern itself (if we allow it to create tuples of classes representing abstract roles, rather than just a single class)

a meta-meta-metaclass is a pattern factory, which corresponds to the GOF pattern groupings, e.g. Creational,  Structural, Behavioural. A factory where you could describe a case of a certain type of problem and it would give you a set of classes that solved it.

a meta-meta-meta-metaclass (as far as I could go), is a pattern factory factory, a factory to which you could perhaps describe the type of your problem and it would give you a pattern factory to ask.

I have found some stuff about this online, but mostly not very useful. One problem is that different languages define metaclasses slightly differently.

Has anyone else used metaclasses like this in python/elsewhere, or seen this used in the wild, or thought about it? What are the analogues in other languages? E.g. in C++ how deep can the template recursion go?

I'd very much like to research it further.

答:
The class system in Smalltalk is an interesting one to study. In Smalltalk, everything is an object and every object has a class. This doesn't imply that the hierarchy goes to infinity. If I remember correctly, it goes something like:

5 -> Integer -> Integer class -> Metaclass -> Metaclass class -> Metaclass -> ... (it loops)

Where '->' denotes "is an instance of".

OwnerDisplayName: Rafał Dowgird


问:
How to force IAR to use desired Cortex-M0+ instructions (optimization will be disabled for this func.)
I need to force IAR tp use certain Cortex-M0+ instruction in some part of my code while codding with C.

Please do not offer pure asm functions or inline asm etc.

I have managed to do this for 51 instruction but could not for ;
ADR, BLX, RSBS, SBCS, SXTH instructions.

Optimization is disabled for this function (#pragma optimization=none)

I have tried many things by considering instruction behaviour.
But IAR preferred to same function with different instructions.

Did anyone else struggle with such a unnecessary thing before or has anyone an idea?

答:
Please do not offer pure asm functions or inline asm etc.

But these are the only solution to your problem that won't depend on compiler version.

You may have

managed to do this for 51 instruction

..but the next (major) compiler version could have a vastly different idea on how to generate instructions for your C code, even when the optimizer is off. BTDT for GCC.

Coding stuff in assembly language directly eliminates this compiler version dependecy altogether. You should even have some example code, as most C-startup (reset handler) code is shipped as assembly language file.


问:
.Net Core App 2.0 not compatible with .Net Standard 2.0 libraries
In Visual Studio 2017, I created a solcution containing the following:

ASP.Net Core web application project (ASP.Net MVC)

two class library projects created as .Net Standard libraries

By default out of the box, VS 2017 makes these class libraries target .Net Standard 2.0, and the web application targets .Net Core 1.1.

Added project dependencies - the web app has both of the two class libraries as project dependencies (as they contain the core functionality, the web app being merely the front end).

Theoretically, VS should have chosen sensible defaults. However, that does not compile. I am getting errors like this:

```<code>Error   CS1705
Assembly 'Entities' with identity 'Entities, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=null' uses 'System.Runtime, Version=4.1.2.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' which has a higher version
than referenced assembly 'System.Runtime' with identity 'System.Runtime,
Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
</code>```

I do not know how to change references to System.Runtime, and find no option in VS to do so.

Okay - .Net Core 1.1 should really not make sense with .Net Standard 2.0 (even though .Net Core 1.1 is not even listed in the official .Net Standard overview graphic, see official MS Github documentation, so I how can we be sure?).

So let's change that and modify the target of the web app to .Net Core 2.0, so that everything targets 2.0 - per the above official chart that should dovetail just fine - so in VS with Projects > Properties we change the target framework to .Net Core 2.0, and rebuild solution.
(Note that my VS instance is set to restore Nuget packages on every rebuild as it is by default.)

Again does not work. Different errors this time - several errors of that kind here:

```<code>    Error   NU1605  Detected package downgrade: System.Net.Primitives from 4.3.0
    to 4.0.11. Reference the package directly from the project to select a
different version.
     UI.Web (>= 1.0.0) -> Microsoft.VisualStudio.Web.BrowserLink (>= 1.1.2) ->
    Microsoft.AspNetCore.Hosting.Abstractions (>= 1.1.2) -> NETStandard.Library
    (>= 1.6.1) -> System.Net.Primitives (>= 4.3.0)
     UI.Web (>= 1.0.0) -> Microsoft.VisualStudio.Web.BrowserLink (>= 1.1.2) ->
    System.Net.Primitives (>= 4.0.11)   UI.Web  C:\Source\Projects\Test
    \UI.Web\UI.Web.csproj
</code>```

In earlier versions of the .Net Core tooling (VS 2015) there had been many JSON files allowing for tweaking of dependency versions but this no longer applies in VS 2017 - csproj is the only one and it's in XML and contains no reference to any of the packages listed above in the error.

So what does this mean? .Net Core 2.0 is not compatible with .Net Standard 2.0 libraries?

Funny thing is, it isn't the first time I have produced that kind of an app and just a few months ago, it worked right out of the box. Looking into an older app which works fine I find that

the .Net standard libraries are on .Net Standard 1.6

ASP.Net Core web app is on .Net Core 1.1

Changed that in my new project - and voila, it works.

But this raises still these questions:

Is .Net Core 2.0 is not compatible with .Net Standard 2.0 libraries?

Is that an issue in VS 2017 that the default frameworks for .Net Core
and .Net Standard libraries do not dovetail, or is that something
I can set up / configure?

答:
To state the obvious, .NET Core 2.0 is .NET Standard 2.0 compliant.

However, you may see error/warning messages such as NU1605 Detected package downgrade. This happens as well when referencing log4net 2.0.8 for instance.

NU1605 is in fact a warning, however, by default it's treated as an error in Visual Studio 2017.

You can change this back to a warning by editing the csproj file (search for something like <WarningsAsErrors>NU1605</WarningsAsErrors>) or from Visual Studio go to project properties > Build > Treat Warnings as Errors.

Body:
In Visual Studio 2017, I created a solcution containing the following:

ASP.Net Core web application project (ASP.Net MVC)

two class library projects created as .Net Standard libraries

By default out of the box, VS 2017 makes these class libraries target .Net Standard 2.0, and the web application targets .Net Core 1.1.

Added project dependencies - the web app has both of the two class libraries as project dependencies (as they contain the core functionality, the web app being merely the front end).

Theoretically, VS should have chosen sensible defaults. However, that does not compile. I am getting errors like this:

Error   CS1705
Assembly 'Entities' with identity 'Entities, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=null' uses 'System.Runtime, Version=4.1.2.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' which has a higher version
than referenced assembly 'System.Runtime' with identity 'System.Runtime,
Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'

I do not know how to change references to System.Runtime, and find no option in VS to do so.

Okay - .Net Core 1.1 should really not make sense with .Net Standard 2.0 (even though .Net Core 1.1 is not even listed in the official .Net Standard overview graphic, see official MS Github documentation, so I how can we be sure?).

So let's change that and modify the target of the web app to .Net Core 2.0, so that everything targets 2.0 - per the above official chart that should dovetail just fine - so in VS with Projects > Properties we change the target framework to .Net Core 2.0, and rebuild solution.
(Note that my VS instance is set to restore Nuget packages on every rebuild as it is by default.)

Again does not work. Different errors this time - several errors of that kind here:

    Error   NU1605  Detected package downgrade: System.Net.Primitives from 4.3.0
    to 4.0.11. Reference the package directly from the project to select a
different version.
     UI.Web (>= 1.0.0) -> Microsoft.VisualStudio.Web.BrowserLink (>= 1.1.2) ->
    Microsoft.AspNetCore.Hosting.Abstractions (>= 1.1.2) -> NETStandard.Library
    (>= 1.6.1) -> System.Net.Primitives (>= 4.3.0)
     UI.Web (>= 1.0.0) -> Microsoft.VisualStudio.Web.BrowserLink (>= 1.1.2) ->
    System.Net.Primitives (>= 4.0.11)   UI.Web  C:\Source\Projects\Test
    \UI.Web\UI.Web.csproj

In earlier versions of the .Net Core tooling (VS 2015) there had been many JSON files allowing for tweaking of dependency versions but this no longer applies in VS 2017 - csproj is the only one and it's in XML and contains no reference to any of the packages listed above in the error.

So what does this mean? .Net Core 2.0 is not compatible with .Net Standard 2.0 libraries?

Funny thing is, it isn't the first time I have produced that kind of an app and just a few months ago, it worked right out of the box. Looking into an older app which works fine I find that

the .Net standard libraries are on .Net Standard 1.6

ASP.Net Core web app is on .Net Core 1.1

Changed that in my new project - and voila, it works.

But this raises still these questions:

Is .Net Core 2.0 is not compatible with .Net Standard 2.0 libraries?

Is that an issue in VS 2017 that the default frameworks for .Net Core
and .Net Standard libraries do not dovetail, or is that something
I can set up / configure?


问:
Yii2 - error handler can not catches database exceptions
I'm working on Yii2 advanced application project and I have a problem with yii2 built-in Error Handler. Here is description of my problem:

I have set errorAction in my backend configuration in this way:

```<code>'errorHandler' => [
    'errorAction' => 'site/error',
],
</code>```

Now, the method actionError() in the SiteController catches every application exceptions, user defined exceptions and also fatal errors, except database related exception such as yii\db\IntegrityException. I don't know why, but when such an exception occurs, actionError() does not do anything! I don't want to catch exception manually with try-catch block and I want the central ErrorHandler catches all exception.

How can I fix this problem? Thank you all specially yii experts for paying attention. Please help me to solve this strange problem.

答:
According to this GitHub issue: yiisoft/yii2/issues/10657 and to the comment made by @Yupik you must change the YII_DEBUG.

If YII_DEBUG is true, you should see proper message about yii\db\IntegrityException in debug mode.

If YII_DEBUG is false(like in a production enviroment) error is redirected to actionError() and see it in a user-friendly mode.

Body:
I'm working on Yii2 advanced application project and I have a problem with yii2 built-in Error Handler. Here is description of my problem:

I have set errorAction in my backend configuration in this way:

'errorHandler' => [
    'errorAction' => 'site/error',
],

Now, the method actionError() in the SiteController catches every application exceptions, user defined exceptions and also fatal errors, except database related exception such as yii\db\IntegrityException. I don't know why, but when such an exception occurs, actionError() does not do anything! I don't want to catch exception manually with try-catch block and I want the central ErrorHandler catches all exception.

How can I fix this problem? Thank you all specially yii experts for paying attention. Please help me to solve this strange problem.