问:
Python global vs local variables?
I'm having trouble understanding why my code works the way it does. Right now, I'm initializing a global variable i set to 0, so it makes sense that if I print it anywhere outside my function, I should get 0.

When I print i inside the function, I get 6 and 12 after calling the function twice. I think this is because the global i is 0, but some local i variable isn't. However, when I'm calling reach_load with i as a parameter, aren't I passing in the global value of i (0)?

```<code>import sys

d = {}
size_0 = sys.getsizeof(d)
i = 0

def reach_load(d, size_0, i):
    size_0 = sys.getsizeof(d)
    while size_0 == sys.getsizeof(d):
        d[i] = i
        i += 1
    print(i)

reach_load(d, size_0, i)
reach_load(d, size_0, i)
</code>```

答: Because the i parameter to reach_load is a formal parameter it's local to the function. It's a local variable with the same label. If you really want to increment the global one, then put global i it the top of the function. However, this is considered bad design. If you need to keep some state define a new object with class to keep it.

Title: Python global vs local variables?

Body:
I'm having trouble understanding why my code works the way it does. Right now, I'm initializing a global variable i set to 0, so it makes sense that if I print it anywhere outside my function, I should get 0.

When I print i inside the function, I get 6 and 12 after calling the function twice. I think this is because the global i is 0, but some local i variable isn't. However, when I'm calling reach_load with i as a parameter, aren't I passing in the global value of i (0)?

import sys

d = {}
size_0 = sys.getsizeof(d)
i = 0

def reach_load(d, size_0, i):
    size_0 = sys.getsizeof(d)
    while size_0 == sys.getsizeof(d):
        d[i] = i
        i += 1
    print(i)

reach_load(d, size_0, i)
reach_load(d, size_0, i)


来源: stackexchange

问:
cmake and make build reproductibility
I'm evaluating the use of cmake to generate makefile for embedded FW. The cmakelists.txt will be shared in the team.

Can you confirm the makefile cannot be shared between different computers ?

Is this still true if project path is identical on both computers ?

Using cmake makefile generation and same version of compiler, will the generated binary be the same on all computers ?

Is this the same behavior as a makefile shared in the project ?

答:
Why would you share a generated makefile anyway!? You usually share the cmake files.

Can you confirm the makefile cannot be shared between different computers ?

You should not share the makefile. It's generated only for you and includes local information as well as the cmake (cached) options and state. There's no serious reason to actually do this!

Is this still true if project path is identical on both computers ?

Yes, because cmake maintains a cache of settings, options etc. So the makefile may differ depending on paths, options and states. You also have to guarantee the paths for any dependency.

Using cmake makefile generation and same version of compiler, will the generated binary be the same on all computers ?

If environment (Compiler, libraries, …) and options (build type, project options, …) are same, Cmake will reliable produce exact the same binaries on all systems.

Is this the same behavior as a makefile shared in the project ?

No, CMake is much better: it's cross-platform. It doesn't depend on make, you can use any other system (like ninja or an IDE project) too – without touching your source or cmake code.

CMake does much more than just creating a makefile. You can even compile a CMake based project with several different compiler / cross-compiler without a single change.

TL;DR

Don't share generated Makfiles, share the Cmake sourcefiles instead – that's what CMake is used for.

ContentLicense: CC BY-SA 3.0

Title: cmake and make build reproductibility


问:
How to differentiate model classes between webapp and unittest
I've started looking in to unittest when using google app engine. And it seems to bit tricky from what I've read. Since you can't (and not suppose to) run your test's against the datastore.

I've written an abstract class to emulate a datastore model class. And it quite works pretty nice returning mockup data on get, all, fetch and so on (only tried on a small scale) returning dbModel like results.

The one thing I haven't found a solution I'm satisfied with is how to differentiate which model class to use. I want to use the mock-ups for unit tests and the actual db.Model for when webapp is running.

My current solution looks like this in my .py containing all db.Models:

```<code>if 'SERVER_SOFTWARE' in os.environ:
    class dbTest(db.Model):
        content = db.StringProperty()
        comments = db.ListProperty(str)
else:
    class dbTest(Abstract):
        content = 'Test'
        comments = ['test1', 'test2']
</code>```

And it kinda feels like it could break any minute. Is this the way to go or could one combine these as one class and if the db.Model is invoked properly use that else the mockup?

答:
Check out gaetestbed (docs). It stubs out the datastore (and all the other services like memcache) and makes testing from the command line very easy. It ensures a clean environment before every test runs.

I personally think it is nicer than the other solutions I have seen.

ContentLicense: CC BY-SA 2.5

Body:
I've started looking in to unittest when using google app engine. And it seems to bit tricky from what I've read. Since you can't (and not suppose to) run your test's against the datastore.

I've written an abstract class to emulate a datastore model class. And it quite works pretty nice returning mockup data on get, all, fetch and so on (only tried on a small scale) returning dbModel like results.

The one thing I haven't found a solution I'm satisfied with is how to differentiate which model class to use. I want to use the mock-ups for unit tests and the actual db.Model for when webapp is running.

My current solution looks like this in my .py containing all db.Models:

if 'SERVER_SOFTWARE' in os.environ:
    class dbTest(db.Model):
        content = db.StringProperty()
        comments = db.ListProperty(str)
else:
    class dbTest(Abstract):
        content = 'Test'
        comments = ['test1', 'test2']

And it kinda feels like it could break any minute. Is this the way to go or could one combine these as one class and if the db.Model is invoked properly use that else the mockup?


问:
Materialize css DataTable
I am making a simple demo with Angular 2 using materialize css.
I want to know is it possible with materialize to design a proper datatable like i found here  http://danielnagy.me/md-data-table/

If yes then please suggest me or any link that can help me.

Here is my simple code :

```<code>    <div class="row">
       <div class="col l8">
  <div class="card z-depth-1">
     <div class="card-content">
        <span class="card-title">{{tableTitle}}</span><br/><br/>
        <table class="centered bordered responsive-table">
           <thead>
              <tr>
                 <th>#</th>
                 <th>Name</th>
                 <th>Age</th>
                 <th>Address</th>
                 <th>Designation</th>
                 <th>Department</th>
                 <th>Salary</th>
              </tr>
           </thead>
           <tbody>
              <tr *ngFor="let item of empData;let i=index">
                 <td>{{i+1}}</td>
                 <td>{{item.Name}}</td>
                 <td>{{item.Age}}</td>
                 <td>{{item.Address}}</td>
                 <td>{{item.Designation}}</td>
                 <td>{{item.Department}}</td>
                 <td>{{item.Salary}}</td>
              </tr>
           </tbody>
        </table>
     </div>
  </div>
</code>```

答:
You can proceed with Tera Data covalent. You can check it here.
https://teradata.github.io/covalent/#/components/data-table

I have checked this, This is really easy and just need to follow few steps to integrate.

Title: Materialize css DataTable

Body:
I am making a simple demo with Angular 2 using materialize css.
I want to know is it possible with materialize to design a proper datatable like i found here  http://danielnagy.me/md-data-table/

If yes then please suggest me or any link that can help me.

Here is my simple code :

        {{tableTitle}}

                 #
                 Name
                 Age
                 Address
                 Designation
                 Department
                 Salary

                 {{i+1}}
                 {{item.Name}}
                 {{item.Age}}
                 {{item.Address}}
                 {{item.Designation}}
                 {{item.Department}}
                 {{item.Salary}}


问:
Java generics error in Linux but not in Windows
I have a class that compiles in Windows, but not in Linux.
The method that doesn't compile is mapA.
The error I get is: "error: type argument B is not within bounds of type-variable B".
Why does Windows accept my code but Linux doesn't?
Can I disable this error somehow?

This is the class:

```<code>/** Either an A or a B. C is some common supertype of A and B. */
public class EitherOr<C, A extends C, B extends C>
{
    private final boolean isA;
    private final A a;
    private final B b;

    protected EitherOr(boolean isA, A a, B b)
    {
        this.isA = isA;
        this.a = a;
        this.b = b;
    }

    /**
     * If f(A) is of type D,
     * maps an EitherOr<C, A, B> to an EitherOr<E, f(A), B>,
     * where E is some common supertype of D and B.
     */
    public<E, D extends E> EitherOr<E, D, B> mapA(Function<A, D> f)
    {
        return (EitherOr<E, D, B>)(isA ? ofA(f.apply(a)) : ofB(b));
    }

    /** Creates an EitherOr<C, A, B> which is actually an A */
    public static<C, A extends C, B extends C> EitherOr<C, A, B> ofA(A a) {...}

    /** Creates an EitherOr<C, A, B> which is actually a B */
    public static<C, A extends C, B extends C> EitherOr<C, A, B> ofB(B b) {...}

    /** If is A, returns a, else throws an exception. */
    public A getA() {...}

    /** If is B, returns b, else throws an exception. */
    public B getB() {...}

    public C getValue() {return isA ? a : b;}

    ...
}
</code>```

答:
So (after adding import java.util.function.*;, a blank line replacing ...s with return null;s) the error is:

```<code>Main.java:22: error: type argument B is not within bounds of type-variable B
    public<E, D extends E> EitherOr<E, D, B> mapA(Function<A, D> f)
                                      ^
  where B,C are type-variables:
    B extends C declared in class EitherOr
    C extends Object declared in class EitherOr
</code>```

That sounds reasonable. B does not necessarily extend E, which it is required to. It does extend C, but that isn't relevant.

The cast is another indication of a problem.

If this code compiles on any compiler, that compiler has major issues.

Body:
I have a class that compiles in Windows, but not in Linux.
The method that doesn't compile is mapA.
The error I get is: "error: type argument B is not within bounds of type-variable B".
Why does Windows accept my code but Linux doesn't?
Can I disable this error somehow?

This is the class:

/** Either an A or a B. C is some common supertype of A and B. */
public class EitherOr<C, A extends C, B extends C>
{
    private final boolean isA;
    private final A a;
    private final B b;

    protected EitherOr(boolean isA, A a, B b)
    {
        this.isA = isA;
        this.a = a;
        this.b = b;
    }

    /**
     * If f(A) is of type D,
     * maps an EitherOr<C, A, B> to an EitherOr<E, f(A), B>,
     * where E is some common supertype of D and B.
     */
    public<E, D extends E> EitherOr<E, D, B> mapA(Function f)
    {
        return (EitherOr<E, D, B>)(isA ? ofA(f.apply(a)) : ofB(b));
    }

    /** Creates an EitherOr<C, A, B> which is actually an A */
    public static<C, A extends C, B extends C> EitherOr<C, A, B> ofA(A a) {...}

    /** Creates an EitherOr<C, A, B> which is actually a B */
    public static<C, A extends C, B extends C> EitherOr<C, A, B> ofB(B b) {...}

    /** If is A, returns a, else throws an exception. */
    public A getA() {...}

    /** If is B, returns b, else throws an exception. */
    public B getB() {...}

    public C getValue() {return isA ? a : b;}

    ...
}

Body:
So (after adding import java.util.function.*;, a blank line replacing ...s with return null;s) the error is:

Main.java:22: error: type argument B is not within bounds of type-variable B
    public<E, D extends E> EitherOr<E, D, B> mapA(Function<A, D> f)
                                      ^
  where B,C are type-variables:
    B extends C declared in class EitherOr
    C extends Object declared in class EitherOr

That sounds reasonable. B does not necessarily extend E, which it is required to. It does extend C, but that isn't relevant.

The cast is another indication of a problem.

If this code compiles on any compiler, that compiler has major issues.


问:
Using Spring MVC with html
Previously, I have used Spring MVC only with jsp files. And everything worked just fine. But today I tried to use an html file for the first time and immediately got into a trouble. For some reason, the content of html file is never displayed in my browser. Below is the configuration.

Config:

```<code>@SpringBootApplication
@ComponentScan("newTestPackage")
public class Config extends WebMvcConfigurerAdapter {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Config.class, args);
    }

    @Bean
    public ViewResolver jspViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".html");
        resolver.setExposeContextBeansAsAttributes(true);
        return resolver;
    }
}
</code>```

Controller:

```<code>@Controller
public class IndexController {

    @RequestMapping(value = "/")
    public String index() {
        return "index";
    }
}
</code>```

html:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

Hello World

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

Project structure:

What the browser displays:

JSP version works fine.
I don't understand why jsp page gets found and displayed and html one doesn't (status 'not found')

答:
By default, spring boot serves the static resources from src/main/resources/static folder, so place your index.html inside that folder.

You can refer here on how Spring boot serves the static content for the web application.

Title: Using Spring MVC with html

Body:
Previously, I have used Spring MVC only with jsp files. And everything worked just fine. But today I tried to use an html file for the first time and immediately got into a trouble. For some reason, the content of html file is never displayed in my browser. Below is the configuration.

Config:

@SpringBootApplication
@ComponentScan("newTestPackage")
public class Config extends WebMvcConfigurerAdapter {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Config.class, args);
    }

    @Bean
    public ViewResolver jspViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".html");
        resolver.setExposeContextBeansAsAttributes(true);
        return resolver;
    }
}

Controller:

@Controller
public class IndexController {

    @RequestMapping(value = "/")
    public String index() {
        return "index";
    }
}

html:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

Hello World

Project structure:

What the browser displays:

JSP version works fine.
I don't understand why jsp page gets found and displayed and html one doesn't (status 'not found')


问:
Security for my android phone which is steal by someone
How can i track someone who steal my phone by doing something previous work before stealing .Can i able to activate some programming on it which can be unbreakable even the thief reset phone .

Thanks .

答: I suppose that a good theft will manage to break or remove all kinds of security apps,etc. Although you can try using this one: Clean Master. To my mind if your smartphone has got a security app built-in, like Sony Xperia does, you can turn it on so that you can track your phone in case it is stolen.</p>


问:
how do you make an arraylist of different enums?
I have tried looking for the answer for quite a bit of time , so can anyone help me ?

Thank you in advance.

@MehdiB. I have no clue of where to start.

@Bohemian so I am building this game which needs certain requirements to unlock certain items. and I would like to store these requirements in an array which has different

something like this :
ArrayList requirements = new ArrayList();

requirements.add(Weapon.AK47);
requirements.add(House.Mansion);

答:
See the following example:

```<code>enum E1 { e1 };
enum E2 { e2 };

public  class Test <E extends Enum> {
  List<E> list = new ArrayList<>();

  void add(E e) { list.add(e); }
  void dump() { System.out.println(list); }

  public static void main(String[] args) throws Exception {
    Test<Enum> test = new Test<>();
    test.add(E1.e1);
    test.add(E2.e2);
    test.dump();
  }
}
</code>```

You can declare a list to accept "any enum"; and as any enum class must be derived from Enum, you can then use that specific class to instantiate a Test that allows to add enum constants coming from enum classes.

Of course, this is more of a "code puzzle"; as I would regard such a design with a lot of caution; not something that I would do in "real world production" code.

Body:
See the following example:

enum E1 { e1 };
enum E2 { e2 };

public  class Test <E extends Enum> {
  List<E> list = new ArrayList<>();

  void add(E e) { list.add(e); }
  void dump() { System.out.println(list); }

  public static void main(String[] args) throws Exception {
    Test<Enum> test = new Test<>();
    test.add(E1.e1);
    test.add(E2.e2);
    test.dump();
  }
}

You can declare a list to accept "any enum"; and as any enum class must be derived from Enum, you can then use that specific class to instantiate a Test that allows to add enum constants coming from enum classes.

Of course, this is more of a "code puzzle"; as I would regard such a design with a lot of caution; not something that I would do in "real world production" code.


问:
Matching string regular expression
I would like to match data from strings like the following:

24.Legacy.S01E08.720p.HDTV.x264-AVS[rarbg]

Colony.S02E09.720p.HDTV.x264-FLEET[rarbg]

24.Legacy (everything before S01E08)

S => 01

E => 08

720p.HDTV.x264 (everything between S01E08 and -)

AVS (everything between - en [)

rarbg (everything between [])

The following test almost works but needs some tweaks:

```<code>preg_match_all(
    '/(.*?).S([0-9]+)E([0-9]+).(.*?)(.*?)[(.*?)]/s',
    $download,
    $posts,
    PREG_SET_ORDER
);
</code>```

答:
You're so close, you just need to add the tests for the second half of the requirements:

```<code>(.*?).S([0-9]+)E([0-9]+).(.*?)-(.*?)\[(.*?)\]
</code>```

https://regex101.com/r/PfgMfq/1

Title: Matching string regular expression

Body:
I would like to match data from strings like the following:

24.Legacy.S01E08.720p.HDTV.x264-AVS[rarbg]

Colony.S02E09.720p.HDTV.x264-FLEET[rarbg]

24.Legacy (everything before S01E08)

S => 01

E => 08

720p.HDTV.x264 (everything between S01E08 and -)

AVS (everything between - en [)

rarbg (everything between [])

The following test almost works but needs some tweaks:

preg_match_all(
    '/(.*?).S([0-9]+)E([0-9]+).(.*?)(.*?)[(.*?)]/s',
    $download,
    $posts,
    PREG_SET_ORDER
);

Body:
You're so close, you just need to add the tests for the second half of the requirements:

(.*?).S([0-9]+)E([0-9]+).(.*?)-(.*?)\[(.*?)\]

https://regex101.com/r/PfgMfq/1


问:
Post raw form data from web page
I would like to send raw post data using straightforward DHTML, but without using the XMLHttpRequest object. Is this possible to do this, for example, by forcing an HTML form element's post data to an arbitrary string?</p>

答:
You can easily generate a string that resembles a POST request. There is not much difference between a POST and a GET. Using GET, the parameters are added behind the url. When POSTing, the parameters are added in the same way, but below the headers. </p>

<p>See developers.sun.com for an example. </p>

Title: Post raw form data from web page

Body:
You can easily generate a string that resembles a POST request. There is not much difference between a POST and a GET. Using GET, the parameters are added behind the url. When POSTing, the parameters are added in the same way, but below the headers.

See developers.sun.com for an example.


问:
How to redirect to another page in php using header after outputting message?
I was making an php file in which I have to add PHP Page redirection using header function after a certain condition is not true.

The problem is that before Redirection I have Outputted some message using echo because of this header function is not working and throwing warning:-

Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs...\search.php:229) in C:\xampp\htdocs...\search.php on line 291

Please help me with this and if there any other alternative for this please tell except that

javscript method window.location=url;

答:
You can do with this ways:

With refresh and URL, this will wait five seconds to redirect you:

```<code>header("refresh:5;url=https://www.google.com.br/");
echo "Redirecting you to Google in 5 seconds.";
</code>```

Or you can use javascript:

```<code>echo '<script language="JavaScript"> alert("Redirecting you to Google BR!");window.location="https://www.google.com.br/";</script><noscript>Click here: <a href="https://www.google.com.br/">aqui</a>.</noscript>';
</code>```

Body:
You can do with this ways:

With refresh and URL, this will wait five seconds to redirect you:

header("refresh:5;url=https://www.google.com.br/");
echo "Redirecting you to Google in 5 seconds.";

Or you can use javascript:

echo '<script language="JavaScript"> alert("Redirecting you to Google BR!");window.location="https://www.google.com.br/";</script><noscript>Click here: <a href="https://www.google.com.br/">aqui</a>.</noscript>';


问:
Dropwizard 0.6.2 File Upload
i used drop-wizard 0.6.2 framework to develop my rest API .so i have not idea regarding upload the file.the upload file can be done in higher version but i cant upgrade because of lots of modification so any idea of uploading file in drop wizard 0.6.2 ?.</p>

答:
If you are talking about a client uploading a file to your REST API you can always do the following:</p>

```<code>@Path("/processFile")
@Consumes("application/octet-stream")
@Produces("application/json")
public String processUploadedFile(InputStream inputStream) throws IOException {
    File tempFile = File.createTempFile("upload-", ".data");
    org.apache.commons.io.FileUtils.copyInputStreamToFile(inputStream, tempFile);
    // do sth with tempFile
    return "{\"status\": \"ok\"}";
}
</code>```

Title: Dropwizard 0.6.2 File Upload

Body:
If you are talking about a client uploading a file to your REST API you can always do the following:

@Path("/processFile")
@Consumes("application/octet-stream")
@Produces("application/json")
public String processUploadedFile(InputStream inputStream) throws IOException {
    File tempFile = File.createTempFile("upload-", ".data");
    org.apache.commons.io.FileUtils.copyInputStreamToFile(inputStream, tempFile);
    // do sth with tempFile
    return "{\"status\": \"ok\"}";
}


问:
username doesn't show when we login
login code

```<code><?php
include("koneksi.php");

$email=$_POST['email'];
$password=md5($_POST['password']);

$q="SELECT * FROM `user` WHERE `user`.`email`='$email' AND `user`.`password`='$password'";
$qe=mysql_query($q);

while ($de=mysql_fetch_array($qe)) {
    $id_user=$de['id_user'];
}
if (mysql_num_rows($qe)>0) {
    session_start();
    $_SESSION['x']=$id_users;

    header('location:home.php');
    exit;
} else{
    header('location:login_user.php');
    exit;
}
</code>```

?>

after login i wanna show or echo the username with this code

```<code><?php
session_start();
$id_user=$_SESSION['x'];

$q="SELECT * FROM `user` WHERE `user`.`id_user`='$id_user'";
$qe=mysql_query($q);
$de=mysql_fetch_array($qe);
    $username=$de['username'];
    echo "
        <li><a href=\"\">$username</a></li>
    ";
</code>```

?>

and the problem is the username doesn't show..
whats wrong.. help me ..

答:
You have a typo in your  login search query. Change to $_SESSION['x'] = $id_user;

Not $id_users

A piece of advice,  use an IDE such as netbeans or eclipse or phpstorm.  They help in identifying unused variables and other minor syntax errors.

Title: username doesn't show when we login

Body:
login code

<?php
include("koneksi.php");

$email=$_POST['email'];
$password=md5($_POST['password']);

$q="SELECT * FROM `user` WHERE `user`.`email`='$email' AND `user`.`password`='$password'";
$qe=mysql_query($q);

while ($de=mysql_fetch_array($qe)) {
    $id_user=$de['id_user'];
}
if (mysql_num_rows($qe)>0) {
    session_start();
    $_SESSION['x']=$id_users;

    header('location:home.php');
    exit;
} else{
    header('location:login_user.php');
    exit;
}

?>

after login i wanna show or echo the username with this code

<?php
session_start();
$id_user=$_SESSION['x'];

$q="SELECT * FROM `user` WHERE `user`.`id_user`='$id_user'";
$qe=mysql_query($q);
$de=mysql_fetch_array($qe);
    $username=$de['username'];
    echo "

$username

    ";

?>

and the problem is the username doesn't show..
whats wrong.. help me ..


问:
when to use Classes vs Objects vs Case Classes vs Traits
This is what I understood so far.

Classes should be used when we need to instantialte objects

We use "Objects" only when we have a singleton requirement meaning no need for multiple instances of "objects". I am thinking when we are building common library functions or utility functions in a project, we can use "objects" that way we need to instantiate each time we use methods/functions in that Object.

Case classes can be used when we want to save boilerplate code. Say we have "Stock" class. Each stock in general has hundreds of member variables. Instead of developer writing code for setters and getters, if we case class, it generates lot of default code.

Traits: don't know when to use. Both Traits and Objects don't take parameters during initialization.

Any more thoughts and ideas kindly share.

答:
In Scala classes act like in any other OO-language (e.g. Java) too - that is you use classes to build objects (not Scala Objects) in your applications, which have a state (e.g. holding attributes, say a name of a Person).

Scala Objects are singletons. You use it in Scala mainly for

creating functions/artifacts, which do not need a state/belong to a specific object. In other OO-languages you use the static keyword for this behavior.

providing factory methods (especially via the apply method) to instantiate classes (see Scala companion objects)

Case classes are intended to be used as lightweight classes (e.g. datacontainers). They are immutable by default and supposed to be structurally be compared (that is by comparing the values/state) and not by reference.
Additionally, they provide features like serialization out of the box.

Traits are like interfaces in Java with some more features. They define the interface of a class/object.

Before you start to dive deeper in Scala, I'd recommend being first familiar with classic OO principles.

ContentLicense: CC BY-SA 4.0


问:
Implement tree data structure
I want to implement a tree data structure. I have a Node struct and want it to hold references to child Nodes. I tried:

```<code>use std::collections::*;

#[derive(Debug)]
struct Node {
    value: String,
    children: HashMap<String, Node>,
}

impl Node {
    fn new(value: String) -> Self {
        Node {
            value: value,
            children: HashMap::new(),
        }
    }

    fn add_child(&mut self, key: String, value: String) -> &mut Node {
        let mut node = Node::new(value);
        self.children.insert(key, node);
        &mut node
    }
}

fn main() {
    let mut root_node = Node::new("root".to_string());
    root_node.add_child("child_1_1".to_string(), "child_1_1_value".to_string());
}
</code>```

This code does not compile:

error: `node` does not live long enough
  --> src/main.rs:22:10
   |
22 |     &mut node
   |          ^^^^ does not live long enough
23 |   }
   |   - borrowed value only lives until here
   |
