问:
How the last line of following recursive program is working?
I was studying Linked List and then I found a code for reversing the Linked List recursively. Here is the C++ code.

```<code>void recursiveReverse(node*& head)
{
  node* first;
  node* rest;

/* checking for an empty list */
  if (head == NULL)
   return;

  first = head;
  rest  = first->next;

/* List has only one node */
  if (rest == NULL)
   return;

  recursiveReverse(rest);
  first->next->next  = first;
  first->next  = NULL;

/* fix the head pointer */
  head = rest;
}
</code>```

I understood the whole code except the last line. Because according to me, the rest pointer is also updated similarly as the first pointer during unwinding of the recursion and therefore, at the end of this code, the head will not point to the last node.

Here's my interpretation of the following code.

Let's take a Linked List 1 -> 2 -> 3.

Initially, first will store the address of the head node and rest
will contain the address of the node 2.

Now, since rest is not NULL, therefore, recursiveReverse(rest) will be called.

Now, first will point to node 2 and rest will point to node 3.

Again, rest is not NULL, therefore, recursiveReverse(rest) will be called.

Now, first will point to node 3 and rest will contain NULL.

After that, the recursion will start unwinding and first will be back to node 2 and the rest will be back to node 3.

Now, the statement first -> next -> next = first; will cause the next part of node 3 to point to node 2 and the Linked List will become 1 -> 2 <- 3. The next part of node 2 will contain NULL and since head = rest, therefore, head will also point to last node as the rest pointer.

After that, first will point to node 1 and the statement first -> next -> next = first; will cause the next part of node 2 to point to node 1 and the Linked List will become 1 <- 2 <- 3. The next part of the node 1 will contain NULL and the statement head = rest will cause the head to point to node 2 and not the node 3 since, the rest (which is first -> next) is currently at node 2.

Can anyone please explain where I am wrong in interpreting this code?

答:
It looks like in step 8. you forgot that head in void recursiveReverse(node*& head) is a reference. So when you recursively call recursiveReverse(rest); then rest is passed by reference. That means that, when inside the recursion, head is a reference to the rest variable in the calling function. Therefore when it was changed to point to 3 inside the recursion then rest in the calling function was also changed.

If this sounds confusing then drawing up the local variables on the stack might help:

1) Initially, head will be a reference to the pointer to the node passed to the function, first will store the address of the head node and rest will contain the address of the node 2.

The stack will look like this (only showing local variables and ignoring whatever was already there when calling the function):

```<code>====================================
head:     reference to original head
first:    node 1
rest:     node 2
</code>```

2) Now, since rest is not NULL, recursiveReverse(rest) will be called.

3) Now, head will reference rest in the calling  function, first will point to node 2 and rest will point to node 3.
The stack will look like this:

```<code>====================================
head:     reference to original head
first:    node 1
rest:     node 2      <---------------+
====================================  |
head:     reference to ---------------+
first:    node 2
rest:     node 3
</code>```

4) Again, rest is not NULL, therefore recursiveReverse(rest) will be called.

5) Now, head will reference rest in the last calling function, first will point to node 3 and rest will contain NULL.
The stack will look like this:

```<code>====================================
head:     reference to original head
first:    node 1
rest:     node 2      <---------------+
====================================  |
head:     reference to ---------------+
first:    node 2
rest:     node 3      <---------------+
====================================  |
head:     reference to ---------------+
first:    node 3
rest:     NULL
</code>```

6) Since rest is NULL we just return and the stack is back to this:

```<code>====================================
head:     reference to original head
first:    node 1
rest:     node 2      <---------------+
====================================  |
head:     reference to ---------------+
first:    node 2
rest:     node 3
</code>```

7) Now, the statement first->next->next = first; will cause the next part of node 3 to point to node 2 and the Linked List will become 1 -> 2 <- 3. The next part of node 2 will contain NULL. Since head is a reference to rest in the calling function then head = rest will make the rest referenced by head to point to the same node as the local rest:

```<code>====================================
head:     reference to original head
first:    node 1
rest:     node 3      <---------------+ (head = rest; made *this* rest
====================================  |  be equal to the *local* rest)
head:     reference to ---------------+
first:    node 2
rest:     node 3
</code>```

8) After that, we return and first will again point to node 1 and the statement first->next->next = first; will cause the next part of node 2 to point to node 1 and the Linked List will become 1 <- 2 <- 3. The next part of the node 1 will contain NULL and the statement head = rest will cause the pointer referenced by head to point to node 3 since rest was changed to point to node 3 in step 7.

Body:
I was studying Linked List and then I found a code for reversing the Linked List recursively. Here is the C++ code.

void recursiveReverse(node*& head)
{
  node* first;
  node* rest;

/* checking for an empty list */
  if (head == NULL)
   return;

  first = head;
  rest  = first->next;

/* List has only one node */
  if (rest == NULL)
   return;

  recursiveReverse(rest);
  first->next->next  = first;
  first->next  = NULL;

/* fix the head pointer */
  head = rest;
}

I understood the whole code except the last line. Because according to me, the rest pointer is also updated similarly as the first pointer during unwinding of the recursion and therefore, at the end of this code, the head will not point to the last node.

Here's my interpretation of the following code.

Let's take a Linked List 1 -> 2 -> 3.

Initially, first will store the address of the head node and rest
will contain the address of the node 2.

Now, since rest is not NULL, therefore, recursiveReverse(rest) will be called.

Now, first will point to node 2 and rest will point to node 3.

Again, rest is not NULL, therefore, recursiveReverse(rest) will be called.

Now, first will point to node 3 and rest will contain NULL.

After that, the recursion will start unwinding and first will be back to node 2 and the rest will be back to node 3.

Now, the statement first -> next -> next = first; will cause the next part of node 3 to point to node 2 and the Linked List will become 1 -> 2 <- 3. The next part of node 2 will contain NULL and since head = rest, therefore, head will also point to last node as the rest pointer.

After that, first will point to node 1 and the statement first -> next -> next = first; will cause the next part of node 2 to point to node 1 and the Linked List will become 1 <- 2 <- 3. The next part of the node 1 will contain NULL and the statement head = rest will cause the head to point to node 2 and not the node 3 since, the rest (which is first -> next) is currently at node 2.

Can anyone please explain where I am wrong in interpreting this code?

Body:
It looks like in step 8. you forgot that head in void recursiveReverse(node*& head) is a reference. So when you recursively call recursiveReverse(rest); then rest is passed by reference. That means that, when inside the recursion, head is a reference to the rest variable in the calling function. Therefore when it was changed to point to 3 inside the recursion then rest in the calling function was also changed.

If this sounds confusing then drawing up the local variables on the stack might help:

1) Initially, head will be a reference to the pointer to the node passed to the function, first will store the address of the head node and rest will contain the address of the node 2.

The stack will look like this (only showing local variables and ignoring whatever was already there when calling the function):

====================================
head:     reference to original head
first:    node 1
rest:     node 2

2) Now, since rest is not NULL, recursiveReverse(rest) will be called.

3) Now, head will reference rest in the calling  function, first will point to node 2 and rest will point to node 3.
The stack will look like this:

====================================
head:     reference to original head
first:    node 1
rest:     node 2      <---------------+
====================================  |
head:     reference to ---------------+
first:    node 2
rest:     node 3

4) Again, rest is not NULL, therefore recursiveReverse(rest) will be called.

5) Now, head will reference rest in the last calling function, first will point to node 3 and rest will contain NULL.
The stack will look like this:

====================================
head:     reference to original head
first:    node 1
rest:     node 2      <---------------+
====================================  |
head:     reference to ---------------+
first:    node 2
rest:     node 3      <---------------+
====================================  |
head:     reference to ---------------+
first:    node 3
rest:     NULL

6) Since rest is NULL we just return and the stack is back to this:

====================================
head:     reference to original head
first:    node 1
rest:     node 2      <---------------+
====================================  |
head:     reference to ---------------+
first:    node 2
rest:     node 3

7) Now, the statement first->next->next = first; will cause the next part of node 3 to point to node 2 and the Linked List will become 1 -> 2 <- 3. The next part of node 2 will contain NULL. Since head is a reference to rest in the calling function then head = rest will make the rest referenced by head to point to the same node as the local rest:

====================================
head:     reference to original head
first:    node 1
rest:     node 3      <---------------+ (head = rest; made *this* rest
====================================  |  be equal to the *local* rest)
head:     reference to ---------------+
first:    node 2
rest:     node 3

8) After that, we return and first will again point to node 1 and the statement first->next->next = first; will cause the next part of node 2 to point to node 1 and the Linked List will become 1 <- 2 <- 3. The next part of the node 1 will contain NULL and the statement head = rest will cause the pointer referenced by head to point to node 3 since rest was changed to point to node 3 in step 7.


来源: stackexchange

问:
cannot set UILabel padding in tableViewcell
I have set my UILabel padding using StackOverflow's popular thread for resolving auto-layout issue.
This thread is basically a UILabel extension.

Part of the answer is:

```<code>class NRLabel : UILabel {

    var textInsets = UIEdgeInsets.zero {
        didSet { invalidateIntrinsicContentSize() }
    }

    override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
        let insetRect = UIEdgeInsetsInsetRect(bounds, textInsets)
        let textRect = super.textRect(forBounds: insetRect, limitedToNumberOfLines: numberOfLines)
        let invertedInsets = UIEdgeInsets(top: -textInsets.top,
                                          left: -textInsets.left,
                                          bottom: -textInsets.bottom,
                                          right: -textInsets.right)
        return UIEdgeInsetsInsetRect(textRect, invertedInsets)
    }

    override func drawText(in rect: CGRect) {
        super.drawText(in: UIEdgeInsetsInsetRect(rect, textInsets))
    }
}
</code>```

Everything is working fine, padding has been added but i need to reload the tableViewcell to see the effect.

I have  overridden my customCell's viewWillLayoutSubviews() function like this for padding

```<code> self.chatLabel.textInsets = UIEdgeInsets.init(top: 10, left: 10, bottom: 10, right: 10)
</code>```

And the effect is like this.

You see, first label is getting it's padding after reloading the cell.

Pls suggest how to  achieve UILabel padding by using the extension mentioned above so that this issue is resolved.

答:
Add
 this two function into your extention and remove all other:</p>

