问:
Navbar bootstrap website
AM trying to make a website using bootstrap and i want it to have a header on top and navbar where by if is scroll my navbar is fixed with the header shown on the first page when i move to other pages i want to see only navbar fixed at top and all my navbar links are on the same page My code is</p>

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Urbanic Home</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="css/style.css">
  </head>
  <body>
    <div class="fad-top-bar"  id="fad-top">
      <div class="container">
      <div class="top">
        <div class="pull-left" id="phone">
          <img src="img/phone.png" alt="phone">
          00000000000
        </div>
        <div class="pull-right" id="email">
          <img src="img/email.png" alt="email">
          @outlook.com
        </div>
        </div>
      </div>
    </div>

    <div class="fad-top-menu">
      <div class="container">
        <nav class="navbar navbar-default" role="navigation">
          <div class="navbar-header">
            <button type="button" class=" collapsed navbar-toggle" data-toggle="collapse" data-target="#myNavbar" aria-expanded="false" aria-controls="myNavbar">
              <span class="sr-only">Toggle Navigation</span>
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
            </button>
            <a href="#" class="navbar-brand"><img src="img/logo.png" alt="Urbanic Fadsoft Investments" title="Urbanic Fadsoft Investments"></a>
          </div>
          <div class="collapse navbar-collapse" id="myNavbar">
            <ul class="nav navbar-nav navbar-right" style="margin-top: 25px;">
              <li class="active"><a href="#fad-top">HOME</a></li>
              <li><a href="#fad-about">ABOUT</a></li>
              <li><a href="#fad-portfolio">PORTFOLIO</a></li>
              <li><a href="#fad-blog">BLOG</a></li>
              <li><a rel="follow" href="http://www.facebook.com/fadsoft Investments"
               class="external-link" target="_parent">EXTERNAL</a></li>
              <li><a href="#fad-contact">CONTACT</a></li>
            </ul>
          </div>
        </nav>
      </div>
    </div>
</code>```

答:
Add .navbar-fixed-top to your nav tag to make it stay fixed at the top.
So change this in your code.

```<code><nav class="navbar navbar-default navbar-fixed-top" role="navigation">
</code>```

Here is the documentation : navbar-fixed-top

Title: Navbar bootstrap website

Body:
AM trying to make a website using bootstrap and i want it to have a header on top and navbar where by if is scroll my navbar is fixed with the header shown on the first page when i move to other pages i want to see only navbar fixed at top and all my navbar links are on the same page My code is

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Urbanic Home</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="css/style.css">

          00000000000

          @outlook.com

            <button type="button" class=" collapsed navbar-toggle" data-toggle="collapse" data-target="#myNavbar" aria-expanded="false" aria-controls="myNavbar">
              Toggle Navigation

            </button>

HOME

ABOUT

PORTFOLIO

BLOG

EXTERNAL

CONTACT

Body:
Add .navbar-fixed-top to your nav tag to make it stay fixed at the top.
So change this in your code.

<nav class="navbar navbar-default navbar-fixed-top" role="navigation">

Here is the documentation : navbar-fixed-top


来源: stackexchange

问:
Java execuetorService running too fast?
By the following code

```<code>    ExecutorService executorService = Executors.newFixedThreadPool(3)
    for (int i=0; i<10; i++){
            executorService.execute(new Runnable() {
                @Override
                void run() {
                    try {
                        Thread.sleep(1*1000)
                        System.out.println("Thread " + Thread.currentThread().getName() + " processing item " + i)
                    } catch (InterruptedException e) {
                        e.printStackTrace()
                    }
                }
            })
    }
</code>```

I am expecting the output as follows:

Thread pool-1-thread-2 processing item 1

Thread pool-1-thread-3 processing item 2

Thread pool-1-thread-2 processing item 3

Thread pool-1-thread-3 processing item 4

Thread pool-1-thread-2 processing item 5

Thread pool-1-thread-2 processing item 7

Thread pool-1-thread-3 processing item 6

Thread pool-1-thread-2 processing item 8

Thread pool-1-thread-3 processing item 9

Thread pool-1-thread-1 processing item 0

But it turns out to be:

Thread pool-1-thread-1 processing item 10

Thread pool-1-thread-1 processing item 10

Thread pool-1-thread-1 processing item 10

Thread pool-1-thread-1 processing item 10

Thread pool-1-thread-1 processing item 10

Thread pool-1-thread-1 processing item 10

Thread pool-1-thread-1 processing item 10

Thread pool-1-thread-1 processing item 10

Thread pool-1-thread-2 processing item 10

Thread pool-1-thread-3 processing item 10

The correct out put is by adding a temp variable before the executorService.exeute method. Here comes the question, what's the cause of the unexpected output?

答:
first off your code won't compile (at least not in Java, probably will do so in Groovy)

'i' cannot be used inside the block because it's not final and it cannot be final because it's used in the for-loop.

What do you mean by "The correct out put is by adding a temp variable before the executorService.exeute method." ?

Also, you shouldn't be expecting that output. You're not guaranteed an order like that, for example I got:

Thread pool-1-thread-1 processing item 0
Thread pool-1-thread-2 processing item 1
Thread pool-1-thread-3 processing item 2
Thread pool-1-thread-3 processing item 5
Thread pool-1-thread-1 processing item 3
Thread pool-1-thread-2 processing item 4
Thread pool-1-thread-1 processing item 7
Thread pool-1-thread-2 processing item 8
Thread pool-1-thread-3 processing item 6
Thread pool-1-thread-1 processing item 9

by using this code:

```<code>    ExecutorService executorService = Executors.newFixedThreadPool(3);
    for (int i = 0; i < 10; i++) {
        final int j = i;
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1 * 1000);
                    System.out.println("Thread "
                            + Thread.currentThread().getName()
                            + " processing item " + j);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Java execuetorService running too fast?

Body:
By the following code

    ExecutorService executorService = Executors.newFixedThreadPool(3)
    for (int i=0; i<10; i++){
            executorService.execute(new Runnable() {
                @Override
                void run() {
                    try {
                        Thread.sleep(1*1000)
                        System.out.println("Thread " + Thread.currentThread().getName() + " processing item " + i)
                    } catch (InterruptedException e) {
                        e.printStackTrace()
                    }
                }
            })
    }

I am expecting the output as follows:

Thread pool-1-thread-2 processing item 1

Thread pool-1-thread-3 processing item 2

Thread pool-1-thread-2 processing item 3

Thread pool-1-thread-3 processing item 4

Thread pool-1-thread-2 processing item 5

Thread pool-1-thread-2 processing item 7

Thread pool-1-thread-3 processing item 6

Thread pool-1-thread-2 processing item 8

Thread pool-1-thread-3 processing item 9

Thread pool-1-thread-1 processing item 0

But it turns out to be:

Thread pool-1-thread-1 processing item 10

Thread pool-1-thread-1 processing item 10

Thread pool-1-thread-1 processing item 10

Thread pool-1-thread-1 processing item 10

Thread pool-1-thread-1 processing item 10

Thread pool-1-thread-1 processing item 10

Thread pool-1-thread-1 processing item 10

Thread pool-1-thread-1 processing item 10

Thread pool-1-thread-2 processing item 10

Thread pool-1-thread-3 processing item 10

The correct out put is by adding a temp variable before the executorService.exeute method. Here comes the question, what's the cause of the unexpected output?

Body:
first off your code won't compile (at least not in Java, probably will do so in Groovy)

'i' cannot be used inside the block because it's not final and it cannot be final because it's used in the for-loop.

What do you mean by "The correct out put is by adding a temp variable before the executorService.exeute method." ?

Also, you shouldn't be expecting that output. You're not guaranteed an order like that, for example I got:

Thread pool-1-thread-1 processing item 0
Thread pool-1-thread-2 processing item 1
Thread pool-1-thread-3 processing item 2
Thread pool-1-thread-3 processing item 5
Thread pool-1-thread-1 processing item 3
Thread pool-1-thread-2 processing item 4
Thread pool-1-thread-1 processing item 7
Thread pool-1-thread-2 processing item 8
Thread pool-1-thread-3 processing item 6
Thread pool-1-thread-1 processing item 9

by using this code:

    ExecutorService executorService = Executors.newFixedThreadPool(3);
    for (int i = 0; i < 10; i++) {
        final int j = i;
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1 * 1000);
                    System.out.println("Thread "
                            + Thread.currentThread().getName()
                            + " processing item " + j);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}


问:
google sign in implementation in codeigniter google return response code with "/" in value which break the code
this is my controller for google login . code does't work after google response code.

```<code>   public function index(){
    // Include the google api php libraries
    require_once APPPATH.'libraries/google-api-php-client/vendor/autoload.php';

    // Google Project API Credentials
    $clientId = 'mentioned';
    $clientSecret = 'mentioned';
    $redirectUrl = base_url() . 'user_authentication/';

    // Google Client Configuration
        $gClient = new Google_Client();
        $gClient->addScope('email');
        $gClient->setApplicationName('REDBUD HOTELS');
        $gClient->setClientId($clientId);
        $gClient->setClientSecret($clientSecret);
        $gClient->setRedirectUri($redirectUrl);
        $google_oauthV2 = new Google_Service($gClient);
//GOOGLE response
        if (isset($_REQUEST['code']))
                  {
                    $gClient->authenticate($_REQUEST['code']);
                    $this->session->set_userdata('token', $gClient->getAccessToken());
                    header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);

                  }
 //check if $token us set
        $token = $this->session->userdata('token');
        if (!empty($token))
            {
            $gClient->setAccessToken($token);
            }

        if ($gClient->getAccessToken())
            {
            $userProfile = $plus->userinfo->get();
            // Preparing data for database insertion
            $userData['oauth_provider'] = 'google';
            $userData['oauth_uid'] = $userProfile['id'];
            $userData['first_name'] = $userProfile['given_name'];
            $userData['last_name'] = $userProfile['family_name'];
            $userData['email'] = $userProfile['email'];
            $userData['gender'] = $userProfile['gender'];
            $userData['locale'] = $userProfile['locale'];
            $userData['profile_url'] = $userProfile['link'];
            $userData['picture_url'] = $userProfile['picture'];
            // Insert or update user data
            $userID = $this->user->checkUser($userData);
            if(!empty($userID))
            {
                $data['userData'] = $userData;
                $this->session->set_userdata('userData',$userData);
            } else
            {
               $data['userData'] = array();
            }
        } else
         {
            $data['authUrl'] = $gClient->createAuthUrl();
         }
        $this->load->view('user_authentication/index',$data);
    }
</code>```

"response Code From Google user_authentication/?code=4/5wcPW5Yv6qNONOzeUz5gun4PtfuPTa6mPN9r97BDhGM# "
please also tell me what should be better  $plus->userinfo->get() or $google_oauthV2->userinfo->get();

