问:
How to aggregate results from making CompletableFuture calls in a loop?
I am just learning and trying to apply CompletableFuture to my problem statement. I have a list of items I am iterating over.

Prop is a class with only two attributes prop1 and prop2, respective getters and setters.

```<code>List<Prop> result = new ArrayList<>();

for ( Item item : items ) {
      item.load();

      Prop temp = new Prop();
      // once the item is loaded, get its properties
      temp.setProp1(item.getProp1());
      temp.setProp2(item.getProp2());

      result.add(temp);
}

return result;
</code>```

However, item.load() here is a blocking call. So, I was thinking to use CompletableFuture something like below -

```<code>for (Item item : items) {
    CompletableFuture<Prop> prop = CompletableFuture.supplyAsync(() -> {
        try {
            item.load();
            return item;
        } catch (Exception e) {
            logger.error("Error");
            return null;
        }
    }).thenApply(item1 -> {
        try {
            Prop temp = new Prop();
            // once the item is loaded, get its properties
            temp.setProp1(item.getProp1());
            temp.setProp2(item.getProp2());

            return temp;
        } catch (Exception e) {
        }
    });
}
</code>```

But I am not sure how I can wait for all the items to be loaded and then aggregate and return their result.

I may be completely wrong in the way of implementing CompletableFutures since this is my first attempt. Please pardon any mistake. Thanks in advance for any help.

答:
There are two issues with your approach of using CompletableFuture.

First, you say item.load() is a blocking call, so the CompletableFuture’s default executor is not suitable for it, as it tries to achieve a level of parallelism matching the number of CPU cores. You could solve this by passing a different Executor to CompletableFuture’s asynchronous methods, but your load() method doesn’t return a value that your subsequent operations rely on. So the use of CompletableFuture complicates the design without a benefit.

You can perform the load() invocations asynchronously and wait for their completion just using an ExecutorService, followed by the loop as-is (without the already performed load() operation, of course):

```<code>ExecutorService es = Executors.newCachedThreadPool();
es.invokeAll(items.stream()
    .map(i -> Executors.callable(i::load))
    .collect(Collectors.toList()));
es.shutdown();

List<Prop> result = new ArrayList<>();

for(Item item : items) {
      Prop temp = new Prop();
      // once the item is loaded, get its properties
      temp.setProp1(item.getProp1());
      temp.setProp2(item.getProp2());

      result.add(temp);
}

return result;
</code>```

You can control the level of parallelism through the choice of the executor, e.g. you could use a Executors.newFixedThreadPool(numberOfThreads) instead of the unbounded thread pool.

Body:
I am just learning and trying to apply CompletableFuture to my problem statement. I have a list of items I am iterating over.

Prop is a class with only two attributes prop1 and prop2, respective getters and setters.

List<Prop> result = new ArrayList<>();

for ( Item item : items ) {
      item.load();

      Prop temp = new Prop();
      // once the item is loaded, get its properties
      temp.setProp1(item.getProp1());
      temp.setProp2(item.getProp2());

      result.add(temp);
}

return result;

However, item.load() here is a blocking call. So, I was thinking to use CompletableFuture something like below -

for (Item item : items) {
    CompletableFuture<Prop> prop = CompletableFuture.supplyAsync(() -> {
        try {
            item.load();
            return item;
        } catch (Exception e) {
            logger.error("Error");
            return null;
        }
    }).thenApply(item1 -> {
        try {
            Prop temp = new Prop();
            // once the item is loaded, get its properties
            temp.setProp1(item.getProp1());
            temp.setProp2(item.getProp2());

            return temp;
        } catch (Exception e) {
        }
    });
}

But I am not sure how I can wait for all the items to be loaded and then aggregate and return their result.

I may be completely wrong in the way of implementing CompletableFutures since this is my first attempt. Please pardon any mistake. Thanks in advance for any help.

Body:
There are two issues with your approach of using CompletableFuture.

First, you say item.load() is a blocking call, so the CompletableFuture’s default executor is not suitable for it, as it tries to achieve a level of parallelism matching the number of CPU cores. You could solve this by passing a different Executor to CompletableFuture’s asynchronous methods, but your load() method doesn’t return a value that your subsequent operations rely on. So the use of CompletableFuture complicates the design without a benefit.

You can perform the load() invocations asynchronously and wait for their completion just using an ExecutorService, followed by the loop as-is (without the already performed load() operation, of course):

ExecutorService es = Executors.newCachedThreadPool();
es.invokeAll(items.stream()
    .map(i -> Executors.callable(i::load))
    .collect(Collectors.toList()));
es.shutdown();

List<Prop> result = new ArrayList<>();

for(Item item : items) {
      Prop temp = new Prop();
      // once the item is loaded, get its properties
      temp.setProp1(item.getProp1());
      temp.setProp2(item.getProp2());

      result.add(temp);
}

return result;

You can control the level of parallelism through the choice of the executor, e.g. you could use a Executors.newFixedThreadPool(numberOfThreads) instead of the unbounded thread pool.


来源: stackexchange

问:
Detecting full screen mode in Windows
I need to detect if some application is currently running in full screen mode. If yes, then I must stop my application. So, how can I detect that?
p.s. Win32 C++</p>

答:
A full implementation of Hooch's answer:</p>

```<code>bool isFullscreen(HWND window)
{
    RECT a, b;
    GetWindowRect(window, &a);
    GetWindowRect(GetDesktopWindow(), &b);
    return (a.left   == b.left  &&
            a.top    == b.top   &&
            a.right  == b.right &&
            a.bottom == b.bottom);
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Detecting full screen mode in Windows

Body:
A full implementation of Hooch's answer:

bool isFullscreen(HWND window)
{
    RECT a, b;
    GetWindowRect(window, &a);
    GetWindowRect(GetDesktopWindow(), &b);
    return (a.left   == b.left  &&
            a.top    == b.top   &&
            a.right  == b.right &&
            a.bottom == b.bottom);
}

ContentLicense: CC BY-SA 3.0


问:
Use Spring Security with JPA
I am new to Spring.

We are using spring security feature.
Database connectivity: eclipselink implementation of JPA.
Database: MySql

While using spring security, Configuration of  authentication provider is as follows,-

```<code><authentication-provider>

    <jdbc-user-service id="userDetailsService" data-source-ref="Datasource" />

    </authentication-provider>
</code>```

But in JPA we do not define datasource, we use Persistence unit with provider jpa.PersistenceProvider.

So how do we configure authentication provider so as to use JPA for database connectivity?

What exactly should data-source-ref field contain to use database for authentication?

Thank you in advance.

答:
Basically you probably need to implement UserDetailsService yourself.

So you would for example have a User entity, and your UserDetailsService implementation would look up the user and convert it to a UserDetails object (or your entity would have to implement UserDetails).

Sample implementation:

```<code>public class MyUserDetailsService implements UserDetailsService{

    private EntityManager entityManager;
    @PersistenceContext
    public void setEntityManager(EntityManager newEm){
        this.entityManager = newEm;
    }

    public UserDetails loadUserByUsername(String username){

        // assuming that you have a User class that implements UserDetails
        return entityManager.createQuery("from User where username = :username", User.class)
                            .setParameter("username", username)
                            .getSingleResult();

    }
}
</code>```

And you add this to user spring-security.xml

```<code><authentication-manager>
   <authentication-provider user-service-ref="MyUserDetailsService" />
</authentication-manager>
</code>```

Title: Use Spring Security with JPA

Body:
I am new to Spring.

We are using spring security feature.
Database connectivity: eclipselink implementation of JPA.
Database: MySql

While using spring security, Configuration of  authentication provider is as follows,-

<authentication-provider>

    <jdbc-user-service id="userDetailsService" data-source-ref="Datasource" />

    </authentication-provider>

But in JPA we do not define datasource, we use Persistence unit with provider jpa.PersistenceProvider.

So how do we configure authentication provider so as to use JPA for database connectivity?

What exactly should data-source-ref field contain to use database for authentication?

Thank you in advance.

Body:
Basically you probably need to implement UserDetailsService yourself.

So you would for example have a User entity, and your UserDetailsService implementation would look up the user and convert it to a UserDetails object (or your entity would have to implement UserDetails).

Sample implementation:

public class MyUserDetailsService implements UserDetailsService{

    private EntityManager entityManager;
    @PersistenceContext
    public void setEntityManager(EntityManager newEm){
        this.entityManager = newEm;
    }

    public UserDetails loadUserByUsername(String username){

        // assuming that you have a User class that implements UserDetails
        return entityManager.createQuery("from User where username = :username", User.class)
                            .setParameter("username", username)
                            .getSingleResult();

    }
}

And you add this to user spring-security.xml

<authentication-manager>
   <authentication-provider user-service-ref="MyUserDetailsService" />
</authentication-manager>


问:
file upload script in php not working
My php code for file upload is not working. I have tried it in various ways. My code is given below:

HTML Code:

```<code><form action="assets/php/regc.php" method="POST" name="rform" enctype="multipart/form-data">
<input name="photo" type="file" placeholder="Attach Photo" required="required"/><br>
<input type="submit" value="upload" name="" />

</form>

PHP Code:
<?php
$pic=$_FILES["photo"]["name"];

$location="assets/";
$myfile= $location.basename($_FILES["photo"]["name"]);

if(isset($_FILES["photo"]["name"]))
{
    $ok=move_uploaded_file($_FILES["photo"]["tmp_name"], $myfile);
    if($ok)
    {
    echo "success";
    }

    else
    {
    echo "Failed";
    }
}
?>
</code>```

答:
You can try this out. It looks similar
https://www.w3schools.com/php/php_file_upload.asp</p>

Title: file upload script in php not working

Body:
My php code for file upload is not working. I have tried it in various ways. My code is given below:

HTML Code:

<form action="assets/php/regc.php" method="POST" name="rform" enctype="multipart/form-data">
<input name="photo" type="file" placeholder="Attach Photo" required="required"/>

<input type="submit" value="upload" name="" />

</form>

PHP Code:
<?php
$pic=$_FILES["photo"]["name"];

$location="assets/";
$myfile= $location.basename($_FILES["photo"]["name"]);

if(isset($_FILES["photo"]["name"]))
{
    $ok=move_uploaded_file($_FILES["photo"]["tmp_name"], $myfile);
    if($ok)
    {
    echo "success";
    }

    else
    {
    echo "Failed";
    }
}
?>


问:
How to get image name from Drawable Object?
Somehow I have Drawable image from Drawable folder like as

```<code>Drawable thumb = mContext.getResources().getDrawable(R.drawable.image_name);
</code>```

i try like this

```<code>String image_name =thumb.getCurrent().toString();
</code>```

But my need image name that means image_name from thumb;

How it is possible?

Any suggestion, comment, consults; provide useful links are highly appreciate. Advance Thanks

答:
You can try like this:</p>

```<code>int imageid = getResources().getIdentifier("image_name", "drawable", getPackageName());
String imageName = getResources().getResourceName(imageid);
</code>```

Body:
Somehow I have Drawable image from Drawable folder like as

Drawable thumb = mContext.getResources().getDrawable(R.drawable.image_name);

i try like this

String image_name =thumb.getCurrent().toString();

But my need image name that means image_name from thumb;

How it is possible?

Any suggestion, comment, consults; provide useful links are highly appreciate. Advance Thanks

Body:
You can try like this:

int imageid = getResources().getIdentifier("image_name", "drawable", getPackageName());
String imageName = getResources().getResourceName(imageid);


问:
What is the best way to add data and upload files to Rest api
My iOS application allows a user to submit a complaint to an online REST API with the following parameters:

Data Fields: such as name, phone number, ...

Voice: recorded from microphone

Image/Video: selected from photo gallery

1- how can i do that with swift?

2- how to get back an ID field from the server after submission?

3- how to manage an upload progress for the voice and media files?

Regards

答:
After few weeks working hardly on it, here is my experience using Swift 3.1 which is run smoothly:

```<code>    //use POSTMAN plugin in Chrome browser to get the read header for your API (optional):
    let headers = [
        "cache-control": "no-cache",
        "postman-token": "00000000-1111-2222-3333-444444444"]

    //this is the important part:
    let strQuery: String = "mobileNo=" + txtMobileNB.text! + "&fullname=" + txtName.text!

    let request = try? NSMutableURLRequest(url: NSURL(string: "http://service.website.com/apiname/?" + strQuery)! as URL,
                                          cachePolicy: .useProtocolCachePolicy,
                                          timeoutInterval: 10.0)
    request?.httpMethod = "POST"
    request?.allHTTPHeaderFields = headers

    if request != nil {

        let session = URLSession.shared
        let dataTask = session.dataTask(with: request! as URLRequest) {data,response,error in

            if let content = data
            {
                let responseData = String(data: content, encoding: String.Encoding.utf8)

                //feedback from server:
                print(responseData)

                //call success function:
                self.showDone()
            } else {

                //call error function:
                self.showWrong()
            }

        }
        dataTask.resume()

    } else {
        //call error function:
        self.showWrong()
    }