```<code> override func drawText(in rect: CGRect) {
            let insets: UIEdgeInsets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
            super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
        }
        override var intrinsicContentSize : CGSize {
            var intrinsicSuperViewContentSize = super.intrinsicContentSize
            intrinsicSuperViewContentSize.height += topInset + bottomInset
            intrinsicSuperViewContentSize.width += leftInset + rightInset
            return intrinsicSuperViewContentSize
        }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have set my UILabel padding using StackOverflow's popular thread for resolving auto-layout issue.
This thread is basically a UILabel extension.

Part of the answer is:

class NRLabel : UILabel {

    var textInsets = UIEdgeInsets.zero {
        didSet { invalidateIntrinsicContentSize() }
    }

    override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
        let insetRect = UIEdgeInsetsInsetRect(bounds, textInsets)
        let textRect = super.textRect(forBounds: insetRect, limitedToNumberOfLines: numberOfLines)
        let invertedInsets = UIEdgeInsets(top: -textInsets.top,
                                          left: -textInsets.left,
                                          bottom: -textInsets.bottom,
                                          right: -textInsets.right)
        return UIEdgeInsetsInsetRect(textRect, invertedInsets)
    }

    override func drawText(in rect: CGRect) {
        super.drawText(in: UIEdgeInsetsInsetRect(rect, textInsets))
    }
}

Everything is working fine, padding has been added but i need to reload the tableViewcell to see the effect.

I have  overridden my customCell's viewWillLayoutSubviews() function like this for padding

 self.chatLabel.textInsets = UIEdgeInsets.init(top: 10, left: 10, bottom: 10, right: 10)

And the effect is like this.

You see, first label is getting it's padding after reloading the cell.

Pls suggest how to  achieve UILabel padding by using the extension mentioned above so that this issue is resolved.

Body:
Add
 this two function into your extention and remove all other:

 override func drawText(in rect: CGRect) {
            let insets: UIEdgeInsets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
            super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
        }
        override var intrinsicContentSize : CGSize {
            var intrinsicSuperViewContentSize = super.intrinsicContentSize
            intrinsicSuperViewContentSize.height += topInset + bottomInset
            intrinsicSuperViewContentSize.width += leftInset + rightInset
            return intrinsicSuperViewContentSize
        }


问:
Securing the token of a token based authentication system
I am using a token based authentication for accessing a few crude web APIs I have designed for my site. At login, the username and password are posted to the login API, and it generates a token with a unique secret key, and the key is stored on the database. At each subsequent call, the token is sent with the request and verified on the server with the secret key.

I am using a web app to consume this API service and deliver a front end to the users. The web application is designed using HTML/Bootstrap/JQuery and the backend is written on php.

I have successfully tested my app and the token based authentication works. However, I have one concern. I find that the user id and token are displayed directly, only using url encoding on the address bar of the browser.

```<code>http://hasconpanel.ckoysolutions.com/hasconpanel.php?inputs={%20%22username%22%20:%20%22Debopam%20Parua%22%20,%20%22uid%22%20:%20%2220170520193421DP%22%20,%20%22token%22%20:%20%22Sa2pHyooWPoI79vfvJzLlw7UO%252B2p5hOpBttkEq7LQ%252BjAGm9XEmxfhLAcnJoLbqrsXCp75%252BG1M7nEUoCgsDVbIQ%253D%253D%22%20,%20%22list_of_devices%22%20:%20[{%22device_code%22:%22b8:27:eb:f1:b3:0f%22,%22device_name%22:%22First-Pi%22}]%20}
</code>```

Now, if this address is copied, or suppose the browser is made to resume the previous session, no matter who tries to access it, they get an entry. Especially in case of public computer centers, if anyone accesses my web app with their credentials, and forgets to logout before killing the browser, the token system seems to fail miserably. Is there anyway to secure the token like encrypting it? Or someway for the app to not store the parameters in case of a browser/browser-tab close or at least not display it on the address bar? I have thought of making a fresh token at each request, but it slows the system drastically, so I want to avoid it.

Please suggest some way to solve this problem.

Thanks in advance.

Edit:
Explaining how the system works now:

The api system is hosted on the main domain of a shared server, and the app is hosted in a sub-domain. The main domain also hosts several webservices that are being called from a few raspberry pis installed at home.

This is how it works, the login is made from the primary website and on successful login, the web app is called with a get call with the user id, the token and a list of working devices for the user. Check is provided to prevent the app page being accessed without any of these three parameters. On fresh load, the user gets the choice to select a device from a drop-down menu. Now, each of these working devices can have three separate systems running. So, on selecting the device, a get call is again being made to the app, with the selected device added as a parameter along with the three previous parameters. This shows the token and the uid on the address-bar.

答:
Token based authentication is very standard in the web world.  The details vary, but what you are trying to do certainly isn't crazy.  However, your security concerns are valid, and there are a number of potential solutions:

Use HTTPS exclusively.  This will protect your token from being easily readable by everyone in between the user and you.  Actually, do this regardless of anything else.  HTTPS should be considered the default for security purposes these days: just pretend that HTTP is deprecated.

Move the token into the header of the request instead of the URL.  As long as you are using HTTPS this doesn't actually change anything from a security standpoint, but it is fairly standard for the industry.  It will also keep the token out of the browser history.

It is strange that you have a URL showing up in the browser address bar.  I would expect a client-side application to make requests exclusively via ajax, which means there should't ever be anything in the address bar.  You might need to clarify more on how exactly this application is working.  I suspect you need to refactor so that none of your application URLs ever end up in the address bar, and instead operate via AJAX requests exclusively.

Still, HTTPS is the most important part.  Your entire transaction after DNS lookup will be transmitted securely, so the token cannot be stolen by a man-in-the-middle.  This is the most important step you have to take to secure it.  If you don't use HTTPS, you might as well broadcast it to the world.  Of course, if you are making non-ajax requests to a URL with the token in the query parameters then the token will be visible in the browser's address bar and history.  Again, avoid that by using ajax requests only and put the cookie in the header.

Once you have HTTPS in place with ajax-only requests, the chances of having a token stolen are much smaller.  Still, it can happen (in particular via an XSS attack), so become familiar with the principle of "defense in depth".  Also, there are steps you can take to try to detect a stolen token an invalidate it.  Things like:

Invalidate a token (for the user to log back in) if the IP Address changes (although this can impact mobile users, which probably isn't desirable)

Invalidate a token if the user agent changes (although that can be spoofed)

Enforce a server-side maximum session length

Make sure and require the user to re-authenticate if they want to change email/password.

Those are just a few suggestions off the top of my head.  Again though, this is a pretty standard problem, so google will be your friend.

Body:
I am using a token based authentication for accessing a few crude web APIs I have designed for my site. At login, the username and password are posted to the login API, and it generates a token with a unique secret key, and the key is stored on the database. At each subsequent call, the token is sent with the request and verified on the server with the secret key.

I am using a web app to consume this API service and deliver a front end to the users. The web application is designed using HTML/Bootstrap/JQuery and the backend is written on php.

I have successfully tested my app and the token based authentication works. However, I have one concern. I find that the user id and token are displayed directly, only using url encoding on the address bar of the browser.

http://hasconpanel.ckoysolutions.com/hasconpanel.php?inputs={%20%22username%22%20:%20%22Debopam%20Parua%22%20,%20%22uid%22%20:%20%2220170520193421DP%22%20,%20%22token%22%20:%20%22Sa2pHyooWPoI79vfvJzLlw7UO%252B2p5hOpBttkEq7LQ%252BjAGm9XEmxfhLAcnJoLbqrsXCp75%252BG1M7nEUoCgsDVbIQ%253D%253D%22%20,%20%22list_of_devices%22%20:%20[{%22device_code%22:%22b8:27:eb:f1:b3:0f%22,%22device_name%22:%22First-Pi%22}]%20}

Now, if this address is copied, or suppose the browser is made to resume the previous session, no matter who tries to access it, they get an entry. Especially in case of public computer centers, if anyone accesses my web app with their credentials, and forgets to logout before killing the browser, the token system seems to fail miserably. Is there anyway to secure the token like encrypting it? Or someway for the app to not store the parameters in case of a browser/browser-tab close or at least not display it on the address bar? I have thought of making a fresh token at each request, but it slows the system drastically, so I want to avoid it.

Please suggest some way to solve this problem.

Thanks in advance.

Edit:
Explaining how the system works now:

The api system is hosted on the main domain of a shared server, and the app is hosted in a sub-domain. The main domain also hosts several webservices that are being called from a few raspberry pis installed at home.

This is how it works, the login is made from the primary website and on successful login, the web app is called with a get call with the user id, the token and a list of working devices for the user. Check is provided to prevent the app page being accessed without any of these three parameters. On fresh load, the user gets the choice to select a device from a drop-down menu. Now, each of these working devices can have three separate systems running. So, on selecting the device, a get call is again being made to the app, with the selected device added as a parameter along with the three previous parameters. This shows the token and the uid on the address-bar.


问:
Magento Redirect From Old Urls To New Urls Which Has Store (Language) Code
The Description:

I set up Magento with store config like this:

Company Name - Webside

Main Store - Store

en - Store View

dk - Store View

My links looked like: https://my-company.com/shop/

Then I reaslised that this was wrong config for my needs and I had to change

English - Webside

Main Store - Store

en - Store View

Danish - Webside

Main Store - Store

dk - Store View

Plus, I enabled Magento feature "Add Store Code to Urls" which was previously disabled.

Now my links look like: https://my-company.com/en/shop/

Problem:

Since I already made sitemap while the changes were not made and submitted it to WebMasters, now I am facing the problem that all of the old links without store code in url does not work anymore (404 code - not found).

Because of WebMasters and other reasons I would really like to achieve this Result:

When somebody tries to open one of the old urls which is without store code (e.g. https://my-company.com/shop/), I would like he is redirected to the new url by just adding the store code as the first segment in url.

I already tried to achieve this by adding some rewrite rules to my nginx config but I ran into the infinite loop and at the end I could not find out the right solution for rewrite rules. (link to my question of nginx rewrite rules: Nginx Config Location Regex With Language Code In Url)

Full Nginx Config:

```<code>server {
    # Listen on port 8080 as well as post 443 for SSL connections.
    listen              8080;
    listen              443 default ssl;

server_name         example.com www.example.com;

large_client_header_buffers 4 16k;

ssl             on;

# Specify path to your SSL certificates.
ssl_certificate         /path/top/certificate.crt;
ssl_certificate_key     /path/to/key.key;

ssl_protocols               TLSv1 TLSv1.1 TLSv1.2;

ssl_ciphers         "EECDH+AESGCM:EDH+AESGCM:ECDHE-RSA-AES128-GCM-SHA256:AES256+EECDH:DHE-RSA-AES128-GCM-SHA256:AES256+EDH:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES128-SHA256:DHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES256-GCM-SHA384:AES128-GCM-SHA256:AES256-SHA256:AES128-SHA256:AES256-SHA:AES128-SHA:DES-CBC3-SHA:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!MD5:!PSK:!RC4";

ssl_prefer_server_ciphers   on;
ssl_dhparam         /path/to/dh_params.pem;
    ssl_session_cache       shared:SSL:10m;
    ssl_session_timeout     10m;
    keepalive_timeout       70;
    add_header          Strict-Transport-Security max-age=15768000;

ssl_stapling            on;
ssl_stapling_verify     on;
resolver            8.8.8.8 8.8.4.4 valid=300s;
resolver_timeout        5s;

ssl_trusted_certificate     /path/to/certificate.crt;

# Path to the files in which you wish to store your access and error logs.
access_log          /path/to/access_log;
error_log           /path/to/error_log;

root                /path/to/root/folder;

location ~* "^/(?![a-z]{2}/)(.+)$" {
    rewrite         / /en/$1 permanent;
}

location / {
    index           index.htm index.html index.php;
    try_files       $uri $uri/ @handler;
}

# Deny access to specific directories no one in particular needs access to anyways.
location /app/          { deny all; }
location /includes/     { deny all; }
location /lib/          { deny all; }
location /media/downloadable/   { deny all; }
location /pkginfo/      { deny all; }
location /report/config.xml { deny all; }
location /var/          { deny all; }

# Allow only those who have a login name and password to view the export folder. Refer to /etc/nginx/htpassword.
location /var/export/ {
    auth_basic      "Restricted";
    auth_basic_user_file    htpasswd;
    autoindex       on;
}

# Deny all attempts to access hidden files such as .htaccess, .htpasswd, etc...
location ~ /\. {
    deny            all;
    access_log      off;
    log_not_found       off;
}

# This redirect is added so to use Magentos common front handler when handling incoming URLs.
location @handler {
    rewrite         / /index.php?$query_string;
}

# Forward paths such as /js/index.php/x.js to their relevant handler.
location ~ .php/ {
    rewrite         ^(.*.php)/ $1 last;
}

# Handle the exectution of .php files.
location ~ .php$ {
    if (!-e $request_filename) {
        rewrite     / /index.php last;
    }

    expires         off;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass        unix:/path/to/php-fpm.sock;
    fastcgi_index       index.php;
    fastcgi_param       HTTPS on;
    fastcgi_param       SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param       MAGE_RUN_CODE en;
    fastcgi_param       MAGE_RUN_TYPE store;
    include         fastcgi_params;
}

}
</code>```

答:
this code i added for my nginx config, maybe will be helpfull for other, it is fix Admin area too:</p>

```<code>location / {
 rewrite "^/(?![a-z]{2}/)(.+)$" /en/$1 permanent;
  rewrite / /index.php?$query_string;
}