答: By just replacing object new Google_Service($gClient); with Google_Service_Oauth2($gClient); solved the Error</p>

Body:
this is my controller for google login . code does't work after google response code.

   public function index(){
    // Include the google api php libraries
    require_once APPPATH.'libraries/google-api-php-client/vendor/autoload.php';

    // Google Project API Credentials
    $clientId = 'mentioned';
    $clientSecret = 'mentioned';
    $redirectUrl = base_url() . 'user_authentication/';

    // Google Client Configuration
        $gClient = new Google_Client();
        $gClient->addScope('email');
        $gClient->setApplicationName('REDBUD HOTELS');
        $gClient->setClientId($clientId);
        $gClient->setClientSecret($clientSecret);
        $gClient->setRedirectUri($redirectUrl);
        $google_oauthV2 = new Google_Service($gClient);
//GOOGLE response
        if (isset($_REQUEST['code']))
                  {
                    $gClient->authenticate($_REQUEST['code']);
                    $this->session->set_userdata('token', $gClient->getAccessToken());
                    header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);

                  }
 //check if $token us set
        $token = $this->session->userdata('token');
        if (!empty($token))
            {
            $gClient->setAccessToken($token);
            }

        if ($gClient->getAccessToken())
            {
            $userProfile = $plus->userinfo->get();
            // Preparing data for database insertion
            $userData['oauth_provider'] = 'google';
            $userData['oauth_uid'] = $userProfile['id'];
            $userData['first_name'] = $userProfile['given_name'];
            $userData['last_name'] = $userProfile['family_name'];
            $userData['email'] = $userProfile['email'];
            $userData['gender'] = $userProfile['gender'];
            $userData['locale'] = $userProfile['locale'];
            $userData['profile_url'] = $userProfile['link'];
            $userData['picture_url'] = $userProfile['picture'];
            // Insert or update user data
            $userID = $this->user->checkUser($userData);
            if(!empty($userID))
            {
                $data['userData'] = $userData;
                $this->session->set_userdata('userData',$userData);
            } else
            {
               $data['userData'] = array();
            }
        } else
         {
            $data['authUrl'] = $gClient->createAuthUrl();
         }
        $this->load->view('user_authentication/index',$data);
    }

"response Code From Google user_authentication/?code=4/5wcPW5Yv6qNONOzeUz5gun4PtfuPTa6mPN9r97BDhGM# "
please also tell me what should be better  $plus->userinfo->get() or $google_oauthV2->userinfo->get();


问:
Null value in column "name" violates not-null constraint when adding new item in django admin
I have added a new model to my admin. This is my models.py:

```<code>class EngineeringToolAttributeType(models.Model):
    name = models.CharField(max_length=50)
    description = models.CharField(max_length=255, blank=True, null=True)
    api_url = models.CharField(max_length=255, blank=True, null=True)
    api_field = models.CharField(max_length=50, blank=True, null=True)
    active = models.BooleanField(default=True)

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

And the admin.py:

```<code>from extras.models import EngineeringToolAttributeType
from django.contrib import admin

class EngineeringToolAttributeTypeAdmin(admin.ModelAdmin):
    fields = ['name', 'description', 'api_url', 'api_field', 'active']
    list_display = ('name', 'description', 'api_url', 'api_field', 'active')

admin.site.register(EngineeringToolAttributeType, EngineeringToolAttributeTypeAdmin)
</code>```

When I try to add (click on add button via the admin), I get this error:

```<code>Internal Server Error: /website/admin/extras/engineeringtoolattributetype/add/

IntegrityError at /admin/extras/engineeringtoolattributetype/add/
null value in column "name" violates not-null constraint
</code>```

This has never happened before. I know name is not allowed to be Null, but I'm still adding a record. How is that possible?

答:
This has a short answer here.

If you specify a field as not null field django will ask you to either provide a default value in code itself or it will ask you to provide a default value when you run migrations.
A better approach would be to provide some sane default in your models.py itself. After that run python manage.py makemigrations and python manage.py migrate. You should be fine.

Body:
I have added a new model to my admin. This is my models.py:

class EngineeringToolAttributeType(models.Model):
    name = models.CharField(max_length=50)
    description = models.CharField(max_length=255, blank=True, null=True)
    api_url = models.CharField(max_length=255, blank=True, null=True)
    api_field = models.CharField(max_length=50, blank=True, null=True)
    active = models.BooleanField(default=True)

    def __str__(self):
        return self.name

And the admin.py:

from extras.models import EngineeringToolAttributeType
from django.contrib import admin

class EngineeringToolAttributeTypeAdmin(admin.ModelAdmin):
    fields = ['name', 'description', 'api_url', 'api_field', 'active']
    list_display = ('name', 'description', 'api_url', 'api_field', 'active')

admin.site.register(EngineeringToolAttributeType, EngineeringToolAttributeTypeAdmin)

When I try to add (click on add button via the admin), I get this error:

Internal Server Error: /website/admin/extras/engineeringtoolattributetype/add/

IntegrityError at /admin/extras/engineeringtoolattributetype/add/
null value in column "name" violates not-null constraint

This has never happened before. I know name is not allowed to be Null, but I'm still adding a record. How is that possible?


问:
jquery - Why do these appended divs ignore their css?
I'm appending some div's with jquery.
And gave them size and color with css.
However they don't seem to pick up on the css?
And how can put some of the divs inside others

Here is my code
http://jsfiddle.net/Eqxzz/

答:
Your CSS for #handler matches only id="handler", not id="handlerXX", you should use a class and a class selector instead, like this:

```<code>'<div id="handler' + (counter) + '" class="handler">' + '</div>'
</code>```

(Note the trailing space on the id is also removed, to be valid)  Also with matching CSS:

```<code>.handler { /* styles */ }
</code>```

The same applies to #drag -> .drag, etc.  You can test it here.

ContentLicense: CC BY-SA 2.5

Body:
Your CSS for #handler matches only id="handler", not id="handlerXX", you should use a class and a class selector instead, like this:

'<div id="handler' + (counter) + '" class="handler">' + '</div>'

(Note the trailing space on the id is also removed, to be valid)  Also with matching CSS:

.handler { /* styles */ }

The same applies to #drag -> .drag, etc.  You can test it here.


问:
Authorization in microservice architecture
currently I develop a backend based on the microservice architecture.
Unfortunately, I have a problem how to realize the authorization.

So let me explaine my system - there are the following services:

OAuth 2.0 Service (issuing JWT)

Group Service

Some Ressource Services (e.g. ToDos Service)

Every user is in one or many groups.
Each resource (like a ToDo list) also belongs to a group.
That means if some user creates a todo list, that list gets stored in the name of the group.

Szenario:

User A is in group A

User B is in group A and B

User C is in group C

User A creats a ToDo list in group A.

User B modifies this ToDo list (he is allowed to do this since he is also in group A)

User C also tries to modify this ToDo list, but he shouldn't allowed to do this since he is only in group C.

Has any body a great idea how I could realize this in a microservice architecture and keep the dependencies between the services on a minimum?

Certainly, I could ask on every request the Group Service if the user is in the group to which the resource belongs to. But so I get a really hard dependency between the Resource Services and the existence of a Group Service - I like to avoid this dependency.
Another option would be to store all groups, to which the user belongs to, in the access token. But with this option the client has to ask every time the OAuth Service for a new token when the user gets a member of a new group.

So is there any other option how I could realize this szenario?

答:
So, you have three domains:

Authentication: responsible for identifying the user

Authorization: responsible for restricting access to resources

Todos: your core domain

You have done well identifying three bounded contexts, one for each domain and implemented in three microservices (MS). You are conforming to the best practices regarding DDD.

No, your question is how could you integrate those three microservices in such a way that the system is resilient, i.e. its microservices continue to work even if some of the other microservices fail.

You have two options regarding integration (communication between microservices):

Synchronous communication: every time the Todos MS receive a request, it queries the Authorization MS to check if the user is permitted to do what it wants. This has the advantage that is simple to implement but it has the disadvantage that is susceptible to cascade failure: if the Authorization MS fails then this MS also fails. So, this option is not good for you.

Asynchronous communication: somehow in the background, there is some data that is replicated from the Authorization MS to the Todos MS. You have at least two options for this replication to be done: a) in cron or scheduled tasks or similar and b) using a event driven architecture. This has the advantage that provides more resilience but it has the disadvantage that is more complex, harder to implement. This option seems to fit your need.

Further reading:

Building microservices


问:
Knockout.js: Bind visibility to validationMessage
I am newbie in Knockout.js . I successfully could bind validaionMessage to
 elements. All those
 elements are placed inside a div and that div has special styling for errors. Now, I'd like to show div only when there are some validationMessage available.
How can I do it?

```<code><div class="error-container" >
     <p data-bind="validationMessage: age"></p>
     <p data-bind="validationMessage: sex"></p>
     <p data-bind="validationMessage: name"></p>
</div>
</code>```

PS: I am using version 1.3.0rc .

答:
```

Try this,

Body:
I am newbie in Knockout.js . I successfully could bind validaionMessage to
 elements. All those
 elements are placed inside a div and that div has special styling for errors. Now, I'd like to show div only when there are some validationMessage available.
How can I do it?

PS: I am using version 1.3.0rc .

Body:
<div class="error-container"  data-bind="if: validationMessage" >
     <p data-bind="validationMessage: age"></p>
     <p data-bind="validationMessage: sex"></p>
     <p data-bind="validationMessage: name"></p>
</div>

Try this,


问:
Django: standard location/conventions for data import scripts?
I'm working on a number of Django projects, and in most of them, I have initial data to import.

This data isn't neat JSON, as shown in the fixture examples in the Django docs - it tends to be messy Excel or CSV files. The scripts tend to look like the following snippet, and I just run them as standalone Python, because I don't know any better:

```<code>import sys
from django.core.management import setup_environ
sys.path.append(LOCATION OF YOUR DJANGO PROJECTS, EX: 'C:\django')
from mysite import settings
setup_environ(settings)

from PROJECT_NAME.APP_NAME.models import MODEL_NAME

import csv
reader = csv.reader(open(COMPLETE PATH TO YOUR DATA, EX: "C:/django/mysite/restaurants.csv"), dialect='excel')

for row in reader:
   COLUMN_ONE_TITLE = row[0]
   COLUMN_TWO_TITLE = row[1]

   MODEL_NAME.objects.get_or_create(MY_FIRST_COLUMN=COLUMN_ONE_TITLE, MY_SECOND_COLUMN=COLUMN_TWO_TITLE)
</code>```

I feel that when I commit these projects to GitHub or send them to the client or whatever, I should include the import scripts. They're an important part of the project.