</code>```

Regarding the other part "how to upload", i've found this framework is a good one (called rebekka) to start your upload project through iOS apps.

hope this helps someone :)

Body:
After few weeks working hardly on it, here is my experience using Swift 3.1 which is run smoothly:

    //use POSTMAN plugin in Chrome browser to get the read header for your API (optional):
    let headers = [
        "cache-control": "no-cache",
        "postman-token": "00000000-1111-2222-3333-444444444"]

    //this is the important part:
    let strQuery: String = "mobileNo=" + txtMobileNB.text! + "&fullname=" + txtName.text!

    let request = try? NSMutableURLRequest(url: NSURL(string: "http://service.website.com/apiname/?" + strQuery)! as URL,
                                          cachePolicy: .useProtocolCachePolicy,
                                          timeoutInterval: 10.0)
    request?.httpMethod = "POST"
    request?.allHTTPHeaderFields = headers

    if request != nil {

        let session = URLSession.shared
        let dataTask = session.dataTask(with: request! as URLRequest) {data,response,error in

            if let content = data
            {
                let responseData = String(data: content, encoding: String.Encoding.utf8)

                //feedback from server:
                print(responseData)

                //call success function:
                self.showDone()
            } else {

                //call error function:
                self.showWrong()
            }

        }
        dataTask.resume()

    } else {
        //call error function:
        self.showWrong()
    }

Regarding the other part "how to upload", i've found this framework is a good one (called rebekka) to start your upload project through iOS apps.

hope this helps someone :)


问:
Not able to successfully upload files using signed URL to google cloud Storage from Advanced REST Client
I am trying to create a signed URL and upload files from my PC to google cloud storage using it.

I am using Advanced REST Client(ARC) as the client side application.  On the server side, I have a jersey based server running on Appengine.

I first send a GET request from ARC, on receiving which the app engine generates a signed URL and returns it back in the response.

After that I do a PUT request with the file I want to upload in the body and the request URL set to what was received in the response to GET.

The code snippet to create signed URL:

```<code>        String encodedUrl = null;
        String contentMD5 = "";
        String contentType = "";
        String httpVerb;

        httpVerb = "PUT";

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 10);
        long expiration = calendar.getTimeInMillis() / 1000L;

        String canonicalizedResource = "/" + bucketName + "/" + objectName;
        String baseURL = "https://storage.googleapis.com" + canonicalizedResource;

        String stringToSign =
                httpVerb + "\n" + contentMD5 + "\n" + contentType + "\n" + expiration + "\n"
                        + canonicalizedResource;

        AppIdentityService service = AppIdentityServiceFactory.getAppIdentityService();
        String googleAccessId = service.getServiceAccountName();

        SigningResult signingResult = service.signForApp(stringToSign.getBytes());
        String encodedSignature = null;
        try {
            encodedSignature =
                    new String(Base64.encodeBase64(signingResult.getSignature(), false), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new InternalServerErrorException();
        }

        String signature = null;
        try {
            signature = URLEncoder.encode(encodedSignature, "UTF-8").toString();
        } catch (UnsupportedEncodingException e) {
            throw new InternalServerErrorException();
        }

        encodedUrl =
                baseURL + "?GoogleAccessId=" + googleAccessId + "&Expires=" + expiration
                        + "&Signature=" + signature;
        System.out.println("Signed URL is: "+encodedUrl);
</code>```

However I observe the following issue:

Whenever I send the PUT request with any file type, I get the following error:

Error - 403

Code - SignatureDoesNotMatch

Message - The request signature we calculated does not match the signature you provided. Check your Google secret key and signing method

Please note that in my code, I am setting the content Type to "" while creating the string to sign. Also while creating the PUT request I don't include any Content-type header.

As far as I understand, if I don't include the contentType in the stringToSign while creating the signed URL and also not add it as a header while sending PUT request it should be fine. So what could be the reason for the error?

After that I changed by code and added the contentType while creating the stringToSign in the code and also gave the corresponding Content-Type header while sending the PUT request.

In this case I am able to upload the file, however the uploaded file is modified/corrupted.I tried with text/plain and image/jpeg.

The problem is that the following text is added at the beginning of the file:

```<code>------WebKitFormBoundaryZX8rPPhnm1WXPrUf
Content-Disposition: form-data; name="fileUpload5"; filename="blob"
Content-Type: text/plain
</code>```

I can see this in the text file and on opening the .jpg file in the hex editor. The .jpg does not open in standard image application since the file has been corrupted by the text in the beginning

Am I missing something here? Is this any issue in the Advanced REST Client?
Actually whenever I send a PUT request with some file in the body, I get a message in the ARC saying that :
The content-type header will be finally changed to multipart/form-data while sending the request
However, I saved exported all the messages to a file from ARC and I didn't find any message with Content-type header set to multipart/form-data.
So why does this message come and is it actually an issue?

答:
URL-signing code is tricky and notoriously hard to debug. Fortunately, Google's google-cloud library has a signUrl function that takes care of this for you. I highly encourage you to use it instead of rewriting it yourself. Here's the documentation.

Now, if you want to debug it yourself, checking the error message is super useful. It will include a complete copy of the string the server checked the signature of. Print out your stringToSign variable and see how it's different. That'll tell you what's wrong.

Now, on to your specific problem: it sounds like you are generating an acceptable signed URL, but then your client is attempting to upload to GCS as if it were doing a multipart, form upload. The text you're looking at is part of an HTTP multipart request, and the "multipart/form-data" warning also points in that direction. See if the app you're using has some sort of "Form" mode/option that you are perhaps accidentally using?

Body:
I am trying to create a signed URL and upload files from my PC to google cloud storage using it.

I am using Advanced REST Client(ARC) as the client side application.  On the server side, I have a jersey based server running on Appengine.

I first send a GET request from ARC, on receiving which the app engine generates a signed URL and returns it back in the response.

After that I do a PUT request with the file I want to upload in the body and the request URL set to what was received in the response to GET.

The code snippet to create signed URL:

        String encodedUrl = null;
        String contentMD5 = "";
        String contentType = "";
        String httpVerb;

        httpVerb = "PUT";

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 10);
        long expiration = calendar.getTimeInMillis() / 1000L;

        String canonicalizedResource = "/" + bucketName + "/" + objectName;
        String baseURL = "https://storage.googleapis.com" + canonicalizedResource;

        String stringToSign =
                httpVerb + "\n" + contentMD5 + "\n" + contentType + "\n" + expiration + "\n"
                        + canonicalizedResource;

        AppIdentityService service = AppIdentityServiceFactory.getAppIdentityService();
        String googleAccessId = service.getServiceAccountName();

        SigningResult signingResult = service.signForApp(stringToSign.getBytes());
        String encodedSignature = null;
        try {
            encodedSignature =
                    new String(Base64.encodeBase64(signingResult.getSignature(), false), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new InternalServerErrorException();
        }

        String signature = null;
        try {
            signature = URLEncoder.encode(encodedSignature, "UTF-8").toString();
        } catch (UnsupportedEncodingException e) {
            throw new InternalServerErrorException();
        }

        encodedUrl =
                baseURL + "?GoogleAccessId=" + googleAccessId + "&Expires=" + expiration
                        + "&Signature=" + signature;
        System.out.println("Signed URL is: "+encodedUrl);

However I observe the following issue:

Whenever I send the PUT request with any file type, I get the following error:

Error - 403

Code - SignatureDoesNotMatch

Message - The request signature we calculated does not match the signature you provided. Check your Google secret key and signing method

Please note that in my code, I am setting the content Type to "" while creating the string to sign. Also while creating the PUT request I don't include any Content-type header.

As far as I understand, if I don't include the contentType in the stringToSign while creating the signed URL and also not add it as a header while sending PUT request it should be fine. So what could be the reason for the error?

After that I changed by code and added the contentType while creating the stringToSign in the code and also gave the corresponding Content-Type header while sending the PUT request.

In this case I am able to upload the file, however the uploaded file is modified/corrupted.I tried with text/plain and image/jpeg.

The problem is that the following text is added at the beginning of the file:

------WebKitFormBoundaryZX8rPPhnm1WXPrUf
Content-Disposition: form-data; name="fileUpload5"; filename="blob"
Content-Type: text/plain

I can see this in the text file and on opening the .jpg file in the hex editor. The .jpg does not open in standard image application since the file has been corrupted by the text in the beginning

Am I missing something here? Is this any issue in the Advanced REST Client?
Actually whenever I send a PUT request with some file in the body, I get a message in the ARC saying that :
The content-type header will be finally changed to multipart/form-data while sending the request
However, I saved exported all the messages to a file from ARC and I didn't find any message with Content-type header set to multipart/form-data.
So why does this message come and is it actually an issue?


问:
What's the proper technical term for "high ascii" characters?
What is the technically correct way of referring to "high ascii" or "extended ascii" characters? I don't just mean the range of 128-255, but any character beyond the 0-127 scope.

Often they're called diacritics, accented letters, sometimes casually referred to as "national" or non-English characters, but these names are either imprecise or they cover only a subset of the possible characters.

What correct, precise term that will programmers immediately recognize? And what would be the best English term to use when speaking to a non-technical audience?

答:
Taken words from an online resource (Cool website though) because I found it useful and appropriate to write and answer.

At first only included capital letters and numbers , but in 1967 was added the lowercase letters and some control characters, forming what is known as US-ASCII, ie the characters 0 through 127.
So with this set of only 128 characters was published in 1967 as standard, containing all you need to write in English language.

In 1981, IBM developed an extension of 8-bit ASCII code, called "code page 437", in this version were replaced some obsolete control characters for graphic characters. Also 128 characters were added , with new symbols, signs, graphics and latin letters, all punctuation signs and characters needed to write texts in other languages, such as Spanish.
In this way was added the ASCII characters ranging from 128 to 255.

IBM includes support for this code page in the hardware of its model 5150, known as "IBM-PC", considered the first personal computer.
The operating system of this model, the "MS-DOS" also used this extended ASCII code.

ContentLicense: CC BY-SA 2.5


问:
PHP - Allowed memory size exhausted (Zend Framework Expressive)
I'm currently struggling because of a new action in my zend expressive project.
Can someone tell me, where to look at?
I tried to comment out all the code in the new action but I always keep getting the following error for the route of this new action.

Can someone help me? I will deliver some more code, if you need.
Thanks a lot!!!

```<code>Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 262144 bytes) in D:\Apache24\htdocs\vendor\zendframework\zend-servicemanager\src\ServiceManager.php on line 200

Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 262144 bytes) in Unknown on line 0

Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 262144 bytes) in Unknown on line 0
</code>```

答:
Low RAM wasn't my problem.

I had made a very big mistake in my ConfigProvider. Instead of declaring the factory like this:

```<code>DashboardAction::class => DashboardActionFactory::class,
</code>```

I mistakenly just wrote:

```<code>DashboardAction::class => DashboardAction::class,
</code>```

This was kind of an endless loop which explains the memory overflow.

Body:
I'm currently struggling because of a new action in my zend expressive project.
Can someone tell me, where to look at?
I tried to comment out all the code in the new action but I always keep getting the following error for the route of this new action.

Can someone help me? I will deliver some more code, if you need.
Thanks a lot!!!

Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 262144 bytes) in D:\Apache24\htdocs\vendor\zendframework\zend-servicemanager\src\ServiceManager.php on line 200

Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 262144 bytes) in Unknown on line 0

Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 262144 bytes) in Unknown on line 0

Body:
Low RAM wasn't my problem.

I had made a very big mistake in my ConfigProvider. Instead of declaring the factory like this:

DashboardAction::class => DashboardActionFactory::class,

I mistakenly just wrote:

DashboardAction::class => DashboardAction::class,

This was kind of an endless loop which explains the memory overflow.


问:
Services stopping automatically from android OS 5.1.1
I am working on an application related to Voip & IM (chatting application). Till android OS 5.0 it is working good and no issues from client also. But from android OS 5.1.1 onwards we are facing issues.

Issues:

If the app is in foreground and if device goes to sleep mode it is working good.

If the app is in background and if device goes to sleep mode after 10 minutes all the services are stopping automatically.

Testing:

For testing I created one timer task to print logs for every 1 minute. So when I close the application (means if the app is in background)

Till android OS 5.0 logs are printing continuously.

From android OS 5.1.1 onwards after going to sleep mode, after 10 minutes logs are not printing. Timer task is stopping

Same problem I am facing for my application also.

After doing some R&D I came to know regarding doze mode and app optimization. Is it anyhow related to stop services automatically running in background.

If yes, can anyone please let me know how to overcome this issue.

答:
This is new thing which google done to prevent unwanted battery usage.
For new versions the background services are restricted for better battery life. The android service consumes almost same as the application running in foreground. So even though app is not running its services may be running and using memory and battery.

If you have to use any kind of background process try to use Job Scheduler which may be something useful for you.

The Job Scheduler groups the task and execute the background task based on the constraints we provide in the implementation.
This have a limitation it support on minimum API 21

To support on lower version you can use Firebase JobDispatcher which support from API 9.

I personally prefer Firebase JobDispatcher

This link help you to understand more about scheduler and its implementation.


问:
Info window overlapped by custom div element as map is not auto panning
I have a custom div which is positioned absolute on google map. Please see the image below.My problem is info window is overlapped by the custom div element as shown in the picture below.

I want that map should pan when i click on the marker and then info window should open.

I am trying to achieve similar result like Google my map. see the picture from google my map below. In google my map when I click on the marker the info window near to the top layer div (The div showing 'Untitled map' text) is not overlapped. Map auto panes when info window opens.

答:
var map;
var chicago = {
  lat: 41.85,
  lng: -87.65
};

/**
 * The CenterControl adds a control to the map that recenters the map on
 * Chicago.
 * This constructor takes the control DIV as an argument.
 * @constructor
 */
function CenterControl(controlDiv, map) {

  // Set CSS for the control border.
  var controlUI = document.createElement('div');
  controlUI.style.backgroundColor = '#fff';
  controlUI.style.border = '2px solid #fff';
  controlUI.style.borderRadius = '3px';
  controlUI.style.boxShadow = '0 2px 6px rgba(0,0,0,.3)';
  controlUI.style.cursor = 'pointer';
  controlUI.style.marginBottom = '22px';
  controlUI.style.textAlign = 'center';
  controlUI.title = 'Click to recenter the map';
  controlDiv.appendChild(controlUI);

  // Set CSS for the control interior.
  var controlText = document.createElement('div');
  controlText.style.color = 'rgb(25,25,25)';
  controlText.style.fontFamily = 'Roboto,Arial,sans-serif';
  controlText.style.fontSize = '16px';
  controlText.style.lineHeight = '38px';
  controlText.style.paddingLeft = '5px';
  controlText.style.paddingRight = '5px';
  controlText.innerHTML = 'Center Map';
  controlUI.appendChild(controlText);

  // Setup the click event listeners: simply set the map to Chicago.
  controlUI.addEventListener('click', function() {
    map.setCenter(chicago);
  });

}

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 12,
    center: chicago
  });

  // Create the DIV to hold the control and call the CenterControl()
  // constructor passing in this DIV.
  var centerControlDiv = document.createElement('div');
  var centerControl = new CenterControl(centerControlDiv, map);

  centerControlDiv.index = 1;
  map.controls[google.maps.ControlPosition.TOP_CENTER].push(centerControlDiv);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */

#map {
  height: 100%;
}

/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}</code>```