location /index.php/admin {
 try_files $uri $uri/ /index.php?$args;
 index index.php index.html index.htm;
}
</code>```

Body:
The Description:

I set up Magento with store config like this:

Company Name - Webside

Main Store - Store

en - Store View

dk - Store View

My links looked like: https://my-company.com/shop/

Then I reaslised that this was wrong config for my needs and I had to change

English - Webside

Main Store - Store

en - Store View

Danish - Webside

Main Store - Store

dk - Store View

Plus, I enabled Magento feature "Add Store Code to Urls" which was previously disabled.

Now my links look like: https://my-company.com/en/shop/

Problem:

Since I already made sitemap while the changes were not made and submitted it to WebMasters, now I am facing the problem that all of the old links without store code in url does not work anymore (404 code - not found).

Because of WebMasters and other reasons I would really like to achieve this Result:

When somebody tries to open one of the old urls which is without store code (e.g. https://my-company.com/shop/), I would like he is redirected to the new url by just adding the store code as the first segment in url.

I already tried to achieve this by adding some rewrite rules to my nginx config but I ran into the infinite loop and at the end I could not find out the right solution for rewrite rules. (link to my question of nginx rewrite rules: Nginx Config Location Regex With Language Code In Url)

Full Nginx Config:

server {
    # Listen on port 8080 as well as post 443 for SSL connections.
    listen              8080;
    listen              443 default ssl;

server_name         example.com www.example.com;

large_client_header_buffers 4 16k;

ssl             on;

# Specify path to your SSL certificates.
ssl_certificate         /path/top/certificate.crt;
ssl_certificate_key     /path/to/key.key;

ssl_protocols               TLSv1 TLSv1.1 TLSv1.2;

ssl_ciphers         "EECDH+AESGCM:EDH+AESGCM:ECDHE-RSA-AES128-GCM-SHA256:AES256+EECDH:DHE-RSA-AES128-GCM-SHA256:AES256+EDH:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES128-SHA256:DHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES256-GCM-SHA384:AES128-GCM-SHA256:AES256-SHA256:AES128-SHA256:AES256-SHA:AES128-SHA:DES-CBC3-SHA:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!MD5:!PSK:!RC4";

ssl_prefer_server_ciphers   on;
ssl_dhparam         /path/to/dh_params.pem;
    ssl_session_cache       shared:SSL:10m;
    ssl_session_timeout     10m;
    keepalive_timeout       70;
    add_header          Strict-Transport-Security max-age=15768000;

ssl_stapling            on;
ssl_stapling_verify     on;
resolver            8.8.8.8 8.8.4.4 valid=300s;
resolver_timeout        5s;

ssl_trusted_certificate     /path/to/certificate.crt;

# Path to the files in which you wish to store your access and error logs.
access_log          /path/to/access_log;
error_log           /path/to/error_log;

root                /path/to/root/folder;

location ~* "^/(?![a-z]{2}/)(.+)$" {
    rewrite         / /en/$1 permanent;
}

location / {
    index           index.htm index.html index.php;
    try_files       $uri $uri/ @handler;
}

# Deny access to specific directories no one in particular needs access to anyways.
location /app/          { deny all; }
location /includes/     { deny all; }
location /lib/          { deny all; }
location /media/downloadable/   { deny all; }
location /pkginfo/      { deny all; }
location /report/config.xml { deny all; }
location /var/          { deny all; }

# Allow only those who have a login name and password to view the export folder. Refer to /etc/nginx/htpassword.
location /var/export/ {
    auth_basic      "Restricted";
    auth_basic_user_file    htpasswd;
    autoindex       on;
}

# Deny all attempts to access hidden files such as .htaccess, .htpasswd, etc...
location ~ /\. {
    deny            all;
    access_log      off;
    log_not_found       off;
}

# This redirect is added so to use Magentos common front handler when handling incoming URLs.
location @handler {
    rewrite         / /index.php?$query_string;
}

# Forward paths such as /js/index.php/x.js to their relevant handler.
location ~ .php/ {
    rewrite         ^(.*.php)/ $1 last;
}

# Handle the exectution of .php files.
location ~ .php$ {
    if (!-e $request_filename) {
        rewrite     / /index.php last;
    }

    expires         off;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass        unix:/path/to/php-fpm.sock;
    fastcgi_index       index.php;
    fastcgi_param       HTTPS on;
    fastcgi_param       SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param       MAGE_RUN_CODE en;
    fastcgi_param       MAGE_RUN_TYPE store;
    include         fastcgi_params;
}

}

Body:
this code i added for my nginx config, maybe will be helpfull for other, it is fix Admin area too:

location / {
 rewrite "^/(?![a-z]{2}/)(.+)$" /en/$1 permanent;
  rewrite / /index.php?$query_string;
}

location /index.php/admin {
 try_files $uri $uri/ /index.php?$args;
 index index.php index.html index.htm;
}


问:
awk command to delete rows if it has number as the first character of first column in a tsv file
I am trying to delete rows if it has number as the first character in the first column in a tsv file. </p>

```<code>abc london
def paris
4ge berlin
323 rome
xyz prague
#56 Bern
</code>```

<p>I would like to delete (rows: 4ge, 323,#56). What I tried is something like this </p>

```<code>awk 'BEGIN{FS=OFS="\t"}{$1=/^[0-9]/; print $1,$2}' train.tsv > train.tsv
</code>```

答:
That's the kind of job grep was invented to do:

```<code>grep -v '^[0-9]'
</code>```

The difference between that and grep '^[^0-9]' is that the former will print blank lines while the latter won't.

Body:
I am trying to delete rows if it has number as the first character in the first column in a tsv file.

abc london
def paris
4ge berlin
323 rome
xyz prague
#56 Bern

I would like to delete (rows: 4ge, 323,#56). What I tried is something like this

awk 'BEGIN{FS=OFS="\t"}{$1=/^[0-9]/; print $1,$2}' train.tsv > train.tsv

Body:
That's the kind of job grep was invented to do:

grep -v '^[0-9]'

The difference between that and grep '^[^0-9]' is that the former will print blank lines while the latter won't.


问:
Creating CSS from a HTML file
I have an html file which contains many elements:

Course Name

        16. Please
        write below the Course Name in order of preference.

      (Please
        see the "Instructions to Candidate" for list of courses)

```

<p>As can be seen, 1 div has many divs in it. Now I want to create a css file that will contain all the styling of this html page (need not be same). Have to write something in java code. I have the DOM object of this file available to me.</p>

<p>Basically, I want all the styles to be removed from here and will be kept under a CSS file like for div with id = imgElt11289447233738dIi15v css will be:</p>