Is there a standard way, in Django, to store the import scripts  that I've written to import this data?

Where in the project should they sit? Should I be using management commands?

Thanks!

答: What if you put all that code in a utility function? so your views.py would have from utils import csv_import or something like that. That way your views can programmatically use that functionality.

Body:
I'm working on a number of Django projects, and in most of them, I have initial data to import.

This data isn't neat JSON, as shown in the fixture examples in the Django docs - it tends to be messy Excel or CSV files. The scripts tend to look like the following snippet, and I just run them as standalone Python, because I don't know any better:

import sys
from django.core.management import setup_environ
sys.path.append(LOCATION OF YOUR DJANGO PROJECTS, EX: 'C:\django')
from mysite import settings
setup_environ(settings)

from PROJECT_NAME.APP_NAME.models import MODEL_NAME

import csv
reader = csv.reader(open(COMPLETE PATH TO YOUR DATA, EX: "C:/django/mysite/restaurants.csv"), dialect='excel')

for row in reader:
   COLUMN_ONE_TITLE = row[0]
   COLUMN_TWO_TITLE = row[1]

   MODEL_NAME.objects.get_or_create(MY_FIRST_COLUMN=COLUMN_ONE_TITLE, MY_SECOND_COLUMN=COLUMN_TWO_TITLE)

I feel that when I commit these projects to GitHub or send them to the client or whatever, I should include the import scripts. They're an important part of the project.

Is there a standard way, in Django, to store the import scripts  that I've written to import this data?

Where in the project should they sit? Should I be using management commands?

Thanks!


问:
will the Dynamically allocated memory be Automatically released,when the program ends
here is the example:

```<code>int *p=new int;
system("Pause");
return 0;
</code>```

If we don't execute the delete p operation,will the memory be automatically released,when the program runs over.

答: This depends on which operating system you are using. Both Linux and Windows will clean up all resources use by a process when the process terminates.</p>

Body:
here is the example:

int *p=new int;
system("Pause");
return 0;

If we don't execute the delete p operation,will the memory be automatically released,when the program runs over.


问:
MalformedJsonException on Retrofit and Gson
I'm trying to make a retrofit call and i'm getting MalformedJsonException.

This is my call:

```<code>String idFoto = "1ead0a1f-bbc4-46bd-901c-7988c0e6c68b";
Retrofit retrofit = new Retrofit.Builder()
     .baseUrl(Global.URL_BASE)
     .addConverterFactory(GsonConverterFactory.create())
     .build();
FotosAPI service = retrofit.create(FotosAPI.class);
Call<String> obtenerFotoCall = service.getFoto(Global.getToken(), idFoto);
</code>```

This is my interface:

```<code>public interface FotosAPI {
     @GET(Global.URL_FOTO + "{id}")
     Call<String> getFoto(@Header("Authorization") String token, @Path("id") String id);
}
</code>```

The call enqueue enters onFailure method, and the error is "com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 2 path $".

I made the changes to set lenient like this:

```<code>Gson gson = new GsonBuilder().setLenient().create();
Retrofit retrofit = new Retrofit.Builder()
     .baseUrl(Global.URL_BASE)
     .addConverterFactory(GsonConverterFactory.create(gson))
     .build();
</code>```

Then, I have a different error: "com.google.gson.stream.MalformedJsonException: Expected value at line 1 column 1 path $"

I think that the error maybe is in the conversion of Gson of the idFoto string value, but I don't know what is wrong.

Can someone help me please?

Thank you guys!

答:
Please check the JSON that you are getting from server, In my case JSON I was getting from the server was not valid.

Try to check your JSON from Postman or some other tool.

Body:
I'm trying to make a retrofit call and i'm getting MalformedJsonException.

This is my call:

String idFoto = "1ead0a1f-bbc4-46bd-901c-7988c0e6c68b";
Retrofit retrofit = new Retrofit.Builder()
     .baseUrl(Global.URL_BASE)
     .addConverterFactory(GsonConverterFactory.create())
     .build();
FotosAPI service = retrofit.create(FotosAPI.class);
Call<String> obtenerFotoCall = service.getFoto(Global.getToken(), idFoto);

This is my interface:

public interface FotosAPI {
     @GET(Global.URL_FOTO + "{id}")
     Call<String> getFoto(@Header("Authorization") String token, @Path("id") String id);
}

The call enqueue enters onFailure method, and the error is "com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 2 path $".

I made the changes to set lenient like this:

Gson gson = new GsonBuilder().setLenient().create();
Retrofit retrofit = new Retrofit.Builder()
     .baseUrl(Global.URL_BASE)
     .addConverterFactory(GsonConverterFactory.create(gson))
     .build();

Then, I have a different error: "com.google.gson.stream.MalformedJsonException: Expected value at line 1 column 1 path $"

I think that the error maybe is in the conversion of Gson of the idFoto string value, but I don't know what is wrong.

Can someone help me please?

Thank you guys!


问:
Global var vs Shared Instance swift
What is the difference between global variable and shared instance in Swift? what are their respective field of use? Could anyone clarify their concept based upon Swift.</p>

答:
A global variable is a variable that is declared at the top level in a file. So if we had a class called Bar, you could store a reference to an instance of Bar in a global variable like this:

```<code>var bar = Bar()
</code>```

You would then be able to access the instance from anywhere, like this:

```<code>bar
bar.foo()
</code>```

A shared instance, or singleton, looks like this:

```<code>class Bar {
    static var shared = Bar()
    private init() {}
    func foo() {}
}
</code>```

Then you can access the shared instance, still from anywhere in the module, like this:

```<code>Bar.shared
Bar.shared.foo()
</code>```

However, one of the most important differences between the two (apart from the fact that global variables are just generally discouraged) is that the singleton pattern restricts you from creating other instances of Bar. In the first example, you could just create more global variables:

```<code>var bar2 = Bar()
var bar3 = Bar()
</code>```

However, using a singleton (shared instance), the initialiser is private, so trying to do this...

```<code>var baaar = Bar()
</code>```

...results in this:

'Bar' initializer is inaccessible due to 'private' protection level

That's a good thing, because the point of a singleton is that there is a single shared instance. Now the only way you can access an instance of Bar is through Bar.shared. It's important to remember to add the private init() in the class, and not add any other initialisers, though, or that won't any longer be enforced.

If you want more information about this, there's a great article by KrakenDev here.

Title: Global var vs Shared Instance swift

Body:
A global variable is a variable that is declared at the top level in a file. So if we had a class called Bar, you could store a reference to an instance of Bar in a global variable like this:

var bar = Bar()

You would then be able to access the instance from anywhere, like this:

bar
bar.foo()

A shared instance, or singleton, looks like this:

class Bar {
    static var shared = Bar()
    private init() {}
    func foo() {}
}

Then you can access the shared instance, still from anywhere in the module, like this:

Bar.shared
Bar.shared.foo()

However, one of the most important differences between the two (apart from the fact that global variables are just generally discouraged) is that the singleton pattern restricts you from creating other instances of Bar. In the first example, you could just create more global variables:

var bar2 = Bar()
var bar3 = Bar()

However, using a singleton (shared instance), the initialiser is private, so trying to do this...

var baaar = Bar()

...results in this:

'Bar' initializer is inaccessible due to 'private' protection level

That's a good thing, because the point of a singleton is that there is a single shared instance. Now the only way you can access an instance of Bar is through Bar.shared. It's important to remember to add the private init() in the class, and not add any other initialisers, though, or that won't any longer be enforced.

If you want more information about this, there's a great article by KrakenDev here.


问:
Garry's mod lua, moving a vector closer
In garry's mod we have a vector metatable: Vector

This is more a kind of a mathematical question.

I have 2 vectors: The players position (1) and one fixed on the map (2).

I want to draw text on the fixed position but because it will be inside things i can't. So how can i move vector 2 towards the player (1). I can make use of the Angle type: Angle. I can just rescale the text.

Thanks in advance!

答:
I guess what you are talking is about points, rather than vectors in the traditional sense.
Let's call the point where the player is V1, and the fixed point V2, then the vector representing the distance from the fixed point to the player, D, is:

D = V1 - V2

Now, we move V2 to a new position closer to the player by, say some fraction c:

V2 = V2 + c * D

So if you wanted to move the position of the text a tenth of the way closer to the player, you would set c= 1/10.

For example, using your libraries we can just directly modify the fixed point vector (2):

```<code>d = v1
d:Sub(v2)
d:Mul(0.1)
v2:Add(d)
</code>```

The above code will move the fixed point, v2, a tenth of the way closer. If you can check whether the text is obstructed by something or not, you can move it step by step until it is unobstructed.

Title: Garry's mod lua, moving a vector closer

Body:
I guess what you are talking is about points, rather than vectors in the traditional sense.
Let's call the point where the player is V1, and the fixed point V2, then the vector representing the distance from the fixed point to the player, D, is:

D = V1 - V2

Now, we move V2 to a new position closer to the player by, say some fraction c:

V2 = V2 + c * D

So if you wanted to move the position of the text a tenth of the way closer to the player, you would set c= 1/10.

For example, using your libraries we can just directly modify the fixed point vector (2):

d = v1
d:Sub(v2)
d:Mul(0.1)
v2:Add(d)

The above code will move the fixed point, v2, a tenth of the way closer. If you can check whether the text is obstructed by something or not, you can move it step by step until it is unobstructed.


问:
TSQL: How to convert local time to UTC? (SQL Server 2008)
We are dealing with an application that needs to handle global time data from different time zones and daylight savings time settings. The idea is to store everything in UTC format internally and only convert back and forth for the localized user interfaces. Does the SQL Server offer any mechanisms for dealing with the translations given a time, a country and a timezone?

This must be a common problem, so I'm surprised google wouldn't turn up anything usable.

Any pointers?

答:
Here is the code to convert one zone DateTime to another zone DateTime

```<code>DECLARE @UTCDateTime DATETIME = GETUTCDATE();
DECLARE @ConvertedZoneDateTime DATETIME;

-- 'UTC' to 'India Standard Time' DATETIME
SET @ConvertedZoneDateTime = @UTCDateTime AT TIME ZONE 'UTC' AT TIME ZONE 'India Standard Time'
SELECT @UTCDateTime AS UTCDATE,@ConvertedZoneDateTime AS IndiaStandardTime

-- 'India Standard Time' to 'UTC' DATETIME
SET @UTCDateTime = @ConvertedZoneDateTime AT TIME ZONE 'India Standard Time' AT TIME ZONE 'UTC'
SELECT @ConvertedZoneDateTime AS IndiaStandardTime,@UTCDateTime AS UTCDATE
</code>```