```

use internal autocomplete, otherwise it's going to be issue for you, all balloon are part of that canvas, so if something is positioned on map canvas.

To fix this you can make is transparent while not hovering over that div.

Body:
var map;
var chicago = {
  lat: 41.85,
  lng: -87.65
};

/**
 * The CenterControl adds a control to the map that recenters the map on
 * Chicago.
 * This constructor takes the control DIV as an argument.
 * @constructor
 */
function CenterControl(controlDiv, map) {

  // Set CSS for the control border.
  var controlUI = document.createElement('div');
  controlUI.style.backgroundColor = '#fff';
  controlUI.style.border = '2px solid #fff';
  controlUI.style.borderRadius = '3px';
  controlUI.style.boxShadow = '0 2px 6px rgba(0,0,0,.3)';
  controlUI.style.cursor = 'pointer';
  controlUI.style.marginBottom = '22px';
  controlUI.style.textAlign = 'center';
  controlUI.title = 'Click to recenter the map';
  controlDiv.appendChild(controlUI);

  // Set CSS for the control interior.
  var controlText = document.createElement('div');
  controlText.style.color = 'rgb(25,25,25)';
  controlText.style.fontFamily = 'Roboto,Arial,sans-serif';
  controlText.style.fontSize = '16px';
  controlText.style.lineHeight = '38px';
  controlText.style.paddingLeft = '5px';
  controlText.style.paddingRight = '5px';
  controlText.innerHTML = 'Center Map';
  controlUI.appendChild(controlText);

  // Setup the click event listeners: simply set the map to Chicago.
  controlUI.addEventListener('click', function() {
    map.setCenter(chicago);
  });

}

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 12,
    center: chicago
  });

  // Create the DIV to hold the control and call the CenterControl()
  // constructor passing in this DIV.
  var centerControlDiv = document.createElement('div');
  var centerControl = new CenterControl(centerControlDiv, map);

  centerControlDiv.index = 1;
  map.controls[google.maps.ControlPosition.TOP_CENTER].push(centerControlDiv);
}

/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */

#map {
  height: 100%;
}

/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

<div id="map"></div>

<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>

use internal autocomplete, otherwise it's going to be issue for you, all balloon are part of that canvas, so if something is positioned on map canvas.

To fix this you can make is transparent while not hovering over that div.


问:
AnjularJS ng-repeat get item from different scope object
I have two different scope objects. First one is 'Details' object, the second one is 'Country' object. I want to fetch data from my 'Country' object using 'CountryId' which is in the 'Details' object.

I have created a function in my scope and I can fetch my Country data (please see the below code. it is working properly) but I'm sure that it should be a better way in AngularJS.
Is there?

```<code><!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script>
    var app = angular.module("myApp", []);
    app.controller("myCtrl", function($scope) {
        $scope.FindSpecificItem = function(obj, field, value, returnField) {
            return jQuery.grep(obj, function(item) {
                return (item[field] == value);
            })[0][returnField];
        };
        $scope.details = [{
            "Name": "John",
            "CountryId": "1"
        }, {
            "Name": "Dave",
            "CountryId": "2"
        }]
        $scope.Countries = [{
            "Id": "1",
            "Country": "USA"
        }, {
            "Id": "2",
            "Country": "England"
        }]
    });
</script>

<body>

    <div ng-app="myApp" ng-controller="myCtrl">
        <table>
            <tr ng-repeat="d in details">
                <td>{{d.Name}}</td>
                <td>{{FindSpecificItem(Countries,"Id",d.CountryId,"Country")}}</td>
            </tr>
        </table>
    </div>

</body>

</html>
</code>```

答:
Just to pull out the use of JQuery, you could use ECMAScript 6, array.Find as :

One line of code:

```<code>$scope.FindSpecificItem = function(Id) {
   return $scope.Countries.find(x => x.Id === Id).Country;
}
</code>```

Please see the documentation for its limited support across browsers.

DEMO:

var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {

  $scope.FindSpecificItem = function(Id) {
    return $scope.Countries.find(x => x.Id === Id).Country;
  }

  $scope.details = [{
      "Name": "John",
      "CountryId": "1"
    },
    {
      "Name": "Dave",
      "CountryId": "2"
    }
  ]

  $scope.Countries = [{
      "Id": "1",
      "Country": "USA"
    },
    {
      "Id": "2",
      "Country": "England"
    }
  ]
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<body>

  <div ng-app="myApp" ng-controller="myCtrl">
    <table>
      <tr ng-repeat="d in details">
        <td>{{d.Name}}</td>
        <td>{{FindSpecificItem(d.CountryId)}}</td>
      </tr>
    </table>
  </div>

</body>

</html></code>```

Body:
I have two different scope objects. First one is 'Details' object, the second one is 'Country' object. I want to fetch data from my 'Country' object using 'CountryId' which is in the 'Details' object.

I have created a function in my scope and I can fetch my Country data (please see the below code. it is working properly) but I'm sure that it should be a better way in AngularJS.
Is there?

<!DOCTYPE html>

                {{d.Name}}
                {{FindSpecificItem(Countries,"Id",d.CountryId,"Country")}}

Body:
Just to pull out the use of JQuery, you could use ECMAScript 6, array.Find as :

One line of code:

$scope.FindSpecificItem = function(Id) {
   return $scope.Countries.find(x => x.Id === Id).Country;
}

Please see the documentation for its limited support across browsers.

DEMO:

var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {

  $scope.FindSpecificItem = function(Id) {
    return $scope.Countries.find(x => x.Id === Id).Country;
  }

  $scope.details = [{
      "Name": "John",
      "CountryId": "1"
    },
    {
      "Name": "Dave",
      "CountryId": "2"
    }
  ]

  $scope.Countries = [{
      "Id": "1",
      "Country": "USA"
    },
    {
      "Id": "2",
      "Country": "England"
    }
  ]
});

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<body>

  <div ng-app="myApp" ng-controller="myCtrl">
    <table>
      <tr ng-repeat="d in details">
        <td>{{d.Name}}</td>
        <td>{{FindSpecificItem(d.CountryId)}}</td>
      </tr>
    </table>
  </div>

</body>

</html>


答:
```<code>String name = getResources().getResourceEntryName(R.drawable.image_name);
Log.e("name", name);
</code>```

or

```<code>String resName = getResourceNameFromClassByID(R.drawable.class,
R.drawable.image_name);
Log.e("name", resName);

public String getResourceNameFromClassByID(Class<?> aClass, int resourceID)
            throws IllegalArgumentException {
        Field[] drawableFields = aClass.getFields();

        for (Field f : drawableFields) {
            try {

                if (resourceID == f.getInt(null))
                    return f.getName(); // Return the name.
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        throw new IllegalArgumentException();
    }
</code>```

Title: How to get image name from Drawable Object?

Body:
String name = getResources().getResourceEntryName(R.drawable.image_name);
Log.e("name", name);

or

String resName = getResourceNameFromClassByID(R.drawable.class,
R.drawable.image_name);
Log.e("name", resName);