<pre class="lang-css prettyprint-override"><code>#imgElt11289447233738dIi15v{BORDER-RIGHT: 0px; BORDER-TOP: 0px; Z-INDEX: 1; LEFT: 795px; BORDER-LEFT: 0px; WIDTH: 90px; CURSOR: auto; BORDER-BOTTOM: 0px; POSITION: absolute; TOP: 186px; HEIGHT: 93px}
</code>```

I am don't till this part but since I don't know how many levels of hierarchy of elements will be there is there any way to do the same for all child elements as well?

I used the following code

```<code>public static Document getStyleInCSSfile(Document aoDoc, String aoPathToWrite, String aoFileName) throws ApplicationException {
    String loValue = null;
    String loID = null;
    String lsContent = "";
    Element loRoot = aoDoc.getRootElement();
    List loTempElementList = loRoot.getChildren();
    int liCounter;
    for (liCounter = 0; liCounter < loTempElementList.size(); liCounter++) {
        Element loTemplateEle = (Element) loTempElementList.get(liCounter);
        String loId=loTemplateEle.getAttribute("id").getValue();
        loID = loTemplateEle.getAttributeValue("id");
        if(null != loID)
        {
            loValue = loTemplateEle.getAttributeValue("style");
            if(loValue!=null && loValue.trim().length()>0)
            {
                loTemplateEle.removeAttribute("style");
                lsContent = lsContent.concat("#"+loID+"{"+loValue+"}\n");
            }
        }
    }
    SaveFormOnLocalUtil.writeToFile(aoPathToWrite,aoFileName,lsContent);
    return aoDoc;
}
</code>```

Edit : got to know that some regular expression may help by getting a string of SAX parser object and and using regular expression on it... any idea? any one? how to implement it

答:
I think you should use SAX instead of DOM. In SAX you can register the handler that is called every time the parser sees new tag, attribute etc. In this case every time you see attribute "style" you should extract its value to CSS file.

The next approach is using Digester from jakarta.apache.org. It uses SAX and allows XML configuration (see DigesterDigester) that maps your value object directly yo your XML document.

Absolutely different solution may made using unix shell commands like grep and sed. The preference to one of the solution depends on your system requirements and how often do you have to run this code. If it is one time transformation use unix shell scripting. If it must be something robust and change the pages on the fly use java solution.

Title: Creating CSS from a HTML file

Body:
I have an html file which contains many elements:

Course Name

        16. Please
        write below the Course Name in order of preference.

      (Please
        see the "Instructions to Candidate" for list of courses)

As can be seen, 1 div has many divs in it. Now I want to create a css file that will contain all the styling of this html page (need not be same). Have to write something in java code. I have the DOM object of this file available to me.

Basically, I want all the styles to be removed from here and will be kept under a CSS file like for div with id = imgElt11289447233738dIi15v css will be:

#imgElt11289447233738dIi15v{BORDER-RIGHT: 0px; BORDER-TOP: 0px; Z-INDEX: 1; LEFT: 795px; BORDER-LEFT: 0px; WIDTH: 90px; CURSOR: auto; BORDER-BOTTOM: 0px; POSITION: absolute; TOP: 186px; HEIGHT: 93px}

I am don't till this part but since I don't know how many levels of hierarchy of elements will be there is there any way to do the same for all child elements as well?

I used the following code

public static Document getStyleInCSSfile(Document aoDoc, String aoPathToWrite, String aoFileName) throws ApplicationException {
    String loValue = null;
    String loID = null;
    String lsContent = "";
    Element loRoot = aoDoc.getRootElement();
    List loTempElementList = loRoot.getChildren();
    int liCounter;
    for (liCounter = 0; liCounter < loTempElementList.size(); liCounter++) {
        Element loTemplateEle = (Element) loTempElementList.get(liCounter);
        String loId=loTemplateEle.getAttribute("id").getValue();
        loID = loTemplateEle.getAttributeValue("id");
        if(null != loID)
        {
            loValue = loTemplateEle.getAttributeValue("style");
            if(loValue!=null && loValue.trim().length()>0)
            {
                loTemplateEle.removeAttribute("style");
                lsContent = lsContent.concat("#"+loID+"{"+loValue+"}\n");
            }
        }
    }
    SaveFormOnLocalUtil.writeToFile(aoPathToWrite,aoFileName,lsContent);
    return aoDoc;
}

Edit : got to know that some regular expression may help by getting a string of SAX parser object and and using regular expression on it... any idea? any one? how to implement it

ContentLicense: CC BY-SA 2.5


问:
Round date long value
In my Java project I used date in long and for example it is 12136219 and by creating Date object as below:

```<code>long time = 12136219;
Date date = new Date(time);
</code>```

and it represent date as Thu Jan 01 04:22:16 CET 1970. How can I round date (in long representation) to minutes ?

For example I want achieve Thu Jan 01 04:22:00 CET 1970 if the seconds are <30 and Thu Jan 01 04:23:00 CET 1970 if the seconds are >=30 but I want round this long time = 12136219 representation. Any idea?

答: You should do it on the Date object. There is no easy way to calculate it in the time epoch, because of various difficulties including the length of a month (28, 29, 30 or 31).</p>

Title: Round date long value

Body:
In my Java project I used date in long and for example it is 12136219 and by creating Date object as below:

long time = 12136219;
Date date = new Date(time);

and it represent date as Thu Jan 01 04:22:16 CET 1970. How can I round date (in long representation) to minutes ?

For example I want achieve Thu Jan 01 04:22:00 CET 1970 if the seconds are <30 and Thu Jan 01 04:23:00 CET 1970 if the seconds are >=30 but I want round this long time = 12136219 representation. Any idea?


问:
Drag&Drop at Sortable.js lists: How to set a different drop area than a Sortable list?
I'm testing Sortable.js lists with this small example. I have a list of elements to be dragged from, and another list to store them by dropping the elements.

NOTE: Sortable.js is different from JQuery-ui sortable, but the lack of Sortable.js documentation is making me consider switching to JQuery-ui Sortable, so I would accept an answer using it.

The thing is, the drop area is the list, and it is a bit frustrating dropping over the edged of that list panel and not getting the item correctly dropped. Also, it is hard to find the list when empty if it has no borders.

Sortable.js has an attribute named ghostClass, and according to the documentation it should store the class name for the drop placeholder.

So I'm using the class name of the second list panel as the ghostClass for the first list. Nevertheless, it is not working, and item only get correctly dropped when over the list and not over the panel.

HTML:

```<code><div class="panel panel-primary">
    <div class="panel-heading">Fruit store</div>
    <div class="panel-body">
        <ul id="fruit-list" class="list-group">
            <li href="#" class="list-group-item" data-type="apple">Apple</li>
            <li href="#" class="list-group-item" data-type="pear">Pear</li>
            <li href="#" class="list-group-item" data-type="banana">Banana</li>
            <li href="#" class="list-group-item" data-type="watermellon">Watermellon</li>
        </ul>
    </div>
</div>
<div class="panel panel-primary droppable-area">
    <div class="panel-heading">Shopping cart</div>
    <div class="panel-body">
        <ul id="cart-list" class="list-group">
            <li href="#" class="list-group-item" data-type="banana">Banana
                <div class="pull-right"> <span id="badge" class="badge">5</span>

                </div>
            </li>
            <li href="#" class="list-group-item" data-type="pear">Pear
                <div class="pull-right"> <span id="badge" class="badge">2</span>

                </div>
            </li>
        </ul>
    </div>
</div>
</code>```

JS:

```<code>// Create fruit store list
var list_element = document.getElementById("fruit-list");
var fruit_list = new Sortable(list_element, {
    group: {
        name: "fruit_group",
        pull: 'clone',
        put: false
    },
    sort: false,
    ghostClass: "droppable-area",
});

// Create shopping cart list
var cart_list_element = document.getElementById("cart-list");
var cart_list = new Sortable(cart_list_element, {
    group: {
        name: "fruit_group",
        pull: true,
        put: true
    },
});
</code>```

Any idea? Here is a working JSFiddle.

答:
This is what the ghostClass setting does:
When dragging an object sortablejs creates a placeholder where the item will be dropped if you let it go that instant. That placeholder will get the class set to it of the ghostClass value.

In your case:

Remove the 'droppable-area' class name in your panel-div.

Create css: .droppable-area { border: 1px solid black; }

Now you'll see a dashed-box of where you'll item wil end up if you'll stop dragging.

Body:
I'm testing Sortable.js lists with this small example. I have a list of elements to be dragged from, and another list to store them by dropping the elements.

NOTE: Sortable.js is different from JQuery-ui sortable, but the lack of Sortable.js documentation is making me consider switching to JQuery-ui Sortable, so I would accept an answer using it.

The thing is, the drop area is the list, and it is a bit frustrating dropping over the edged of that list panel and not getting the item correctly dropped. Also, it is hard to find the list when empty if it has no borders.

Sortable.js has an attribute named ghostClass, and according to the documentation it should store the class name for the drop placeholder.

So I'm using the class name of the second list panel as the ghostClass for the first list. Nevertheless, it is not working, and item only get correctly dropped when over the list and not over the panel.

HTML:

Fruit store

Apple

Pear

Banana

Watermellon

Shopping cart

Banana

 5

Pear

 2

JS:

// Create fruit store list
var list_element = document.getElementById("fruit-list");
var fruit_list = new Sortable(list_element, {
    group: {
        name: "fruit_group",
        pull: 'clone',
        put: false
    },
    sort: false,
    ghostClass: "droppable-area",
});

// Create shopping cart list
var cart_list_element = document.getElementById("cart-list");
var cart_list = new Sortable(cart_list_element, {
    group: {
        name: "fruit_group",
        pull: true,
        put: true
    },
});

Any idea? Here is a working JSFiddle.


问:
Implementation of comment system (Facebook like)
I am looking for a way to create comment system that behaves like Facebook's post comment section.

Right now I have this structure:

But I need to implement also replies to comments and replies to replies and so on.
What should be done to achieve the behavior same to Facebook's?

答:
To implement swipe to reply or delete and other things, use this library:
MGSwipeTableCell

For reply and delete do like this:

```<code>private func addFuncButtons(to cell: CommentCell, at row: Int) {
  let currentUserId = User.getCurrentUserId()

  if (cell.comment.userId == currentUserId // if its current user comment
     || userId! == currentUserId) // if current user is post author
     && cell.comment.key != "" { // cant delete desc
     cell.rightButtons = [
        MGSwipeButton(title: "", icon: UIImage(named:"delete.png"), backgroundColor: .red) {
           (sender: MGSwipeTableCell!) -> Bool in
           self.removeCell(cell, at: row)
           return true
        },
        MGSwipeButton(title: "", icon: UIImage(named:"reply.png"), backgroundColor: .darkGray) {
           (sender: MGSwipeTableCell!) -> Bool in
           self.replyToUser(with: cell.userNickName.currentTitle!)
           return true
        }
     ]
  } else {
     // add only reply button
     cell.rightButtons = [
        MGSwipeButton(title: "", icon: UIImage(named:"reply.png"), backgroundColor: .darkGray) {
           (sender: MGSwipeTableCell!) -> Bool in
           self.replyToUser(with: cell.userNickName.currentTitle!)
           return true
        }
     ]
  }

  cell.rightSwipeSettings.transition = .rotate3D
}
</code>```

Actions:

```<code>private func removeCell(_ cell: CommentCell, at row: Int) {
  removeCellFromTable(cell, at: row)
  removeCellFromDataBase(cell)
}

private func removeCellFromTable(_ cell: CommentCell, at row: Int) {
   comments.remove(at: row)
   tableView.reloadData()
}

private func removeCellFromDataBase(_ cell: CommentCell) {
   Comment.remove(cell.comment, from: post)
}