Note: AT TIME ZONE works only on SQL Server 2016+ and the advantage is that it automatically considers Daylight when converting to a particular Time zone

Body:
Here is the code to convert one zone DateTime to another zone DateTime

DECLARE @UTCDateTime DATETIME = GETUTCDATE();
DECLARE @ConvertedZoneDateTime DATETIME;

-- 'UTC' to 'India Standard Time' DATETIME
SET @ConvertedZoneDateTime = @UTCDateTime AT TIME ZONE 'UTC' AT TIME ZONE 'India Standard Time'
SELECT @UTCDateTime AS UTCDATE,@ConvertedZoneDateTime AS IndiaStandardTime

-- 'India Standard Time' to 'UTC' DATETIME
SET @UTCDateTime = @ConvertedZoneDateTime AT TIME ZONE 'India Standard Time' AT TIME ZONE 'UTC'
SELECT @ConvertedZoneDateTime AS IndiaStandardTime,@UTCDateTime AS UTCDATE

Note: AT TIME ZONE works only on SQL Server 2016+ and the advantage is that it automatically considers Daylight when converting to a particular Time zone

ContentLicense: CC BY-SA 4.0


问:
Swift 3 comparable protocol
Create a Name structure. A name has two parts a first name (also called a given
name or personal name) and a last name (family or surname). The Name structure should
implement the Comparable protocol.

I was trying with the following code but I don't know how to include the givenName, personalName,familyName and surName in the comparison

```<code>struct Name : Comparable {
let firstName : String
let lastName: String

init(firstName : String, lastName:String) {
    self.firstName = firstName
    self.lastName=lastName
}
}func < (lhs: Name, rhs: Name) -> Bool {
return lhs.firstName < rhs.firstName && lhs.lastName < rhs.lastName
}func == (lhs: Name, rhs: Name) -> Bool {
return lhs.firstName == rhs.firstName && lhs.lastName == rhs.lastName
}

let firstName = Name(firstName: "Paul", lastName: "Smith")
let givenName = Name(firstName: "Paul" , lastName: "Smithe")
let personalName = Name(firstName: "Paul", lastName: "Smith")
print (firstName == givenName)
</code>```

答:
```<code>class ViewController: UIViewController, myprotocol{

    @IBOutlet weak var lbl1: UILabel!
    @IBOutlet weak var text1: UITextField!

    func testfirst(info:String) {

        lbl1.text = info as String
    }

    override func viewDidLoad() {
        super.viewDidLoad()

    }

        @IBAction func btnshow(_ sender: UIButton)
    {

        let storyBoard = UIStoryboard(name: "Main", bundle: nil)

        let svc = storyBoard.instantiateViewController(withIdentifier: "secondViewController") as! secondViewController
        svc.delegate = self

        svc.str = text1.text!

        self.navigationController?.pushViewController(svc, animated: true)

    }
</code>```

2)

```<code>protocol myprotocol {

    func testfirst(info:String)
}
</code>```

3)

```<code>class secondViewController: UIViewController {

    var delegate : myprotocol?

    @IBOutlet weak var lbl2: UILabel!
    @IBOutlet weak var txt2: UITextField!

    var str = String()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        lbl2.text = str
    }

    @IBAction func btn2(_ sender: UIButton)
    {
        if (delegate != nil)
        {
            let information:String = lbl2.text!+txt2.text!

            delegate?.testfirst(info: information)

            self.navigationController?.popViewController(animated: true)
        }
    }
</code>```

Title: Swift 3 comparable protocol

Body:
Create a Name structure. A name has two parts a first name (also called a given
name or personal name) and a last name (family or surname). The Name structure should
implement the Comparable protocol.

I was trying with the following code but I don't know how to include the givenName, personalName,familyName and surName in the comparison

struct Name : Comparable {
let firstName : String
let lastName: String

init(firstName : String, lastName:String) {
    self.firstName = firstName
    self.lastName=lastName
}
}func < (lhs: Name, rhs: Name) -> Bool {
return lhs.firstName < rhs.firstName && lhs.lastName < rhs.lastName
}func == (lhs: Name, rhs: Name) -> Bool {
return lhs.firstName == rhs.firstName && lhs.lastName == rhs.lastName
}

let firstName = Name(firstName: "Paul", lastName: "Smith")
let givenName = Name(firstName: "Paul" , lastName: "Smithe")
let personalName = Name(firstName: "Paul", lastName: "Smith")
print (firstName == givenName)

Body:
class ViewController: UIViewController, myprotocol{

    @IBOutlet weak var lbl1: UILabel!
    @IBOutlet weak var text1: UITextField!

    func testfirst(info:String) {

        lbl1.text = info as String
    }

    override func viewDidLoad() {
        super.viewDidLoad()

    }

        @IBAction func btnshow(_ sender: UIButton)
    {

        let storyBoard = UIStoryboard(name: "Main", bundle: nil)

        let svc = storyBoard.instantiateViewController(withIdentifier: "secondViewController") as! secondViewController
        svc.delegate = self

        svc.str = text1.text!

        self.navigationController?.pushViewController(svc, animated: true)

    }

2)

protocol myprotocol {

    func testfirst(info:String)
}

3)

class secondViewController: UIViewController {

    var delegate : myprotocol?

    @IBOutlet weak var lbl2: UILabel!
    @IBOutlet weak var txt2: UITextField!

    var str = String()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        lbl2.text = str
    }

    @IBAction func btn2(_ sender: UIButton)
    {
        if (delegate != nil)
        {
            let information:String = lbl2.text!+txt2.text!

            delegate?.testfirst(info: information)

            self.navigationController?.popViewController(animated: true)
        }
    }


答:
I assume you are talking about css for #drag?

I see no #drag element in your HTML or being produced with JS.

You do create elements whose ID starts with drag and ends with a number, but #drag1, #drag2, #drag3.. they are all different than #drag.

Same goes for #handler.

Title: jquery - Why do these appended divs ignore their css?

Body:
I'm appending some div's with jquery.
And gave them size and color with css.
However they don't seem to pick up on the css?
And how can put some of the divs inside others

Here is my code
http://jsfiddle.net/Eqxzz/


问:
php image file is not copying in the folder
This is error showing page.i cant find any clues why showing these errors. The image file is not copying the images folder.

Notice: Undefined index: image in C:\xampp\htdocs\Project\Manpower.php on line 36

  Notice: Undefined index: image in C:\xampp\htdocs\Project\Manpower.php on line 38

  Warning: copy(): Filename cannot be empty in C:\xampp\htdocs\Project\Manpower.php on line 38

```<code>        <?php
        include_once'db_connect.php';
        session_start();

        $mysqli = new mysqli("localhost", "root", "", "travelagent");

        if(isset($_POST['status']))
        {

          if (!isset($_SESSION["username"]))

          {

           $message = "please login!!";
           echo "<script type='text/javascript'>alert('$message');</script>";

         }

         else

         {
          $id = mysqli_real_escape_string($mysqli, $_POST['id']);
          $username=$_SESSION["username"];

          $_SESSION['id']=$id;
          $sql = "UPDATE product SET status='1' WHERE id='$id' " ;

          if(mysqli_query($mysqli,$sql)==true)

          {

         $image_path= mysqli_real_escape_string( $mysqli ,'images/'.$_FILES['image']['name']);

         if(copy($_FILES['image']['tmp_name'],$image_path))

         {

            $_SESSION['image']=$image_path;

            $image=$_SESSION['image'];

           $sql="INSERT INTO cart (user_name, product_id,image) VALUES ('$username','$id','$image')";

           $result=$mysqli->query($sql);

           $message = "added to cart!! ";

           echo "<script type='text/javascript'>alert('$message');</script>";

           session_destroy();
             }
         }

       }
     }

     ?>

     <!DOCTYPE html>
     <html lang="en">
     <head>
      <meta charset="utf-8">
      <title>Polyworld Services</title>
      <meta name="Description" content="Polyworld">
      <meta name="viewport" content="width:device-width" initial-scale="1">
      <!-- Latest compiled and minified CSS -->
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

      <!-- Optional theme -->
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

      <!-- Latest compiled and minified JavaScript -->
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

      <script
      src="https://code.jquery.com/jquery-2.2.4.js"
      integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI="
      crossorigin="anonymous"></script>

      <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">

      <link href="css/bootstrap.min.css" rel="stylesheet">

      <!-- Custom CSS -->
      <link href="css/full-slider.css" rel="stylesheet">
      <link rel="stylesheet" type="text/css" href="css/style.css">

    </head>

    <body  data-spy="scroll" data-target="#my-navbar">

      <?php

      include'header.php';

      ?>

      <h1 style="text-align:center;">Welcome to Manpower page</h1>

      <div class="row" id="content">
        <?php

        $result=$mysqli->query("SELECT * FROM product WHERE category_id='1' AND sub_category_id='1' AND status='0'" );

        while($row=$result->fetch_array())

        {
         ?>

         <div class="col-md-3">

          <ul>

            <li>picture : <?php    echo "<img src='admin/".$row['image']. "' height='200' width='200'>";  ?> </li>
            <li>Name: <?php  echo $row['name'];           ?></li>

            <li>Description :<?php    echo $row['description'];        ?></li>
            <li ><a href="#">Details</a></li>
            <form action="" method="post">
              <input type="text" name="id" value="<?php echo $row['id']; ?>">
              <input type="hidden" name="image" value="<?php echo $row['image']; ?>">

              <li><input type="submit" name="status" value="add to cart"></li></br>
            </form>
          </ul>

        </div>

        <?php

      }

      ?>
    </div>

    <?php  include'footer.php'; ?>

    <script type="text/javascript">

    </script>

    </script>

    <script type="text/javascript" src="js/custom.js">

    </script>

    <script src="js/jquery.js"></script>

    <!-- Bootstrap Core JavaScript -->
    <script src="js/bootstrap.min.js"></script>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

    </body>
    </html>
</code>```

答:
Try this code to upload file</p>

```<code>$dir="image/";//name of the folder where the file need to be copied
$file=$dir . basename($_FILES["photo"]["name"]);// where 'photo' is the field name of file input
$filetype=pathinfo($file,PATHINFO_EXTENSION);

if(move_uploaded_file($_FILES["photo"]["tmp_name"], $file)) {
echo "upload success";
}
</code>```

Body:
This is error showing page.i cant find any clues why showing these errors. The image file is not copying the images folder.