note: borrowed value must be valid for the anonymous lifetime #1 defined on the body at 19:67...
  --> src/main.rs:19:68
   |
19 |     fn add_child(&mut self, key: String, value: String) -> &mut Node {
   |  ____________________________________________________________________^ starting here...
20 | |     let mut node = Node::new(value);
21 | |     self.children.insert(key, node);
22 | |     &mut node
23 | |   }
   | |___^ ...ending here

error[E0382]: use of moved value: `node`
  --> src/main.rs:22:10
   |
21 |     self.children.insert(key, node);
   |                               ---- value moved here
22 |     &mut node
   |          ^^^^ value used here after move
   |
   = note: move occurs because `node` has type `Node`, which does not implement the `Copy` trait
```

How can I implement this?

答:
In this case, it's actually necessary to look at the second error message in the compiler output:

error[E0382]: use of moved value: `node`
  --> src/main.rs:22:10
   |
21 |     self.children.insert(key, node);
   |                               ---- value moved here
22 |     &mut node
   |          ^^^^ value used here after move
   |
   = note: move occurs because `node` has type `Node`, which does not implement the `Copy` trait
```

<p>The variable <code>node</code> is moved <em>into</em> the hashmap in line 21. You can't use it afterwards! In Rust we have <em>move semantics</em>, meaning that everything gets moved by default instead of cloned by default (C++) or referenced by default (Java). You want to return a reference to the <code>Node</code> object <em>inside</em> the hashmap!</p>

<p>An easy way would be to insert <code>node</code> as you are already doing and afterwards fetching the value from the hashmap:</p>

```let mut node = Node::new(value);
self.children.insert(key.clone(), node);
self.children.get_mut(key).unwrap()
```

<p>This should make clear what the function actually does. However, this code has some disadvantages: First, we have to clone <code>key</code> (we need it for the insertion and the query) and secondly, the hashmap needs calculate the hash of the key twice which is not very efficient. </p>

<p>Luckily, Rust's <code>HashMap</code> has a nice <code>entry()</code>-API. We could change the function like that:</p>

```self.children.entry(key).or_insert_with(|| Node::new(value))
```

<p>This is the whole body of <code>add_child()</code>! Now, however, we notice that ... we haven't really thought about what is supposed to happen if the hashmap already contains a value associated with the given key! In the code above, the old value is kept and returned. If you want to do something else (e.g. replace the value), you could just use <code>match</code> on the <code>Entry</code> object:</p>

```let node = Node::new(value);
match self.children.entry(key) {
    Entry::Occupied(e) => {
        // Maybe you want to panic!() here... but we will just
        // replace the value:
        e.insert(node);  // discarding old value...
        e.get_mut()
    }
    Entry::Vacant(e) => insert(node),
}
```

Title: Implement tree data structure

Body:
I want to implement a tree data structure. I have a Node struct and want it to hold references to child Nodes. I tried:

use std::collections::*;

#[derive(Debug)]
struct Node {
    value: String,
    children: HashMap<String, Node>,
}

impl Node {
    fn new(value: String) -> Self {
        Node {
            value: value,
            children: HashMap::new(),
        }
    }

    fn add_child(&mut self, key: String, value: String) -> &mut Node {
        let mut node = Node::new(value);
        self.children.insert(key, node);
        &mut node
    }
}

fn main() {
    let mut root_node = Node::new("root".to_string());
    root_node.add_child("child_1_1".to_string(), "child_1_1_value".to_string());
}

This code does not compile:

error: `node` does not live long enough
  --> src/main.rs:22:10
   |
22 |     &mut node
   |          ^^^^ does not live long enough
23 |   }
   |   - borrowed value only lives until here
   |
note: borrowed value must be valid for the anonymous lifetime #1 defined on the body at 19:67...
  --> src/main.rs:19:68
   |
19 |     fn add_child(&mut self, key: String, value: String) -> &mut Node {
   |  ____________________________________________________________________^ starting here...
20 | |     let mut node = Node::new(value);
21 | |     self.children.insert(key, node);
22 | |     &mut node
23 | |   }
   | |___^ ...ending here

error[E0382]: use of moved value: `node`
  --> src/main.rs:22:10
   |
21 |     self.children.insert(key, node);
   |                               ---- value moved here
22 |     &mut node
   |          ^^^^ value used here after move
   |
   = note: move occurs because `node` has type `Node`, which does not implement the `Copy` trait

How can I implement this?

Body:
In this case, it's actually necessary to look at the second error message in the compiler output:

error[E0382]: use of moved value: `node`
  --> src/main.rs:22:10
   |
21 |     self.children.insert(key, node);
   |                               ---- value moved here
22 |     &mut node
   |          ^^^^ value used here after move
   |
   = note: move occurs because `node` has type `Node`, which does not implement the `Copy` trait

The variable node is moved into the hashmap in line 21. You can't use it afterwards! In Rust we have move semantics, meaning that everything gets moved by default instead of cloned by default (C++) or referenced by default (Java). You want to return a reference to the Node object inside the hashmap!

An easy way would be to insert node as you are already doing and afterwards fetching the value from the hashmap:

let mut node = Node::new(value);
self.children.insert(key.clone(), node);
self.children.get_mut(key).unwrap()

This should make clear what the function actually does. However, this code has some disadvantages: First, we have to clone key (we need it for the insertion and the query) and secondly, the hashmap needs calculate the hash of the key twice which is not very efficient.

Luckily, Rust's HashMap has a nice entry()-API. We could change the function like that:

self.children.entry(key).or_insert_with(|| Node::new(value))

This is the whole body of add_child()! Now, however, we notice that ... we haven't really thought about what is supposed to happen if the hashmap already contains a value associated with the given key! In the code above, the old value is kept and returned. If you want to do something else (e.g. replace the value), you could just use match on the Entry object:

let node = Node::new(value);
match self.children.entry(key) {
    Entry::Occupied(e) => {
        // Maybe you want to panic!() here... but we will just
        // replace the value:
        e.insert(node);  // discarding old value...
        e.get_mut()
    }
    Entry::Vacant(e) => insert(node),
}


问:
Why is bottom-up parsing more common than top-down parsing?
It seems that recursive-descent parsers are not only the simplest to explain, but also the simplest to design and maintain. They aren't limited to LALR(1) grammars, and the code itself can be understood by mere mortals. In contrast, bottom up parsers have limits on the grammars they are able to recognize, and need to be generated by special tools (because the tables that drive them are next-to-impossible to generate by hand).

Why then, is bottom-up (i.e. shift-reduce) parsing more common than top-down (i.e. recursive descent) parsing?

答:
If you choose a powerful parser generator, you can code your grammar without worrying about peculiar properties. (LA)LR means you don't have to worry about left recursion, one less headache. GLR means you don't have to worry about local ambiguity or lookahead.

And the bottom-up parsers tend to be pretty efficient. So, once you've paid the price of a bit of complicated machinery, it is easier to write grammars and the parsers perform well.