private func replyToUser(with login: String) {
   newCommentTextField.text = newCommentTextField.text?.appending(" @" + login)
}
</code>```

Like that.

Hope it helps

Body:
To implement swipe to reply or delete and other things, use this library:
MGSwipeTableCell

For reply and delete do like this:

private func addFuncButtons(to cell: CommentCell, at row: Int) {
  let currentUserId = User.getCurrentUserId()

  if (cell.comment.userId == currentUserId // if its current user comment
     || userId! == currentUserId) // if current user is post author
     && cell.comment.key != "" { // cant delete desc
     cell.rightButtons = [
        MGSwipeButton(title: "", icon: UIImage(named:"delete.png"), backgroundColor: .red) {
           (sender: MGSwipeTableCell!) -> Bool in
           self.removeCell(cell, at: row)
           return true
        },
        MGSwipeButton(title: "", icon: UIImage(named:"reply.png"), backgroundColor: .darkGray) {
           (sender: MGSwipeTableCell!) -> Bool in
           self.replyToUser(with: cell.userNickName.currentTitle!)
           return true
        }
     ]
  } else {
     // add only reply button
     cell.rightButtons = [
        MGSwipeButton(title: "", icon: UIImage(named:"reply.png"), backgroundColor: .darkGray) {
           (sender: MGSwipeTableCell!) -> Bool in
           self.replyToUser(with: cell.userNickName.currentTitle!)
           return true
        }
     ]
  }

  cell.rightSwipeSettings.transition = .rotate3D
}

Actions:

private func removeCell(_ cell: CommentCell, at row: Int) {
  removeCellFromTable(cell, at: row)
  removeCellFromDataBase(cell)
}

private func removeCellFromTable(_ cell: CommentCell, at row: Int) {
   comments.remove(at: row)
   tableView.reloadData()
}

private func removeCellFromDataBase(_ cell: CommentCell) {
   Comment.remove(cell.comment, from: post)
}

private func replyToUser(with login: String) {
   newCommentTextField.text = newCommentTextField.text?.appending(" @" + login)
}

Like that.

Hope it helps


问:
Why does my program print 0 instead of the calculated sine?
```<code>#include <cs50.h>
#include <stdio.h>

float sine(float a, float b);

int main()
{
    printf ("Choose an option:\n1- Sin\n2-Cos\n3-Tan\n");
    int option = get_int();
    if (option==1)
    {
        printf("What is the hypotnuse of the triangle?\n");
        float hypotnuse = get_float();
        printf("What is the opposite side of the triangle?\n");
        float opposite = get_float();
        sine(opposite, hypotnuse);
        printf ("The answer is %f", sine);

    }
    // else … cosine, tangent
}

float sine(float a, float b)
{
  return a/b;
}
</code>```

Whatever value I provide for hypotnuse and opposite, the output I get is 0.000000. Please explain what's wrong with the code?

答:
sine is the address of the function sine().

You must use the return value of the function sine():

```<code>float result = sine(opposite, hypotnuse);
printf("The answer is %f\n", result);
</code>```

There are different ways to do this in C, an other example that consume the result "on the fly" like jonathan-leffler propose:

```<code>printf("sine(%f, %f) = %f\n", opposite, hypotnuse, sine(opposite, hypotnuse));
</code>```

This is working because the result of the call to the function sine() is send directly to printf() as an argument.

Body:
#include <cs50.h>
#include <stdio.h>

float sine(float a, float b);

int main()
{
    printf ("Choose an option:\n1- Sin\n2-Cos\n3-Tan\n");
    int option = get_int();
    if (option==1)
    {
        printf("What is the hypotnuse of the triangle?\n");
        float hypotnuse = get_float();
        printf("What is the opposite side of the triangle?\n");
        float opposite = get_float();
        sine(opposite, hypotnuse);
        printf ("The answer is %f", sine);

    }
    // else … cosine, tangent
}

float sine(float a, float b)
{
  return a/b;
}

Whatever value I provide for hypotnuse and opposite, the output I get is 0.000000. Please explain what's wrong with the code?

Body:
sine is the address of the function sine().

You must use the return value of the function sine():

float result = sine(opposite, hypotnuse);
printf("The answer is %f\n", result);

There are different ways to do this in C, an other example that consume the result "on the fly" like jonathan-leffler propose:

printf("sine(%f, %f) = %f\n", opposite, hypotnuse, sine(opposite, hypotnuse));

This is working because the result of the call to the function sine() is send directly to printf() as an argument.


问:
Spring data mongo can't save GeoData b/c of No property type found
When trying to update an object with geoData spring data mongo throws the ff exception

org.springframework.data.mapping.context.InvalidPersistentPropertyPath: No property type found on org.springframework.data.mongodb.core.geo.GeoJsonGeometryCollection!

an example object structure is like this

```<code>class Location{
    ....
    @GeoSpatialIndexed(type = GeoSpatialIndexType.GEO_2DSPHERE)
    GeoJsonGeometryCollection geomerty
}
</code>```

repository

```<code>interface LocationRepository extends MongoRepository<Location, String> {

}
</code>```

the save method (which is called on update)

```<code>//the exception is thrown here
locationRepository.save(updatedLocation)
</code>```

I haven't added the type field, it is added by GeoJsonGeometryCollection conveter .

Any workaround is welcome.

答: It started working when I upgraded my spring boot version from 1.3 to 1.4</p>

Body:
When trying to update an object with geoData spring data mongo throws the ff exception

org.springframework.data.mapping.context.InvalidPersistentPropertyPath: No property type found on org.springframework.data.mongodb.core.geo.GeoJsonGeometryCollection!

an example object structure is like this

class Location{
    ....
    @GeoSpatialIndexed(type = GeoSpatialIndexType.GEO_2DSPHERE)
    GeoJsonGeometryCollection geomerty
}

repository

interface LocationRepository extends MongoRepository<Location, String> {

}

the save method (which is called on update)

//the exception is thrown here
locationRepository.save(updatedLocation)

I haven't added the type field, it is added by GeoJsonGeometryCollection conveter .

Any workaround is welcome.

ContentLicense: CC BY-SA 4.0


问:
How can I disable jobs in the Quartz JDBCJobStore?
What is the best way to disable a job in the JDBCJobStore without deleting it's job or trigger records and without wiping the cron expression?</p>

答:
Use scheduler.pauseJob() or scheduler.pauseTrigger().

Alternatively you can use the following SQL script:

```<code>UPDATE QRTZ_TRIGGERS SET TRIGGER_STATE = "PAUSED"
</code>```

Body:
Use scheduler.pauseJob() or scheduler.pauseTrigger().

Alternatively you can use the following SQL script:

UPDATE QRTZ_TRIGGERS SET TRIGGER_STATE = "PAUSED"


问:
Removing matching ID of 2 Eloquent collection in Laravel
I have this in the database:

```<code>item: id
item_propiety_list: id
found_item_propieties: item_id, item_propiety_list_id
</code>```

So for each $item I get a collection of found_item_propieties. If such propieties are not found, nothing is stored in found_item_propieties

I want to get an eloquent collection of the NOT FOUND item_propiety_list.

I already do this with SQL, but there is surely some way to do this in Eloquent.

Any advice?

答:
You can use where() collection method. If it's a standard Eloquent collection, this should work:

```<code>$notFound = $collection->where('found_item_properties', null);
</code>```

Update

You can use filter():

```<code>$notFound = $collection->filter(function($i) {
    return empty($i->found_item_properties);
});
</code>```

Body:
I have this in the database:

item: id
item_propiety_list: id
found_item_propieties: item_id, item_propiety_list_id

So for each $item I get a collection of found_item_propieties. If such propieties are not found, nothing is stored in found_item_propieties

I want to get an eloquent collection of the NOT FOUND item_propiety_list.

I already do this with SQL, but there is surely some way to do this in Eloquent.

Any advice?

Body:
You can use where() collection method. If it's a standard Eloquent collection, this should work:

$notFound = $collection->where('found_item_properties', null);

Update

You can use filter():

$notFound = $collection->filter(function($i) {
    return empty($i->found_item_properties);
});


问:
Dart Element: call function on embedded JS Object
In this particular case, it's for SVG.  I can get an SVG Element via a query as follows:

```<code>Element svgEL = querySelector('svg');
</code>```

If I look at the 'svgEL' object, it contains (in brief):

```<code>[[javascript view]]: svg
[[class]]: SvgSvgElementImpl
  ...
  getScreenCTM: function()       // I want to call this
  ...
</code>```

I presume I'd instantiate a JsObject on something and then do a callMethod on that, but I don't seem to be able to figure out how to make that work.

Any ideas?

答:
Thanks Jonas for the heads-up on the dart:svg library.

It turns out I didn't need it because I'm handling this in an event, and the event target object is the raw js 'g' object (this is on a mouseover).  So, I was able to get what I needed thusly:

```<code>var jsvg = event.target.ownerSvgElement;

var mtx = jsvg.getScreenCtm();
...
</code>```

And then I can create the point and do the inverse transform and all of that.

Body:
In this particular case, it's for SVG.  I can get an SVG Element via a query as follows:

Element svgEL = querySelector('svg');

If I look at the 'svgEL' object, it contains (in brief):

[[javascript view]]: svg
[[class]]: SvgSvgElementImpl
  ...
  getScreenCTM: function()       // I want to call this
  ...

I presume I'd instantiate a JsObject on something and then do a callMethod on that, but I don't seem to be able to figure out how to make that work.

Any ideas?

Body:
Thanks Jonas for the heads-up on the dart:svg library.

It turns out I didn't need it because I'm handling this in an event, and the event target object is the raw js 'g' object (this is on a mouseover).  So, I was able to get what I needed thusly:

var jsvg = event.target.ownerSvgElement;

var mtx = jsvg.getScreenCtm();
...

And then I can create the point and do the inverse transform and all of that.


问:
Blender Exporting OBJ - material is not exported
I am new to blender so I don't know how it works properly.

Here is my story,
I worked on a model and added material to it using the cycles render method.

Then I exported the project with these settings

To confirm that everything is right, I imported this model to a new blender

And I didn't get what I wanted

I wanted the materials to show up too

Does anyone know why this is happening,
Thanks in advance

答:
You can however export a single image texture with the obj without making a Blender internal material :

temporarily switch to Blender internal

enter Edit mode

in the UV/Image Editor, select the image

exit Edit mode

Switch back to Cycles

export

But you can't export multi-texture materials like Blender internal does.


问:
How do you package a keyboard layout for Windows 8?
I've been searching for a way to do this. I use a slightly modified Colemak keyboard layout and I can't figure out how to add it as a supported input method in the new language selection in Windows 8. The installer that the Colemak guys distribute sort of works; you can choose the layout after installing it, but it forces the EN-us language, and can't be chosen for other languages.

If anyone knows how to do this properly, I'm sure the Colemak guys would appreciate hearing about it, and it would let me make the modifications I want to.

答:
You can choose the language if you make your custom keyboard layout with MSKLC: in the "Properties" part, or, if it does not work (though I'm sure it does), you can edit the .klc file manually.

Build it and setup with the executable. You are done.


问:
Selenium Webdriver C# wait for existence when using PageFactory
I need to click an okay button which might appear after completing a field - it might take 5 seconds to appear. So i need (if) Wait for existence 5 seconds. I'm using PageFactory in a pages framework, I've seen some solutions but cant figure out how to implement them in this context.

```<code>[FindsBy(How = How.Name, Using = "OK")]
private IWebElement alertOKBtn;