Notice: Undefined index: image in C:\xampp\htdocs\Project\Manpower.php on line 36

  Notice: Undefined index: image in C:\xampp\htdocs\Project\Manpower.php on line 38

  Warning: copy(): Filename cannot be empty in C:\xampp\htdocs\Project\Manpower.php on line 38

        <?php
        include_once'db_connect.php';
        session_start();

        $mysqli = new mysqli("localhost", "root", "", "travelagent");

        if(isset($_POST['status']))
        {

          if (!isset($_SESSION["username"]))

          {

           $message = "please login!!";
           echo "";

         }

         else

         {
          $id = mysqli_real_escape_string($mysqli, $_POST['id']);
          $username=$_SESSION["username"];

          $_SESSION['id']=$id;
          $sql = "UPDATE product SET status='1' WHERE id='$id' " ;

          if(mysqli_query($mysqli,$sql)==true)

          {

         $image_path= mysqli_real_escape_string( $mysqli ,'images/'.$_FILES['image']['name']);

         if(copy($_FILES['image']['tmp_name'],$image_path))

         {

            $_SESSION['image']=$image_path;

            $image=$_SESSION['image'];

           $sql="INSERT INTO cart (user_name, product_id,image) VALUES ('$username','$id','$image')";

           $result=$mysqli->query($sql);

           $message = "added to cart!! ";

           echo "";

           session_destroy();
             }
         }

       }
     }

     ?>

     <!DOCTYPE html>

      <meta charset="utf-8">
      <title>Polyworld Services</title>
      <meta name="Description" content="Polyworld">
      <meta name="viewport" content="width:device-width" initial-scale="1">

      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

      <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">

      <link href="css/bootstrap.min.css" rel="stylesheet">

      <link href="css/full-slider.css" rel="stylesheet">
      <link rel="stylesheet" type="text/css" href="css/style.css">

      <?php

      include'header.php';

      ?>

Welcome to Manpower page

        <?php

        $result=$mysqli->query("SELECT * FROM product WHERE category_id='1' AND sub_category_id='1' AND status='0'" );

        while($row=$result->fetch_array())

        {
         ?>

picture : <?php    echo "";  ?>

Name: <?php  echo $row['name'];           ?>

Description :<?php    echo $row['description'];        ?>

Details

            <form action="" method="post">
              <input type="text" name="id" value="<?php echo $row['id']; ?>">
              <input type="hidden" name="image" value="<?php echo $row['image']; ?>">

<input type="submit" name="status" value="add to cart">

            </form>

        <?php

      }

      ?>

    <?php  include'footer.php'; ?>

    </script>

Body:
Try this code to upload file

$dir="image/";//name of the folder where the file need to be copied
$file=$dir . basename($_FILES["photo"]["name"]);// where 'photo' is the field name of file input
$filetype=pathinfo($file,PATHINFO_EXTENSION);

if(move_uploaded_file($_FILES["photo"]["tmp_name"], $file)) {
echo "upload success";
}


问:
is there a way to access a non-global shadowed variable in javascript
I'm currently learning javascript scope and was just wondering whether it is possible to access a non-global shadowed variable in javascript? i.e. in the example below, the variable a that equal to 10 in the aFunc function

```<code>var a = 1;
function aFunc(){
    var a = 10;
    function innerFunc(){
        var a = 100;
        console.log("innerFunc a = " + a);
        console.log("is it possible to access outer function's a variable?");
        console.log("global a = " + window.a);
    }
    innerFunc();
}
aFunc();
</code>```

ps - I understand naming your variables with the same name is very bad practice, but I guess I asked this question out of curiosity

答: No you cannot do this with Javascript at least. There is no way that you can access it since you have intentionally shadowed it (accept it as a feature ;)). Javascript doesn't have a mechanism to access variables in lexical scope (one step up).</p>

Body:
I'm currently learning javascript scope and was just wondering whether it is possible to access a non-global shadowed variable in javascript? i.e. in the example below, the variable a that equal to 10 in the aFunc function

var a = 1;
function aFunc(){
    var a = 10;
    function innerFunc(){
        var a = 100;
        console.log("innerFunc a = " + a);
        console.log("is it possible to access outer function's a variable?");
        console.log("global a = " + window.a);
    }
    innerFunc();
}
aFunc();

ps - I understand naming your variables with the same name is very bad practice, but I guess I asked this question out of curiosity


问:
how to refresh custom listview using baseadapter in android
sir, how can i refresh my custom listview using baseadapter.  i don't know what to place, or where to place it in my code. please help me. thanks in advance

```<code>public class EditDetails extends Activity{
public String nameChanged;
public String numChanged;
public String name;
public String num;
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.editdetails);
    final EditText sqlName = (EditText)findViewById(R.id.editName);
    final EditText sqlNumber = (EditText)findViewById(R.id.editNumber);
    name = CustomListView.name;
    num = CustomListView.number;
    Button bUpdate = (Button)findViewById(R.id.editUpdate);
    Button bView = (Button)findViewById(R.id.editView);
    sqlName.setText(name);
    sqlNumber.setText(num);

    bUpdate.setOnClickListener(new OnClickListener() {

        public void onClick(View arg0) {
            nameChanged = sqlName.getText().toString();
            numChanged = sqlNumber.getText().toString();
            GroupDb info = new GroupDb(EditDetails.this);
            info.open();
            long rowid = info.getRowId(name, num);
            info.updateNameNumber(rowid, nameChanged, numChanged);
            ArrayList<Contact> searchResults = info.getView();
            MyCustomBaseAdapter mcba = new MyCustomBaseAdapter(EditDetails.this, searchResults);
            Toast.makeText(getApplicationContext(), "Update Successful!", Toast.LENGTH_LONG).show();
            info.close();
            }
        });
    bView.setOnClickListener(new OnClickListener() {

        public void onClick(View arg0) {
            Intent intent = new Intent();
            intent.setClass(EditDetails.this, CustomListView.class);

            startActivityForResult(intent, 0);
            }
        });
}

}
</code>```

here is where i displayed my listview

```<code>public class CustomListView extends Activity {
final Context context = this;
public static String name;
public static String number;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    GroupDb info = new GroupDb(this);
    info.open();
    ArrayList<Contact> searchResults = info.getView();

    final ListView lv = (ListView) findViewById(R.id.srListView);
    lv.setAdapter(new MyCustomBaseAdapter(this, searchResults));
    info.close();

    lv.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> a, View v, int position, long id) {
            // TODO Auto-generated method stub
            Object o = lv.getItemAtPosition(position);
            final Contact fullObject = (Contact)o;
            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
            alertDialogBuilder
            .setMessage("Select action")
            .setCancelable(false)
            .setPositiveButton("Edit", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,int id) {
                    Toast.makeText(getApplicationContext(), "Edit ", Toast.LENGTH_LONG).show();
                    name = fullObject.getName();
                    number = fullObject.getPhoneNumber();
                    Intent contactIntent = new Intent("myfolder.proj.EDITDETAILS");
                    startActivity(contactIntent);
                }
              })
</code>```

and here is my baseadapter class

```<code>public class MyCustomBaseAdapter extends BaseAdapter {
private static ArrayList<Contact> searchArrayList;

private LayoutInflater mInflater;

public MyCustomBaseAdapter(Context context, ArrayList<Contact> results) {
    searchArrayList = results;
    mInflater = LayoutInflater.from(context);
}

public int getCount() {
    return searchArrayList.size();
}

public Object getItem(int position) {
    return searchArrayList.get(position);
}

public long getItemId(int position) {
    return position;
}

public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.custom_row_view, null);
        holder = new ViewHolder();
        holder.txtName = (TextView) convertView.findViewById(R.id.name);

        holder.txtPhone = (TextView) convertView.findViewById(R.id.phone);

        holder.status = (TextView) convertView.findViewById(R.id.status);
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    holder.txtName.setText(searchArrayList.get(position).getName());

    holder.txtPhone.setText(searchArrayList.get(position).getPhoneNumber());

    holder.status.setText(searchArrayList.get(position).getStatus());

    return convertView;
}

static class ViewHolder {
    TextView txtName;
    TextView txtPhone;
    TextView status;
}
}
</code>```

答:
Thanks guys with solution above worked for me. I am calling listupdate method in every event

```<code>  public void updateResults(List<TalebeDataUser> results) {
    talebeList = results;
    //Triggers the list update
    notifyDataSetChanged();
}
</code>```

and after updatng list I also refreshing my button action in every touch. For instance I have lots of buttons to click in my listview item so every touch chaging others style

```<code>    private void setColor(TalebeDataUser talebeDataUser) {
    if (talebeDataUser.isVar()) {
        holder.mVar.setBackgroundResource(R.drawable.aw_secili);
        holder.mGorevli.setBackgroundResource(R.drawable.aw_shadow);
        holder.mYok.setBackgroundResource(R.drawable.aw_shadow);
        holder.mIzinli.setBackgroundResource(R.drawable.aw_shadow);
        holder.mHatimde.setBackgroundResource(R.drawable.aw_shadow);
    } else if (talebeDataUser.isGorevli()) {
        holder.mVar.setBackgroundResource(R.drawable.aw_shadow);
        holder.mGorevli.setBackgroundResource(R.drawable.aw_secili);
        holder.mYok.setBackgroundResource(R.drawable.aw_shadow);
        holder.mIzinli.setBackgroundResource(R.drawable.aw_shadow);
        holder.mHatimde.setBackgroundResource(R.drawable.aw_shadow);
    } else if (talebeDataUser.isYok()) {
        holder.mVar.setBackgroundResource(R.drawable.aw_shadow);
        holder.mGorevli.setBackgroundResource(R.drawable.aw_shadow);
        holder.mYok.setBackgroundResource(R.drawable.aw_secili);
        holder.mIzinli.setBackgroundResource(R.drawable.aw_shadow);
        holder.mHatimde.setBackgroundResource(R.drawable.aw_shadow);
    } else if (talebeDataUser.isIzinli()) {
        holder.mVar.setBackgroundResource(R.drawable.aw_shadow);
        holder.mGorevli.setBackgroundResource(R.drawable.aw_shadow);
        holder.mYok.setBackgroundResource(R.drawable.aw_shadow);
        holder.mIzinli.setBackgroundResource(R.drawable.aw_secili);
        holder.mHatimde.setBackgroundResource(R.drawable.aw_shadow);
    } else if (talebeDataUser.isHatimde()) {
        holder.mVar.setBackgroundResource(R.drawable.aw_shadow);
        holder.mGorevli.setBackgroundResource(R.drawable.aw_shadow);
        holder.mYok.setBackgroundResource(R.drawable.aw_shadow);
        holder.mIzinli.setBackgroundResource(R.drawable.aw_shadow);
        holder.mHatimde.setBackgroundResource(R.drawable.aw_secili);
    }

}
</code>```

Just an example inside one of my button