You should expect to see this kind of choice wherever there is some programming construct that commonly occurs: if it is easier to specify, and it performs pretty well, even if the machinery is complicated, complex machinery will win.  As another example, the database world has gone to relational tools, in spite of the fact that you can hand-build an indexed file yourself. It's easier to write the data schemas, it's easier to specify the indexes, and with complicated enough machinery behind (you don't have to look at the gears, you just use them), they can be pretty fast with almost no effort.  Same reasons.


问:
Why I receive this TypeERROR:'str' object is not callable, in python?
I'm doing my first currency Convertor in python, only with two currencies,  and I don't understand why that doesn't work properly? I decide to define all in functions and then call them back, but that isn't working.
I'm doing it in portuguese.

This is my code:

```<code>from decimal import Decimal as dec

def menu_conv():
    print(" ")
    print("»»»»»»»»»»»»»»» Bem-vindo ««««««««««««««")
    print("»»»»»»»»»» Conversor de Moeda ««««««««««")
    print(" ")
    print("**** Selecione a conversao desejada ****")
    print(" ")
    print("********* 1. Euros -> Dólares **********")
    print("********* 2. Dólares -> Euros **********")
    print("*************** 3. Saír ****************")
    print(" ")

def opcao():
    opcao = int(input("Insira a sua opçao:  "))
    if opcao == 1:
        dolar()
    elif opcao == 2:
        euro()
    else:
        nao()

def dolar():
    print(" ")
    montante = dec(input("Qual o montante que deseja converter? €"))
    DOLAR = dec(1.39)
    cambioDolar = dec(montante / DOLAR)
    print(" ")
    print("O Valor em Dólares é: ${:.2f}".format(cambioDolar))
    print(" ")
    print("Deseja fazer nova conversao?")
    print(" ")
    opcao_txt()

def euro():
    print(" ")
    montante = dec(input("Qual o montante que deseja converter? $"))
    EURO = dec(1.39)
    cambioEuro = dec(montante / EURO)
    print(" ")
    print(" O Valor em Euros é: €{:.2f}".format(cambioEuro))
    print(" ")
    print("Deseja fazer nova conversao?")
    print(" ")
    opcao_txt()

def opcao_txt():
    opcao = input("» S/N: ")
    if opcao == 'S'or's':
        menu_conv()
        opcao()
    else:
        nao()

def nao():
    print("Até à próxima!")
    exit()

menu_conv()
opcao()
</code>```

This is the ERROR I get when I try to do other convertion:

```<code>»»»»»»»»»»»»»»» Bem-vindo ««««««««««««««
»»»»»»»»»» Conversor de Moeda ««««««««««

**** Selecione a conversao desejada ****

********* 1. Euros -> Dólares **********
********* 2. Dólares -> Euros **********
*************** 3. Saír ****************

Insira a sua opçao:  1

Qual o montante que deseja converter? €1000

O Valor em Dólares é: $719.42

Deseja fazer nova conversao?

» S/N: s

»»»»»»»»»»»»»»» Bem-vindo ««««««««««««««
»»»»»»»»»» Conversor de Moeda ««««««««««

**** Selecione a conversao desejada ****

********* 1. Euros -> Dólares **********
********* 2. Dólares -> Euros **********
*************** 3. Saír ****************

Traceback (most recent call last):
  File "conversor_moeda.py", line 68, in <module>
    opcao()
  File "conversor_moeda.py", line 20, in opcao
    dolar()
  File "conversor_moeda.py", line 37, in dolar
    opcao_txt()
  File "conversor_moeda.py", line 57, in opcao_txt
    opcao()
TypeError: 'str' object is not callable
</code>```

答: It's because in your function opcao_txt you have a string variable named opcao which is also a function. So when you call opcao() you're actually trying to call the string. </p>

Body:
I'm doing my first currency Convertor in python, only with two currencies,  and I don't understand why that doesn't work properly? I decide to define all in functions and then call them back, but that isn't working.
I'm doing it in portuguese.

This is my code:

from decimal import Decimal as dec

def menu_conv():
    print(" ")
    print("»»»»»»»»»»»»»»» Bem-vindo ««««««««««««««")
    print("»»»»»»»»»» Conversor de Moeda ««««««««««")
    print(" ")
    print("**** Selecione a conversao desejada ****")
    print(" ")
    print("********* 1. Euros -> Dólares **********")
    print("********* 2. Dólares -> Euros **********")
    print("*************** 3. Saír ****************")
    print(" ")

def opcao():
    opcao = int(input("Insira a sua opçao:  "))
    if opcao == 1:
        dolar()
    elif opcao == 2:
        euro()
    else:
        nao()

def dolar():
    print(" ")
    montante = dec(input("Qual o montante que deseja converter? €"))
    DOLAR = dec(1.39)
    cambioDolar = dec(montante / DOLAR)
    print(" ")
    print("O Valor em Dólares é: ${:.2f}".format(cambioDolar))
    print(" ")
    print("Deseja fazer nova conversao?")
    print(" ")
    opcao_txt()

def euro():
    print(" ")
    montante = dec(input("Qual o montante que deseja converter? $"))
    EURO = dec(1.39)
    cambioEuro = dec(montante / EURO)
    print(" ")
    print(" O Valor em Euros é: €{:.2f}".format(cambioEuro))
    print(" ")
    print("Deseja fazer nova conversao?")
    print(" ")
    opcao_txt()

def opcao_txt():
    opcao = input("» S/N: ")
    if opcao == 'S'or's':
        menu_conv()
        opcao()
    else:
        nao()

def nao():
    print("Até à próxima!")
    exit()

menu_conv()
opcao()

This is the ERROR I get when I try to do other convertion:

»»»»»»»»»»»»»»» Bem-vindo ««««««««««««««
»»»»»»»»»» Conversor de Moeda ««««««««««

**** Selecione a conversao desejada ****

********* 1. Euros -> Dólares **********
********* 2. Dólares -> Euros **********
*************** 3. Saír ****************

Insira a sua opçao:  1

Qual o montante que deseja converter? €1000

O Valor em Dólares é: $719.42

Deseja fazer nova conversao?

» S/N: s

»»»»»»»»»»»»»»» Bem-vindo ««««««««««««««
»»»»»»»»»» Conversor de Moeda ««««««««««

**** Selecione a conversao desejada ****

********* 1. Euros -> Dólares **********
********* 2. Dólares -> Euros **********
*************** 3. Saír ****************

Traceback (most recent call last):
  File "conversor_moeda.py", line 68, in <module>
    opcao()
  File "conversor_moeda.py", line 20, in opcao
    dolar()
  File "conversor_moeda.py", line 37, in dolar
    opcao_txt()
  File "conversor_moeda.py", line 57, in opcao_txt
    opcao()
TypeError: 'str' object is not callable


问:
Left div is static while the right div is scrolling
I'm trying to recreate the effect seen in the about and work section on this website: http://www.melaniedaveid.com/

I want to be able to scroll down and once the div on the left is reached, only the right side is scrolling now. I'm assuming both are wrapped in a div and the right div's overflow is scrolled to, but I'm unsure how to lock the div in place until reaching the bottom.

Any help would be appreciated, thanks!

答:
the effect you're looking for is called "sticky"
Basically, you listen for the scroll event and set the css property position: fixed to your element A conditionally -> until the bottom position of element A is equal or greater than element B's bottom position


答: In opcao_txt you created a local variable named opcao, which takes precedence. It has a string value. You then try to call it with calling syntax () and you get that error. Use a different name for the variable should fix it.

Title: Why I receive this TypeERROR:'str' object is not callable, in python?


问:
How to execute a CMD /C command with ( round bracket in the path name
I'm trying to execute a command like this:

```<code>CMD /C "C:\Users\Richard(R)D\abc.bat"
</code>```

I get the error message:

```<code>'C:\Users\Richard' is not recognized as an internal or external command
</code>```

How can I execute the command that resides in a folder that uses round brackets?

答:
Why?

If you read the cmd /? output you will find

```<code>If /C or /K is specified, then the remainder of the command line after
the switch is processed as a command line, where the following logic is
used to process quote (") characters:

    1.  If all of the following conditions are met, then quote characters
        on the command line are preserved:

        - no /S switch
        - exactly two quote characters
        - no special characters between the two quote characters,
          where special is one of: &<>()@^|
        - there are one or more whitespace characters between the
          two quote characters
        - the string between the two quote characters is the name
          of an executable file.

    2.  Otherwise, old behavior is to see if the first character is
        a quote character and if so, strip the leading character and
        remove the last quote character on the command line, preserving
        any text after the last quote character.
</code>```

This means that

```<code>cmd /c "C:\Users\Richard(R)D\abc.bat"
</code>```

gets the quotes removed and the remaining command

```<code>cmd /c C:\Users\Richard(R)D\abc.bat
</code>```

has a problem with the parenthesis.

How?

For this precise command, you can escape the parenthesis

```<code>cmd /c "C:\Users\Richard^(R^)D\abc.bat"
</code>```

Or for a general solution you can include quotes for the file

```<code>cmd /c ""C:\Users\Richard(R)D\abc.bat""
</code>```

and better (if executing from command line) also escape the first quote to avoid parser problems in quoted areas start/stop (not needed in this case)

```<code>cmd /c ^""C:\Users\Richard(R)D\abc.bat""
</code>```

Body:
I'm trying to execute a command like this:

CMD /C "C:\Users\Richard(R)D\abc.bat"

I get the error message:

'C:\Users\Richard' is not recognized as an internal or external command

How can I execute the command that resides in a folder that uses round brackets?

Body:
Why?

If you read the cmd /? output you will find

If /C or /K is specified, then the remainder of the command line after
the switch is processed as a command line, where the following logic is
used to process quote (") characters:

    1.  If all of the following conditions are met, then quote characters
        on the command line are preserved:

        - no /S switch
        - exactly two quote characters
        - no special characters between the two quote characters,
          where special is one of: &<>()@^|
        - there are one or more whitespace characters between the
          two quote characters
        - the string between the two quote characters is the name
          of an executable file.

    2.  Otherwise, old behavior is to see if the first character is
        a quote character and if so, strip the leading character and
        remove the last quote character on the command line, preserving
        any text after the last quote character.

This means that

cmd /c "C:\Users\Richard(R)D\abc.bat"

gets the quotes removed and the remaining command

cmd /c C:\Users\Richard(R)D\abc.bat

has a problem with the parenthesis.

How?

For this precise command, you can escape the parenthesis

cmd /c "C:\Users\Richard^(R^)D\abc.bat"

Or for a general solution you can include quotes for the file

cmd /c ""C:\Users\Richard(R)D\abc.bat""

and better (if executing from command line) also escape the first quote to avoid parser problems in quoted areas start/stop (not needed in this case)

cmd /c ^""C:\Users\Richard(R)D\abc.bat""


问:
Docker commands fails (in Windows)
I am trying to use Docker on a windows machine and is hit with every possible issue it seems. My latest one is this:
My machine is running but I can't seem to interact with it using the docker commands. If I run a very standard command like:

```<code>docker ps
</code>```

I get an error message like this:

```<code>An error occurred trying to connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v
1.23/containers/json: open //./pipe/docker_engine: The system cannot find the file specified.
</code>```

So apparently some path is all messed up. Do anyone know which path this is and how to fix this?

答:
below resolved. i copied answer from another forum

I had this problem after update. After re-installing VB I switched on "VirtualBox NDIS6 Bridged Networking Driver" in properties network connection.

It property switched off default in my case.

Title: Docker commands fails (in Windows)

Body:
I am trying to use Docker on a windows machine and is hit with every possible issue it seems. My latest one is this:
My machine is running but I can't seem to interact with it using the docker commands. If I run a very standard command like:

docker ps

I get an error message like this:

An error occurred trying to connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v
1.23/containers/json: open //./pipe/docker_engine: The system cannot find the file specified.

So apparently some path is all messed up. Do anyone know which path this is and how to fix this?


问:
execute ssis package for another server, didn't see any files
I have SSIS package and on VISUAL STUDIO working good, for another server pre production also, but when i use production server and try loading xls files nothing do, didn't see any files. I hv the same permission both server sql so i Somebody can help me? I will be maximum enjoye if somebody will react!</p>

答:
Thank you very much for the suggestions!
My package imports xls files into a database on sql server
In the package I have a foreich loop cointainer and in the directory I use the variable " input folder path" .In the expression on my menager connection i have variable "Full Path" (with file name)
On preproduction server, the package is great and loads xls files. On production  server no. And i have comunicat :"For each file enumerator, no files were found that matched the file pattern or the specified directory was empty."
I set delay validation (connection manager, task) is true, When i deploy on server my project again, the message "another user uses files" Nobody use this folder. only me.
I Use the mapped path // fileserv / clientspath.filename.
I do not know what else i can write about this will be help self ..</p>


问:
Creating a Doctrine behavior: How to access actAs() params from within a listener object
I'm creating a behavior (one template and one listener). In the template class, I'm using the addListener() method to attach the listener to the model.

```<code>// Inside the template's setTableDefinition() method
$this->addListener(new RemoraSaveListener);
</code>```

Pretty standard stuff, it seems.

From within the listener, how to I access the template options that have been set using the model's actAs() method? You know, the ones that automatically occupy the _options property of the template object.

答:
Your template class should have a protected $_options = array() property.

Pass this property to your listener, like so:

```<code>$this->addListener(new RemoraSaveListener($this->_options));
</code>```

In your listener class you should also have a protected $_options property.

Add this to your listener:

```<code>public function __construct($options) {
    $this->_options = $options;
}
</code>```

You should now be able to access the options from within your listener class (e.x from within a preSave call).

Body:
I'm creating a behavior (one template and one listener). In the template class, I'm using the addListener() method to attach the listener to the model.

// Inside the template's setTableDefinition() method
$this->addListener(new RemoraSaveListener);

Pretty standard stuff, it seems.

From within the listener, how to I access the template options that have been set using the model's actAs() method? You know, the ones that automatically occupy the _options property of the template object.

Body:
Your template class should have a protected $_options = array() property.

Pass this property to your listener, like so:

$this->addListener(new RemoraSaveListener($this->_options));

In your listener class you should also have a protected $_options property.

Add this to your listener:

public function __construct($options) {
    $this->_options = $options;
}

You should now be able to access the options from within your listener class (e.x from within a preSave call).


问:
When and why to 'return false' in JavaScript?
When and why to return false in JavaScript?

答: return false using only if you have some worng in function (by some test) or you want to stop some function, example use return false in end "onsubmit"</p>


问:
This is the error Android studio is showing me when i am pressing the button
Logcat Output:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String firebase.firebasepractice.User.getUsername()' on a null object reference. ...

User:

MainActivity:

```<code>public class MainActivity extends AppCompatActivity {

  private EditText name,password;
  Button btn;
  TextView tv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    name = (EditText) findViewById(R.id.userName);
    password= (EditText) findViewById(R.id.password);
    btn= (Button) findViewById(R.id.submit);
    tv= (TextView) findViewById(R.id.tv);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            DatabaseReference myRef=FirebaseDatabase.getInstance().getReference("Users");

                String userId=myRef.push().getKey();

            myRef.child(userId).addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    User user=dataSnapshot.getValue(User.class);
                    tv.setText("Name is "+user.getUsername()+"    Email is "+user.getEmail());
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

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

答:
You are missing a no-args constructor in User class:

Please add:

```<code>public User() {
}
</code>```

Then, you are initialising myRef like this:

```<code>myRef=FirebaseDatabase.getInstance().getReference("Users");
</code>```

And then again accessing 'Users' node under 'Users'

```<code>myRef.child("Users")
</code>```

Lastly, I believe you are passing a wrong variable to a .child() call in:

```<code>myRef.child("Users")
    .addValueEventListener ...
</code>```

You should be doing:

```<code>myRef.child(userId) // this line is changed
    .addValueEventListener ...
</code>```

Your final code should look like:

```<code>DatabaseReference myRef = FirebaseDatabase.getInstance().getReference("Users");

String userId = myRef.push().getKey();

myRef.child(userId) // Change: "Users" -> userId
    .addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            User user = dataSnapshot.getValue(User.class);
            tv.setText("Name is " + user.getUsername() + "\tEmail is " + user.getEmail());
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
</code>```

Body:
Logcat Output:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String firebase.firebasepractice.User.getUsername()' on a null object reference. ...

User:

MainActivity:

public class MainActivity extends AppCompatActivity {

  private EditText name,password;
  Button btn;
  TextView tv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    name = (EditText) findViewById(R.id.userName);
    password= (EditText) findViewById(R.id.password);
    btn= (Button) findViewById(R.id.submit);
    tv= (TextView) findViewById(R.id.tv);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            DatabaseReference myRef=FirebaseDatabase.getInstance().getReference("Users");

                String userId=myRef.push().getKey();

            myRef.child(userId).addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    User user=dataSnapshot.getValue(User.class);
                    tv.setText("Name is "+user.getUsername()+"    Email is "+user.getEmail());
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
        }
    });
}
}

Body:
You are missing a no-args constructor in User class:

Please add:

public User() {
}

Then, you are initialising myRef like this:

myRef=FirebaseDatabase.getInstance().getReference("Users");

And then again accessing 'Users' node under 'Users'

myRef.child("Users")

Lastly, I believe you are passing a wrong variable to a .child() call in:

myRef.child("Users")
    .addValueEventListener ...

You should be doing:

myRef.child(userId) // this line is changed
    .addValueEventListener ...

Your final code should look like:

DatabaseReference myRef = FirebaseDatabase.getInstance().getReference("Users");

String userId = myRef.push().getKey();

myRef.child(userId) // Change: "Users" -> userId
    .addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            User user = dataSnapshot.getValue(User.class);
            tv.setText("Name is " + user.getUsername() + "\tEmail is " + user.getEmail());
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });


问:
How to convert a PDF to image format (jpeg, png,...) using my C program?
I'm working with Visual Studio and OpenCV for image processing, but all my documents are PDF so I need to convert them to image format so I can compatibilize them with OpenCV

This is my code to open a image:

enter image description here

Is there any way to modify it to open and read PDF's as an image?

Many thanks!

答: You may want to take a look at ImageMagick. The CLI tool is able to convert PDF to images and I believe they provide C libraries too.</p>


问:
Persistent css rule changes for dynamically created elements
I want to permanently modify a css rule (such that new elements will take on this css rule). It appears that all jquery modifications using css do not persist (Say modifying a background color for future elements does not persist when they are created):

```<code>$(".red").css("background-color", "blue");
</code>```

See my fiddle here:

https://jsfiddle.net/Lvm0c7m6/

I would like all future elements to now have the new rule created by css, is there a way to do this (with good cross browser support).

答:
You order javascript at execution time to add an inline style to all elements with class 'red', coloring them blue. After that you add new elements to the DOM. They have no knowledge of the earlier command an therefore are not influenced by them.

This solves your problem, as this adds a style rule to the document. This influences all elements and is 'persistent':

```<code>$( "<style>.red { background: blue; }</style>" ).appendTo( "body" );
</code>```

See: https://jsfiddle.net/aLghL2ke/

Note that if you want to run this command multiple times, it would be nice to remove the old style block from your code. This can be done with jQuery too using this command:

```<code>$( "body style" ).remove();
</code>```

See: https://jsfiddle.net/4duxsz0a/

Body:
I want to permanently modify a css rule (such that new elements will take on this css rule). It appears that all jquery modifications using css do not persist (Say modifying a background color for future elements does not persist when they are created):

$(".red").css("background-color", "blue");

See my fiddle here:

https://jsfiddle.net/Lvm0c7m6/

I would like all future elements to now have the new rule created by css, is there a way to do this (with good cross browser support).

Body:
You order javascript at execution time to add an inline style to all elements with class 'red', coloring them blue. After that you add new elements to the DOM. They have no knowledge of the earlier command an therefore are not influenced by them.

This solves your problem, as this adds a style rule to the document. This influences all elements and is 'persistent':

$( "<style>.red { background: blue; }</style>" ).appendTo( "body" );

See: https://jsfiddle.net/aLghL2ke/

Note that if you want to run this command multiple times, it would be nice to remove the old style block from your code. This can be done with jQuery too using this command:

$( "body style" ).remove();

See: https://jsfiddle.net/4duxsz0a/


问:
Tkinter.Label not showing after button pressed
I'm trying to make, that after I press the button, I get the taken info shown in the label, however, I can't seem to make the label appear in the GUI. I get error, when I press "Vartotojo informacija > type in name and press "rodyti informacija" and I get error on this line w.pack(LEFT) (should be line 95-ish):

Full traceback:

'id' is not recognized as an internal or external command,
operable program or batch file.
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python\lib\lib-tk\Tkinter.py", line 1542, in __call__
    return self.func(*args)
  File "tkinter-label-not-showing-after-button-pressed.py", line 96, in <lambda>
    myg1 = Button(virsus, text="Rodyti informacija", command=lambda: gauti())
  File "tkinter-label-not-showing-after-button-pressed.py", line 103, in gauti
    w.pack(LEFT)
  File "C:\Python\lib\lib-tk\Tkinter.py", line 1946, in pack_configure
    + self._options(cnf, kw))
  File "C:\Python\lib\lib-tk\Tkinter.py", line 1169, in _options
    for k, v in cnf.items():
AttributeError: 'str' object has no attribute 'items'
```

<p>My code:</p>

```from Tkinter import *
import tkMessageBox
from sys import version_info
import subprocess

root = Tk()
root.title("Administravimas")

virsus = Frame(root)
virsus.pack()
apacia = Frame(root)
apacia.pack(side=BOTTOM)

def filtras():
    root = Tk()
    root.title("Filtravimas pagal uzklausa")
    root.geometry("300x100")
    tekstas = Text(root, height=1, width=15)
    tekstas.pack(side=TOP)
    virsus = Frame(root)
    virsus.pack()
    apacia = Frame(root)
    apacia.pack(side=BOTTOM)
    myg1 = Button(virsus, text="Filtruoti", command=lambda: gauti())
    myg1.pack(side=BOTTOM)

    def gauti():
        imti=tekstas.get("1.0", "end-1c")
        subprocess.call("grep -i '{imti}' /var/log/syslog > "
                        "logai/uzklausa/$(date +%d_%m_%Y.txt)".format(imti=imti),
                        shell=True)

def vartotojas():
    root = Tk()
    root.title("Filtravimas pagal vartotoju prisijungimus")
    root.geometry("300x100")
    tekstas = Text(root, height=1, width=15)
    tekstas.pack(side=TOP)
    virsus = Frame(root)
    virsus.pack()
    apacia = Frame(root)
    apacia.pack(side=BOTTOM)
    myg1 = Button(virsus, text="Filtruoti", command=lambda: gauti())
    myg1.pack(side=BOTTOM)

    def gauti():
        imti = tekstas.get("1.0", "end-1c")
        subprocess.call("grep -i '{imti}' /var/log/auth.log > "
                        "logai/vartotojai/$(date +%d_%m_%Y.txt)".format(imti=imti),
                        shell=True)

def portas():
    root = Tk()
    root.title("Atidaryti/uzdaryti portus")
    root.geometry("300x100")
    virsus = Frame(root)
    virsus.pack()
    apacia = Frame(root)
    apacia.pack(side=BOTTOM)
    myg1 = Button(virsus, text="Atidaryti porta")
    myg2 = Button(virsus, text="Uzdaryti porta")
    myg1.pack(side=LEFT)
    myg2.pack(side=LEFT)
    root.mainloop()

def administ():
    root = Tk()
    root.title("Administrouti vartotojus")
    root.geometry("400x100")
    virsus = Frame(root)
    virsus.pack()
    apacia = Frame(root)
    apacia.pack(side=BOTTOM)
    myg1 = Button(virsus, text="Kurti vartotoja")
    myg1.pack(side=LEFT)
    myg2 = Button(virsus, text="Naikinti vartotoja")
    myg2.pack(side=LEFT)
    myg3 = Button(virsus, text="Keisti vartotojo grupe")
    myg3.pack(side=BOTTOM)
    root.mainloop()

def informacija():
    root = Tk()
    root.title("Vartotoju informacija")
    root.geometry("400x100")
    tekstas = Text(root, height=1, width=15)
    tekstas.pack(side=TOP)

    virsus = Frame(root)
    virsus.pack()
    apacia = Frame(root)
    apacia.pack(side=BOTTOM)
    myg1 = Button(virsus, text="Rodyti informacija", command=lambda: gauti())
    myg1.pack(side=BOTTOM)

    def gauti():
        imti = tekstas.get("1.0", "end-1c")
        info = subprocess.call("id '{imti}' ".format(imti=imti), shell=True)
        w = Label(root, text= "info")
        w.pack(LEFT)

    root.mainloop()

myg1 = Button(virsus, text="Filtruoti pagal uzklausa", command=filtras)
myg2 = Button(apacia, text="Filtrouti pagal vartotoju prisijungimus", command=vartotojas)
myg3 = Button(virsus, text="Atidaryti/uzdaryti portus", command=portas)
myg4 = Button(apacia, text="Administruoti vartotojus", command=administ)
myg5 = Button(apacia, text="Vartotojo informacija", command=informacija)

myg1.pack(side=LEFT)
myg2.pack(side=RIGHT)
myg3.pack(side=LEFT)
myg4.pack(side=RIGHT)
myg5.pack(side=RIGHT)

root.mainloop()
```

答: For what I can see, the statement w.pack(LEFT) just needs a keyword (i.e. w.pack(side=LEFT). Without keyword, it expects an argument of another kind (when calling help(Button.pack), you'll see that this positional argument would be a dictionary)

Body:
I'm trying to make, that after I press the button, I get the taken info shown in the label, however, I can't seem to make the label appear in the GUI. I get error, when I press "Vartotojo informacija > type in name and press "rodyti informacija" and I get error on this line w.pack(LEFT) (should be line 95-ish):

Full traceback:

'id' is not recognized as an internal or external command,
operable program or batch file.
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python\lib\lib-tk\Tkinter.py", line 1542, in __call__
    return self.func(*args)
  File "tkinter-label-not-showing-after-button-pressed.py", line 96, in <lambda>
    myg1 = Button(virsus, text="Rodyti informacija", command=lambda: gauti())
  File "tkinter-label-not-showing-after-button-pressed.py", line 103, in gauti
    w.pack(LEFT)
  File "C:\Python\lib\lib-tk\Tkinter.py", line 1946, in pack_configure
    + self._options(cnf, kw))
  File "C:\Python\lib\lib-tk\Tkinter.py", line 1169, in _options
    for k, v in cnf.items():
AttributeError: 'str' object has no attribute 'items'

My code:

from Tkinter import *
import tkMessageBox
from sys import version_info
import subprocess

root = Tk()
root.title("Administravimas")

virsus = Frame(root)
virsus.pack()
apacia = Frame(root)
apacia.pack(side=BOTTOM)

def filtras():
    root = Tk()
    root.title("Filtravimas pagal uzklausa")
    root.geometry("300x100")
    tekstas = Text(root, height=1, width=15)
    tekstas.pack(side=TOP)
    virsus = Frame(root)
    virsus.pack()
    apacia = Frame(root)
    apacia.pack(side=BOTTOM)
    myg1 = Button(virsus, text="Filtruoti", command=lambda: gauti())
    myg1.pack(side=BOTTOM)

    def gauti():
        imti=tekstas.get("1.0", "end-1c")
        subprocess.call("grep -i '{imti}' /var/log/syslog > "
                        "logai/uzklausa/$(date +%d_%m_%Y.txt)".format(imti=imti),
                        shell=True)

def vartotojas():
    root = Tk()
    root.title("Filtravimas pagal vartotoju prisijungimus")
    root.geometry("300x100")
    tekstas = Text(root, height=1, width=15)
    tekstas.pack(side=TOP)
    virsus = Frame(root)
    virsus.pack()
    apacia = Frame(root)
    apacia.pack(side=BOTTOM)
    myg1 = Button(virsus, text="Filtruoti", command=lambda: gauti())
    myg1.pack(side=BOTTOM)

    def gauti():
        imti = tekstas.get("1.0", "end-1c")
        subprocess.call("grep -i '{imti}' /var/log/auth.log > "
                        "logai/vartotojai/$(date +%d_%m_%Y.txt)".format(imti=imti),
                        shell=True)

def portas():
    root = Tk()
    root.title("Atidaryti/uzdaryti portus")
    root.geometry("300x100")
    virsus = Frame(root)
    virsus.pack()
    apacia = Frame(root)
    apacia.pack(side=BOTTOM)
    myg1 = Button(virsus, text="Atidaryti porta")
    myg2 = Button(virsus, text="Uzdaryti porta")
    myg1.pack(side=LEFT)
    myg2.pack(side=LEFT)
    root.mainloop()

def administ():
    root = Tk()
    root.title("Administrouti vartotojus")
    root.geometry("400x100")
    virsus = Frame(root)
    virsus.pack()
    apacia = Frame(root)
    apacia.pack(side=BOTTOM)
    myg1 = Button(virsus, text="Kurti vartotoja")
    myg1.pack(side=LEFT)
    myg2 = Button(virsus, text="Naikinti vartotoja")
    myg2.pack(side=LEFT)
    myg3 = Button(virsus, text="Keisti vartotojo grupe")
    myg3.pack(side=BOTTOM)
    root.mainloop()

def informacija():
    root = Tk()
    root.title("Vartotoju informacija")
    root.geometry("400x100")
    tekstas = Text(root, height=1, width=15)
    tekstas.pack(side=TOP)

    virsus = Frame(root)
    virsus.pack()
    apacia = Frame(root)
    apacia.pack(side=BOTTOM)
    myg1 = Button(virsus, text="Rodyti informacija", command=lambda: gauti())
    myg1.pack(side=BOTTOM)

    def gauti():
        imti = tekstas.get("1.0", "end-1c")
        info = subprocess.call("id '{imti}' ".format(imti=imti), shell=True)
        w = Label(root, text= "info")
        w.pack(LEFT)

    root.mainloop()

myg1 = Button(virsus, text="Filtruoti pagal uzklausa", command=filtras)
myg2 = Button(apacia, text="Filtrouti pagal vartotoju prisijungimus", command=vartotojas)
myg3 = Button(virsus, text="Atidaryti/uzdaryti portus", command=portas)
myg4 = Button(apacia, text="Administruoti vartotojus", command=administ)
myg5 = Button(apacia, text="Vartotojo informacija", command=informacija)

myg1.pack(side=LEFT)
myg2.pack(side=RIGHT)
myg3.pack(side=LEFT)
myg4.pack(side=RIGHT)
myg5.pack(side=RIGHT)

root.mainloop()


问:
Awk, gsub, ampersands and unexpected expansion
First, apologies for the potentially duplicate question. I'm new to bash scripting and I can't even figure out some keywords to search with. With that said, I tried to simplify problem description as much as I can:

I have a text file (test.txt) that contains only this line:

```<code>REPLACE
</code>```

I ran the following command which is supposed to replace file's text (i.e REPLACE) with code variable value if (A & B).

```<code>code="if (A & B)" ; awk -v var="${code}" '{ gsub(/REPLACE/, var); print }' test.txt
</code>```

Expected output I expect code variable value to be printed as is:

```<code>if (A & B)
</code>```

Actual output somehow the ampersand is expanded into 'REPLACE', which is gsub regexp parameter:

```<code>if (A REPLACE B)
</code>```

Perhaps I need to escape the ampersand but unfortunately, code variable population is out of my control, so I can't manipulate its value manually.

FYI awk version is "GNU Awk 4.1.4, API: 1.1 (GNU MPFR 3.1.5, GNU MP 6.1.2)"

Thanks!

答:
& is a backreference metacharacter in many tools and it means "the string that matched the regexp you searched for". If you're trying to use literal strings then use literal strings instead of regexps and backreferences.

e.g.:

```<code>code="if (A & B)"
awk -v old="REPLACE" -v new="$code" 's=index($0,old){$0=substr($0,1,s-1) new substr($0,s+length(old))} 1' test.txt
</code>```

The alternative, trying to santize regexps and replacements, is complicated and error prone and generally is not for the faint of heart, see: Is it possible to escape regex metacharacters reliably with sed

Body:
First, apologies for the potentially duplicate question. I'm new to bash scripting and I can't even figure out some keywords to search with. With that said, I tried to simplify problem description as much as I can:

I have a text file (test.txt) that contains only this line:

REPLACE

I ran the following command which is supposed to replace file's text (i.e REPLACE) with code variable value if (A & B).

code="if (A & B)" ; awk -v var="${code}" '{ gsub(/REPLACE/, var); print }' test.txt

Expected output I expect code variable value to be printed as is:

if (A & B)

Actual output somehow the ampersand is expanded into 'REPLACE', which is gsub regexp parameter:

if (A REPLACE B)

Perhaps I need to escape the ampersand but unfortunately, code variable population is out of my control, so I can't manipulate its value manually.

FYI awk version is "GNU Awk 4.1.4, API: 1.1 (GNU MPFR 3.1.5, GNU MP 6.1.2)"

Thanks!

Body:
& is a backreference metacharacter in many tools and it means "the string that matched the regexp you searched for". If you're trying to use literal strings then use literal strings instead of regexps and backreferences.

e.g.:

code="if (A & B)"
awk -v old="REPLACE" -v new="$code" 's=index($0,old){$0=substr($0,1,s-1) new substr($0,s+length(old))} 1' test.txt

The alternative, trying to santize regexps and replacements, is complicated and error prone and generally is not for the faint of heart, see: Is it possible to escape regex metacharacters reliably with sed


问:
Facebook SDK login never calls back my application on iOS 9
I've followed this guide to update my application to use Facebook SDK 4.6 to work properly when built with the iOS 9 SDK.

When I tap the login button now, a Safari view controller gets presented (shouldn't it redirect to the Facebook app?), but after accepting permission the Safari view controller is never dismissed. It loads a new blank page and sits there doing nothing. If I tap the Done button, the returned FBSDKLoginManagerLoginResult's isCancelled is true.

Is it normal that the SDK is choosing the Safari view controller over the Facebook app? And why am I not getting callbacks after login is complete?

答:
for xamarin users :</p>

```<code>public override bool OpenUrl(UIApplication application, NSUrl url, string sourceApplication, NSObject annotation)
        {

            OnUrlProtocolDetected(url.ToString());
            if (url.AbsoluteString.StartsWith("fb"))
            {
                return ApplicationDelegate.SharedInstance.OpenUrl(application, url, sourceApplication, annotation);
            }

}
</code>```

Body:
for xamarin users :

public override bool OpenUrl(UIApplication application, NSUrl url, string sourceApplication, NSObject annotation)
        {

            OnUrlProtocolDetected(url.ToString());
            if (url.AbsoluteString.StartsWith("fb"))
            {
                return ApplicationDelegate.SharedInstance.OpenUrl(application, url, sourceApplication, annotation);
            }

}


问:
C# add items to listview not working
```<code>private void showResultsList()
{
    IWebElement table = resultFinder.FindElementById("records");
    IList<IWebElement> trElements = table.FindElements(By.TagName("tr"));
    IList<IWebElement> tdElements;
    IList<IWebElement> aElements = table.FindElements(By.TagName("a"));

    mainWindow.Dispatcher.Invoke(() =>
    {
        ListView listView = (ListView)mainWindow.FindName("Search_ResultsList");
        ItemCollection resultsListItems = listView.Items;
        listView.Items.Clear();

        for (int i = 0; i < trElements.Count; i++)
        {
            IWebElement trElement = trElements[i];
            tdElements = trElement.FindElements(By.TagName("td"));
            aElements = trElement.FindElements(By.TagName("a"));
            string index = (i + 1).ToString();
            string text = tdElements[2].Text;
            // this line removes the last part of the content, which says "Aggiungi ai preferiti"
            string result = text.Substring(0, text.LastIndexOf('\n'));
            string hyperLink = aElements[0].GetAttribute("href");

            resultsListItems.Add(new ResultsListItem { Index = index, Result = result, HyperLink = hyperLink });
        }
    });
}
</code>```

XAML file

```<code><ListView Name="Search_ResultsList" HorizontalAlignment="Left" Height="886" Margin="10,10,0,0" VerticalAlignment="Top" Width="440" BorderBrush="#FF707070">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="N." Width="30" DisplayMemberBinding="{Binding Index}"/>
            <GridViewColumn Header="Result" Width="387" DisplayMemberBinding="{Binding Result}"/>
        </GridView>
    </ListView.View>
</ListView>
</code>```

ResultsListItem class

```<code>class ResultsListItem : ListViewItem
{
    public string Index { get; set; }
    public string Result { get; set; }
    public string HyperLink { get; set; }
}
</code>```

I'm trying to show this list into a ListView object by adding the ResultsListItem to the collection of items. When I run the program the list doesn't show the content of the listItems, just a list of empty items. What do I do wrong?
Thanks in advance.

答:
As you have already noticed your ResultsListItem should not inherit from ListViewItem:

```<code>public class ResultsListItem
{
    public string Index { get; set; }
    public string Result { get; set; }
    public string HyperLink { get; set; }
}
</code>```

The reason for this is that an implicit ListViewItem container is automatically generated for each item in the Items/ItemsSource collection of the ListView that is not a ListViewItem.

If you add a ListViewItem to the Items/ItemsSource, no container is generated and that's why you don't see any values in your ListView.

Also, it doesn't make any sense for a data object to inherit from a UI type.

Title: C# add items to listview not working

Body:
private void showResultsList()
{
    IWebElement table = resultFinder.FindElementById("records");
    IList<IWebElement> trElements = table.FindElements(By.TagName("tr"));
    IList<IWebElement> tdElements;
    IList<IWebElement> aElements = table.FindElements(By.TagName("a"));

    mainWindow.Dispatcher.Invoke(() =>
    {
        ListView listView = (ListView)mainWindow.FindName("Search_ResultsList");
        ItemCollection resultsListItems = listView.Items;
        listView.Items.Clear();

        for (int i = 0; i < trElements.Count; i++)
        {
            IWebElement trElement = trElements[i];
            tdElements = trElement.FindElements(By.TagName("td"));
            aElements = trElement.FindElements(By.TagName("a"));
            string index = (i + 1).ToString();
            string text = tdElements[2].Text;
            // this line removes the last part of the content, which says "Aggiungi ai preferiti"
            string result = text.Substring(0, text.LastIndexOf('\n'));
            string hyperLink = aElements[0].GetAttribute("href");

            resultsListItems.Add(new ResultsListItem { Index = index, Result = result, HyperLink = hyperLink });
        }
    });
}

XAML file

<ListView Name="Search_ResultsList" HorizontalAlignment="Left" Height="886" Margin="10,10,0,0" VerticalAlignment="Top" Width="440" BorderBrush="#FF707070">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="N." Width="30" DisplayMemberBinding="{Binding Index}"/>
            <GridViewColumn Header="Result" Width="387" DisplayMemberBinding="{Binding Result}"/>
        </GridView>
    </ListView.View>
</ListView>

ResultsListItem class

class ResultsListItem : ListViewItem
{
    public string Index { get; set; }
    public string Result { get; set; }
    public string HyperLink { get; set; }
}

I'm trying to show this list into a ListView object by adding the ResultsListItem to the collection of items. When I run the program the list doesn't show the content of the listItems, just a list of empty items. What do I do wrong?
Thanks in advance.

Body:
As you have already noticed your ResultsListItem should not inherit from ListViewItem:

public class ResultsListItem
{
    public string Index { get; set; }
    public string Result { get; set; }
    public string HyperLink { get; set; }
}

The reason for this is that an implicit ListViewItem container is automatically generated for each item in the Items/ItemsSource collection of the ListView that is not a ListViewItem.

If you add a ListViewItem to the Items/ItemsSource, no container is generated and that's why you don't see any values in your ListView.

Also, it doesn't make any sense for a data object to inherit from a UI type.


问:
dotnet pack - How do you specify the name of the package?
I am trying to pack a library as a NuGet package in powershell, like so:

```<code>function Create-NuGetPackages($projects) {

    if (!(Test-Path $NuGetPackageDirectory)) {
        New-Item $NuGetPackageDirectory -ItemType Directory
    }

    foreach ($project in $projects) {
        pushd $project.DirectoryName

        & dotnet.exe pack --configuration $Configuration --output $NuGetPackageDirectory --no-build

        popd
    }

    return $NuGetPackageDirectory
}
</code>```

The project is using a project.json and a .xproj file (there is also a .csproj file for working on the project in .NET 4.5.1). The above command functions, but I end up with a NuGet package name MyProject.Core and I need it to be MyProject to match the legacy packages.

The project is a port and the most sensible thing to do is name the folder after the Java package, which is MyProject.Core, but I can't seem to figure out how to make it generate a NuGet package with a different name.

I have tried using this command on the CLI:

```<code>dotnet pack "src\MyProject.Core\MyProject.csproj" --output NuGetPackages\ --configuration "Release"
</code>```

but it gives the error:

```<code>Unable to find a project.json in src\MyProject.Core\MyProject.csproj\project.json
</code>```

According to this page:

PROJECT

The project to pack. It's either a path to a csproj file or to a directory. If omitted, it defaults to the current directory.

So why if I specify the path of the csproj does it look for a project.json file?

I was able to work around this issue for the name of the assembly by specifying:

```<code>"buildOptions": { "outputName": "MyProject" },
</code>```

But the pack command totally ignores this. There also doesn't seem to be an option to specify the name of the NuGet package in the packOptions section.

I had a look at this old question but it looks like they are talking about the nuget tool, not the dotnet tool.

Is my only option to rename the folder (which will likely cause a lot of other stuff to break now), or is there another way to specify the NuGet package name for the dotnet pack command?

On a side note, I have read in several places that project.json is going away and we are going back to .csproj, but it is unclear when that will take effect. Should I be aiming to eliminate the project.json file or is it too early for that?

答:
Metadata are specified in csproj, as the documentation says,

https://learn.microsoft.com/en-us/nuget/guides/create-net-standard-packages-vs2017#edit-metadata-in-the--csproj-file

```<code><PropertyGroup>
 <TargetFramework>netstandard1.4</TargetFramework>
 <PackageId>AppLogger.YOUR_NAME</PackageId>
 <PackageVersion>1.0.0</PackageVersion>
 <Authors>YOUR_NAME</Authors>
 <Description>Awesome application logging utility</Description>
 <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance>
 <PackageReleaseNotes>First release</PackageReleaseNotes>
 <Copyright>Copyright 2016 (c) Contoso Corporation. All rights reserved.</Copyright>
 <PackageTags>logger logging logs</PackageTags>
</PropertyGroup>
</code>```

Body:
I am trying to pack a library as a NuGet package in powershell, like so:

function Create-NuGetPackages($projects) {

    if (!(Test-Path $NuGetPackageDirectory)) {
        New-Item $NuGetPackageDirectory -ItemType Directory
    }

    foreach ($project in $projects) {
        pushd $project.DirectoryName

        & dotnet.exe pack --configuration $Configuration --output $NuGetPackageDirectory --no-build

        popd
    }

    return $NuGetPackageDirectory
}

The project is using a project.json and a .xproj file (there is also a .csproj file for working on the project in .NET 4.5.1). The above command functions, but I end up with a NuGet package name MyProject.Core and I need it to be MyProject to match the legacy packages.

The project is a port and the most sensible thing to do is name the folder after the Java package, which is MyProject.Core, but I can't seem to figure out how to make it generate a NuGet package with a different name.

I have tried using this command on the CLI:

dotnet pack "src\MyProject.Core\MyProject.csproj" --output NuGetPackages\ --configuration "Release"

but it gives the error:

Unable to find a project.json in src\MyProject.Core\MyProject.csproj\project.json

According to this page:

PROJECT

The project to pack. It's either a path to a csproj file or to a directory. If omitted, it defaults to the current directory.

So why if I specify the path of the csproj does it look for a project.json file?

I was able to work around this issue for the name of the assembly by specifying:

"buildOptions": { "outputName": "MyProject" },

But the pack command totally ignores this. There also doesn't seem to be an option to specify the name of the NuGet package in the packOptions section.

I had a look at this old question but it looks like they are talking about the nuget tool, not the dotnet tool.

Is my only option to rename the folder (which will likely cause a lot of other stuff to break now), or is there another way to specify the NuGet package name for the dotnet pack command?

On a side note, I have read in several places that project.json is going away and we are going back to .csproj, but it is unclear when that will take effect. Should I be aiming to eliminate the project.json file or is it too early for that?

Body:
Metadata are specified in csproj, as the documentation says,

https://learn.microsoft.com/en-us/nuget/guides/create-net-standard-packages-vs2017#edit-metadata-in-the--csproj-file

<PropertyGroup>
 <TargetFramework>netstandard1.4</TargetFramework>
 <PackageId>AppLogger.YOUR_NAME</PackageId>
 <PackageVersion>1.0.0</PackageVersion>
 <Authors>YOUR_NAME</Authors>
 <Description>Awesome application logging utility</Description>
 <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance>
 <PackageReleaseNotes>First release</PackageReleaseNotes>
 <Copyright>Copyright 2016 (c) Contoso Corporation. All rights reserved.</Copyright>
 <PackageTags>logger logging logs</PackageTags>
</PropertyGroup>


问:
How to test an unsigned Firefox extension?
Firefox 43 now enforces add-on signing. I don't understand how one is to test and debug an extension in these versions of Firefox prior to having the extension signed.

If I'm writing a new extension, how do I go about testing the unsigned version in the latest versions of Firefox? Is there an explicit way to disable the signing enforcement for developers?

答: Install Waterfox. It is identical to Firefox, but allows unsigned extensions. You won't even know it is not regular Firefox. Problem solved.</p>


问:
How can I create raster plots with the same colour scale in R
I'm creating some maps from raster files using the "raster" package in R. I'd like to create comparison rasters, showing several maps side by side. It's important for this that the colour scales used are the same for all maps, regardless of the values in each map. For example, if map 1 has values from 0-1, and map 2 has values from 0-0.5, cells with a value of 0.5 should have the same colour on both maps.

For example:

map 1 has values from 0 to 1

map 2 has values from 0 to 0.5

the colour goes from red (lowest) to green (highest)

I would like a value of 0.5 to have the same colour in both maps (i.e. yellow, as halfway between red and green). The current behaviour is that it is yellow in map 1, and green in map 2.

I can't find a way to make this work. I can't see any way to set the range of pixel values to use with the plotting function. setMinMax() doesn't help (as 'plot' always calculates the values). Even trying to set the values by hand (e.g. g1@data@max <- 10) doesn't work (these are ignored when plotting).

Finally, making a stack of the maps (which might be expected to plot everything on the same colour scale) doesn't work either - each map still has it's own colour scale.

Any thoughts on how to do this?

EDIT:

The solution I ended up using is:

```<code>plot( d, col=rev( rainbow( 99, start=0,end=1 ) ), breaks=seq(min(minValue( d )),max(maxValue(d)),length.out=100) )
</code>```

答:
There is more work to be done here in 'raster' but here is a hack:

```<code> library(raster)
 r1 <- r2 <- r3 <- raster(ncol=10, nrow=10)
 r1[] <- runif(ncell(r1))
 r2[] <- runif(ncell(r2)) / 2
 r3[] <- runif(ncell(r3)) * 1.5
 r3 <- min(r3, 1)
 s <- stack(r1, r2, r3)

 brk <- c(0, 0.25, 0.5, 0.75, 1)
 par(mfrow=c(1,3))
 plot(r1, breaks=brk, col=rainbow(4), legend=F)
 plot(r1, breaks=brk, col=rainbow(4), legend.only=T, box=F)
 plot(r2, breaks=brk, col=rainbow(4), legend=F)
 plot(r1, breaks=brk, col=rainbow(4), legend.only=T, box=F)
 plot(r3, breaks=brk, col=rainbow(4), legend=F)
 plot(r1, breaks=brk, col=rainbow(4), legend.only=T, box=F)
</code>```

You can also use the spplot function (sp package)

```<code> s <- stack(r1, r2, r3)
 sp <- as(s, 'SpatialGridDataFrame')
 spplot(sp)
</code>```

You can also send the values to ggplot (search the r-sig-geo archives for examples)
If your RasterLayer links to a very large file, you might first do, before going to ggplot

```<code>r <- sampleRegular(r, size=100000, asRaster=TRUE)
</code>```

and then perhaps

```<code>m <- as.matrix(r)
</code>```

Body:
I'm creating some maps from raster files using the "raster" package in R. I'd like to create comparison rasters, showing several maps side by side. It's important for this that the colour scales used are the same for all maps, regardless of the values in each map. For example, if map 1 has values from 0-1, and map 2 has values from 0-0.5, cells with a value of 0.5 should have the same colour on both maps.

For example:

map 1 has values from 0 to 1

map 2 has values from 0 to 0.5

the colour goes from red (lowest) to green (highest)

I would like a value of 0.5 to have the same colour in both maps (i.e. yellow, as halfway between red and green). The current behaviour is that it is yellow in map 1, and green in map 2.

I can't find a way to make this work. I can't see any way to set the range of pixel values to use with the plotting function. setMinMax() doesn't help (as 'plot' always calculates the values). Even trying to set the values by hand (e.g. g1@data@max <- 10) doesn't work (these are ignored when plotting).

Finally, making a stack of the maps (which might be expected to plot everything on the same colour scale) doesn't work either - each map still has it's own colour scale.

Any thoughts on how to do this?

EDIT:

The solution I ended up using is:

plot( d, col=rev( rainbow( 99, start=0,end=1 ) ), breaks=seq(min(minValue( d )),max(maxValue(d)),length.out=100) )

Body:
There is more work to be done here in 'raster' but here is a hack:

 library(raster)
 r1 <- r2 <- r3 <- raster(ncol=10, nrow=10)
 r1[] <- runif(ncell(r1))
 r2[] <- runif(ncell(r2)) / 2
 r3[] <- runif(ncell(r3)) * 1.5
 r3 <- min(r3, 1)
 s <- stack(r1, r2, r3)

 brk <- c(0, 0.25, 0.5, 0.75, 1)
 par(mfrow=c(1,3))
 plot(r1, breaks=brk, col=rainbow(4), legend=F)
 plot(r1, breaks=brk, col=rainbow(4), legend.only=T, box=F)
 plot(r2, breaks=brk, col=rainbow(4), legend=F)
 plot(r1, breaks=brk, col=rainbow(4), legend.only=T, box=F)
 plot(r3, breaks=brk, col=rainbow(4), legend=F)
 plot(r1, breaks=brk, col=rainbow(4), legend.only=T, box=F)

You can also use the spplot function (sp package)

 s <- stack(r1, r2, r3)
 sp <- as(s, 'SpatialGridDataFrame')
 spplot(sp)

You can also send the values to ggplot (search the r-sig-geo archives for examples)
If your RasterLayer links to a very large file, you might first do, before going to ggplot

r <- sampleRegular(r, size=100000, asRaster=TRUE)

and then perhaps

m <- as.matrix(r)


问:
Scaling a site title uniformly with CSS
I have a site title in a Wordpress site that is scaled on hover with some CSS code. The problem is that the title is not scaled uniformly, but runs left. How to solve this?

The HTML code:

```<code><div class="site-branding" style="margin-bottom: 58px;">
    <div class="wrap">
        <div class="site-branding-text">
            <h1 class="site-title"><a href="http://dev.infopsi.md/" rel="home">InfoPsi.md</a></h1>
            <p class="site-description">Portalul comunității psihologice din Republica Moldova</p>
        </div><!-- .site-branding-text -->
    </div><!-- .wrap -->
</div>
</code>```

And the CSS:

```<code>.site-title {
    font-size: 1.5rem;
    text-transform: initial;
    margin-top: 5px;
    font-family: cursive;
    font-weight: initial;
    line-height: initial;
    letter-spacing: initial;
    text-shadow: 1px 1px 0 #CCC, 2px 2px 0 #CCC, 3px 3px 0 #444, 4px 4px 0 #444, 5px 5px 0 #444, 6px 6px 0 #444;
}
.site-title:hover {
    /* CSS3 Transform Effect */
    -webkit-transform: scale(1.1);     /* Safari & Chrome */
    -moz-transform: scale(1.1);        /* Firefox */
    -o-transform: scale(1.1);          /* Opera */
}
.site-title a {
    color: red;
}
</code>```

See a working example:
https://jsfiddle.net/iuriemalai/o4r8xegu/5/

答:
Add

```<code>display:inline-block
</code>```

to your .site-title CSS rules

Title: Scaling a site title uniformly with CSS

Body:
I have a site title in a Wordpress site that is scaled on hover with some CSS code. The problem is that the title is not scaled uniformly, but runs left. How to solve this?

The HTML code:

InfoPsi.md

Portalul comunității psihologice din Republica Moldova

And the CSS:

.site-title {
    font-size: 1.5rem;
    text-transform: initial;
    margin-top: 5px;
    font-family: cursive;
    font-weight: initial;
    line-height: initial;
    letter-spacing: initial;
    text-shadow: 1px 1px 0 #CCC, 2px 2px 0 #CCC, 3px 3px 0 #444, 4px 4px 0 #444, 5px 5px 0 #444, 6px 6px 0 #444;
}
.site-title:hover {
    /* CSS3 Transform Effect */
    -webkit-transform: scale(1.1);     /* Safari & Chrome */
    -moz-transform: scale(1.1);        /* Firefox */
    -o-transform: scale(1.1);          /* Opera */
}
.site-title a {
    color: red;
}

See a working example:
https://jsfiddle.net/iuriemalai/o4r8xegu/5/

Body:
Add

display:inline-block

to your .site-title CSS rules


问:
Visual Studio 2012 ALT+Number Sendkeys Doesn't Work
Hello I am making a vs2012 project where when the timer reaches 10 seconds the program will send ALT+2. the F1 alone worked with sendkeys but wont work with ALT TAB or ALT+Number. Here are some codes i tried so far that doesn't work.

```<code>    If mintCount = 16 Then SendKeys.Send("%2")
    If mintCount = 16 Then SendKeys.Send("%(2)")
    If mintCount = 16 Then SendKeys.Send("(%2)")
    If mintCount = 16 Then SendKeys.Send("%{2}")
    If mintCount = 16 Then SendKeys.Send("%{TAB}")
</code>```

any suggestion or tip would be appreciated thank you so much..

答:
You can utilize my InputHelper class. It P/Invokes the native SendInput() function of the WinAPI. It is more flexible than SendKeys and also supports a wider set of keys!

EDIT (2019-09-20)

InputHelper has since long been moved to its own library. The answer has been updated to reflect this change.

Download InputHelper from GitHub:

  https://github.com/Visual-Vincent/InputHelper/releases

Usage:

```<code>InputHelper.Keyboard.SetKeyState(Keys.Alt, True) 'True = Hold ALT key down.
InputHelper.Keyboard.PressKey(Keys.D2) 'Press "2".
InputHelper.Keyboard.SetKeyState(Keys.Alt, False) 'False = Release ALT key.
</code>```

Body:
Hello I am making a vs2012 project where when the timer reaches 10 seconds the program will send ALT+2. the F1 alone worked with sendkeys but wont work with ALT TAB or ALT+Number. Here are some codes i tried so far that doesn't work.

    If mintCount = 16 Then SendKeys.Send("%2")
    If mintCount = 16 Then SendKeys.Send("%(2)")
    If mintCount = 16 Then SendKeys.Send("(%2)")
    If mintCount = 16 Then SendKeys.Send("%{2}")
    If mintCount = 16 Then SendKeys.Send("%{TAB}")

any suggestion or tip would be appreciated thank you so much..

Body:
You can utilize my InputHelper class. It P/Invokes the native SendInput() function of the WinAPI. It is more flexible than SendKeys and also supports a wider set of keys!

EDIT (2019-09-20)

InputHelper has since long been moved to its own library. The answer has been updated to reflect this change.

Download InputHelper from GitHub:

  https://github.com/Visual-Vincent/InputHelper/releases

Usage:

InputHelper.Keyboard.SetKeyState(Keys.Alt, True) 'True = Hold ALT key down.
InputHelper.Keyboard.PressKey(Keys.D2) 'Press "2".
InputHelper.Keyboard.SetKeyState(Keys.Alt, False) 'False = Release ALT key.