public String getResourceNameFromClassByID(Class<?> aClass, int resourceID)
            throws IllegalArgumentException {
        Field[] drawableFields = aClass.getFields();

        for (Field f : drawableFields) {
            try {

                if (resourceID == f.getInt(null))
                    return f.getName(); // Return the name.
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        throw new IllegalArgumentException();
    }


问:
Remove tiny scroll bar - Ionic 3
You can see that there is a tiny scroll bar as shown below.Can you tell me how to remove that? This is Ionic 3 app. I have tried many ways.But no luck yet.

Please see how bad it is on the device :(

This on the browser:

.sass

```<code> .height-70 {
        height: 70px;
        overflow: hidden;
    }
</code>```

.html

```<code><ion-content padding>
  <ion-grid>
    <ion-row>
      <ion-col class="height-70" col-12>
        <ion-content>
          <button ion-button icon-left full (click)="loginWithLinkedin()" class="background-color-linkedin"><ion-icon name="logo-linkedin" class="margin-top-minus-4"></ion-icon><span>Continue with Linkedin</span></button>
        </ion-content>
      </ion-col>
    </ion-row>
  </ion-grid>
</ion-content>
</code>```

Chrome css(run time): below padding:16px is the problem.But how can I remove it? Because I need padding too.Any workaround?

答: What I have experienced is sometimes you see scrollbar in browser but not on device. I would suggest to you to verify the same in device or try chrome device emulator in dev tools by pressing Ctrl+Shift+M.

Title: Remove tiny scroll bar - Ionic 3

Body:
You can see that there is a tiny scroll bar as shown below.Can you tell me how to remove that? This is Ionic 3 app. I have tried many ways.But no luck yet.

Please see how bad it is on the device :(

This on the browser:

.sass

 .height-70 {
        height: 70px;
        overflow: hidden;
    }

.html

<ion-content padding>
  <ion-grid>
    <ion-row>
      <ion-col class="height-70" col-12>
        <ion-content>
          <button ion-button icon-left full (click)="loginWithLinkedin()" class="background-color-linkedin"><ion-icon name="logo-linkedin" class="margin-top-minus-4"></ion-icon>Continue with Linkedin</button>
        </ion-content>
      </ion-col>
    </ion-row>
  </ion-grid>
</ion-content>

Chrome css(run time): below padding:16px is the problem.But how can I remove it? Because I need padding too.Any workaround?


问:
Searching Two Columns in a Data Frame in R
I have a question about searching for values in R, it is actually a bit similar to a question which was posted yesterday (as given over here: Searching a vector/data table backwards in R) except I think my problem is a bit more complicated (and also the opposite of what I want to do), and since I'm very new to R I'm not too sure how to solve this problem.

I have a data frame similar to one given below, and I wish to find a previous index value to my current one where the Times column is different to my current time and the Midquote column does not have an NA value.

```<code>Index               Times    |    Midquote
                -----------------------------
   1            10:30:45.58  |    5.319
   2            10:30:45.93  |    5.323
   3            10:30:45.104 |    5.325
   4            10:30:45.127 |    5.322
   5            10:30:45.188 |    5.325
   6            10:30:45.188 |    NA
   7            10:30:45.212 |    NA
   8            10:30:45.231 |    5.321
   9            10:30:45.231 |    5.321
</code>```

If we start at the bottom of the data frame  and take this to be the 'current' time, this is found to be at index 9 and which has a Times value of 10:30:45.231 and Midquote value of 5.321, then if I want to find the first index where the time is different to my current time, we see this is found to be index 7, which has a time of 10:30:45.212 (since index 8 has the same time). But we also see that at index 7 the Midquote value is NA so I now have to check the data frame again. Index 6 again has a different time (i.e. 10:30:45.188 ) but it also has an NA value again in the Midquote column, so moving up again to index 5 we see that the Times column has a different time to my current time (i.e. 10:30:45.188 again)  and that the Midquotes  value is 5.325.

Therefore, since at index 5 the time is 10:30:45.188 (which is different to my current time which was 10:30:45.231) and since the Midquote value at index 5 is not NA, I wish to obtain the output '5' since it is the index value which fulfills both criteria.

My question is, is there a good way of doing this? I am sorry if this is an easy question, I am very new to R and I don't know much about working with data frames...

EDIT: I would also like to do it preferably without adding another column to the data frame (as is given in the top answer of the link I mentioned above), if that is possible

答:
Working with dates is tough especially with fractional seconds.
If you could convert the times to doubles it would be easier to work with.
Assuming your 'Times' are in order you could use this

```<code>library(magrittr)
which(df$Times < df[9,1] & !is.na(df$Midquote)) %>% max()
</code>```

The which gives a vector of the 'Index' where 'Times' are less than that in 9 AND the 'Midquote' is not NA. The %>% sends the vector to max() which gives the highest value. This is pretty inelegant, but will get the job done.

Body:
I have a question about searching for values in R, it is actually a bit similar to a question which was posted yesterday (as given over here: Searching a vector/data table backwards in R) except I think my problem is a bit more complicated (and also the opposite of what I want to do), and since I'm very new to R I'm not too sure how to solve this problem.

I have a data frame similar to one given below, and I wish to find a previous index value to my current one where the Times column is different to my current time and the Midquote column does not have an NA value.

Index               Times    |    Midquote
                -----------------------------
   1            10:30:45.58  |    5.319
   2            10:30:45.93  |    5.323
   3            10:30:45.104 |    5.325
   4            10:30:45.127 |    5.322
   5            10:30:45.188 |    5.325
   6            10:30:45.188 |    NA
   7            10:30:45.212 |    NA
   8            10:30:45.231 |    5.321
   9            10:30:45.231 |    5.321

If we start at the bottom of the data frame  and take this to be the 'current' time, this is found to be at index 9 and which has a Times value of 10:30:45.231 and Midquote value of 5.321, then if I want to find the first index where the time is different to my current time, we see this is found to be index 7, which has a time of 10:30:45.212 (since index 8 has the same time). But we also see that at index 7 the Midquote value is NA so I now have to check the data frame again. Index 6 again has a different time (i.e. 10:30:45.188 ) but it also has an NA value again in the Midquote column, so moving up again to index 5 we see that the Times column has a different time to my current time (i.e. 10:30:45.188 again)  and that the Midquotes  value is 5.325.

Therefore, since at index 5 the time is 10:30:45.188 (which is different to my current time which was 10:30:45.231) and since the Midquote value at index 5 is not NA, I wish to obtain the output '5' since it is the index value which fulfills both criteria.

My question is, is there a good way of doing this? I am sorry if this is an easy question, I am very new to R and I don't know much about working with data frames...

EDIT: I would also like to do it preferably without adding another column to the data frame (as is given in the top answer of the link I mentioned above), if that is possible

Body:
Working with dates is tough especially with fractional seconds.
If you could convert the times to doubles it would be easier to work with.
Assuming your 'Times' are in order you could use this

library(magrittr)
which(df$Times < df[9,1] & !is.na(df$Midquote)) %>% max()

The which gives a vector of the 'Index' where 'Times' are less than that in 9 AND the 'Midquote' is not NA. The %>% sends the vector to max() which gives the highest value. This is pretty inelegant, but will get the job done.


问:
database connectivity in c#
I am working on c# windows project.I am using Microsoft Access database with OleDbConnection connection.My database "email.mdb" is in My document directory and my "email_db.udl" is in "D: drive".This is running well on my computer.But whenever i am making an exe installer file for installment on other Pc this is not working.I am placing "mdb" and "udl" file is in same directory as they are on my PC.I am supposing this ('udl' file) is not connected with my database.
How will i resolve this problem for installation on any windows pc.
Thanks</p>

答:
You can put the database files in your project's directory (where sln file is) and access them through their bare filenames (without D:...., only filename).
In case of the installation you have to set the installer to put it in the installation folder (where the exe file is)

This is a good way to carry everything in one folder and be organized.

Probably here you have a problem because the "My Document" directory has a different path in every PC.

Title: database connectivity in c#


问:
How to match value from scala Map

I am new to scala and was working with Maps. I do a get on Map, but I am not sure how to check for the return type and use it.

I have following code which gives following compilation error "Pattern Type is incompatible with expected Type: TestClass.type required Option[TestClass].

```<code>object MapOptionUsage extends App {
 val map : Map[Int, TestClass] = Map[Int, TestClass]()
 var i = 0
 for(i <- 0 to 5){
   map.put(i, createObj(i))
 }
 var a = map.get(5)

 a match {
     case TestClass => {//dosomething
    }
     case None => {//dosomething
    }
   }
   def createObj(i: Int): TestClass = {
     return new TestClass(i)
  }
}
case class TestClass(val id: Int)
</code>```

答:
get() returns Option[], and TestClass takes a constructor parameter, so you have to match for both those things.

```<code>case Some(TestClass(x)) => {//dosomething
</code>```

BTW, good Scala code doesn't use var or return.

Title: How to match value from scala Map

Body:
I am new to scala and was working with Maps. I do a get on Map, but I am not sure how to check for the return type and use it.

I have following code which gives following compilation error "Pattern Type is incompatible with expected Type: TestClass.type required Option[TestClass].

object MapOptionUsage extends App {
 val map : Map[Int, TestClass] = Map[Int, TestClass]()
 var i = 0
 for(i <- 0 to 5){
   map.put(i, createObj(i))
 }
 var a = map.get(5)

 a match {
     case TestClass => {//dosomething
    }
     case None => {//dosomething
    }
   }
   def createObj(i: Int): TestClass = {
     return new TestClass(i)
  }
}
case class TestClass(val id: Int)

Body:
get() returns Option[], and TestClass takes a constructor parameter, so you have to match for both those things.

case Some(TestClass(x)) => {//dosomething

BTW, good Scala code doesn't use var or return.


问:
Which stdio.h was included for the hello.c?
The source code.

```<code>#include<stdio.h>
#include<stdlib.h>
int main(int argc,char **argv)
{

    printf("Hello,Linux.\n");
    exit(0);
}
</code>```

To compile it with gcc.

```<code>gcc -o hello hello.c
</code>```

To run it with hello.

```<code>sudo find / -name 'stdio.h'
/usr/include/stdio.h
/usr/include/x86_64-linux-gnu/bits/stdio.h
/usr/include/c++/4.9/tr1/stdio.h
</code>```

For the statement #include<stdio.h>, Which file ,/usr/include/stdio.h or/usr/include/x86_64-linux-gnu/bits/stdio.h , used ?

The os:

```<code>uname -a
Linux debian 3.16.0-4-amd64 #1 SMP Debian 3.16.39-1+deb8u2 (2017-03-07) x86_64 GNU/Linux

gcc -o -H  hello hello.c
hello: In function `_fini':
(.fini+0x0): multiple definition of `_fini'
/usr/lib/gcc/x86_64-linux-gnu/4.9/../../../x86_64-linux-gnu/crti.o:(.fini+0x0): first defined here
hello: In function `data_start':
(.data+0x0): multiple definition of `__data_start'
/usr/lib/gcc/x86_64-linux-gnu/4.9/../../../x86_64-linux-gnu/crt1.o:(.data+0x0): first defined here
hello: In function `data_start':
(.data+0x8): multiple definition of `__dso_handle'
/usr/lib/gcc/x86_64-linux-gnu/4.9/crtbegin.o:(.data+0x0): first defined here
hello:(.rodata+0x0): multiple definition of `_IO_stdin_used'
/usr/lib/gcc/x86_64-linux-gnu/4.9/../../../x86_64-linux-gnu/crt1.o:(.rodata.cst4+0x0): first defined here
hello: In function `_start':
(.text+0x0): multiple definition of `_start'
/usr/lib/gcc/x86_64-linux-gnu/4.9/../../../x86_64-linux-gnu/crt1.o:(.text+0x0): first defined here
hello: In function `_init':
(.init+0x0): multiple definition of `_init'
/usr/lib/gcc/x86_64-linux-gnu/4.9/../../../x86_64-linux-gnu/crti.o:(.init+0x0): first defined here
/tmp/ccNhnGzH.o: In function `main':
hello.c:(.text+0x0): multiple definition of `main'
hello:(.text+0xf6): first defined here
/usr/lib/gcc/x86_64-linux-gnu/4.9/crtend.o:(.tm_clone_table+0x0): multiple definition of `__TMC_END__'
hello:(.data+0x10): first defined here
/usr/bin/ld: error in hello(.eh_frame); no .eh_frame_hdr table will be created.
collect2: error: ld returned 1 exit status

gcc -H -o hello hello.c
. /usr/include/stdio.h
.. /usr/include/features.h
... /usr/include/x86_64-linux-gnu/sys/cdefs.h
.... /usr/include/x86_64-linux-gnu/bits/wordsize.h
... /usr/include/x86_64-linux-gnu/gnu/stubs.h
.... /usr/include/x86_64-linux-gnu/gnu/stubs-64.h
.. /usr/lib/gcc/x86_64-linux-gnu/4.9/include/stddef.h
.. /usr/include/x86_64-linux-gnu/bits/types.h
... /usr/include/x86_64-linux-gnu/bits/wordsize.h
... /usr/include/x86_64-linux-gnu/bits/typesizes.h
.. /usr/include/libio.h
... /usr/include/_G_config.h
.... /usr/lib/gcc/x86_64-linux-gnu/4.9/include/stddef.h
.... /usr/include/wchar.h
... /usr/lib/gcc/x86_64-linux-gnu/4.9/include/stdarg.h
.. /usr/include/x86_64-linux-gnu/bits/stdio_lim.h
.. /usr/include/x86_64-linux-gnu/bits/sys_errlist.h
. /usr/include/stdlib.h
.. /usr/lib/gcc/x86_64-linux-gnu/4.9/include/stddef.h
.. /usr/include/x86_64-linux-gnu/bits/waitflags.h
.. /usr/include/x86_64-linux-gnu/bits/waitstatus.h
... /usr/include/endian.h
.... /usr/include/x86_64-linux-gnu/bits/endian.h
.... /usr/include/x86_64-linux-gnu/bits/byteswap.h
..... /usr/include/x86_64-linux-gnu/bits/wordsize.h
..... /usr/include/x86_64-linux-gnu/bits/byteswap-16.h
.. /usr/include/x86_64-linux-gnu/sys/types.h
... /usr/include/time.h
... /usr/lib/gcc/x86_64-linux-gnu/4.9/include/stddef.h
... /usr/include/x86_64-linux-gnu/sys/select.h
.... /usr/include/x86_64-linux-gnu/bits/select.h
..... /usr/include/x86_64-linux-gnu/bits/wordsize.h
.... /usr/include/x86_64-linux-gnu/bits/sigset.h
.... /usr/include/time.h
.... /usr/include/x86_64-linux-gnu/bits/time.h
... /usr/include/x86_64-linux-gnu/sys/sysmacros.h
... /usr/include/x86_64-linux-gnu/bits/pthreadtypes.h
.... /usr/include/x86_64-linux-gnu/bits/wordsize.h
.. /usr/include/alloca.h
... /usr/lib/gcc/x86_64-linux-gnu/4.9/include/stddef.h
.. /usr/include/x86_64-linux-gnu/bits/stdlib-float.h
Multiple include guards may be useful for:
/usr/include/wchar.h
/usr/include/x86_64-linux-gnu/bits/byteswap-16.h
/usr/include/x86_64-linux-gnu/bits/byteswap.h
/usr/include/x86_64-linux-gnu/bits/endian.h
/usr/include/x86_64-linux-gnu/bits/select.h
/usr/include/x86_64-linux-gnu/bits/sigset.h
/usr/include/x86_64-linux-gnu/bits/stdio_lim.h
/usr/include/x86_64-linux-gnu/bits/stdlib-float.h
/usr/include/x86_64-linux-gnu/bits/sys_errlist.h
/usr/include/x86_64-linux-gnu/bits/time.h
/usr/include/x86_64-linux-gnu/bits/typesizes.h
/usr/include/x86_64-linux-gnu/bits/waitflags.h
/usr/include/x86_64-linux-gnu/bits/waitstatus.h
/usr/include/x86_64-linux-gnu/gnu/stubs-64.h
/usr/include/x86_64-linux-gnu/gnu/stubs.h
</code>```

答:
You misused the -H option — you supplied it as the output file name for the -o option.  When you use gcc -o -H hello hello.c, that attempts to create an output file ./-H from the binary hello and the result of compiling hello.c. You need: gcc -H -o hello hello.c!

```<code>$ gcc -H -o hello hello.c
. /usr/include/stdio.h
.. /usr/include/sys/cdefs.h
... /usr/include/sys/_symbol_aliasing.h
... /usr/include/sys/_posix_availability.h
.. /usr/include/Availability.h
... /opt/gcc/v7.1.0/lib/gcc/x86_64-apple-darwin16.5.0/7.1.0/include-fixed/AvailabilityInternal.h
.. /usr/include/_types.h
... /usr/include/sys/_types.h
.... /usr/include/machine/_types.h
..... /usr/include/i386/_types.h
.... /usr/include/sys/_pthread/_pthread_types.h
.. /usr/include/sys/_types/_va_list.h
.. /usr/include/sys/_types/_size_t.h
.. /usr/include/sys/_types/_null.h
.. /usr/include/sys/stdio.h
.. /usr/include/sys/_types/_off_t.h
.. /usr/include/sys/_types/_ssize_t.h
.. /usr/include/secure/_stdio.h
... /usr/include/secure/_common.h
. /usr/include/stdlib.h
.. /usr/include/sys/wait.h
... /usr/include/sys/_types/_pid_t.h
... /usr/include/sys/_types/_id_t.h
... /usr/include/sys/signal.h
.... /usr/include/sys/appleapiopts.h
.... /usr/include/machine/signal.h
..... /usr/include/i386/signal.h
.... /usr/include/machine/_mcontext.h
..... /usr/include/i386/_mcontext.h
...... /usr/include/mach/i386/_structs.h
.... /usr/include/sys/_pthread/_pthread_attr_t.h
.... /usr/include/sys/_types/_sigaltstack.h
.... /usr/include/sys/_types/_ucontext.h
.... /usr/include/sys/_types/_sigset_t.h
.... /usr/include/sys/_types/_uid_t.h
... /usr/include/sys/resource.h
.... /opt/gcc/v7.1.0/lib/gcc/x86_64-apple-darwin16.5.0/7.1.0/include/stdint.h
..... /opt/gcc/v7.1.0/lib/gcc/x86_64-apple-darwin16.5.0/7.1.0/include-fixed/stdint.h
...... /usr/include/sys/_types/_int8_t.h
...... /usr/include/sys/_types/_int16_t.h
...... /usr/include/sys/_types/_int32_t.h
...... /usr/include/sys/_types/_int64_t.h
...... /usr/include/_types/_uint8_t.h
...... /usr/include/_types/_uint16_t.h
...... /usr/include/_types/_uint32_t.h
...... /usr/include/_types/_uint64_t.h
...... /usr/include/sys/_types/_intptr_t.h
...... /usr/include/sys/_types/_uintptr_t.h
...... /usr/include/_types/_intmax_t.h
...... /usr/include/_types/_uintmax_t.h
.... /usr/include/sys/_types/_timeval.h
... /usr/include/machine/endian.h
.... /usr/include/i386/endian.h
..... /usr/include/sys/_endian.h
...... /usr/include/libkern/_OSByteOrder.h
....... /usr/include/libkern/i386/_OSByteOrder.h
.. /usr/include/alloca.h
.. /usr/include/sys/_types/_ct_rune_t.h
.. /usr/include/sys/_types/_rune_t.h
.. /usr/include/sys/_types/_wchar_t.h
.. /usr/include/machine/types.h
... /usr/include/i386/types.h
.... /usr/include/sys/_types/_u_int8_t.h
.... /usr/include/sys/_types/_u_int16_t.h
.... /usr/include/sys/_types/_u_int32_t.h
.... /usr/include/sys/_types/_u_int64_t.h
.. /usr/include/sys/_types/_dev_t.h
.. /usr/include/sys/_types/_mode_t.h
Multiple include guards may be useful for:
/usr/include/machine/_mcontext.h
/usr/include/secure/_stdio.h
/usr/include/sys/_posix_availability.h
/usr/include/sys/_symbol_aliasing.h
$
</code>```

This is compiling your code on a Mac running macOS Sierra 10.12.5 using GCC 7.1.0.  The list will be similar in spirit but radically different in detail on a Linux machine.

The number of leading dots tells you about the nested inclusion level.

The output from gcc -H is written on stderr, not stdout.  If you want to capture it, therefore (assuming a POSIX-like shell such as Bash or Korn shell), you'd use:

```<code>$ gcc -H -o hello hello.c 2>header.info
$
</code>```

Body:
The source code.

#include<stdio.h>
#include<stdlib.h>
int main(int argc,char **argv)
{

    printf("Hello,Linux.\n");
    exit(0);
}

To compile it with gcc.

gcc -o hello hello.c

To run it with hello.

sudo find / -name 'stdio.h'
/usr/include/stdio.h
/usr/include/x86_64-linux-gnu/bits/stdio.h
/usr/include/c++/4.9/tr1/stdio.h

For the statement #include<stdio.h>, Which file ,/usr/include/stdio.h or/usr/include/x86_64-linux-gnu/bits/stdio.h , used ?

The os:

uname -a
Linux debian 3.16.0-4-amd64 #1 SMP Debian 3.16.39-1+deb8u2 (2017-03-07) x86_64 GNU/Linux

gcc -o -H  hello hello.c
hello: In function `_fini':
(.fini+0x0): multiple definition of `_fini'
/usr/lib/gcc/x86_64-linux-gnu/4.9/../../../x86_64-linux-gnu/crti.o:(.fini+0x0): first defined here
hello: In function `data_start':
(.data+0x0): multiple definition of `__data_start'
/usr/lib/gcc/x86_64-linux-gnu/4.9/../../../x86_64-linux-gnu/crt1.o:(.data+0x0): first defined here
hello: In function `data_start':
(.data+0x8): multiple definition of `__dso_handle'
/usr/lib/gcc/x86_64-linux-gnu/4.9/crtbegin.o:(.data+0x0): first defined here
hello:(.rodata+0x0): multiple definition of `_IO_stdin_used'
/usr/lib/gcc/x86_64-linux-gnu/4.9/../../../x86_64-linux-gnu/crt1.o:(.rodata.cst4+0x0): first defined here
hello: In function `_start':
(.text+0x0): multiple definition of `_start'
/usr/lib/gcc/x86_64-linux-gnu/4.9/../../../x86_64-linux-gnu/crt1.o:(.text+0x0): first defined here
hello: In function `_init':
(.init+0x0): multiple definition of `_init'
/usr/lib/gcc/x86_64-linux-gnu/4.9/../../../x86_64-linux-gnu/crti.o:(.init+0x0): first defined here
/tmp/ccNhnGzH.o: In function `main':
hello.c:(.text+0x0): multiple definition of `main'
hello:(.text+0xf6): first defined here
/usr/lib/gcc/x86_64-linux-gnu/4.9/crtend.o:(.tm_clone_table+0x0): multiple definition of `__TMC_END__'
hello:(.data+0x10): first defined here
/usr/bin/ld: error in hello(.eh_frame); no .eh_frame_hdr table will be created.
collect2: error: ld returned 1 exit status

gcc -H -o hello hello.c
. /usr/include/stdio.h
.. /usr/include/features.h
... /usr/include/x86_64-linux-gnu/sys/cdefs.h
.... /usr/include/x86_64-linux-gnu/bits/wordsize.h
... /usr/include/x86_64-linux-gnu/gnu/stubs.h
.... /usr/include/x86_64-linux-gnu/gnu/stubs-64.h
.. /usr/lib/gcc/x86_64-linux-gnu/4.9/include/stddef.h
.. /usr/include/x86_64-linux-gnu/bits/types.h
... /usr/include/x86_64-linux-gnu/bits/wordsize.h
... /usr/include/x86_64-linux-gnu/bits/typesizes.h
.. /usr/include/libio.h
... /usr/include/_G_config.h
.... /usr/lib/gcc/x86_64-linux-gnu/4.9/include/stddef.h
.... /usr/include/wchar.h
... /usr/lib/gcc/x86_64-linux-gnu/4.9/include/stdarg.h
.. /usr/include/x86_64-linux-gnu/bits/stdio_lim.h
.. /usr/include/x86_64-linux-gnu/bits/sys_errlist.h
. /usr/include/stdlib.h
.. /usr/lib/gcc/x86_64-linux-gnu/4.9/include/stddef.h
.. /usr/include/x86_64-linux-gnu/bits/waitflags.h
.. /usr/include/x86_64-linux-gnu/bits/waitstatus.h
... /usr/include/endian.h
.... /usr/include/x86_64-linux-gnu/bits/endian.h
.... /usr/include/x86_64-linux-gnu/bits/byteswap.h
..... /usr/include/x86_64-linux-gnu/bits/wordsize.h
..... /usr/include/x86_64-linux-gnu/bits/byteswap-16.h
.. /usr/include/x86_64-linux-gnu/sys/types.h
... /usr/include/time.h
... /usr/lib/gcc/x86_64-linux-gnu/4.9/include/stddef.h
... /usr/include/x86_64-linux-gnu/sys/select.h
.... /usr/include/x86_64-linux-gnu/bits/select.h
..... /usr/include/x86_64-linux-gnu/bits/wordsize.h
.... /usr/include/x86_64-linux-gnu/bits/sigset.h
.... /usr/include/time.h
.... /usr/include/x86_64-linux-gnu/bits/time.h
... /usr/include/x86_64-linux-gnu/sys/sysmacros.h
... /usr/include/x86_64-linux-gnu/bits/pthreadtypes.h
.... /usr/include/x86_64-linux-gnu/bits/wordsize.h
.. /usr/include/alloca.h
... /usr/lib/gcc/x86_64-linux-gnu/4.9/include/stddef.h
.. /usr/include/x86_64-linux-gnu/bits/stdlib-float.h
Multiple include guards may be useful for:
/usr/include/wchar.h
/usr/include/x86_64-linux-gnu/bits/byteswap-16.h
/usr/include/x86_64-linux-gnu/bits/byteswap.h
/usr/include/x86_64-linux-gnu/bits/endian.h
/usr/include/x86_64-linux-gnu/bits/select.h
/usr/include/x86_64-linux-gnu/bits/sigset.h
/usr/include/x86_64-linux-gnu/bits/stdio_lim.h
/usr/include/x86_64-linux-gnu/bits/stdlib-float.h
/usr/include/x86_64-linux-gnu/bits/sys_errlist.h
/usr/include/x86_64-linux-gnu/bits/time.h
/usr/include/x86_64-linux-gnu/bits/typesizes.h
/usr/include/x86_64-linux-gnu/bits/waitflags.h
/usr/include/x86_64-linux-gnu/bits/waitstatus.h
/usr/include/x86_64-linux-gnu/gnu/stubs-64.h
/usr/include/x86_64-linux-gnu/gnu/stubs.h

Body:
You misused the -H option — you supplied it as the output file name for the -o option.  When you use gcc -o -H hello hello.c, that attempts to create an output file ./-H from the binary hello and the result of compiling hello.c. You need: gcc -H -o hello hello.c!

$ gcc -H -o hello hello.c
. /usr/include/stdio.h
.. /usr/include/sys/cdefs.h
... /usr/include/sys/_symbol_aliasing.h
... /usr/include/sys/_posix_availability.h
.. /usr/include/Availability.h
... /opt/gcc/v7.1.0/lib/gcc/x86_64-apple-darwin16.5.0/7.1.0/include-fixed/AvailabilityInternal.h
.. /usr/include/_types.h
... /usr/include/sys/_types.h
.... /usr/include/machine/_types.h
..... /usr/include/i386/_types.h
.... /usr/include/sys/_pthread/_pthread_types.h
.. /usr/include/sys/_types/_va_list.h
.. /usr/include/sys/_types/_size_t.h
.. /usr/include/sys/_types/_null.h
.. /usr/include/sys/stdio.h
.. /usr/include/sys/_types/_off_t.h
.. /usr/include/sys/_types/_ssize_t.h
.. /usr/include/secure/_stdio.h
... /usr/include/secure/_common.h
. /usr/include/stdlib.h
.. /usr/include/sys/wait.h
... /usr/include/sys/_types/_pid_t.h
... /usr/include/sys/_types/_id_t.h
... /usr/include/sys/signal.h
.... /usr/include/sys/appleapiopts.h
.... /usr/include/machine/signal.h
..... /usr/include/i386/signal.h
.... /usr/include/machine/_mcontext.h
..... /usr/include/i386/_mcontext.h
...... /usr/include/mach/i386/_structs.h
.... /usr/include/sys/_pthread/_pthread_attr_t.h
.... /usr/include/sys/_types/_sigaltstack.h
.... /usr/include/sys/_types/_ucontext.h
.... /usr/include/sys/_types/_sigset_t.h
.... /usr/include/sys/_types/_uid_t.h
... /usr/include/sys/resource.h
.... /opt/gcc/v7.1.0/lib/gcc/x86_64-apple-darwin16.5.0/7.1.0/include/stdint.h
..... /opt/gcc/v7.1.0/lib/gcc/x86_64-apple-darwin16.5.0/7.1.0/include-fixed/stdint.h
...... /usr/include/sys/_types/_int8_t.h
...... /usr/include/sys/_types/_int16_t.h
...... /usr/include/sys/_types/_int32_t.h
...... /usr/include/sys/_types/_int64_t.h
...... /usr/include/_types/_uint8_t.h
...... /usr/include/_types/_uint16_t.h
...... /usr/include/_types/_uint32_t.h
...... /usr/include/_types/_uint64_t.h
...... /usr/include/sys/_types/_intptr_t.h
...... /usr/include/sys/_types/_uintptr_t.h
...... /usr/include/_types/_intmax_t.h
...... /usr/include/_types/_uintmax_t.h
.... /usr/include/sys/_types/_timeval.h
... /usr/include/machine/endian.h
.... /usr/include/i386/endian.h
..... /usr/include/sys/_endian.h
...... /usr/include/libkern/_OSByteOrder.h
....... /usr/include/libkern/i386/_OSByteOrder.h
.. /usr/include/alloca.h
.. /usr/include/sys/_types/_ct_rune_t.h
.. /usr/include/sys/_types/_rune_t.h
.. /usr/include/sys/_types/_wchar_t.h
.. /usr/include/machine/types.h
... /usr/include/i386/types.h
.... /usr/include/sys/_types/_u_int8_t.h
.... /usr/include/sys/_types/_u_int16_t.h
.... /usr/include/sys/_types/_u_int32_t.h
.... /usr/include/sys/_types/_u_int64_t.h
.. /usr/include/sys/_types/_dev_t.h
.. /usr/include/sys/_types/_mode_t.h
Multiple include guards may be useful for:
/usr/include/machine/_mcontext.h
/usr/include/secure/_stdio.h
/usr/include/sys/_posix_availability.h
/usr/include/sys/_symbol_aliasing.h
$

This is compiling your code on a Mac running macOS Sierra 10.12.5 using GCC 7.1.0.  The list will be similar in spirit but radically different in detail on a Linux machine.

The number of leading dots tells you about the nested inclusion level.

The output from gcc -H is written on stderr, not stdout.  If you want to capture it, therefore (assuming a POSIX-like shell such as Bash or Korn shell), you'd use:

$ gcc -H -o hello hello.c 2>header.info
$


问:
UIScrollView bug, is there a better alternative?
There is a bug with my UIScrollView populated with xib files that does not accurately resize xibs to fit the view. As such, when scrolling there is a noticeable offset emanating from the right side of each presented xib element and the contexts of the next element bleed into the previous. It formats correctly on the iPhone 6, but no screen larger than it.

Given that there are no constants in my code and the dimensions should be retrieved from the view itself regardless of size (using view.frame.width and view.frame.height), I wonder if there's some larger point I'm missing about UIScrollView or wether or not it simply isn't the best solution to my problem. Is there another class for creating a sort of scrollable horizontal slide-show?

答: You need to add constraints in order to make it work correctly in different screen sizes.


问:
python selenium unable to click on a tag
I'm trying to click on this button shown below named “Segment Metrix 2.0 Consumer Target Profile report“

and I found corresponding HTML as shown below.

I tried to write code as below:

```<code>elem = driver.find_elements_by_xpath("//*[contains(text(), 'Segment Metrix 2.0 Consumer Target Profile report ')]")
print (elem)
</code>```

it gives me:

```<code>[<selenium.webdriver.remote.webelement.WebElement (session="daf65f4e5ed0485027d04eed8db8aca7", element="0.8079987809618281-1")>]
</code>```

But I can't click on it by adding elem[0].click(), it throws me an "element not visible" error. What should I do?

答:
The problem is that the element has to be visible. It means that even if it's in html, it's not enough, it has to been visible from the browser. Try to click on the dropdown first in order to see its elements and only than click on one of the elements. Also, after clicking on the dropdown, don't forget to wait until your element will be seen, either explicitly or implicitly.

Do you sure you need to click on it? If it is just an object with an url, exact the url and use driver.get(url)

Body:
I'm trying to click on this button shown below named “Segment Metrix 2.0 Consumer Target Profile report“

and I found corresponding HTML as shown below.

I tried to write code as below:

elem = driver.find_elements_by_xpath("//*[contains(text(), 'Segment Metrix 2.0 Consumer Target Profile report ')]")
print (elem)

it gives me:

[<selenium.webdriver.remote.webelement.WebElement (session="daf65f4e5ed0485027d04eed8db8aca7", element="0.8079987809618281-1")>]

But I can't click on it by adding elem[0].click(), it throws me an "element not visible" error. What should I do?


答:
There's several issues.

, your map is immutable, you can't put things inside a immutable map.
val map : mutable.Map[Int, TestClass] = mutable.Map[Int, TestClass]()

is case Some(x)=> {//dosomething Since the return is an Option, you need a Some type to match against.

is def createObj(i: Int): TestClass = { needs to be defined on your object, not inside your match statement.

Edit: To address comments.

```<code>case Some(x)=> {//dosomething
    System.out.println(x.id)
}
</code>```

Will match and create a new value, where x is equal to the contents of Some, that is, the TestClass contained inside the map.

Title: How to match value from scala Map

Body:
There's several issues.

, your map is immutable, you can't put things inside a immutable map.
val map : mutable.Map[Int, TestClass] = mutable.Map[Int, TestClass]()

is case Some(x)=> {//dosomething Since the return is an Option, you need a Some type to match against.

is def createObj(i: Int): TestClass = { needs to be defined on your object, not inside your match statement.

Edit: To address comments.

case Some(x)=> {//dosomething
    System.out.println(x.id)
}

Will match and create a new value, where x is equal to the contents of Some, that is, the TestClass contained inside the map.


问:
Preventing cheating for on-line arcade high score board
I'm going to be developing an online arcade for HTML5/Javascript games written in a to-be-released IDE.

The game will use Ajax requests to the server to record scores when people play these games.

I theoretically have complete control over the design of this, including the mechanics of the code that logs the high scores, game code, everything.

I know it's never impossible to hack client side games such as this or spoof high scores, but I want to make it difficult enough so that anyone competent enough wont be bothered enough to do it (wishful thinking).

I've read:

How can you prevent bogus high scores from appearing on a global high score list?

Which is a slightly different question as this is HTML/JS specific.

My initial idea is that the ajax request checks the source of the request is from the correct location, which is a simple and effective block for most hacking attempts.

答: Add a md5 hash of the highscore code and compare it on the server. But do not the md5 exactly of the highscore, not on all chars of the highscore only some of the chars, like second to last char. In this case it will be difficult to see what the md5 consists of, when just tracing the ajax calls. </p>


问:
RecyclerView not updated with notifyDatasetChanged till Scrolled upwards
I am using gridLayoutManager on my recycler view and want to implement pagination on it. My problem is that when i reach the bottom of the view and add data from the service and i use notifyDataSetChanged or notifyItemRangeChanged the recyclerView do not update till i scroll it upwards. And if i set the adapter again and set the position to the previous position the there is a flickering effect, which is not smooth. this is what i tried, but nothing seems to be working

```<code>//adding data to my list
mNewsList.addAll((List<NewDataModel>) response.body());

// i set the adapter again
int currentPosition =
gaggeredGridLayoutManager.findLastVisibleItemPosition();
adapter = new RecyclerViewAdapter(mNewsList, Utilities.getThin(getActivity()), (AppCompatActivity) getActivity(), mHeaderTextView.getText().toString());
recyclerView.setAdapter(adapter);
gaggeredGridLayoutManager.scrollToPosition(currentPosition+1);
</code>```

And

```<code>//adding data to my list
mNewsList.addAll((List<NewDataModel>) response.body());
adapter.notifyDataSetChanged();
</code>```

And

```<code>adapter.notifyItemRangeChanged(0,adapter.getItemCount());
</code>```

答:
To avoid flickering effect you have to use handler, after adapter set

```<code>Handler handler = new Handler();
handler.postDelayed(new Runnable() {
  @Override
  public void run() {

    //do anything

    rv_products.scrollToPosition(lastPos);
  }
}, 100);
</code>```

I have implement pagination using following way

```<code>rv_products.addOnScrollListener(new RecyclerView.OnScrollListener() {

  @Override
  public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
    super.onScrolled(recyclerView, dx, dy);

    visibleItemCount = rv_products.getChildCount();
    if (productListAdapter.getViewType() == 1)
      totalItemCount = mGridLayoutManager.getItemCount();
    else
      totalItemCount = mSingleLayoutManager.getItemCount();

    if (productListAdapter.getViewType() == 1)
      firstVisibleItem = mGridLayoutManager.findFirstVisibleItemPosition();
    else
      firstVisibleItem = mSingleLayoutManager.findFirstVisibleItemPosition();

    if (loading) {
      if (totalItemCount > previousTotal) {
        loading = false;
        previousTotal = totalItemCount;
      }
    }
    if (!loading && (totalItemCount - visibleItemCount)
          <= (firstVisibleItem + visibleThreshold)) {

    if (lstProducts.size() < totalCount)
      getProducts(category_id);

      loading = true;
    }
  }
});

public void getProducts(String id) {

  pDialog.setCancelable(false);
  pDialog.show();
  PreferenceSetting preferenceSetting = PreferenceSetting.getInstance(activity);
  Map<String, String> postParam = new HashMap<String, String>();
  postParam.put("category_id", id);
  postParam.put("customer_id", preferenceSetting.getCustomerId());
  postParam.put("eventName", Constants.EVENT_GET_PRODUCTS);
  postParam.put("page", (pageIndex++) + "");

  CommonUtility.setLog("getProducts", postParam.toString());
  JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
      Constants.Server_URL, new JSONObject(postParam),
          new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
              Log.e(getBaseActivity().getLocalClassName(), response.toString());
              pDialog.dismiss();
              try {
                String message = response.getString(Constants.KEY_MESSAGE);
                if (response.getString(Constants.KEY_STATUS).equals(Constants.VALUE_STATUS_SUCCESS)) {
                  Gson gson = new Gson();
                  ProductsReponse productsReponse = gson.fromJson(response.toString(), ProductsReponse.class);
                  ((MainActivity) activity).setCartListCount(productsReponse.getData().getCartItemCount());
                  lstProducts.addAll(productsReponse.getData().getProductDetail());
                  totalCount = Integer.parseInt(productsReponse.getData().getTotalItem());
                  productListAdapter.notifyDataSetChanged();
                  tv_count.setText("(" + totalCount + " items)");

                } else {
                  // CommonUtility.ShowToast(activity, message, "");
                }
              } catch (JSONException e) {
                e.printStackTrace();

              }

            }
          }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
              pDialog.dismiss();
            }
        }) {

            /**
             * Passing some request headers
             */
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
              HashMap<String, String> headers = new HashMap<String, String>();
              headers.put("Content-Type", "application/json; charset=utf-8");
              return headers;
            }

        };

  // Adding request to request queue
  MyApp.getInstance().addToRequestQueue(jsonObjReq);
}
</code>```

Body:
I am using gridLayoutManager on my recycler view and want to implement pagination on it. My problem is that when i reach the bottom of the view and add data from the service and i use notifyDataSetChanged or notifyItemRangeChanged the recyclerView do not update till i scroll it upwards. And if i set the adapter again and set the position to the previous position the there is a flickering effect, which is not smooth. this is what i tried, but nothing seems to be working

//adding data to my list
mNewsList.addAll((List<NewDataModel>) response.body());

// i set the adapter again
int currentPosition =
gaggeredGridLayoutManager.findLastVisibleItemPosition();
adapter = new RecyclerViewAdapter(mNewsList, Utilities.getThin(getActivity()), (AppCompatActivity) getActivity(), mHeaderTextView.getText().toString());
recyclerView.setAdapter(adapter);
gaggeredGridLayoutManager.scrollToPosition(currentPosition+1);

And

//adding data to my list
mNewsList.addAll((List<NewDataModel>) response.body());
adapter.notifyDataSetChanged();

And

adapter.notifyItemRangeChanged(0,adapter.getItemCount());

Body:
To avoid flickering effect you have to use handler, after adapter set

Handler handler = new Handler();
handler.postDelayed(new Runnable() {
  @Override
  public void run() {

    //do anything

    rv_products.scrollToPosition(lastPos);
  }
}, 100);

I have implement pagination using following way

rv_products.addOnScrollListener(new RecyclerView.OnScrollListener() {

  @Override
  public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
    super.onScrolled(recyclerView, dx, dy);

    visibleItemCount = rv_products.getChildCount();
    if (productListAdapter.getViewType() == 1)
      totalItemCount = mGridLayoutManager.getItemCount();
    else
      totalItemCount = mSingleLayoutManager.getItemCount();

    if (productListAdapter.getViewType() == 1)
      firstVisibleItem = mGridLayoutManager.findFirstVisibleItemPosition();
    else
      firstVisibleItem = mSingleLayoutManager.findFirstVisibleItemPosition();

    if (loading) {
      if (totalItemCount > previousTotal) {
        loading = false;
        previousTotal = totalItemCount;
      }
    }
    if (!loading && (totalItemCount - visibleItemCount)
          <= (firstVisibleItem + visibleThreshold)) {

    if (lstProducts.size() < totalCount)
      getProducts(category_id);

      loading = true;
    }
  }
});

public void getProducts(String id) {

  pDialog.setCancelable(false);
  pDialog.show();
  PreferenceSetting preferenceSetting = PreferenceSetting.getInstance(activity);
  Map<String, String> postParam = new HashMap<String, String>();
  postParam.put("category_id", id);
  postParam.put("customer_id", preferenceSetting.getCustomerId());
  postParam.put("eventName", Constants.EVENT_GET_PRODUCTS);
  postParam.put("page", (pageIndex++) + "");

  CommonUtility.setLog("getProducts", postParam.toString());
  JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
      Constants.Server_URL, new JSONObject(postParam),
          new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
              Log.e(getBaseActivity().getLocalClassName(), response.toString());
              pDialog.dismiss();
              try {
                String message = response.getString(Constants.KEY_MESSAGE);
                if (response.getString(Constants.KEY_STATUS).equals(Constants.VALUE_STATUS_SUCCESS)) {
                  Gson gson = new Gson();
                  ProductsReponse productsReponse = gson.fromJson(response.toString(), ProductsReponse.class);
                  ((MainActivity) activity).setCartListCount(productsReponse.getData().getCartItemCount());
                  lstProducts.addAll(productsReponse.getData().getProductDetail());
                  totalCount = Integer.parseInt(productsReponse.getData().getTotalItem());
                  productListAdapter.notifyDataSetChanged();
                  tv_count.setText("(" + totalCount + " items)");

                } else {
                  // CommonUtility.ShowToast(activity, message, "");
                }
              } catch (JSONException e) {
                e.printStackTrace();

              }

            }
          }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
              pDialog.dismiss();
            }
        }) {

            /**
             * Passing some request headers
             */
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
              HashMap<String, String> headers = new HashMap<String, String>();
              headers.put("Content-Type", "application/json; charset=utf-8");
              return headers;
            }

        };

  // Adding request to request queue
  MyApp.getInstance().addToRequestQueue(jsonObjReq);
}


问:
Sql conditional sum computation on other column value check
i have following sql query.

```<code>SELECT (SELECT ISNULL(SUM(Qty),0)
From Bills
JOIN BillMaster on Bills.BillNumber = BillMaster.BillNumber
where SessionID = '" + DBHandler.SessionID(Date) + "'
and BillMaster.ShiftID = " + SHiftID + "
and Bills.ProductID = products.id ) [qty],
products.price , products.name
FROM products.
</code>```

In "Bills" table there is column "isDeal". I want that sum will execute only when "isDeal" = 0
I attached Bills table screenshot in which it can be seen that there is column "isDeal"
and i am attaching output report where i want that when isDeal = 0 then sum will compute other wise sum shouldn't compute

so how can i compute this ?

答:
Use conditional aggregation on isDeal:

```<code>SELECT
    (SELECT ISNULL(SUM(CASE WHEN isDeal = 0 THEN Qty ELSE 0 END), 0)
     FROM Bills t1
     INNER JOIN BillMaster t2
         ON t1.BillNumber = t2.BillNumber
     WHERE SessionID = '" + DBHandler.SessionID(Date) + "' AND
           t2.ShiftID = " + SHiftID + " AND
           t1.ProductID = products.id
    ) [qty],
    products.price,
    products.name
FROM products
</code>```

Body:
i have following sql query.

SELECT (SELECT ISNULL(SUM(Qty),0)
From Bills
JOIN BillMaster on Bills.BillNumber = BillMaster.BillNumber
where SessionID = '" + DBHandler.SessionID(Date) + "'
and BillMaster.ShiftID = " + SHiftID + "
and Bills.ProductID = products.id ) [qty],
products.price , products.name
FROM products.

In "Bills" table there is column "isDeal". I want that sum will execute only when "isDeal" = 0
I attached Bills table screenshot in which it can be seen that there is column "isDeal"
and i am attaching output report where i want that when isDeal = 0 then sum will compute other wise sum shouldn't compute

so how can i compute this ?

Body:
Use conditional aggregation on isDeal:

SELECT
    (SELECT ISNULL(SUM(CASE WHEN isDeal = 0 THEN Qty ELSE 0 END), 0)
     FROM Bills t1
     INNER JOIN BillMaster t2
         ON t1.BillNumber = t2.BillNumber
     WHERE SessionID = '" + DBHandler.SessionID(Date) + "' AND
           t2.ShiftID = " + SHiftID + " AND
           t1.ProductID = products.id
    ) [qty],
    products.price,
    products.name
FROM products


问:
How to save another new files one by one in different name by using .csv file in C#
I have .csv file that sample of file is like this,

```<code>    Date,Pass,CutMark1,Marks1,CutMark2,Marks2
22/06/2017 13:04:18,FALSE,TRUE,TRUE,FALSE,FALSE
22/06/2017 13:04:20,FALSE,TRUE,TRUE,FALSE,FALSE
22/06/2017 13:04:35,FALSE,TRUE,TRUE,FALSE,FALSE
22/06/2017 13:04:37,FALSE,TRUE,TRUE,FALSE,FALSE
22/06/2017 13:04:37,FALSE,TRUE,TRUE,FALSE,FALSE
22/06/2017 13:04:38,FALSE,FALSE,TRUE,FALSE,FALSE
22/06/2017 13:04:39,FALSE,FALSE,TRUE,FALSE,FALSE
22/06/2017 13:04:40,FALSE,FALSE,TRUE,TRUE,FALSE
22/06/2017 13:04:41,FALSE,FALSE,TRUE,TRUE,TRUE
22/06/2017 13:04:42,FALSE,FALSE,FALSE,TRUE,TRUE
22/06/2017 13:04:44,FALSE,FALSE,FALSE,TRUE,TRUE
22/06/2017 13:04:45,TRUE,FALSE,FALSE,TRUE,TRUE
22/06/2017 13:04:46,TRUE,FALSE,FALSE,TRUE,TRUE
22/06/2017 13:04:48,TRUE,FALSE,FALSE,FALSE,TRUE
22/06/2017 13:04:49,TRUE,FALSE,FALSE,FALSE,TRUE
22/06/2017 13:04:50,TRUE,FALSE,FALSE,FALSE,TRUE
22/06/2017 13:04:52,FALSE,TRUE,TRUE,FALSE,TRUE
22/06/2017 13:04:53,FALSE,TRUE,TRUE,FALSE,TRUE
22/06/2017 13:04:54,FALSE,TRUE,TRUE,FALSE,TRUE
22/06/2017 13:04:56,FALSE,TRUE,TRUE,FALSE,TRUE
22/06/2017 13:04:57,FALSE,TRUE,TRUE,FALSE,TRUE
22/06/2017 13:04:58,FALSE,TRUE,TRUE,FALSE,TRUE
22/06/2017 13:05:00,TRUE,TRUE,TRUE,TRUE,FALSE
22/06/2017 13:05:01,TRUE,TRUE,TRUE,TRUE,FALSE
22/06/2017 13:05:02,TRUE,TRUE,TRUE,TRUE,FALSE
22/06/2017 13:05:04,TRUE,TRUE,TRUE,TRUE,FALSE
22/06/2017 13:05:05,TRUE,TRUE,TRUE,TRUE,FALSE
22/06/2017 13:05:06,TRUE,TRUE,TRUE,TRUE,FALSE
22/06/2017 13:05:08,TRUE,TRUE,TRUE,TRUE,FALSE
</code>```

So now I want to save this file as follows;In here Pass column data flow is like this,FALSE>TRUE>FALSE>TRUE ..this is sample of my .csv file.but there is more raw in original file.In here I want to Separate this original .csv file like following ;

First met False so all of False details And check Marks1=TRUE then save Discharge1_Mark1.csv,and look at Marks2 column and if that column true then save Discharge1_Mark2.csv.

Secondly Pass column meet True then check Marks1=TRUE then save Charge1_Mark1.csv,then if  Marks2=true then save Charge1_Mark2.csv.

NOw again Pass column meet False then want to save file Discharge2_Marks1.csv.
like that I want to save my files.

I want to say in here Accordingly Pass column TRUE,False you want to save file like i mentioned before as which time that TRUE,FALSE meet.1,2,3,...you want to check respective pass column TRUE false with respective Marks1,Marks2 column.
In here I want to save my generated file respective therir columns.

If I save Marks1 then column headers should (Date,Pass,CutMarks1,Marks1 )
If i save Marks2 then column header should (Date,Pass,CutMarks2,Marks2)

Please give how I generate files as I mentioned before in my code.my code is following.

```<code>using System.Globalization;

  public static string dateFormatString = "dd/MM/yyyy HH:mm:ss";

  private void btnSeperateFile_Click(object sender, EventArgs e)
        {
            int discharge_counter = 0;
            int charge_counter = 0;

            if (tbOutputFilePath2 != null)
            {

                List<DrawNew> ObservingData = new List<DrawNew>(); // List to store all available DrawNew objects from the CSV

                // Loops through each lines in the CSV
                foreach (string line in System.IO.File.ReadAllLines(outputFilePath.Text).Skip(1)) // .Skip(1) is for skipping header
                {

                    string[] valuesCsvLine = line.Split(',');
                    DrawNew mngInstance = new DrawNew();

                    mngInstance.Date = DateTime.ParseExact(valuesCsvLine[0], dateFormatString, CultureInfo.InvariantCulture);
                    mngInstance.Pass = (valuesCsvLine[1] == "TRUE" ? true : false);
                    mngInstance.CutMark1 = (valuesCsvLine[2] == "TRUE" ?true: false);
                    mngInstance.Marks1 = (valuesCsvLine[3] == "TRUE" ?true: false);
                    mngInstance.CutMark2 = (valuesCsvLine[4] == "TRUE" ? true : false);
                    mngInstance.Marks2 = (valuesCsvLine[5] == "TRUE" ?true: false);

                    ObserveData.Add(mngInstance);

                    if (mngInstance.Pass==true && mngInstance.Marks1==true)
                    {

                    }
                    if (mngInstance.Pass == false && mngInstance.Marks1 == true)
                    {

                    }
                    if (mngInstance.Pass == true && mngInstance.Marks2 == true)
                    {

                    }
                    if (mngInstance.Pass == false && mngInstance.Marks2 == true )
                    {

                    }
                }
            }
</code>```

This is the class for storing data of .csv file:

```<code>class DrawNew
    {
        public DateTime Date { get; set; } // property to store Date
        public bool Pass { get; set; } // property to store ChargeMode
        public bool CutMark1 { get; set; } // property to store ChargeMode
        public bool Marks1 { get; set; } // property to store ScheduleStep
        public bool CutMark2 { get; set; } // property to store ChargeMode
        public bool Marks2 { get; set; } // property to store ScheduleStep
     }
</code>```

My problem is How I generate these files as I mentioned before.please help to solve my problem.

答:
You will need 4 lists for each type of the output csv file as listed below. Depending on your if condition on each DrawNew object, you add that into its own list.

List<DrawNew> dischargeMark1List

List<DrawNew> dischargeMark2List

List<DrawNew> charge1Mark1List

List<DrawNew>  charge1Mark2List

You create a method GenerateOutputCsv(List<DrawNew> selectedData) to write the data to the correct file name. You just have to do the same checking as you did in btnSeperateFile_Click(..) method.

Body:
I have .csv file that sample of file is like this,

    Date,Pass,CutMark1,Marks1,CutMark2,Marks2
22/06/2017 13:04:18,FALSE,TRUE,TRUE,FALSE,FALSE
22/06/2017 13:04:20,FALSE,TRUE,TRUE,FALSE,FALSE
22/06/2017 13:04:35,FALSE,TRUE,TRUE,FALSE,FALSE
22/06/2017 13:04:37,FALSE,TRUE,TRUE,FALSE,FALSE
22/06/2017 13:04:37,FALSE,TRUE,TRUE,FALSE,FALSE
22/06/2017 13:04:38,FALSE,FALSE,TRUE,FALSE,FALSE
22/06/2017 13:04:39,FALSE,FALSE,TRUE,FALSE,FALSE
22/06/2017 13:04:40,FALSE,FALSE,TRUE,TRUE,FALSE
22/06/2017 13:04:41,FALSE,FALSE,TRUE,TRUE,TRUE
22/06/2017 13:04:42,FALSE,FALSE,FALSE,TRUE,TRUE
22/06/2017 13:04:44,FALSE,FALSE,FALSE,TRUE,TRUE
22/06/2017 13:04:45,TRUE,FALSE,FALSE,TRUE,TRUE
22/06/2017 13:04:46,TRUE,FALSE,FALSE,TRUE,TRUE
22/06/2017 13:04:48,TRUE,FALSE,FALSE,FALSE,TRUE
22/06/2017 13:04:49,TRUE,FALSE,FALSE,FALSE,TRUE
22/06/2017 13:04:50,TRUE,FALSE,FALSE,FALSE,TRUE
22/06/2017 13:04:52,FALSE,TRUE,TRUE,FALSE,TRUE
22/06/2017 13:04:53,FALSE,TRUE,TRUE,FALSE,TRUE
22/06/2017 13:04:54,FALSE,TRUE,TRUE,FALSE,TRUE
22/06/2017 13:04:56,FALSE,TRUE,TRUE,FALSE,TRUE
22/06/2017 13:04:57,FALSE,TRUE,TRUE,FALSE,TRUE
22/06/2017 13:04:58,FALSE,TRUE,TRUE,FALSE,TRUE
22/06/2017 13:05:00,TRUE,TRUE,TRUE,TRUE,FALSE
22/06/2017 13:05:01,TRUE,TRUE,TRUE,TRUE,FALSE
22/06/2017 13:05:02,TRUE,TRUE,TRUE,TRUE,FALSE
22/06/2017 13:05:04,TRUE,TRUE,TRUE,TRUE,FALSE
22/06/2017 13:05:05,TRUE,TRUE,TRUE,TRUE,FALSE
22/06/2017 13:05:06,TRUE,TRUE,TRUE,TRUE,FALSE
22/06/2017 13:05:08,TRUE,TRUE,TRUE,TRUE,FALSE

So now I want to save this file as follows;In here Pass column data flow is like this,FALSE>TRUE>FALSE>TRUE ..this is sample of my .csv file.but there is more raw in original file.In here I want to Separate this original .csv file like following ;

First met False so all of False details And check Marks1=TRUE then save Discharge1_Mark1.csv,and look at Marks2 column and if that column true then save Discharge1_Mark2.csv.

Secondly Pass column meet True then check Marks1=TRUE then save Charge1_Mark1.csv,then if  Marks2=true then save Charge1_Mark2.csv.

NOw again Pass column meet False then want to save file Discharge2_Marks1.csv.
like that I want to save my files.

I want to say in here Accordingly Pass column TRUE,False you want to save file like i mentioned before as which time that TRUE,FALSE meet.1,2,3,...you want to check respective pass column TRUE false with respective Marks1,Marks2 column.
In here I want to save my generated file respective therir columns.

If I save Marks1 then column headers should (Date,Pass,CutMarks1,Marks1 )
If i save Marks2 then column header should (Date,Pass,CutMarks2,Marks2)

Please give how I generate files as I mentioned before in my code.my code is following.

using System.Globalization;

  public static string dateFormatString = "dd/MM/yyyy HH:mm:ss";

  private void btnSeperateFile_Click(object sender, EventArgs e)
        {
            int discharge_counter = 0;
            int charge_counter = 0;

            if (tbOutputFilePath2 != null)
            {

                List<DrawNew> ObservingData = new List<DrawNew>(); // List to store all available DrawNew objects from the CSV

                // Loops through each lines in the CSV
                foreach (string line in System.IO.File.ReadAllLines(outputFilePath.Text).Skip(1)) // .Skip(1) is for skipping header
                {

                    string[] valuesCsvLine = line.Split(',');
                    DrawNew mngInstance = new DrawNew();

                    mngInstance.Date = DateTime.ParseExact(valuesCsvLine[0], dateFormatString, CultureInfo.InvariantCulture);
                    mngInstance.Pass = (valuesCsvLine[1] == "TRUE" ? true : false);
                    mngInstance.CutMark1 = (valuesCsvLine[2] == "TRUE" ?true: false);
                    mngInstance.Marks1 = (valuesCsvLine[3] == "TRUE" ?true: false);
                    mngInstance.CutMark2 = (valuesCsvLine[4] == "TRUE" ? true : false);
                    mngInstance.Marks2 = (valuesCsvLine[5] == "TRUE" ?true: false);

                    ObserveData.Add(mngInstance);

                    if (mngInstance.Pass==true && mngInstance.Marks1==true)
                    {

                    }
                    if (mngInstance.Pass == false && mngInstance.Marks1 == true)
                    {

                    }
                    if (mngInstance.Pass == true && mngInstance.Marks2 == true)
                    {

                    }
                    if (mngInstance.Pass == false && mngInstance.Marks2 == true )
                    {

                    }
                }
            }

This is the class for storing data of .csv file:

class DrawNew
    {
        public DateTime Date { get; set; } // property to store Date
        public bool Pass { get; set; } // property to store ChargeMode
        public bool CutMark1 { get; set; } // property to store ChargeMode
        public bool Marks1 { get; set; } // property to store ScheduleStep
        public bool CutMark2 { get; set; } // property to store ChargeMode
        public bool Marks2 { get; set; } // property to store ScheduleStep
     }

My problem is How I generate these files as I mentioned before.please help to solve my problem.