```<code>  holder.mYok.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //talebeList.remove(currentTalebe);
            setOgrenciNameByDurum(talebeList.get(i));
            talebeList.get(i).setYok(true);
            //setOgrenciNameByDurum(currentTalebe);
            talebeList.get(i).setVar(false);
            talebeList.get(i).setGorevli(false);
            talebeList.get(i).setIzinli(false);
            talebeList.get(i).setHatimde(false);
            updateResults(talebeList);
            setColor(talebeList.get(i));
            //saveCurrentTalebeOnShare(currentTalebe);
        }
    });
</code>```

talebeList is just of List<MyModel> talebeList

Body:
sir, how can i refresh my custom listview using baseadapter.  i don't know what to place, or where to place it in my code. please help me. thanks in advance

public class EditDetails extends Activity{
public String nameChanged;
public String numChanged;
public String name;
public String num;
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.editdetails);
    final EditText sqlName = (EditText)findViewById(R.id.editName);
    final EditText sqlNumber = (EditText)findViewById(R.id.editNumber);
    name = CustomListView.name;
    num = CustomListView.number;
    Button bUpdate = (Button)findViewById(R.id.editUpdate);
    Button bView = (Button)findViewById(R.id.editView);
    sqlName.setText(name);
    sqlNumber.setText(num);

    bUpdate.setOnClickListener(new OnClickListener() {

        public void onClick(View arg0) {
            nameChanged = sqlName.getText().toString();
            numChanged = sqlNumber.getText().toString();
            GroupDb info = new GroupDb(EditDetails.this);
            info.open();
            long rowid = info.getRowId(name, num);
            info.updateNameNumber(rowid, nameChanged, numChanged);
            ArrayList<Contact> searchResults = info.getView();
            MyCustomBaseAdapter mcba = new MyCustomBaseAdapter(EditDetails.this, searchResults);
            Toast.makeText(getApplicationContext(), "Update Successful!", Toast.LENGTH_LONG).show();
            info.close();
            }
        });
    bView.setOnClickListener(new OnClickListener() {

        public void onClick(View arg0) {
            Intent intent = new Intent();
            intent.setClass(EditDetails.this, CustomListView.class);

            startActivityForResult(intent, 0);
            }
        });
}

}

here is where i displayed my listview

public class CustomListView extends Activity {
final Context context = this;
public static String name;
public static String number;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    GroupDb info = new GroupDb(this);
    info.open();
    ArrayList<Contact> searchResults = info.getView();

    final ListView lv = (ListView) findViewById(R.id.srListView);
    lv.setAdapter(new MyCustomBaseAdapter(this, searchResults));
    info.close();

    lv.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> a, View v, int position, long id) {
            // TODO Auto-generated method stub
            Object o = lv.getItemAtPosition(position);
            final Contact fullObject = (Contact)o;
            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
            alertDialogBuilder
            .setMessage("Select action")
            .setCancelable(false)
            .setPositiveButton("Edit", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,int id) {
                    Toast.makeText(getApplicationContext(), "Edit ", Toast.LENGTH_LONG).show();
                    name = fullObject.getName();
                    number = fullObject.getPhoneNumber();
                    Intent contactIntent = new Intent("myfolder.proj.EDITDETAILS");
                    startActivity(contactIntent);
                }
              })

and here is my baseadapter class

public class MyCustomBaseAdapter extends BaseAdapter {
private static ArrayList<Contact> searchArrayList;

private LayoutInflater mInflater;

public MyCustomBaseAdapter(Context context, ArrayList<Contact> results) {
    searchArrayList = results;
    mInflater = LayoutInflater.from(context);
}

public int getCount() {
    return searchArrayList.size();
}

public Object getItem(int position) {
    return searchArrayList.get(position);
}

public long getItemId(int position) {
    return position;
}

public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.custom_row_view, null);
        holder = new ViewHolder();
        holder.txtName = (TextView) convertView.findViewById(R.id.name);

        holder.txtPhone = (TextView) convertView.findViewById(R.id.phone);

        holder.status = (TextView) convertView.findViewById(R.id.status);
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    holder.txtName.setText(searchArrayList.get(position).getName());

    holder.txtPhone.setText(searchArrayList.get(position).getPhoneNumber());

    holder.status.setText(searchArrayList.get(position).getStatus());

    return convertView;
}

static class ViewHolder {
    TextView txtName;
    TextView txtPhone;
    TextView status;
}
}

Body:
Thanks guys with solution above worked for me. I am calling listupdate method in every event

  public void updateResults(List<TalebeDataUser> results) {
    talebeList = results;
    //Triggers the list update
    notifyDataSetChanged();
}

and after updatng list I also refreshing my button action in every touch. For instance I have lots of buttons to click in my listview item so every touch chaging others style

    private void setColor(TalebeDataUser talebeDataUser) {
    if (talebeDataUser.isVar()) {
        holder.mVar.setBackgroundResource(R.drawable.aw_secili);
        holder.mGorevli.setBackgroundResource(R.drawable.aw_shadow);
        holder.mYok.setBackgroundResource(R.drawable.aw_shadow);
        holder.mIzinli.setBackgroundResource(R.drawable.aw_shadow);
        holder.mHatimde.setBackgroundResource(R.drawable.aw_shadow);
    } else if (talebeDataUser.isGorevli()) {
        holder.mVar.setBackgroundResource(R.drawable.aw_shadow);
        holder.mGorevli.setBackgroundResource(R.drawable.aw_secili);
        holder.mYok.setBackgroundResource(R.drawable.aw_shadow);
        holder.mIzinli.setBackgroundResource(R.drawable.aw_shadow);
        holder.mHatimde.setBackgroundResource(R.drawable.aw_shadow);
    } else if (talebeDataUser.isYok()) {
        holder.mVar.setBackgroundResource(R.drawable.aw_shadow);
        holder.mGorevli.setBackgroundResource(R.drawable.aw_shadow);
        holder.mYok.setBackgroundResource(R.drawable.aw_secili);
        holder.mIzinli.setBackgroundResource(R.drawable.aw_shadow);
        holder.mHatimde.setBackgroundResource(R.drawable.aw_shadow);
    } else if (talebeDataUser.isIzinli()) {
        holder.mVar.setBackgroundResource(R.drawable.aw_shadow);
        holder.mGorevli.setBackgroundResource(R.drawable.aw_shadow);
        holder.mYok.setBackgroundResource(R.drawable.aw_shadow);
        holder.mIzinli.setBackgroundResource(R.drawable.aw_secili);
        holder.mHatimde.setBackgroundResource(R.drawable.aw_shadow);
    } else if (talebeDataUser.isHatimde()) {
        holder.mVar.setBackgroundResource(R.drawable.aw_shadow);
        holder.mGorevli.setBackgroundResource(R.drawable.aw_shadow);
        holder.mYok.setBackgroundResource(R.drawable.aw_shadow);
        holder.mIzinli.setBackgroundResource(R.drawable.aw_shadow);
        holder.mHatimde.setBackgroundResource(R.drawable.aw_secili);
    }

}

Just an example inside one of my button

  holder.mYok.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //talebeList.remove(currentTalebe);
            setOgrenciNameByDurum(talebeList.get(i));
            talebeList.get(i).setYok(true);
            //setOgrenciNameByDurum(currentTalebe);
            talebeList.get(i).setVar(false);
            talebeList.get(i).setGorevli(false);
            talebeList.get(i).setIzinli(false);
            talebeList.get(i).setHatimde(false);
            updateResults(talebeList);
            setColor(talebeList.get(i));
            //saveCurrentTalebeOnShare(currentTalebe);
        }
    });

talebeList is just of List<MyModel> talebeList


问:
Echo arrays with regular text
How would I write this so I'm only using one echo? </p>

```<code>echo "<div class='post'>";
echo $row['title'];
echo "</div>";
</code>```

<p>I'm using an array to echo out a table's values but it would be a lot easier on the eyes if I could combine these into one echo statement. However, when I try to the page goes blank. </p>

答:
you forgot to close the div</p>

```<code>> echo "<div class='post'"; should be
> echo "<div class='post'>";
</code>```

Title: Echo arrays with regular text

Body:
How would I write this so I'm only using one echo?

echo "
";
echo $row['title'];
echo "
";

I'm using an array to echo out a table's values but it would be a lot easier on the eyes if I could combine these into one echo statement. However, when I try to the page goes blank.

Body:
you forgot to close the div

> echo "<div class='post'"; should be
> echo "<div class='post'>";


问:
XSLT: Other way of creating a duplicate
I got the following XML as input:

```<code><?xml version="1.0" encoding="ISO-8859-1" ?>

<Telefonliste>
    <Eintrag PNr="p1" >
        <Name>Meier</Name>
        <TelNr Vorwahl="0271">891234</TelNr>
    </Eintrag>
    <Eintrag PNr="p2" >
        <Name>Schmitz</Name>
        <TelNr Vorwahl="0228">870887</TelNr>
    </Eintrag>
</Telefonliste>
</code>```

And the following xsl script for transformation:

```<code><?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform version="1.0" encoding="UTF-8" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" />

<xsl:template match="/ | * | @*">
    <xsl:copy>
        <xsl:apply-templates />
    </xsl:copy>
</xsl:template>

<xsl:template match=" text() | @* ">
    <xsl:value-of select="." />
</xsl:template>

</xsl:transform>
</code>```

If I use my script, it produces the following output:

```<code><?xml version="1.0"?>
<Telefonliste>
    <Eintrag>
        <Name>Meier</Name>
        <TelNr>891234</TelNr>
    </Eintrag>
    <Eintrag>
        <Name>Schmitz</Name>
        <TelNr>870887</TelNr>
    </Eintrag>
</Telefonliste>
</code>```

This is quite near on what I want, but there are the attributes missing...Why are the attributes missing and how can I add them? I don't want to use THE identity transformation https://en.wikipedia.org/wiki/Identity_transform#Using_XSLT. Second question is, how copies the identity transformation attributes? The xsl:copy command does not copy attribute nodes as far as I know.

答:
Why are the attributes missing and how can I add them?

The attributes are missing because you neither copy them nor create new ones instead. That should also answer the second part; either one of these:

```<code><xsl:template match="@*">
    <xsl:copy/>
</xsl:template>
</code>```

or:

```<code><xsl:template match="@*">
    <xsl:attribute name="{name()}">
        <xsl:value-of select="." />
    </xsl:attribute>
</xsl:template>
</code>```

will re-create the attributes.

However, in order for this to work, you must first apply templates to the attributes. Your current stylesheet does not do that - the instruction:

```<code><xsl:apply-templates />
</code>```

applies templates to child nodes, not to attributes.

The xsl:copy command does not copy attribute nodes as far as I know...

That is incorrect. As explained above, the problem lies elsewhere.

I dont want to use THE identity transformation

I would question the wisdom of such decision. Your approach is unnecessarily convoluted. Note also that your two templates conflict since both will match an attribute.

Title: XSLT: Other way of creating a duplicate