public void PopulateFields //method to populate the form
{
   // Populate fields
   dateFromField.SendKeys(DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
   // Click on this field
   descriptionField.Click();

   //OK button might appear, might take 5secs - pseudcode
   if ( ***alertOKBtn exists, wait for it for 5 secs..*** )
   {
     alertOkBtn.Click();
   }

   //continue populating form

   }
</code>```

The PopulateFields method is called from the [Test] as:-

Pages.PTW.PopulateFields();

where Pages.PTW is a get method to PageFactory.InitElements(browser.Driver, page); return page;

答:
Managed to resolve it - in PopulateFields i now do this:-

```<code>          //wait to see if alert popup appears - give it 8 secs
        string waitToSee = browser.wait(alertOKBtn, 8);

        if ( waitToSee == "true" )
        {
            alertOKBtn.Click(); //alert popup did appear

        }
</code>```

Then I've added a method to my browser.class :-

```<code>    public static string wait(IWebElement elem, int timeout  ) //waits for existence of element up to timeout amount
    {
        try
        {
            var wait = new WebDriverWait(webDriver, TimeSpan.FromSeconds(timeout));
            wait.Until(ExpectedConditions.ElementToBeClickable(elem));
            return "true";
        }
        catch (Exception e ) //didnt appear so exception thrown return false

        {
            return "false";
        }
</code>```

So it now waits up to 8 seconds and if it doesnt appear it ignores and moves on. Thanks Bendram for the pointers.

Body:
I need to click an okay button which might appear after completing a field - it might take 5 seconds to appear. So i need (if) Wait for existence 5 seconds. I'm using PageFactory in a pages framework, I've seen some solutions but cant figure out how to implement them in this context.

[FindsBy(How = How.Name, Using = "OK")]
private IWebElement alertOKBtn;

public void PopulateFields //method to populate the form
{
   // Populate fields
   dateFromField.SendKeys(DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
   // Click on this field
   descriptionField.Click();

   //OK button might appear, might take 5secs - pseudcode
   if ( ***alertOKBtn exists, wait for it for 5 secs..*** )
   {
     alertOkBtn.Click();
   }

   //continue populating form

   }

The PopulateFields method is called from the [Test] as:-

Pages.PTW.PopulateFields();

where Pages.PTW is a get method to PageFactory.InitElements(browser.Driver, page); return page;

Body:
Managed to resolve it - in PopulateFields i now do this:-

          //wait to see if alert popup appears - give it 8 secs
        string waitToSee = browser.wait(alertOKBtn, 8);

        if ( waitToSee == "true" )
        {
            alertOKBtn.Click(); //alert popup did appear

        }

Then I've added a method to my browser.class :-

    public static string wait(IWebElement elem, int timeout  ) //waits for existence of element up to timeout amount
    {
        try
        {
            var wait = new WebDriverWait(webDriver, TimeSpan.FromSeconds(timeout));
            wait.Until(ExpectedConditions.ElementToBeClickable(elem));
            return "true";
        }
        catch (Exception e ) //didnt appear so exception thrown return false

        {
            return "false";
        }

So it now waits up to 8 seconds and if it doesnt appear it ignores and moves on. Thanks Bendram for the pointers.


问:
How can I reinitialize a bootstrap datepicker?
A bootstrap datepicker is initialized on load. How can I change the options for that datepicker after the page is loaded and the datepicker has already been initialized?

See here for an example http://jsfiddle.net/Leoqs1xg/

The weekStart is set to 4 (Thursday) at first with

```<code>$('#mydate').datepicker({weekStart: 4});
</code>```

but if I change it to something else with

```<code>$('#mydate').datepicker({weekStart: 1});
</code>```

weekStart is still 4.

答:
There is no re-initialization. However if you update the value of the input programmatically, for example another part of your code, and want to see the change when you open the picker you could use setDate to read the new value.</p>

```<code>// var mynewdate = your-converted-to-date-string;
$('.datepicker').datepicker('setDate', mynewdate);
</code>```

Body:
A bootstrap datepicker is initialized on load. How can I change the options for that datepicker after the page is loaded and the datepicker has already been initialized?

See here for an example http://jsfiddle.net/Leoqs1xg/

The weekStart is set to 4 (Thursday) at first with

$('#mydate').datepicker({weekStart: 4});

but if I change it to something else with

$('#mydate').datepicker({weekStart: 1});

weekStart is still 4.

Body:
There is no re-initialization. However if you update the value of the input programmatically, for example another part of your code, and want to see the change when you open the picker you could use setDate to read the new value.

// var mynewdate = your-converted-to-date-string;
$('.datepicker').datepicker('setDate', mynewdate);


问:
Removing code from GitHub
Is there a way to entirely remove a directory and its history from GitHub?</p>

答: Go to the edit tab; there’s a delete link at the bottom of the page.</p>

OwnerDisplayName: namin

Title: Removing code from GitHub

OwnerDisplayName: Rich B


问:
memcpy to string buffer defined in macro
i am using avrx to build a software run on custom tiny device, but i'm still newbie to C.
As indicated by makefile, it's using "c99 plus GCC extensions".
Today i finally ran into a piece of code written by some old colleague, it made me very confused:

```<code>#define SOMEDATA    "ABC"
void main(void)
{
    memcpy(SOMEDATA, "OK", sizeof("OK"));
    printf(SOMEDATA);//it works just fine?!?!?

    memcpy(SOMEDATA, "VERY_LONG", sizeof("VERY_LONG"));
    printf(SOMEDATA);//well, now it go nuts. all i see is some random data.
}
</code>```

Why?
Why the logic in main() behaved like that? I used to thought that MACROs acts like constant and cannot be modified.

答:
In your code

```<code>  memcpy(SOMEDATA, "OK", sizeof("OK"));
</code>```

which is the same as

```<code>  memcpy("ABC", "OK", sizeof("OK"));
</code>```

is a very unusual way of attempting to modify a string literal. It  causes undefined behavior. Same as in the other case and, as we know, the outcome of UB is, well, anything.

That said,

```<code>   printf(SOMEDATA);
</code>```

may be valid but a poor practice, if there's no conversion required, safer to use puts() or fputs().

Finally,

I used to thought that MACROs acts like constant and cannot be modified.

Well, probably you're interested in #define statements. #define statements are textual replacements which takes place at compile time. In case, a literal (or constant) value is used as a define statement, yes, it cannot be changed (following the property of a constant or literal) but in case, a define statement defines a variable name, then that variable, if a modifiable lvalue, can be modified for sure.

TL;DR #define statements are textual replacement, and their alteration depends on the element in replacement list.

Body:
i am using avrx to build a software run on custom tiny device, but i'm still newbie to C.
As indicated by makefile, it's using "c99 plus GCC extensions".
Today i finally ran into a piece of code written by some old colleague, it made me very confused:

#define SOMEDATA    "ABC"
void main(void)
{
    memcpy(SOMEDATA, "OK", sizeof("OK"));
    printf(SOMEDATA);//it works just fine?!?!?

    memcpy(SOMEDATA, "VERY_LONG", sizeof("VERY_LONG"));
    printf(SOMEDATA);//well, now it go nuts. all i see is some random data.
}

Why?
Why the logic in main() behaved like that? I used to thought that MACROs acts like constant and cannot be modified.

Body:
In your code

  memcpy(SOMEDATA, "OK", sizeof("OK"));

which is the same as

  memcpy("ABC", "OK", sizeof("OK"));

is a very unusual way of attempting to modify a string literal. It  causes undefined behavior. Same as in the other case and, as we know, the outcome of UB is, well, anything.

That said,

   printf(SOMEDATA);

may be valid but a poor practice, if there's no conversion required, safer to use puts() or fputs().

Finally,

I used to thought that MACROs acts like constant and cannot be modified.

Well, probably you're interested in #define statements. #define statements are textual replacements which takes place at compile time. In case, a literal (or constant) value is used as a define statement, yes, it cannot be changed (following the property of a constant or literal) but in case, a define statement defines a variable name, then that variable, if a modifiable lvalue, can be modified for sure.

TL;DR #define statements are textual replacement, and their alteration depends on the element in replacement list.


问:
TYPO3 Extbase query with CONCAT
Is it possible to use CONCAT in an extbase query like this one?

```<code>$query = $this->createQuery();
$query
  ->matching(
    $query->logicalOr(
      $query->like('street', '%' . $search . '%'),
      $query->like('street_number', '%' . $search . '%'),
    )
  )
  ->execute();
</code>```

Now, I'ld like to also query for CONCAT(street, ' ', street_number).

The resulting SQL query should look like this:

```<code>SELECT * FROM myTable WHERE street LIKE '%abc%' OR street_number LIKE '%abc%' OR CONCAT(street, ' ', street_number) LIKE '%abc%';
</code>```

答:
You may use statement() for this kind of query if you are using TYPO3 below version 8 LTS.

```<code>$query = $this->createQuery();
$query
  ->statement('SELECT * FROM myTable WHERE street LIKE "%abc%" OR street_number LIKE "%abc%" OR CONCAT(street, " ", street_number) LIKE "%abc%"')
  )
  ->execute();
</code>```

In TYPO3 8 LTS the new Doctrine DBAL should have functions for this, too. But I don't have a snippet next to my hand right now.

Title: TYPO3 Extbase query with CONCAT

Body:
Is it possible to use CONCAT in an extbase query like this one?

$query = $this->createQuery();
$query
  ->matching(
    $query->logicalOr(
      $query->like('street', '%' . $search . '%'),
      $query->like('street_number', '%' . $search . '%'),
    )
  )
  ->execute();

Now, I'ld like to also query for CONCAT(street, ' ', street_number).

The resulting SQL query should look like this:

SELECT * FROM myTable WHERE street LIKE '%abc%' OR street_number LIKE '%abc%' OR CONCAT(street, ' ', street_number) LIKE '%abc%';

Body:
You may use statement() for this kind of query if you are using TYPO3 below version 8 LTS.

$query = $this->createQuery();
$query
  ->statement('SELECT * FROM myTable WHERE street LIKE "%abc%" OR street_number LIKE "%abc%" OR CONCAT(street, " ", street_number) LIKE "%abc%"')
  )
  ->execute();

In TYPO3 8 LTS the new Doctrine DBAL should have functions for this, too. But I don't have a snippet next to my hand right now.


问:
php artisan serve -- throws error
So I just beginning learning Laravel today and installed Composer and Laravel

I created a new application using :-

```<code>laravel new application
</code>```

in my folder :-

```<code>/Library/WebServer/Documents/
</code>```

However, when I try to run :-

```<code>php artisan serve
</code>```

I get this error :-

```<code>Warning: require(/Library/WebServer/Documents/application/bootstrap/../vendor/autoload.php): failed to open stream: No such file or directory in /Library/WebServer/Documents/application/bootstrap/autoload.php on line 17

Fatal error: require(): Failed opening required '/Library/WebServer/Documents/application/bootstrap/../vendor/autoload.php' (include_path='.:') in /Library/WebServer/Documents/application/bootstrap/autoload.php on line 17
</code>```

I've already tried updating my composer, didn't work.
What am I doing wrong here?

Edit

Running composer install gives this :-

```<code>Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - This package requires php >=5.6.4 but your PHP version (5.5.34) does not satisfy that requirement.
  Problem 2
    - Installation request for laravel/framework v5.4.24 -> satisfiable by laravel/framework[v5.4.24].
    - laravel/framework v5.4.24 requires php >=5.6.4 -> your PHP version (5.5.34) does not satisfy that requirement.
  Problem 3
    - Installation request for phpunit/php-code-coverage 4.0.8 -> satisfiable by phpunit/php-code-coverage[4.0.8].
    - phpunit/php-code-coverage 4.0.8 requires php ^5.6 || ^7.0 -> your PHP version (5.5.34) does not satisfy that requirement.
  Problem 4
    - Installation request for phpunit/phpunit 5.7.20 -> satisfiable by phpunit/phpunit[5.7.20].
    - phpunit/phpunit 5.7.20 requires php ^5.6 || ^7.0 -> your PHP version (5.5.34) does not satisfy that requirement.
  Problem 5
    - Installation request for phpunit/phpunit-mock-objects 3.4.3 -> satisfiable by phpunit/phpunit-mock-objects[3.4.3].
    - phpunit/phpunit-mock-objects 3.4.3 requires php ^5.6 || ^7.0 -> your PHP version (5.5.34) does not satisfy that requirement.
  Problem 6
    - Installation request for sebastian/code-unit-reverse-lookup 1.0.1 -> satisfiable by sebastian/code-unit-reverse-lookup[1.0.1].
    - sebastian/code-unit-reverse-lookup 1.0.1 requires php ^5.6 || ^7.0 -> your PHP version (5.5.34) does not satisfy that requirement.
  Problem 7
    - Installation request for sebastian/environment 2.0.0 -> satisfiable by sebastian/environment[2.0.0].
    - sebastian/environment 2.0.0 requires php ^5.6 || ^7.0 -> your PHP version (5.5.34) does not satisfy that requirement.
  Problem 8
    - Installation request for sebastian/object-enumerator 2.0.1 -> satisfiable by sebastian/object-enumerator[2.0.1].
    - sebastian/object-enumerator 2.0.1 requires php >=5.6 -> your PHP version (5.5.34) does not satisfy that requirement.
  Problem 9
    - Installation request for sebastian/resource-operations 1.0.0 -> satisfiable by sebastian/resource-operations[1.0.0].
    - sebastian/resource-operations 1.0.0 requires php >=5.6.0 -> your PHP version (5.5.34) does not satisfy that requirement.
  Problem 10
    - Installation request for sebastian/version 2.0.1 -> satisfiable by sebastian/version[2.0.1].
    - sebastian/version 2.0.1 requires php >=5.6 -> your PHP version (5.5.34) does not satisfy that requirement.
  Problem 11
    - laravel/framework v5.4.24 requires php >=5.6.4 -> your PHP version (5.5.34) does not satisfy that requirement.
    - laravel/tinker v1.0.1 requires illuminate/console ~5.1 -> satisfiable by laravel/framework[v5.4.24].
    - Installation request for laravel/tinker v1.0.1 -> satisfiable by laravel/tinker[v1.0.1].
</code>```

答:
Note:You are using laravel 5.4, which requires php 5.6(minimum), either update your php to 5.6 or use laravel 5.2, that is the reason
  use this command to install laravel 5.2

```<code>composer create-project --prefer-dist laravel/laravel your_project_name "5.2.*"
</code>```

Go to Command Prompt(In Windows)

set path to www/{ur project}

For me : www/laravel5

Then type this command : composer install

It will automatically install all dependency in vendor/

Title: php artisan serve -- throws error

Body:
So I just beginning learning Laravel today and installed Composer and Laravel

I created a new application using :-

laravel new application

in my folder :-

/Library/WebServer/Documents/

However, when I try to run :-

php artisan serve

I get this error :-

Warning: require(/Library/WebServer/Documents/application/bootstrap/../vendor/autoload.php): failed to open stream: No such file or directory in /Library/WebServer/Documents/application/bootstrap/autoload.php on line 17

Fatal error: require(): Failed opening required '/Library/WebServer/Documents/application/bootstrap/../vendor/autoload.php' (include_path='.:') in /Library/WebServer/Documents/application/bootstrap/autoload.php on line 17

I've already tried updating my composer, didn't work.
What am I doing wrong here?

Edit

Running composer install gives this :-

Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - This package requires php >=5.6.4 but your PHP version (5.5.34) does not satisfy that requirement.
  Problem 2
    - Installation request for laravel/framework v5.4.24 -> satisfiable by laravel/framework[v5.4.24].
    - laravel/framework v5.4.24 requires php >=5.6.4 -> your PHP version (5.5.34) does not satisfy that requirement.
  Problem 3
    - Installation request for phpunit/php-code-coverage 4.0.8 -> satisfiable by phpunit/php-code-coverage[4.0.8].
    - phpunit/php-code-coverage 4.0.8 requires php ^5.6 || ^7.0 -> your PHP version (5.5.34) does not satisfy that requirement.
  Problem 4
    - Installation request for phpunit/phpunit 5.7.20 -> satisfiable by phpunit/phpunit[5.7.20].
    - phpunit/phpunit 5.7.20 requires php ^5.6 || ^7.0 -> your PHP version (5.5.34) does not satisfy that requirement.
  Problem 5
    - Installation request for phpunit/phpunit-mock-objects 3.4.3 -> satisfiable by phpunit/phpunit-mock-objects[3.4.3].
    - phpunit/phpunit-mock-objects 3.4.3 requires php ^5.6 || ^7.0 -> your PHP version (5.5.34) does not satisfy that requirement.
  Problem 6
    - Installation request for sebastian/code-unit-reverse-lookup 1.0.1 -> satisfiable by sebastian/code-unit-reverse-lookup[1.0.1].
    - sebastian/code-unit-reverse-lookup 1.0.1 requires php ^5.6 || ^7.0 -> your PHP version (5.5.34) does not satisfy that requirement.
  Problem 7
    - Installation request for sebastian/environment 2.0.0 -> satisfiable by sebastian/environment[2.0.0].
    - sebastian/environment 2.0.0 requires php ^5.6 || ^7.0 -> your PHP version (5.5.34) does not satisfy that requirement.
  Problem 8
    - Installation request for sebastian/object-enumerator 2.0.1 -> satisfiable by sebastian/object-enumerator[2.0.1].
    - sebastian/object-enumerator 2.0.1 requires php >=5.6 -> your PHP version (5.5.34) does not satisfy that requirement.
  Problem 9
    - Installation request for sebastian/resource-operations 1.0.0 -> satisfiable by sebastian/resource-operations[1.0.0].
    - sebastian/resource-operations 1.0.0 requires php >=5.6.0 -> your PHP version (5.5.34) does not satisfy that requirement.
  Problem 10
    - Installation request for sebastian/version 2.0.1 -> satisfiable by sebastian/version[2.0.1].
    - sebastian/version 2.0.1 requires php >=5.6 -> your PHP version (5.5.34) does not satisfy that requirement.
  Problem 11
    - laravel/framework v5.4.24 requires php >=5.6.4 -> your PHP version (5.5.34) does not satisfy that requirement.
    - laravel/tinker v1.0.1 requires illuminate/console ~5.1 -> satisfiable by laravel/framework[v5.4.24].
    - Installation request for laravel/tinker v1.0.1 -> satisfiable by laravel/tinker[v1.0.1].

Body:
Note:You are using laravel 5.4, which requires php 5.6(minimum), either update your php to 5.6 or use laravel 5.2, that is the reason
  use this command to install laravel 5.2

composer create-project --prefer-dist laravel/laravel your_project_name "5.2.*"

Go to Command Prompt(In Windows)

set path to www/{ur project}

For me : www/laravel5

Then type this command : composer install

It will automatically install all dependency in vendor/


问:
How to save TextBox text to text file using streamwriter
Firstoff I have to say that I am new to the c# programming. My problem is, that I have a window with a textbox and a button in it and what I am trying to accomplish is to write some text into the textbox and on button click I'd like to save that text into the ukony.txt file. But using the code bellow, after clicking a button nothing happens.</p>

```<code>public partial class Window1 : Window {
    public Window1() {
        InitializeComponent();

    }

    private void button_Click(object sender, RoutedEventArgs e)
        {
        string writerfile = @"D:\Games\ukony.txt";
        Window1 a = new Window1();
        using (StreamWriter writer = new StreamWriter(writerfile))
            {
            writer.WriteLine(a.textBlock.Text);
            writer.WriteLine(a.textBlock1.Text);
            }
        }
    }
</code>```

答:
don't use a new instance of the window. Use the current one. To access the textblocks of the current instance you should use the this keyword:

```<code>private void button_Click(object sender, RoutedEventArgs e)
{
    string writerfile = @"D:\Games\ukony.txt";

    using (StreamWriter writer = new StreamWriter(writerfile))
    {
        writer.WriteLine(this.textBlock.Text);
        writer.WriteLine(this.textBlock1.Text);
    }
}
</code>```

Problem in detail: with this line:

```<code>Window1 a = new Window1();
</code>```

you create a new Window with empty controls. These are not the same as the ones you see on the screen and in which you have probably typed in something.

Body:
Firstoff I have to say that I am new to the c# programming. My problem is, that I have a window with a textbox and a button in it and what I am trying to accomplish is to write some text into the textbox and on button click I'd like to save that text into the ukony.txt file. But using the code bellow, after clicking a button nothing happens.

public partial class Window1 : Window {
    public Window1() {
        InitializeComponent();

    }

    private void button_Click(object sender, RoutedEventArgs e)
        {
        string writerfile = @"D:\Games\ukony.txt";
        Window1 a = new Window1();
        using (StreamWriter writer = new StreamWriter(writerfile))
            {
            writer.WriteLine(a.textBlock.Text);
            writer.WriteLine(a.textBlock1.Text);
            }
        }
    }

Body:
don't use a new instance of the window. Use the current one. To access the textblocks of the current instance you should use the this keyword:

private void button_Click(object sender, RoutedEventArgs e)
{
    string writerfile = @"D:\Games\ukony.txt";

    using (StreamWriter writer = new StreamWriter(writerfile))
    {
        writer.WriteLine(this.textBlock.Text);
        writer.WriteLine(this.textBlock1.Text);
    }
}

Problem in detail: with this line:

Window1 a = new Window1();

you create a new Window with empty controls. These are not the same as the ones you see on the screen and in which you have probably typed in something.


问:
How to make Heroku recoginize file that is hidden by gitignore?
So I'm developing a Flask app and use Heroku as my server. It works fine until I put my app_secret, app_id and some other sensitive info into a file (config.py) and use gitignore to hide it. Now even Heroku couldn't find it. Is there a way to get around this?</p>

答:
Gitignore files are entirely ignored from your GIT repository by design.
They remain only on your own machine, and are never sent to the repository.

Therefore, Heroku cannot get them.

You need to regenerate those files on your instance, or even better, use configuration variables.


问:
How should I handle the key events in J2ME?
How should I handle the key events for CustomItem in J2ME?

答: I got the solution. We should override the method "protected void keyPressed(int key)" of CustomItem in the derived class of CustomItem.</p>


问:
cannot set UILabel padding in tableViewcell
I have set my UILabel padding using StackOverflow's popular thread for resolving auto-layout issue.
This thread is basically a UILabel extension.

Part of the answer is:

```<code>class NRLabel : UILabel {

    var textInsets = UIEdgeInsets.zero {
        didSet { invalidateIntrinsicContentSize() }
    }

    override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
        let insetRect = UIEdgeInsetsInsetRect(bounds, textInsets)
        let textRect = super.textRect(forBounds: insetRect, limitedToNumberOfLines: numberOfLines)
        let invertedInsets = UIEdgeInsets(top: -textInsets.top,
                                          left: -textInsets.left,
                                          bottom: -textInsets.bottom,
                                          right: -textInsets.right)
        return UIEdgeInsetsInsetRect(textRect, invertedInsets)
    }

    override func drawText(in rect: CGRect) {
        super.drawText(in: UIEdgeInsetsInsetRect(rect, textInsets))
    }
}
</code>```

Everything is working fine, padding has been added but i need to reload the tableViewcell to see the effect.

I have  overridden my customCell's viewWillLayoutSubviews() function like this for padding

```<code> self.chatLabel.textInsets = UIEdgeInsets.init(top: 10, left: 10, bottom: 10, right: 10)
</code>```

And the effect is like this.

You see, first label is getting it's padding after reloading the cell.

Pls suggest how to  achieve UILabel padding by using the extension mentioned above so that this issue is resolved.

答:
Using your NRLabel class, this works fine for me. The theLabel is added in Storyboard TableViewCell Prototype, with constraints set to allow auto-sizing rows.

```<code>class PaddedLabelCell : UITableViewCell {

    @IBOutlet weak var theLabel: NRLabel!

    override func awakeFromNib() {
        super.awakeFromNib()
        self.setupLabel()
    }

    func setupLabel() -> Void {
        theLabel.layer.cornerRadius = 8.0
        theLabel.layer.masksToBounds = true
        theLabel.textInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
        // any other setup stuff can go here....
    }

}
</code>```

Body:
I have set my UILabel padding using StackOverflow's popular thread for resolving auto-layout issue.
This thread is basically a UILabel extension.

Part of the answer is:

class NRLabel : UILabel {

    var textInsets = UIEdgeInsets.zero {
        didSet { invalidateIntrinsicContentSize() }
    }

    override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
        let insetRect = UIEdgeInsetsInsetRect(bounds, textInsets)
        let textRect = super.textRect(forBounds: insetRect, limitedToNumberOfLines: numberOfLines)
        let invertedInsets = UIEdgeInsets(top: -textInsets.top,
                                          left: -textInsets.left,
                                          bottom: -textInsets.bottom,
                                          right: -textInsets.right)
        return UIEdgeInsetsInsetRect(textRect, invertedInsets)
    }

    override func drawText(in rect: CGRect) {
        super.drawText(in: UIEdgeInsetsInsetRect(rect, textInsets))
    }
}

Everything is working fine, padding has been added but i need to reload the tableViewcell to see the effect.

I have  overridden my customCell's viewWillLayoutSubviews() function like this for padding

 self.chatLabel.textInsets = UIEdgeInsets.init(top: 10, left: 10, bottom: 10, right: 10)

And the effect is like this.

You see, first label is getting it's padding after reloading the cell.

Pls suggest how to  achieve UILabel padding by using the extension mentioned above so that this issue is resolved.

Body:
Using your NRLabel class, this works fine for me. The theLabel is added in Storyboard TableViewCell Prototype, with constraints set to allow auto-sizing rows.

class PaddedLabelCell : UITableViewCell {

    @IBOutlet weak var theLabel: NRLabel!

    override func awakeFromNib() {
        super.awakeFromNib()
        self.setupLabel()
    }

    func setupLabel() -> Void {
        theLabel.layer.cornerRadius = 8.0
        theLabel.layer.masksToBounds = true
        theLabel.textInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
        // any other setup stuff can go here....
    }

}


问:
How to get aws instance metadata remotely using CLI?
I am very new to AWS. I have a Windows Server EC2 instance. I installed AWS CLI on my laptop. Then I opened a CMD window, typed in "aws configure", put in the access key credentials, and was able to connect to the EC2.

From here, how do I get the http://169.254.169.254/latest/meta-data working? How do I retrieve some meta data?

答:
When running on an EC2 instance, you can query the metadata service, like so:

```<code>curl http://169.254.169.254/latest/meta-data/public-ipv4
</code>```

You can also use:

```<code>curl http://instance-data/latest/meta-data/public-ipv4
</code>```

From outside the EC2 instance, you can use the awscli, like so:

```<code>aws ec2 describe-instances
    --instance-ids i-01234567890123456
    --query "Reservations[0].Instances[0].PublicIpAddress"
    --output text