Body:
I got the following XML as input:

<?xml version="1.0" encoding="ISO-8859-1" ?>

<Telefonliste>
    <Eintrag PNr="p1" >
        <Name>Meier</Name>
        <TelNr Vorwahl="0271">891234</TelNr>
    </Eintrag>
    <Eintrag PNr="p2" >
        <Name>Schmitz</Name>
        <TelNr Vorwahl="0228">870887</TelNr>
    </Eintrag>
</Telefonliste>

And the following xsl script for transformation:

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform version="1.0" encoding="UTF-8" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" />

<xsl:template match="/ | * | @*">
    <xsl:copy>
        <xsl:apply-templates />
    </xsl:copy>
</xsl:template>

<xsl:template match=" text() | @* ">
    <xsl:value-of select="." />
</xsl:template>

</xsl:transform>

If I use my script, it produces the following output:

<?xml version="1.0"?>
<Telefonliste>
    <Eintrag>
        <Name>Meier</Name>
        <TelNr>891234</TelNr>
    </Eintrag>
    <Eintrag>
        <Name>Schmitz</Name>
        <TelNr>870887</TelNr>
    </Eintrag>
</Telefonliste>

This is quite near on what I want, but there are the attributes missing...Why are the attributes missing and how can I add them? I don't want to use THE identity transformation https://en.wikipedia.org/wiki/Identity_transform#Using_XSLT. Second question is, how copies the identity transformation attributes? The xsl:copy command does not copy attribute nodes as far as I know.

Body:
Why are the attributes missing and how can I add them?

The attributes are missing because you neither copy them nor create new ones instead. That should also answer the second part; either one of these:

<xsl:template match="@*">
    <xsl:copy/>
</xsl:template>

or:

<xsl:template match="@*">
    <xsl:attribute name="{name()}">
        <xsl:value-of select="." />
    </xsl:attribute>
</xsl:template>

will re-create the attributes.

However, in order for this to work, you must first apply templates to the attributes. Your current stylesheet does not do that - the instruction:

<xsl:apply-templates />

applies templates to child nodes, not to attributes.

The xsl:copy command does not copy attribute nodes as far as I know...

That is incorrect. As explained above, the problem lies elsewhere.

I dont want to use THE identity transformation

I would question the wisdom of such decision. Your approach is unnecessarily convoluted. Note also that your two templates conflict since both will match an attribute.


问:
Powershell: regex replacement with inline calculation
I have the files named with yyyymm and I need to rename this files with mmyyyy but the mm in the new name have to be less for a one. And I need to do it inline during the replacement process.

I can do regex replace of the string abc201706.txt to the abc062017.txt with pattern

'abc201706.txt' -replace '^(.*)([0-9]{4})([0-9]{2})(\..*)$','$1$3$2$4'

How can I do regex replace to the abc052017.txt?

In other words I need inline subtraction of the one month from $3 which means the initial month.

I have searched for the answer to my question a lot of posts but without the result. Please do not mark my question as duplicate and answer to it.

答:
No beauty, but should work:

```<code>$myfilepath = 'C:\temp\abc2017 06.txt'
$file = Get-Item $myFilePath -Force
$basename = $file.basename

$basename -match '^(?<name>\D+)(?<year>\d{4})\s(?<month>\d{2})'

$dateString = "{0}/{1}/01" -f $matches.year, $matches.month
$Datetime = $dateString | Get-Date
$Datetime = $Datetime.AddMonths(-1)

$newBasename = "{0} {1} {2}{3}" -f $matches.name, $Datetime.ToString('MM'), $Datetime.ToString('yyyy'), $file.Extension
</code>```

update: Your regex did not match, I changed it a bit.

Update2: Write this to a file, and call it however you want.

```<code>param(
    [string]$myFilePath
)
$file = Get-Item $myFilePath -Force
$basename = $file.basename

$null = $basename -match '^(?<name>\D+)(?<year>\d{4})\s(?<month>\d{2})'

$dateString = "{0}/{1}/01" -f $matches.year, $matches.month
$Datetime = $dateString | Get-Date
$Datetime = $Datetime.AddMonths(-1)

$newFilename = "{0} {1} {2}{3}" -f $matches.name, $Datetime.ToString('MM'), $Datetime.ToString('yyyy'), $file.Extension

return $newFilename
</code>```

e.g.: ConvertFilename.ps1 -myFilePath "c:\Blah"

Body:
No beauty, but should work:

$myfilepath = 'C:\temp\abc2017 06.txt'
$file = Get-Item $myFilePath -Force
$basename = $file.basename

$basename -match '^(?<name>\D+)(?<year>\d{4})\s(?<month>\d{2})'

$dateString = "{0}/{1}/01" -f $matches.year, $matches.month
$Datetime = $dateString | Get-Date
$Datetime = $Datetime.AddMonths(-1)

$newBasename = "{0} {1} {2}{3}" -f $matches.name, $Datetime.ToString('MM'), $Datetime.ToString('yyyy'), $file.Extension

update: Your regex did not match, I changed it a bit.

Update2: Write this to a file, and call it however you want.

param(
    [string]$myFilePath
)
$file = Get-Item $myFilePath -Force
$basename = $file.basename

$null = $basename -match '^(?<name>\D+)(?<year>\d{4})\s(?<month>\d{2})'

$dateString = "{0}/{1}/01" -f $matches.year, $matches.month
$Datetime = $dateString | Get-Date
$Datetime = $Datetime.AddMonths(-1)

$newFilename = "{0} {1} {2}{3}" -f $matches.name, $Datetime.ToString('MM'), $Datetime.ToString('yyyy'), $file.Extension

return $newFilename

e.g.: ConvertFilename.ps1 -myFilePath "c:\Blah"


问:
Configuring a diff-tool for Git on Windows
Since git diff in powershell mostly results in a unreadable amount of whitespace or strange characters, I installed Perforce P4Merge, to handle merging and diff.

However, I can't make git diff open the p4merge application to view the diff in. So far my .gitconfig looks like this:

```<code>[diff]
    tool = p4diff

[difftool "p4diff"]
    external = 'C:/PROGRA~1/Perforce/p4merge.exe "$LOCAL" "$REMOTE"'
    prompt = false

[merge]
    keepBackup = false
    tool = p4merge

[mergetool "p4merge"]
    cmd = "$BASE" "$LOCAL" "$REMOTE" "$MERGED"
    path = 'C:/PROGRA~1/Perforce/p4merge.exe'
    prompt = false
    keepBackup = false
    keepTemporaries = false
    trustExitCode = false
</code>```

The paths are correct. But alas, git still attempts to present the diff in Powershell, when using git diff.

So what's the trick to make this work?

答:
git config --global diff.tool p4merge

git config --global difftool.p4merge.cmd "p4merge \"$LOCAL\" \"$REMOTE\""

add p4merge.exe path("C:\Program Files\Perforce\p4merge.exe") to environment path

ps:

in step 2,you've to add \"$LOCAL\" \"$REMOTE\"(local diff remote),or p4merge won't know what to diff

Body:
Since git diff in powershell mostly results in a unreadable amount of whitespace or strange characters, I installed Perforce P4Merge, to handle merging and diff.

However, I can't make git diff open the p4merge application to view the diff in. So far my .gitconfig looks like this:

[diff]
    tool = p4diff

[difftool "p4diff"]
    external = 'C:/PROGRA~1/Perforce/p4merge.exe "$LOCAL" "$REMOTE"'
    prompt = false

[merge]
    keepBackup = false
    tool = p4merge

[mergetool "p4merge"]
    cmd = "$BASE" "$LOCAL" "$REMOTE" "$MERGED"
    path = 'C:/PROGRA~1/Perforce/p4merge.exe'
    prompt = false
    keepBackup = false
    keepTemporaries = false
    trustExitCode = false

The paths are correct. But alas, git still attempts to present the diff in Powershell, when using git diff.

So what's the trick to make this work?


问:
Javascript - Using Promises on Websocket?
I am using Websockets in pure Javascript and I want to implement Promises into the Websocket functions. I don't get any errors but the Promise doesn't work.

Using the following code I can connect succesful to the socketserver but the Promise seems to be skipped because the output of the alert is always "failed".

Does somebody knows what the problem is in this case?
Ps: I did the tests in the latest Google Chrome browser and the latest Mozilla Firefox browser, and I left out some basic checking/error handling for this example.

```<code>function Connect()
{
    server = new WebSocket('mysite:1234');

    server.onopen = (function()
    {
        return new Promise(function(resolve, reject)
        {
            if (true)
            {
                resolve();
            }
            else
            {
                reject();
            }
        });
    }).then = (function()
    {
        alert('succeeed');
    }).catch = (function()
    {
        alert('failed');
    });
}
</code>```

答:
I faced exactly the same problem and created tiny websocket-as-promised library. It returns promises for connecting / disconnecting and sending messages:

```<code>const WebSocketAsPromised = require('websocket-as-promised');
const wsp = new WebSocketAsPromised();

// connect
wsp.open('ws://echo.websocket.org')
  .then(() => console.log('Connected.'))
  // send data and expect response message from server
  .then(() => wsp.sendRequest({foo: 'bar'}))
  .then(response => console.log('Response message received', response))
  // disconnect
  .then(() => wsp.close())
  .then(() => console.log('Disconnected.'));
</code>```

Concerning messages there are two options:

if you send data and expect response message - you can use promise via .sendRequest() method:

```<code>wsp.sendRequest({foo: 'bar'}); // returns promise
// actually sends message with unique id: {id: 'xxxxx', foo: 'bar'}
// promise waits response message with the same id: {id: 'xxxxx', response: 'ok'}
</code>```

if you just want to send message and do not expect response - use .send() method:

```<code>wsp.send(data); // returns undefined
</code>```

Body:
I am using Websockets in pure Javascript and I want to implement Promises into the Websocket functions. I don't get any errors but the Promise doesn't work.

Using the following code I can connect succesful to the socketserver but the Promise seems to be skipped because the output of the alert is always "failed".

Does somebody knows what the problem is in this case?
Ps: I did the tests in the latest Google Chrome browser and the latest Mozilla Firefox browser, and I left out some basic checking/error handling for this example.

function Connect()
{
    server = new WebSocket('mysite:1234');

    server.onopen = (function()
    {
        return new Promise(function(resolve, reject)
        {
            if (true)
            {
                resolve();
            }
            else
            {
                reject();
            }
        });
    }).then = (function()
    {
        alert('succeeed');
    }).catch = (function()
    {
        alert('failed');
    });
}

Body:
I faced exactly the same problem and created tiny websocket-as-promised library. It returns promises for connecting / disconnecting and sending messages:

const WebSocketAsPromised = require('websocket-as-promised');
const wsp = new WebSocketAsPromised();

// connect
wsp.open('ws://echo.websocket.org')
  .then(() => console.log('Connected.'))
  // send data and expect response message from server
  .then(() => wsp.sendRequest({foo: 'bar'}))
  .then(response => console.log('Response message received', response))
  // disconnect
  .then(() => wsp.close())
  .then(() => console.log('Disconnected.'));

Concerning messages there are two options:

if you send data and expect response message - you can use promise via .sendRequest() method:

wsp.sendRequest({foo: 'bar'}); // returns promise
// actually sends message with unique id: {id: 'xxxxx', foo: 'bar'}
// promise waits response message with the same id: {id: 'xxxxx', response: 'ok'}

if you just want to send message and do not expect response - use .send() method:

wsp.send(data); // returns undefined


问:
Get a list of duplicates from list based on properties comparison
I have a List<Demo>

```<code>public class Demo
{
    public Demo()
    {

    }

    public int Id { get; set; }
    public string Name { get; set; }
    public string Title { get; set; }
}
</code>```

The Id property is unique for every record in the list.

How can I get a List<Demo> from the original List<Demo> with all the duplicates where the Name and Title are same.

What I did so far but what I get is one single record:

```<code>List<Demo> demo = new List<Demo>();

demo.Add(new Demo()
{
    Id = 1,
    Name = "Demo",
    Title = "A"
});

demo.Add(new Demo()
{
    Id = 2,
    Name = "Demo",
    Title = "A"
});

demo.Add(new Demo()
{
    Id = 3,
    Name = "Demo",
    Title = "A"
});

demo.Add(new Demo()
{
    Id = 4,
    Name = "Demo1",
    Title = "A"
});

demo.Add(new Demo()
{
    Id = 5,
    Name = "Demo2",
    Title = "A"
});
</code>```

and then i am doing:

```<code>var duplicates = demo.GroupBy(t => new { t.Name, t.Title })
                     .Where(t => t.Count() > 1)
                     .Select(g => g.Key).ToList();
</code>```

From the example above I should get a List<Demo> with the first 3 items where the ids are:1,2,3 because Name and Title are same.

答:
It sounds like all you're missing is a SelectMany call. Currently you're creating all the appropriate groups and filtering down to groups with more than one entry - but if you want a single flat list, you need to flatten those groups back to their elements:

```<code>var duplicates = demo
    .GroupBy(t => new { t.Name, t.Title })
    .Where(t => t.Count() > 1)
    .SelectMany(x => x) // Flatten groups to a single sequence
    .ToList();
</code>```

Note that this doesn't mean every entry in the resulting list will have the same name and title. It does mean that every entry will have a name/title combination in common with at least one other entry.

Body:
I have a List<Demo>

public class Demo
{
    public Demo()
    {

    }

    public int Id { get; set; }
    public string Name { get; set; }
    public string Title { get; set; }
}

The Id property is unique for every record in the list.

How can I get a List<Demo> from the original List<Demo> with all the duplicates where the Name and Title are same.

What I did so far but what I get is one single record:

List<Demo> demo = new List<Demo>();

demo.Add(new Demo()
{
    Id = 1,
    Name = "Demo",
    Title = "A"
});

demo.Add(new Demo()
{
    Id = 2,
    Name = "Demo",
    Title = "A"
});

demo.Add(new Demo()
{
    Id = 3,
    Name = "Demo",
    Title = "A"
});

demo.Add(new Demo()
{
    Id = 4,
    Name = "Demo1",
    Title = "A"
});

demo.Add(new Demo()
{
    Id = 5,
    Name = "Demo2",
    Title = "A"
});

and then i am doing:

var duplicates = demo.GroupBy(t => new { t.Name, t.Title })
                     .Where(t => t.Count() > 1)
                     .Select(g => g.Key).ToList();

From the example above I should get a List<Demo> with the first 3 items where the ids are:1,2,3 because Name and Title are same.

Body:
It sounds like all you're missing is a SelectMany call. Currently you're creating all the appropriate groups and filtering down to groups with more than one entry - but if you want a single flat list, you need to flatten those groups back to their elements:

var duplicates = demo
    .GroupBy(t => new { t.Name, t.Title })
    .Where(t => t.Count() > 1)
    .SelectMany(x => x) // Flatten groups to a single sequence
    .ToList();

Note that this doesn't mean every entry in the resulting list will have the same name and title. It does mean that every entry will have a name/title combination in common with at least one other entry.


问:
About ![CDATA[, what is it?

Possible Duplicate:

  what is the meaning of CDATA

What is, and when is used the ![CDATA[ string/variable/constant? (I don't know what is it)

答:
The term CDATA ((Unparsed) Character Data) is used about text data that should not be parsed by the XML parser.

Some text, like JavaScript code, contains a lot of "<" or "&" characters. To avoid errors script code can be defined as CDATA.

Ref

Title: About ![CDATA[, what is it?


问:
How to add "Done" button to Numpad in iOS using Swift?
It works fine with the default keyboard, but I cant get it working with the numpad.

Any ideas?

答:
Swift 5 solution using @IBInpectable and extension. A dropdown will appear under the Attribute Inspector in the Interface Builder for every UITextField in the project.

```<code>extension UITextField{
    @IBInspectable var doneAccessory: Bool{
        get{
            return self.doneAccessory
        }
        set (hasDone) {
            if hasDone{
                addDoneButtonOnKeyboard()
            }
        }
    }

    func addDoneButtonOnKeyboard()
    {
        let doneToolbar: UIToolbar = UIToolbar(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50))
        doneToolbar.barStyle = .default

        let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        let done: UIBarButtonItem = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(self.doneButtonAction))

        let items = [flexSpace, done]
        doneToolbar.items = items
        doneToolbar.sizeToFit()

        self.inputAccessoryView = doneToolbar
    }

    @objc func doneButtonAction()
    {
        self.resignFirstResponder()
    }
}
</code>```

Body:
Swift 5 solution using @IBInpectable and extension. A dropdown will appear under the Attribute Inspector in the Interface Builder for every UITextField in the project.

extension UITextField{
    @IBInspectable var doneAccessory: Bool{
        get{
            return self.doneAccessory
        }
        set (hasDone) {
            if hasDone{
                addDoneButtonOnKeyboard()
            }
        }
    }

    func addDoneButtonOnKeyboard()
    {
        let doneToolbar: UIToolbar = UIToolbar(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50))
        doneToolbar.barStyle = .default

        let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        let done: UIBarButtonItem = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(self.doneButtonAction))

        let items = [flexSpace, done]
        doneToolbar.items = items
        doneToolbar.sizeToFit()

        self.inputAccessoryView = doneToolbar
    }

    @objc func doneButtonAction()
    {
        self.resignFirstResponder()
    }
}


问:
Cannot access QML singleton residing in same dir
I'm getting this error:

qrc:/qml/Accessor.qml:5: ReferenceError: MySingleton is not defined

My project structure:

```<code>| main.cpp
| main.qml
| qml/
+--- Accessor.qml
+--- MySingleton.qml
+--- qmldir
</code>```

Contents of the files:

main.cpp:

```<code>#include <QGuiApplication>
#include <QQmlApplicationEngine>

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    return app.exec();
}
</code>```

main.qml:

```<code>import QtQuick 2.6
import QtQuick.Window 2.2
import "qml/"

Accessor {
}
</code>```

qml/Accessor.qml:

```<code>import QtQml 2.2
//import qml 1.0

QtObject {
    property int foo: MySingleton.foo
}
</code>```

qml/MySingleton.qml:

```<code>pragma Singleton
import QtQml 2.2

QtObject {
    property int foo: 0
}
</code>```

qml/qmldir:

```<code>module qml

singleton MySingleton 1.0 MySingleton.qml
</code>```

qml.qrc:

```<code><RCC>
    <qresource prefix="/">
        <file>main.qml</file>
        <file>qml/Accessor.qml</file>
        <file>qml/MySingleton.qml</file>
        <file>qml/qmldir</file>
    </qresource>
</RCC>
</code>```

Uncommenting the import qml 1.0 in Accessor.qml doesn't help. But when Accessor.qml is in the project root, it works fine.

Any ideas?

答: Solution: I had to add import "." into Accessor.qml.

Body:
I'm getting this error:

qrc:/qml/Accessor.qml:5: ReferenceError: MySingleton is not defined

My project structure:

| main.cpp
| main.qml
| qml/
+--- Accessor.qml
+--- MySingleton.qml
+--- qmldir

Contents of the files:

main.cpp:

#include <QGuiApplication>
#include <QQmlApplicationEngine>

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    return app.exec();
}

main.qml:

import QtQuick 2.6
import QtQuick.Window 2.2
import "qml/"

Accessor {
}

qml/Accessor.qml:

import QtQml 2.2
//import qml 1.0

QtObject {
    property int foo: MySingleton.foo
}

qml/MySingleton.qml:

pragma Singleton
import QtQml 2.2

QtObject {
    property int foo: 0
}

qml/qmldir:

module qml

singleton MySingleton 1.0 MySingleton.qml

qml.qrc:

<RCC>
    <qresource prefix="/">
        <file>main.qml</file>
        <file>qml/Accessor.qml</file>
        <file>qml/MySingleton.qml</file>
        <file>qml/qmldir</file>
    </qresource>
</RCC>

Uncommenting the import qml 1.0 in Accessor.qml doesn't help. But when Accessor.qml is in the project root, it works fine.

Any ideas?


问:
IBM Watson IoT Platform - How to create application interface?
I've created devices and managed them with Node-RED. And receiving real-time data in my IoT platform board. So i wanted to access those data by REST API which i found this: https://docs.internetofthings.ibmcloud.com/apis/swagger/v0002-beta/info-mgmt-beta.html

Specially wanted to use this
/device/types/{typeId}/devices/{deviceId}/state/{applicationInterfaceId}

And i created schema by following this: https://developer.ibm.com/courses/labs/create-device-schema-internet-things-platform-service-ibm-bluemix-dwc013/

Then i requested to /api/v0002/applicationinterfaces, /api/v0002/schemas.

But both result was:

{"results": [], "meta": {"total_rows": 0}}

How can i create schema and application interface?

答:
The /api/v0002/applicationinterfaces, /api/v0002/schemas will return 0 results because you need to use the POST methods described in https://docs.internetofthings.ibmcloud.com/apis/swagger/v0002-beta/info-mgmt-beta.html to create the schema and application interface.

However, from your question I think you simply want to access the device data. In which case view the documentation for developing applications https://console.bluemix.net/docs/services/IoT/applications/api.html#api, in particular you can access the last event for a particular device using the last event cache e.g. /api/v0002/device/types/{deviceType}/devices/{deviceId}/events