</code>```

Body:
When running on an EC2 instance, you can query the metadata service, like so:

curl http://169.254.169.254/latest/meta-data/public-ipv4

You can also use:

curl http://instance-data/latest/meta-data/public-ipv4

From outside the EC2 instance, you can use the awscli, like so:

aws ec2 describe-instances
    --instance-ids i-01234567890123456
    --query "Reservations[0].Instances[0].PublicIpAddress"
    --output text


问:
NSStrikethroughStyleAttributeName , How to strike out the string in iOS 10.3?
I have used this line of code before release of iOS 10.3 ,and worked fine.

```<code>NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@\n%@",strMRP,strOffer]];

[attributeString addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:12] range:NSMakeRange(0, strMRP.length)];

[attributeString addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:15] range:NSMakeRange(strMRP.length, strOffer.length+1)];

[attributeString addAttribute:NSStrikethroughStyleAttributeName
                        value:[NSNumber numberWithInteger: NSUnderlineStyleDouble]
                        range:NSMakeRange(0,strMRP.length)];
</code>```

But now it is stopped working ,is there any alternate way to do the strike out ?

答:
Just Use this :-

NSMutableAttributedString *costPrice = [[NSMutableAttributedString
  alloc] initWithString:[NSString stringWithFormat:@"₹ %@",strDetails]];
  [costPrice addAttribute:NSBaselineOffsetAttributeName
                              value:[NSNumber numberWithInteger: NSUnderlineStyleSingle] range:NSMakeRange(0,costPrice.length)];

This is temp solution . Hope it works

Body:
I have used this line of code before release of iOS 10.3 ,and worked fine.

NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@\n%@",strMRP,strOffer]];

[attributeString addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:12] range:NSMakeRange(0, strMRP.length)];

[attributeString addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:15] range:NSMakeRange(strMRP.length, strOffer.length+1)];

[attributeString addAttribute:NSStrikethroughStyleAttributeName
                        value:[NSNumber numberWithInteger: NSUnderlineStyleDouble]
                        range:NSMakeRange(0,strMRP.length)];

But now it is stopped working ,is there any alternate way to do the strike out ?


问:
Detect body scroll offset
I need to put the scrolling behaviour on the body rather than the HTML, due to using CSS Parallax. However, I have got an issue with adding sticky classes to my header using JavaScript.

I need to be able to detect that the body has scrolled, this works fine, however i'm unable to get the offset that the user has scrolled to!

I have tried everything when is online, for example:

```<code>$('body').scrollTop()
document.body.scrollTop
document.getElementsByTagName('body')[0].pageYOffset
</code>```

None of this is working, it always returns 0!

Edit:

I can't modify any of the HTML apart from what is between the comments.

```<code><html>
  <body>
    <div itemscope itemtype="http://schema.org/AutoDealer">
      <div id="main-wrap" class="parallax">
        <div class="row">
          <div class="main twelvecol">

            <!-- Editable -->
            <div>
              <div class="row-block finance parallax__group">
                <div class="parallax__layer--back parallax__layer"></div>
                <div class="wrapper">
                  <div class="container">
                    <div class="parallax__layer--base parallax__layer">
                      <p>This is all of the top level content</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <!-- END Editable -->

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

here is a codepen showing the various examples not working
https://codepen.io/anon/pen/RgPrQv

答:
You are looking for</p>

```<code>$(window).scroll(function() {
    $(window).scrollTop();
});
</code>```

Title: Detect body scroll offset

Body:
I need to put the scrolling behaviour on the body rather than the HTML, due to using CSS Parallax. However, I have got an issue with adding sticky classes to my header using JavaScript.

I need to be able to detect that the body has scrolled, this works fine, however i'm unable to get the offset that the user has scrolled to!

I have tried everything when is online, for example:

$('body').scrollTop()
document.body.scrollTop
document.getElementsByTagName('body')[0].pageYOffset

None of this is working, it always returns 0!

Edit:

I can't modify any of the HTML apart from what is between the comments.

This is all of the top level content

here is a codepen showing the various examples not working
https://codepen.io/anon/pen/RgPrQv

Body:
You are looking for

$(window).scroll(function() {
    $(window).scrollTop();
});