问:
I am creating an email spammer, for an outstanding cause
In Cuba, web access is extremely censored, so I created a tool that allows more than 50,000 people to browse the Internet through email. Cubans send me an email with an URL in the subject line, and I email them back with the response. Read more at https://apretaste.com.

It was working like a charm, till the communist government of Cuba started blocking my emails. My solution was rotation.

I started with Amazon SES, and I was changing the domain each time it was blocked, but Amazon adds a header to all emails, and once they blocked the header no email from SES was able to reach Cuba any more. The same happened with Mailgun and others, they all add headers.

Currently I am creating Gmail accounts and sending via SMTP, but Google blocks me for no reason and only allows to send 100 emails a day per account. Also I can only create few emails using the same IP address/phone, so I was forced to use anonymous proxies and fake Chinese phones. Now I am fighting a war on two fronts.

An email can be blocked by three parameters: IP address, domain, and email address.

It will be terrific if I can set up my own Postfix server at a VPS that auto-rotates the IP address. Even better if I can simulate "gmail.com", to avoid purchasing a new domain every day.

All the intents to create what I call "the ultimate sender" just either reach the spam folder or add unwanted headers making it too easy to block. I feel exhausted. I hit a knowledge barrier here.

I know I am crossing to the dark side, but this is for a very good cause. Thousands count on this service as their only source of unbiased news, social network and to feel part of the 21st century.

Can you please help me implementing "the ultimate sender", or pointing to another solution that I may be missing?

答:
Since the users are willing to receive emails form you then your shouldn't be blocked.

When you mentioned you are getting block does it mean your mail is going in spam or is getting lost in between sending and receiving or it is getting bounced back??

My suggestion would be to setup your own mail server and follow as below:

-Get approx 25 or more ip to rotate. (IP is the most imp part which is tracked and is accountable for the reputation of your mail server)

Don't start sending emails in bulk from the word go it is better to gradullay increase the email volume so that mail server reputation nicely built

keep changing the format of the email often

encourage user to add yourself to there contact list

your best part is user are willing to receive emails from you and you would reply to revived email is the USP of yours but still i will recommend you to  register for FBL so that you would know which user is reporting you as spam and you can remove him from your list and never send him email again.

using best practice to send emails like dkim, SPF, dmarc are also vital.

Hope my answer was of some help to you. If you need step by step guide to step up mail server let me know.


来源: stackexchange

问:
Hardware and software setup for accessing and monitoring text messages on a phone connection
What hardware/software do I need to setup a machine that monitors incoming text ("SMS") messages on a phone connection? The software needs to be able to read the message, copy it to a database and then delete it.</p>

答:
Three ideas:

Use google voice instead of a cell phone, and your received SMS will arrive as email

Obtain a cheap phone that features a serial port on the headset connection and can use AT commands (AT+CMGR or something like that) to receive SMS, connect this to a computer's serial port using a cable with level translation

Use an Android phone and write an application which does this.

ContentLicense: CC BY-SA 2.5


问:
Set "Homepage" in Asp.Net MVC
In asp.net MVC the "homepage" (ie the route that displays when hitting www.foo.com) is set to Home/Index .

Where is this value stored?

How can I change the "homepage"?

Is there anything more elegant than using RedirectToRoute() in the Index action of the home controller?

I tried grepping for Home/Index in my project and couldn't find a reference, nor could I see anything in IIS (6). I looked at the default.aspx page in the root, but that didn't seem to do anything relevent.

Thanks

答:
Attribute Routing in MVC 5

Before MVC 5 you could map URLs to specific actions and controllers by calling routes.MapRoute(...) in the RouteConfig.cs file. This is where the url for the homepage is stored (Home/Index). However if you modify the default route as shown below,

```<code>routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
</code>```

keep in mind that this will affect the URLs of other actions and controllers. For example, if you had a controller class named ExampleController and an action method inside of it called DoSomething, then the expected default url ExampleController/DoSomething will no longer work because the default route was changed.

A workaround for this is to not mess with the default route and create new routes in the RouteConfig.cs file for other actions and controllers like so,

```<code>routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
    name: "Example",
    url: "hey/now",
    defaults: new { controller = "Example", action = "DoSomething", id = UrlParameter.Optional }
);
</code>```

Now the DoSomething action of the ExampleController class will be mapped to the url hey/now. But this can get tedious to do for every time you want to define routes for different actions. So in MVC 5 you can now add attributes to match urls to actions like so,

```<code>public class HomeController : Controller
{
    // url is now 'index/' instead of 'home/index'
    [Route("index")]
    public ActionResult Index()
    {
        return View();
    }
    // url is now 'create/new' instead of 'home/create'
    [Route("create/new")]
    public ActionResult Create()
    {
        return View();
    }
}
</code>```

Title: Set "Homepage" in Asp.Net MVC

Body:
Attribute Routing in MVC 5

Before MVC 5 you could map URLs to specific actions and controllers by calling routes.MapRoute(...) in the RouteConfig.cs file. This is where the url for the homepage is stored (Home/Index). However if you modify the default route as shown below,

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

keep in mind that this will affect the URLs of other actions and controllers. For example, if you had a controller class named ExampleController and an action method inside of it called DoSomething, then the expected default url ExampleController/DoSomething will no longer work because the default route was changed.

A workaround for this is to not mess with the default route and create new routes in the RouteConfig.cs file for other actions and controllers like so,

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
    name: "Example",
    url: "hey/now",
    defaults: new { controller = "Example", action = "DoSomething", id = UrlParameter.Optional }
);

Now the DoSomething action of the ExampleController class will be mapped to the url hey/now. But this can get tedious to do for every time you want to define routes for different actions. So in MVC 5 you can now add attributes to match urls to actions like so,

public class HomeController : Controller
{
    // url is now 'index/' instead of 'home/index'
    [Route("index")]
    public ActionResult Index()
    {
        return View();
    }
    // url is now 'create/new' instead of 'home/create'
    [Route("create/new")]
    public ActionResult Create()
    {
        return View();
    }
}

ContentLicense: CC BY-SA 3.0


问:
Definition and Restriction of RESTFUL service
I currently have an c#.net app that is communicating with another c#.net app. One is installed on client and the other is installed on the server. They are both binded in socket using tcp connection. When the client requests a resource, the server returns the requested resource in JSON format. I keep hearing in other forums that REST requires HTTP. However, I am not using HTTP here.. Does this mean that I am not using REST as well? even though my application is stateless? If not, What do you formally call this communication?</p>

答:
REST is protocol-independent, per the Fielding Dissertation that defined it. You can have systems which employ the REST architectural style over non-HTTP protocols.

The Representational State Transfer (REST) style is an abstraction of the architectural elements within a distributed hypermedia system. REST ignores the details of component implementation and protocol syntax in order to focus on the roles of components, the constraints upon their interaction with other components, and their interpretation of significant data elements. It encompasses the fundamental constraints upon components, connectors, and data that define the basis of the Web architecture, and thus the essence of its behavior as a network-based application.

Please note that statelessness does not mean it is REST. You still need a hypermedia-driven system written around resources.


问:
Top and bottom borders
I have some code here, this gives me a bottom border, how can I add to it to make it show top and bottom borders?

table.bottomBorder {
  border-collapse: collapse;
}

table.bottomBorder td,
table.bottomBorder th {
  border-bottom: 1px solid lightgrey;
  padding: 10px;
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table class="bottomBorder">
  <tr>
    <th>Table Header</th>
    <th>Table Header</th>
  </tr>
  <tr>
    <td>Table cell</td>
    <td>Table cell</td>
  </tr>
  <tr>
    <td>Table cell</td>
    <td>Table cell</td>
  </tr>
</table></code>```

答:
```<code>table.bottomBorder th {
  border-bottom: 1px solid lightgrey;
  border-top: 1px solid lightgrey;
  padding: 10px;
  text-align: center;
}
</code>```

read more about borders here: http://www.cssbasics.com/chapter_13_css_borders.html

Title: Top and bottom borders

Body:
I have some code here, this gives me a bottom border, how can I add to it to make it show top and bottom borders?

table.bottomBorder {
  border-collapse: collapse;
}

table.bottomBorder td,
table.bottomBorder th {
  border-bottom: 1px solid lightgrey;
  padding: 10px;
  text-align: center;
}

    Table Header
    Table Header

    Table cell
    Table cell

    Table cell
    Table cell

Body:
table.bottomBorder th {
  border-bottom: 1px solid lightgrey;
  border-top: 1px solid lightgrey;
  padding: 10px;
  text-align: center;
}

read more about borders here: http://www.cssbasics.com/chapter_13_css_borders.html


问:
Inline plugin doesn't work
According to the Chart.js docs, the following code should work:

```<code>new Chart(document.getElementById(chartID), {
   type: 'pie',
   responsive: true,
   maintainAspectRatio: false,
   data: {
      labels: graph.globals.labels,
      datasets: [{
         backgroundColor: pieOptions.backgrounds,
         data: pieOptions.objToArr(graph.meetingsData),
         hoverBorderWidth: 5,
         borderColor: 'transparent',
      }]
   },
   options: {
      title: {
         display: true,
         text: graph.globals.title,
      },
      legend: {
         display: true,
         position: 'bottom',
         fullWidth: false,
         onClick: () => {},
         labels: {
            generateLabels: (chart) => {
               return pieOptions.legendLeft(chart);
            }
         }
      },
      plugins: [{
         beforeInit: function(chart, options) {
            console.log('yolo');
         }
      }]
      rotation: 3.9,
   }
});
</code>```

However, when I create the plugin using a variable, or create it inline like shown above, it doesn't log anything. The only way that I can use plugin, is when I register it globally.

Can somebody explain to me why it doesn't work?

答:
plugins should be placed in its own config section, and not nested under options.

Instead of:

```<code>options: {
    title: {
        display: true,
        text: graph.globals.title,
    },
    legend: {
        display: true,
        position: 'bottom',
        fullWidth: false,
        onClick: () => {},
        labels: {
            generateLabels: (chart) => {
                return pieOptions.legendLeft(chart);
            }
        }
    },
    plugins: [{
        beforeInit: function(chart, options) {
            console.log('yolo');
        }
    }]
    rotation: 3.9,
}
</code>```

Your code should look like:

```<code>options: {
    title: {
        display: true,
        text: graph.globals.title,
    },
    legend: {
        display: true,
        position: 'bottom',
        fullWidth: false,
        onClick: () => {},
        labels: {
        //   generateLabels: (chart) => {
        //      return pieOptions.legendLeft(chart);
        //    }
        }
    },
    rotation: 3.9,
},
plugins: [{
    beforeInit: function(chart, options) {
        console.log('yolo');
    }
}]
</code>```

Working JSFiddle: https://jsfiddle.net/r1x63b8v/

Title: Inline plugin doesn't work

Body:
According to the Chart.js docs, the following code should work:

new Chart(document.getElementById(chartID), {
   type: 'pie',
   responsive: true,
   maintainAspectRatio: false,
   data: {
      labels: graph.globals.labels,
      datasets: [{
         backgroundColor: pieOptions.backgrounds,
         data: pieOptions.objToArr(graph.meetingsData),
         hoverBorderWidth: 5,
         borderColor: 'transparent',
      }]
   },
   options: {
      title: {
         display: true,
         text: graph.globals.title,
      },
      legend: {
         display: true,
         position: 'bottom',
         fullWidth: false,
         onClick: () => {},
         labels: {
            generateLabels: (chart) => {
               return pieOptions.legendLeft(chart);
            }
         }
      },
      plugins: [{
         beforeInit: function(chart, options) {
            console.log('yolo');
         }
      }]
      rotation: 3.9,
   }
});

However, when I create the plugin using a variable, or create it inline like shown above, it doesn't log anything. The only way that I can use plugin, is when I register it globally.

Can somebody explain to me why it doesn't work?

Body:
plugins should be placed in its own config section, and not nested under options.

Instead of:

options: {
    title: {
        display: true,
        text: graph.globals.title,
    },
    legend: {
        display: true,
        position: 'bottom',
        fullWidth: false,
        onClick: () => {},
        labels: {
            generateLabels: (chart) => {
                return pieOptions.legendLeft(chart);
            }
        }
    },
    plugins: [{
        beforeInit: function(chart, options) {
            console.log('yolo');
        }
    }]
    rotation: 3.9,
}

Your code should look like:

options: {
    title: {
        display: true,
        text: graph.globals.title,
    },
    legend: {
        display: true,
        position: 'bottom',
        fullWidth: false,
        onClick: () => {},
        labels: {
        //   generateLabels: (chart) => {
        //      return pieOptions.legendLeft(chart);
        //    }
        }
    },
    rotation: 3.9,
},
plugins: [{
    beforeInit: function(chart, options) {
        console.log('yolo');
    }
}]

Working JSFiddle: https://jsfiddle.net/r1x63b8v/


问:
Spring Data REST - RepositoryEventHandler methods not getting invoked for POST method?
I have the following domain object and DTO defined.

Country.java

```<code>@Data
@Entity
public class Country extends ResourceSupport {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long countryID;

    @NotBlank(message = "Country name is a required field")
    private String countryName;

    private String countryNationality;
}
</code>```

CountryDTO.java

```<code>@Data

public class CountryDTO {

    private List<Country> countries;
}
</code>```

I have overridden the POST method in the RepositoryRestController for the country class.

```<code>@RepositoryRestController
public class CountryController {

    @Autowired
    private CountryRepository repo;

    @RequestMapping(method = POST, value = "countries")
    public @ResponseBody ResponseEntity<?> createCountry(@RequestBody Resource<CountryDTO> dto,
            Pageable page, PersistentEntityResourceAssembler resourceAssembler) {

        Country savedCountry = repo.save(dto.getContent().getCountries());
        return new ResponseEntity<>(resourceAssembler.toResource(savedCountry), HttpStatus.OK);
    }

}
</code>```

Now I have defined a RepositoryEventHandler to handle validations.

```<code>@Component
@RepositoryEventHandler
public class CountryHandler {

    @HandleBeforeCreate
    public void handleBeforeCreate(Country country) {

        System.out.println("testing");

}
</code>```

But when I send a POST request to the endpoint http://localhost:8080/countries, the eventhandler does not get invoked. Is there anything I am doing wrong?

UPDATE 1:
I am sending the following JSON to the endpoint using Postman.

```<code>"countries":[{
    "countryName":"Australia",
    "countryNationality":"Australian"

}]
</code>```

答:
Try editing maybe  the Controller class annotation from:

```<code>@RepositoryRestController
</code>```

to

```<code>@RestController
</code>```

and mainly the method annotation from:

```<code>@RequestMapping(method = POST, value = "countries")
</code>```

to

```<code>@RequestMapping(value = "/countries", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
</code>```

PS: produces = MediaType.APPLICATION_JSON_VALUE if you are going to return json.

Body:
I have the following domain object and DTO defined.

Country.java

@Data
@Entity
public class Country extends ResourceSupport {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long countryID;

    @NotBlank(message = "Country name is a required field")
    private String countryName;

    private String countryNationality;
}

CountryDTO.java

@Data

public class CountryDTO {

    private List<Country> countries;
}

I have overridden the POST method in the RepositoryRestController for the country class.

@RepositoryRestController
public class CountryController {

    @Autowired
    private CountryRepository repo;

    @RequestMapping(method = POST, value = "countries")
    public @ResponseBody ResponseEntity<?> createCountry(@RequestBody Resource<CountryDTO> dto,
            Pageable page, PersistentEntityResourceAssembler resourceAssembler) {

        Country savedCountry = repo.save(dto.getContent().getCountries());
        return new ResponseEntity<>(resourceAssembler.toResource(savedCountry), HttpStatus.OK);
    }

}

Now I have defined a RepositoryEventHandler to handle validations.

@Component
@RepositoryEventHandler
public class CountryHandler {

    @HandleBeforeCreate
    public void handleBeforeCreate(Country country) {

        System.out.println("testing");

}

But when I send a POST request to the endpoint http://localhost:8080/countries, the eventhandler does not get invoked. Is there anything I am doing wrong?

UPDATE 1:
I am sending the following JSON to the endpoint using Postman.

"countries":[{
    "countryName":"Australia",
    "countryNationality":"Australian"

}]

Body:
Try editing maybe  the Controller class annotation from:

@RepositoryRestController

to

@RestController

and mainly the method annotation from:

@RequestMapping(method = POST, value = "countries")

to

@RequestMapping(value = "/countries", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)

PS: produces = MediaType.APPLICATION_JSON_VALUE if you are going to return json.


问:
Ruby on Rails: Are "form_for(:product, ...)" and "form_for(@product, ...)" equivalent?
Is

```<code><%= form_for(:product, :url => {:action => 'update', :id => @product.id})) do |f| %>
  ...
<% end %>
</code>```

and

```<code><%= form_for(@product, :url => {:action => 'update', :id => @product.id})) do |f| %>
  ...
<% end %>
</code>```

exactly the same ?

答:
That's quite a long form_for you've got there. The short answer to your question: @product is useful for determining what action to go to for a resource that can have many objects, which is what this sounds like. :product on the other hand will always go to the same action, update. This is best used for singular resources. A great explanation of the resources can be found in the Routing Guide. It's also explained in the Getting Started guide.

Your second form_for could be shorted right down to this:

```<code><%= form_for @product do |f| %>
   ...
<% end %>
</code>```

All is explained in the Routing and Getting Started guides.

Also, I saw in your profile you're from Melbourne. There's the Ruby on Rails Oceania Google group which lists the meetups around the country. There's one each month in Melbourne which you may want to attend to meet like minded people.

Body:
Is

<%= form_for(:product, :url => {:action => 'update', :id => @product.id})) do |f| %>
  ...
<% end %>

and

<%= form_for(@product, :url => {:action => 'update', :id => @product.id})) do |f| %>
  ...
<% end %>

exactly the same ?

Body:
That's quite a long form_for you've got there. The short answer to your question: @product is useful for determining what action to go to for a resource that can have many objects, which is what this sounds like. :product on the other hand will always go to the same action, update. This is best used for singular resources. A great explanation of the resources can be found in the Routing Guide. It's also explained in the Getting Started guide.

Your second form_for could be shorted right down to this:

<%= form_for @product do |f| %>
   ...
<% end %>

All is explained in the Routing and Getting Started guides.

Also, I saw in your profile you're from Melbourne. There's the Ruby on Rails Oceania Google group which lists the meetups around the country. There's one each month in Melbourne which you may want to attend to meet like minded people.


问:
How to choose software version number?
I plan to attribute a version number to my software. This number will help me to track the evolution and possible issue of each version.

I often see software with different version like v3.1.5 or v5.3.1. Is there a standard for attributing such number or it depend of the developer?

Even if I'm just a hobbyiste I want to learn and makes things right.

Feel free to add Tags for question tracking. I have no idea of which one I should use.

答:
It's all on the developer and project management. Typically before 1 is pre-release.

Whatever you define as a deliverable product would be 1. If you have a release schedule or planned features that you would call a 2.0, then the scale building up to that release would be 1.x.

There's no set: 2.0 has to be twice the product as 1.0. It's just that you remain consistent with measurable goals. If you have 1.0 and you want to implement a user forum feature by 2.0. Then maybe a working user registration and profile would be a 1.5. Improving on bugs related to user registration might be 1.5.1.

If it's a less formal project management style you are following, you can increment however you want. But consistency is key.

Title: How to choose software version number?


问:
broadleaf override controller method
I'm new on broadleaf.

I have problem, I wanted to obscure the method that removes my order in admin:

I create controller :

```<code>public class NewOrderController extends AdminBasicEntityController {

    private static final Logger LOGGER = Logger.getLogger(NewOrderController.class);

    protected static final String SECTION_KEY = "order";

    @Override
    protected String getSectionKey(Map<String, String> pathVars) {
        if (super.getSectionKey(pathVars) != null) {
            return super.getSectionKey(pathVars);
        }
        return SECTION_KEY;
    }

    @Override
    @RequestMapping(
        value = {"/{id}/delete"},
        method = {RequestMethod.POST}
    )
    public String removeEntity(HttpServletRequest request, HttpServletResponse response, Model model, Map<String, String> pathVars, String id, EntityForm entityForm, BindingResult result, RedirectAttributes ra) throws Exception {

        LOGGER.info("wywołanie nadpisane metody: " + NewOrderController.class.toString());
        return "String";
    }

}
</code>```

in applicationContext-admin.xml

add :

All the time it calls me the not overwritten method.

答:
When you create a controller, the bean must be in the servlet context, not in the root context. If you are modifying applicationContext-admin.xml then you are actually adding the bean to the root context.

Add your bean to applicationContext-servlet-admin.xml or add a new <component-scan> entry into applicationContext-servlet-admin.xml to scan your new bean.

One more thing: you likely do not want to override the entire AdminBasicEntityController and it looks like you just want to override /order/* methods. In that case, you should annotate your controller with @Controller and add an @RequestMapping for your section key like this:

```<code>@Controller
@RequestMapping("/" + SECTION_KEY)
public class NewOrderController extends AdminBasicEntityController {

    private static final Logger LOGGER = Logger.getLogger(NewOrderController.class);

    protected static final String SECTION_KEY = "order";

    @Override
    protected String getSectionKey(Map<String, String> pathVars) {
        if (super.getSectionKey(pathVars) != null) {
            return super.getSectionKey(pathVars);
        }
        return SECTION_KEY;
    }

    @Override
    @RequestMapping(
        value = {"/{id}/delete"},
        method = {RequestMethod.POST}
    )
    public String removeEntity(HttpServletRequest request, HttpServletResponse response, Model model, Map<String, String> pathVars, String id, EntityForm entityForm, BindingResult result, RedirectAttributes ra) throws Exception {

        LOGGER.info("wywołanie nadpisane metody: " + NewOrderController.class.toString());
        return "String";
    }

}
</code>```

Title: broadleaf override controller method

Body:
I'm new on broadleaf.

I have problem, I wanted to obscure the method that removes my order in admin:

I create controller :

public class NewOrderController extends AdminBasicEntityController {

    private static final Logger LOGGER = Logger.getLogger(NewOrderController.class);

    protected static final String SECTION_KEY = "order";

    @Override
    protected String getSectionKey(Map<String, String> pathVars) {
        if (super.getSectionKey(pathVars) != null) {
            return super.getSectionKey(pathVars);
        }
        return SECTION_KEY;
    }

    @Override
    @RequestMapping(
        value = {"/{id}/delete"},
        method = {RequestMethod.POST}
    )
    public String removeEntity(HttpServletRequest request, HttpServletResponse response, Model model, Map<String, String> pathVars, String id, EntityForm entityForm, BindingResult result, RedirectAttributes ra) throws Exception {

        LOGGER.info("wywołanie nadpisane metody: " + NewOrderController.class.toString());
        return "String";
    }

}

in applicationContext-admin.xml

add :

All the time it calls me the not overwritten method.

Body:
When you create a controller, the bean must be in the servlet context, not in the root context. If you are modifying applicationContext-admin.xml then you are actually adding the bean to the root context.

Add your bean to applicationContext-servlet-admin.xml or add a new <component-scan> entry into applicationContext-servlet-admin.xml to scan your new bean.

One more thing: you likely do not want to override the entire AdminBasicEntityController and it looks like you just want to override /order/* methods. In that case, you should annotate your controller with @Controller and add an @RequestMapping for your section key like this:

@Controller
@RequestMapping("/" + SECTION_KEY)
public class NewOrderController extends AdminBasicEntityController {

    private static final Logger LOGGER = Logger.getLogger(NewOrderController.class);

    protected static final String SECTION_KEY = "order";

    @Override
    protected String getSectionKey(Map<String, String> pathVars) {
        if (super.getSectionKey(pathVars) != null) {
            return super.getSectionKey(pathVars);
        }
        return SECTION_KEY;
    }

    @Override
    @RequestMapping(
        value = {"/{id}/delete"},
        method = {RequestMethod.POST}
    )
    public String removeEntity(HttpServletRequest request, HttpServletResponse response, Model model, Map<String, String> pathVars, String id, EntityForm entityForm, BindingResult result, RedirectAttributes ra) throws Exception {

        LOGGER.info("wywołanie nadpisane metody: " + NewOrderController.class.toString());
        return "String";
    }

}


问:
How to call npm version (to update my own package's version and then commit)
Nothing happens when I run

```<code>npm version minor -m "test"
</code>```

As a note, there is output if I run npm version without any arguments:

```<code>$ npm version
{ 'my-app': '0.7.0',
  npm: '4.2.0',
  ares: '1.10.1-DEV',
  cldr: '30.0.3',
  http_parser: '2.7.0',
  icu: '58.2',
  modules: '51',
  node: '7.10.0',
  openssl: '1.0.2k',
  tz: '2016j',
  unicode: '9.0',
  uv: '1.11.0',
  v8: '5.5.372.43',
  zlib: '1.2.11' }
</code>```

How am I supposed to use npm-version? I expect it to update the version number in package.json, run the 'version' script that I've specified in the package.json scripts list, and then commit. I can use npm run version to execute the 'version' script that I specified, but how do I run npm-version correctly?

答: The call will fail (silently) if in a git repo that is not clean. You can force it to succeed with -f or --force.

Body:
Nothing happens when I run

npm version minor -m "test"

As a note, there is output if I run npm version without any arguments:

$ npm version
{ 'my-app': '0.7.0',
  npm: '4.2.0',
  ares: '1.10.1-DEV',
  cldr: '30.0.3',
  http_parser: '2.7.0',
  icu: '58.2',
  modules: '51',
  node: '7.10.0',
  openssl: '1.0.2k',
  tz: '2016j',
  unicode: '9.0',
  uv: '1.11.0',
  v8: '5.5.372.43',
  zlib: '1.2.11' }

How am I supposed to use npm-version? I expect it to update the version number in package.json, run the 'version' script that I've specified in the package.json scripts list, and then commit. I can use npm run version to execute the 'version' script that I specified, but how do I run npm-version correctly?


问:
Gradle com.android.support and com.google.android.gms library conflict
I'm working on a Firebase chat app inside my main project and I added Firebase dependencies to my build.gradle, but then I got this message after sync:

All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes.) Found versions 25.3.1, 25.0.0, 23.4.0. Examples include com.android.support:animated-vector-drawable:25.3.1 and com.android.support:palette-v7:25.0.0

on

```<code>compile 'com.android.support:appcompat-v7:25.3.1'
</code>```

and

All com.google.android.gms libraries must use the exact same version specification (mixing versions can lead to runtime crashes.) Found versions 9.8.0, 10.2.6. Example include com.google.android.gms:play-services-auth-base:9.8.0 and com.google.android.gms:play-services-ads-lite:10.2.6

on

```<code>compile 'com.google.android.gms:play-services-ads:10.2.6'
</code>```

Here is my dependencies in build.gradle (Module:app):

```<code>dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile files('lib/mysql-connector-java-5.1.6.jar')
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.google.android.gms:play-services-ads:10.2.6'
compile 'com.android.support:design:25.3.1'
testCompile 'junit:junit:4.12'

//Chat dependencies
compile 'com.android.support:design:25.3.1'
compile 'com.firebaseui:firebase-ui:0.6.2'
compile 'com.github.hani-momanii:SuperNova-Emoji:1.0'
}
</code>```

答:
according to your build.gradle file,
duplicate line of code found

```<code>compile 'com.android.support:design:25.3.1'
</code>```

remove one and try .

Body:
I'm working on a Firebase chat app inside my main project and I added Firebase dependencies to my build.gradle, but then I got this message after sync:

All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes.) Found versions 25.3.1, 25.0.0, 23.4.0. Examples include com.android.support:animated-vector-drawable:25.3.1 and com.android.support:palette-v7:25.0.0

on

compile 'com.android.support:appcompat-v7:25.3.1'

and

All com.google.android.gms libraries must use the exact same version specification (mixing versions can lead to runtime crashes.) Found versions 9.8.0, 10.2.6. Example include com.google.android.gms:play-services-auth-base:9.8.0 and com.google.android.gms:play-services-ads-lite:10.2.6

on

compile 'com.google.android.gms:play-services-ads:10.2.6'

Here is my dependencies in build.gradle (Module:app):

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile files('lib/mysql-connector-java-5.1.6.jar')
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.google.android.gms:play-services-ads:10.2.6'
compile 'com.android.support:design:25.3.1'
testCompile 'junit:junit:4.12'

//Chat dependencies
compile 'com.android.support:design:25.3.1'
compile 'com.firebaseui:firebase-ui:0.6.2'
compile 'com.github.hani-momanii:SuperNova-Emoji:1.0'
}

Body:
according to your build.gradle file,
duplicate line of code found

compile 'com.android.support:design:25.3.1'

remove one and try .


问:
How to update specific records in MySQL db based on dynamically created input boxes
I am creating a database front end that will populate a table with the records in a the db, putting all values into input boxes so that they can be changed. I want to be able to make changes and have it update just that specific record.
This is what I currently have.

```<code>{
if($row["order_number"]===NULL)
        {
            $on='<input type="number" name="orderNo" />';
        } else {$on='<input type="number" name="orderNo" value="'. $row["order_number"] . '" />';}
        if($row["name"]===NULL)
        {
            $cn='<input type="text" name="cusName" />';
        }else {$cn='<input type="text" name="cusName" value="'. $row["name"] . '" />';}
        if($row["product_type"]===NULL)
        {
            $pt='<input type="text" name="prodType" />';
        } else {$pt='<input type="text" name="prodType" value="'. $row["product_type"] . '" />';}
        $id='<input type="number" name="orderID" value="'.$row["order_id"].'"/>';
        $tableCode.='<tr><td>' . $on . '</td><td>' . $cn . '</td><td>' . $pt . '</td><td><input type="submit" value="Update" name="'. $row["order_id"]. '" /></td><td hidden>'.$id.'</td></tr>';
}
</code>```

This code is looped for all results in the table. samples.html.php simply sticks the results in some table tags on a webpage, along with the headers. The order_id is the primary key of the table (actually 2 tables, but I know how to handle that side of it)

Any help in this would be appreciated! Thanks!

答:
OK, as promised, here is what I came up with. Mignt not be the best way, but it seems to work for my relatively small application.

```<code>while($row = mysqli_fetch_assoc($result))
{
    $on='';
    $cn='';
    $pt='';
    $id='';
    if($row["order_number"]===NULL)
    {
        $on='<input type="number" name="orderNo" />';
    } else {$on='<input type="number" name="orderNo" value="'. $row["order_number"] . '" />';}
    if($row["name"]===NULL)
    {
        $cn='<input type="text" name="cusName" />';
    }else {$cn='<input type="text" name="cusName" value="'. $row["name"] . '" />';}
    if($row["product_type"]===NULL)
    {
        $pt='<input type="text" name="prodType" />';
    } else {$pt='<input type="text" name="prodType" value="'. $row["product_type"] . '" />';}
    $id='<input type="number" name="orderID" value="'.$row["order_id"].'"/>';
    $tableCode.='<form class="tr" action="?" method="post"><span class="td">' . $on . '</span><span class="td">' . $cn . '</span><span class="td">' . $pt . '</span><span class="td"><input type="submit" value="Update" name="Update" /></span><span hidden class="td_hidden">'.$id.'</span></form>';
}
</code>```

This way, only the values from the form that I used get submitted, so only that row is updated. I used CSS display:table styling to get it to look like a table, similar to the third answer of this question.

Thanks everyone for their willingness to help! If anyone has ideas for improvements, I am open to them.

Body:
I am creating a database front end that will populate a table with the records in a the db, putting all values into input boxes so that they can be changed. I want to be able to make changes and have it update just that specific record.
This is what I currently have.

{
if($row["order_number"]===NULL)
        {
            $on='<input type="number" name="orderNo" />';
        } else {$on='<input type="number" name="orderNo" value="'. $row["order_number"] . '" />';}
        if($row["name"]===NULL)
        {
            $cn='<input type="text" name="cusName" />';
        }else {$cn='<input type="text" name="cusName" value="'. $row["name"] . '" />';}
        if($row["product_type"]===NULL)
        {
            $pt='<input type="text" name="prodType" />';
        } else {$pt='<input type="text" name="prodType" value="'. $row["product_type"] . '" />';}
        $id='<input type="number" name="orderID" value="'.$row["order_id"].'"/>';
        $tableCode.='
' . $on . '	' . $cn . '	' . $pt . '	<input type="submit" value="Update" name="'. $row["order_id"]. '" />	'.$id.'
';
}

This code is looped for all results in the table. samples.html.php simply sticks the results in some table tags on a webpage, along with the headers. The order_id is the primary key of the table (actually 2 tables, but I know how to handle that side of it)

Any help in this would be appreciated! Thanks!

Body:
OK, as promised, here is what I came up with. Mignt not be the best way, but it seems to work for my relatively small application.

while($row = mysqli_fetch_assoc($result))
{
    $on='';
    $cn='';
    $pt='';
    $id='';
    if($row["order_number"]===NULL)
    {
        $on='<input type="number" name="orderNo" />';
    } else {$on='<input type="number" name="orderNo" value="'. $row["order_number"] . '" />';}
    if($row["name"]===NULL)
    {
        $cn='<input type="text" name="cusName" />';
    }else {$cn='<input type="text" name="cusName" value="'. $row["name"] . '" />';}
    if($row["product_type"]===NULL)
    {
        $pt='<input type="text" name="prodType" />';
    } else {$pt='<input type="text" name="prodType" value="'. $row["product_type"] . '" />';}
    $id='<input type="number" name="orderID" value="'.$row["order_id"].'"/>';
    $tableCode.='<form class="tr" action="?" method="post"><span class="td">' . $on . '</span><span class="td">' . $cn . '</span><span class="td">' . $pt . '</span><span class="td"><input type="submit" value="Update" name="Update" /></span><span hidden class="td_hidden">'.$id.'</span></form>';
}

This way, only the values from the form that I used get submitted, so only that row is updated. I used CSS display:table styling to get it to look like a table, similar to the third answer of this question.

Thanks everyone for their willingness to help! If anyone has ideas for improvements, I am open to them.


问:
Integrate OnsenUI in Angular 4
I'm really struggling with integrating OnsenUI in my Angular 2 (version 4) App. The project was generated using the latest Angular CLI.
It seems the OnsenUI docs are not up to date.

So if add

```<code>import {OnsenModule} from 'angular2-onsenui';
import {CUSTOM_ELEMENTS_SCHEMA} from '@angular/core';
.
.
.
@NgModule({
imports: [
    OnsenModule,
    BrowserModule
],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
</code>```

as it is described in the docs:
https://onsen.io/v2/docs/guide/angular2/

I'm getting the following error:

```<code>Uncaught ReferenceError: ons is not defined
at Object../node_modules/angular2-onsenui/dist/src/ons/notification.js (notification.js:5)
at __webpack_require__ (bootstrap 43794b3…:54)
at Object../node_modules/angular2-onsenui/dist/src/angular2-onsenui.js (angular2-onsenui.js:16)
at __webpack_require__ (bootstrap 43794b3…:54)
at Object../src/app/app.module.ts (app.component.ts:12)
at __webpack_require__ (bootstrap 43794b3…:54)
at Object../src/main.ts (environment.ts:8)
at __webpack_require__ (bootstrap 43794b3…:54)
at Object.2 (main.ts:12)
at __webpack_require__ (bootstrap 43794b3…:54)
./node_modules/angular2-onsenui/dist/src/ons/notification.js @
notification.js:5
__webpack_require__ @ bootstrap 43794b3…:54
./node_modules/angular2-onsenui/dist/src/angular2-onsenui.js @     angular2-onsenui.js:16
__webpack_require__ @ bootstrap 43794b3…:54
./src/app/app.module.ts @ app.component.ts:12
__webpack_require__ @ bootstrap 43794b3…:54
./src/main.ts @ environment.ts:8
__webpack_require__ @ bootstrap 43794b3…:54
2 @ main.ts:12
__webpack_require__ @ bootstrap 43794b3…:54
webpackJsonpCallback @ bootstrap 43794b3…:25
(anonymous) @ main.bundle.js:1
</code>```

I don't want to use the monaca template, this will not solve the problem.

答:
Exactly the same problem. But, install angular-cli dependency and update the .angular-cli.json didn't worked for me (At origin, my project was not generated by angular-cli).
It seems they're working on Angular 4 support:

https://github.com/OnsenUI/OnsenUI/tree/angular4-support

Wait and see...

Title: Integrate OnsenUI in Angular 4

Body:
I'm really struggling with integrating OnsenUI in my Angular 2 (version 4) App. The project was generated using the latest Angular CLI.
It seems the OnsenUI docs are not up to date.

So if add

import {OnsenModule} from 'angular2-onsenui';
import {CUSTOM_ELEMENTS_SCHEMA} from '@angular/core';
.
.
.
@NgModule({
imports: [
    OnsenModule,
    BrowserModule
],
schemas: [CUSTOM_ELEMENTS_SCHEMA]

as it is described in the docs:
https://onsen.io/v2/docs/guide/angular2/

I'm getting the following error:

Uncaught ReferenceError: ons is not defined
at Object../node_modules/angular2-onsenui/dist/src/ons/notification.js (notification.js:5)
at __webpack_require__ (bootstrap 43794b3…:54)
at Object../node_modules/angular2-onsenui/dist/src/angular2-onsenui.js (angular2-onsenui.js:16)
at __webpack_require__ (bootstrap 43794b3…:54)
at Object../src/app/app.module.ts (app.component.ts:12)
at __webpack_require__ (bootstrap 43794b3…:54)
at Object../src/main.ts (environment.ts:8)
at __webpack_require__ (bootstrap 43794b3…:54)
at Object.2 (main.ts:12)
at __webpack_require__ (bootstrap 43794b3…:54)
./node_modules/angular2-onsenui/dist/src/ons/notification.js @
notification.js:5
__webpack_require__ @ bootstrap 43794b3…:54
./node_modules/angular2-onsenui/dist/src/angular2-onsenui.js @     angular2-onsenui.js:16
__webpack_require__ @ bootstrap 43794b3…:54
./src/app/app.module.ts @ app.component.ts:12
__webpack_require__ @ bootstrap 43794b3…:54
./src/main.ts @ environment.ts:8
__webpack_require__ @ bootstrap 43794b3…:54
2 @ main.ts:12
__webpack_require__ @ bootstrap 43794b3…:54
webpackJsonpCallback @ bootstrap 43794b3…:25
(anonymous) @ main.bundle.js:1

I don't want to use the monaca template, this will not solve the problem.


问:
using dynamic linq to filter a list of objects
I have two class like this

```<code>public class Error{
   public string Code{get;set;}
   public string Description{get;set;}
}

public class Row{
   public List<Error> Errors {get;set;}
   ....
}
</code>```

So, for each row, can exists more errors.
It's possible using dynamic linq select the row that have an error code(for example Code1)?

So, if the row contains Code1 and Code2, i want select the row.

if in the example below query has a list of rows i want a query like this

```<code>query.Where("Errors != null && Errors.Code.contains('Code1')")
</code>```

答:
What you really want to do is to use something like the PredicateBuilder:
http://www.albahari.com/nutshell/predicatebuilder.aspx</p>

```<code>IQueryable<Error> SearchProducts(Row row, string[] codes, string[] keywords)
{
    var predicate = PredicateBuilder.False<Error>();

    foreach (string code  in codes)
    {
        string temp = code;
        predicate = predicate.Or(p => p.Code.Contains(temp));
    }
    foreach (string keyword in keywords)
    {
        string temp = keyword;
        predicate = predicate.Or(p => p.Description.Contains(temp));
    }
    return row.Errors.AsQueryable().Where(predicate);
}
</code>```

Body:
I have two class like this

public class Error{
   public string Code{get;set;}
   public string Description{get;set;}
}

public class Row{
   public List<Error> Errors {get;set;}
   ....
}

So, for each row, can exists more errors.
It's possible using dynamic linq select the row that have an error code(for example Code1)?

So, if the row contains Code1 and Code2, i want select the row.

if in the example below query has a list of rows i want a query like this

query.Where("Errors != null && Errors.Code.contains('Code1')")

Body:
What you really want to do is to use something like the PredicateBuilder:
http://www.albahari.com/nutshell/predicatebuilder.aspx

IQueryable<Error> SearchProducts(Row row, string[] codes, string[] keywords)
{
    var predicate = PredicateBuilder.False<Error>();

    foreach (string code  in codes)
    {
        string temp = code;
        predicate = predicate.Or(p => p.Code.Contains(temp));
    }
    foreach (string keyword in keywords)
    {
        string temp = keyword;
        predicate = predicate.Or(p => p.Description.Contains(temp));
    }
    return row.Errors.AsQueryable().Where(predicate);
}


问:
Excel VBA - creating a collection class within a parent class
I've been trying to create a class that is a collection of objects (of another class) and that is within a parent class. I've looked at several questions here but couldn't get it working. So if anyone can post a short code with my parameters, I'd be very grateful.

My parent class is Sample. It should contain a collection SampleFields which should contain objects from the class SampleField. The SampleField objects have only a Name property and it is taken from cells A1 to D1. It should be possible to add and remove items from the SampleFields collection and modify the Name property of the SampleField objects. The SampleFields collection gets its objects upon the initialization of the Sample class.

I need to access it like this - Sample.SampleFields(1).Name

I think it's useless to post my attempt but here it is:

```<code>Sub test()

Dim a As New Sample, i As Variant

a.GetFields

For Each i In a.SampleFields
    Debug.Print i.Name
Next

End Sub
</code>```

Sample class:

```<code>Private pFields As New SampleFields

Public Property Get SampleFields() As SampleFields
    Set SampleFields= pFields
End Property

Public Property Set SampleFields(ByVal value As SampleFields)
    Set pFields = value
End Property

Private Sub Initialize_Class()
    Set pFields = New SampleFields
End Sub

Public Sub GetFields()

Dim rngHeaders As Range, rngCell As Range
Set rngHeaders = Range("A1").CurrentRegion.Rows(1)

For Each rngCell In rngHeaders.Cells
    Dim newField As SampleField
    newField.Name = rngCell.Value2
    Me.Fields.AddNewField (newField)   'crashes here with Method or data member not found
Next

End Sub
</code>```

SampleFields class:

```<code>Private pFields As New Collection

Public Sub AddNewField(FieldName As SampleField)
    Me.AddNewField (FieldName)
End Sub
</code>```

SampleField class:

```<code>Private pName As String

Public Property Let Name(value As String)
    pName = value
End Property

Public Property Get Name() As String
    Name = pName
End Property
</code>```

Thanks!

答:
Very old post, but let me at least answer this:
In the sample class, have a Collection. You can forget about the SampleFields class, it's not needed.

Then you only need to have one SampleField class that you pass to this SampleClass method "AddField" that you use to increase the size of the collection.

Sample class should look like this:

```<code>Private p_SampleFields as Collection
Private p_SampleField as SampleField

'Initialize this class with it's collection:
Private Sub Class_Initialize()
    Set p_SampleFields = New Collection
End Sub

'Allow for adding SampleFields:
Public Sub AddField(field as SampleField)
    Set p_SampleField = field
    p_sampleFields.add field
End Sub

'Expose the collection:
Public Property Get SampleFields() as Collection
    Set SampleFields = p_SampleFields
End Property
</code>```

In a regular module you can then use the following:

```<code>Sub Test()
    Dim sField as SampleField
    Dim sClass as SampleClass

    Set sField = New SampleField
    Set sClass = New SampleClass

    sField.Name = "SomeName"
    sClass.AddField sField 'This adds it to the collection

    'Access as per requirement:
    msgbox sClass.SampleFields(1).Name 'Pop-up saying "SomeName"
End Sub
</code>```

Body:
I've been trying to create a class that is a collection of objects (of another class) and that is within a parent class. I've looked at several questions here but couldn't get it working. So if anyone can post a short code with my parameters, I'd be very grateful.

My parent class is Sample. It should contain a collection SampleFields which should contain objects from the class SampleField. The SampleField objects have only a Name property and it is taken from cells A1 to D1. It should be possible to add and remove items from the SampleFields collection and modify the Name property of the SampleField objects. The SampleFields collection gets its objects upon the initialization of the Sample class.

I need to access it like this - Sample.SampleFields(1).Name

I think it's useless to post my attempt but here it is:

Sub test()

Dim a As New Sample, i As Variant

a.GetFields

For Each i In a.SampleFields
    Debug.Print i.Name
Next

End Sub

Sample class:

Private pFields As New SampleFields

Public Property Get SampleFields() As SampleFields
    Set SampleFields= pFields
End Property

Public Property Set SampleFields(ByVal value As SampleFields)
    Set pFields = value
End Property

Private Sub Initialize_Class()
    Set pFields = New SampleFields
End Sub

Public Sub GetFields()

Dim rngHeaders As Range, rngCell As Range
Set rngHeaders = Range("A1").CurrentRegion.Rows(1)

For Each rngCell In rngHeaders.Cells
    Dim newField As SampleField
    newField.Name = rngCell.Value2
    Me.Fields.AddNewField (newField)   'crashes here with Method or data member not found
Next

End Sub

SampleFields class:

Private pFields As New Collection

Public Sub AddNewField(FieldName As SampleField)
    Me.AddNewField (FieldName)
End Sub

SampleField class:

Private pName As String

Public Property Let Name(value As String)
    pName = value
End Property

Public Property Get Name() As String
    Name = pName
End Property

Thanks!

Body:
Very old post, but let me at least answer this:
In the sample class, have a Collection. You can forget about the SampleFields class, it's not needed.

Then you only need to have one SampleField class that you pass to this SampleClass method "AddField" that you use to increase the size of the collection.

Sample class should look like this:

Private p_SampleFields as Collection
Private p_SampleField as SampleField

'Initialize this class with it's collection:
Private Sub Class_Initialize()
    Set p_SampleFields = New Collection
End Sub

'Allow for adding SampleFields:
Public Sub AddField(field as SampleField)
    Set p_SampleField = field
    p_sampleFields.add field
End Sub

'Expose the collection:
Public Property Get SampleFields() as Collection
    Set SampleFields = p_SampleFields
End Property

In a regular module you can then use the following:

Sub Test()
    Dim sField as SampleField
    Dim sClass as SampleClass

    Set sField = New SampleField
    Set sClass = New SampleClass

    sField.Name = "SomeName"
    sClass.AddField sField 'This adds it to the collection

    'Access as per requirement:
    msgbox sClass.SampleFields(1).Name 'Pop-up saying "SomeName"
End Sub


问:
Create an array of primitives or objects in Java

Possible Duplicate:

  Can a single Java variable accept an array of either primitives or objects?

I want to create an method that accepts either an arbitrary array. The array can be an array of primitives, or an array of objects.

Unfortunately, I can't do

```<code>public void myMethod(Object[] a) {...}
</code>```

because primitives aren't objects! Is there a way to abstract this one level further?

EDIT I understand that I can pass it as an Object, but then how do I access it as an array within the method? I can't do:

```<code>public void myMethod(Object[] a) {
     Object something = a[0];
     }
</code>```

答:
Unfortunately, there is no better solution (at the moment) than overloading myMethod to handle each kind of primitive type you want to handle. You can for example see the signatures of the binarySearch methods in the class Arrays

Of course, you can also pass an Object and check if it is an array (and in this case, check the type of this array) using reflection. However, you're application will become less typesafe if you do so.

Body:
Possible Duplicate:

  Can a single Java variable accept an array of either primitives or objects?

I want to create an method that accepts either an arbitrary array. The array can be an array of primitives, or an array of objects.

Unfortunately, I can't do

public void myMethod(Object[] a) {...}

because primitives aren't objects! Is there a way to abstract this one level further?

EDIT I understand that I can pass it as an Object, but then how do I access it as an array within the method? I can't do:

public void myMethod(Object[] a) {
     Object something = a[0];
     }


问:
I have written DFS for graph using stack and adjecent lists, its not working like it should
```<code>typedef struct nodeTAG{
    int data;
    struct nodeTAG *next;
}nodeT;

typedef struct listTAG{
    nodeT *front;
    nodeT *end;
}listT;

void listinit (listT *plist)
{
    plist -> front = NULL;
    plist -> end = NULL;
}

int isempty (listT *plist)
{
    if (plist -> front == NULL)
        return 1;
    else
        return 0;
}

void addfront (listT *plist, int x)
{
    nodeT *temp;
    temp = (nodeT*)malloc(sizeof(nodeT));
    temp -> data =x;

    if (plist -> front == NULL)
    {
        temp -> next = NULL;
        plist -> front = temp;
        plist -> end = temp;
    }
    else
    {
        temp -> next = plist -> front;
        plist -> front = temp;
    }
}

void removefront (listT *plist, int *x)
{
    if (isempty(plist) == 0)
    {
        nodeT *temp;
        *x = plist -> front -> data;
        temp = plist -> front;
        plist -> front = temp -> next;
        free(temp);
    }
}

void DFS(int wierz){
    int v;
    nodeT *p;
    addfront(&Stos, wierz);//adding element on stack
    tabzaznaczen[wierz]==1;//array of visited elements

    while(Stos){
        removefront(&Stos, &v);
        printf("%d", v);
        for(p = tabwierz[v].front; p; p = p->next){//tabwierz is array of pointers to adjecent lists
            if(tabzaznaczen[p->data]==0){
                addfront(&Stos, p->data);
                tabzaznaczen[p->data] = 1;
            }
    }
}}
</code>```

I used lisinit on stack and declared it global.

Its not working like it should, adding some useless integers. This is my project for school. So it is important for me, I think its like a small mistake but I cant see it.

答: Ok, i fixed it. I used == instead of = in one place.</p>

Body:
typedef struct nodeTAG{
    int data;
    struct nodeTAG *next;
}nodeT;

typedef struct listTAG{
    nodeT *front;
    nodeT *end;
}listT;

void listinit (listT *plist)
{
    plist -> front = NULL;
    plist -> end = NULL;
}

int isempty (listT *plist)
{
    if (plist -> front == NULL)
        return 1;
    else
        return 0;
}

void addfront (listT *plist, int x)
{
    nodeT *temp;
    temp = (nodeT*)malloc(sizeof(nodeT));
    temp -> data =x;

    if (plist -> front == NULL)
    {
        temp -> next = NULL;
        plist -> front = temp;
        plist -> end = temp;
    }
    else
    {
        temp -> next = plist -> front;
        plist -> front = temp;
    }
}

void removefront (listT *plist, int *x)
{
    if (isempty(plist) == 0)
    {
        nodeT *temp;
        *x = plist -> front -> data;
        temp = plist -> front;
        plist -> front = temp -> next;
        free(temp);
    }
}

void DFS(int wierz){
    int v;
    nodeT *p;
    addfront(&Stos, wierz);//adding element on stack
    tabzaznaczen[wierz]==1;//array of visited elements

    while(Stos){
        removefront(&Stos, &v);
        printf("%d", v);
        for(p = tabwierz[v].front; p; p = p->next){//tabwierz is array of pointers to adjecent lists
            if(tabzaznaczen[p->data]==0){
                addfront(&Stos, p->data);
                tabzaznaczen[p->data] = 1;
            }
    }
}}

I used lisinit on stack and declared it global.

Its not working like it should, adding some useless integers. This is my project for school. So it is important for me, I think its like a small mistake but I cant see it.


答:
```<code>border-bottom: 1px solid lightgrey;
border-top: 1px solid lightgrey;
</code>```

This will assign a top border and a bottom border and keep both, they won't overwrite each other or anything.

Title: Top and bottom borders

Body:
I have some code here, this gives me a bottom border, how can I add to it to make it show top and bottom borders?

table.bottomBorder {
  border-collapse: collapse;
}

table.bottomBorder td,
table.bottomBorder th {
  border-bottom: 1px solid lightgrey;
  padding: 10px;
  text-align: center;
}

    Table Header
    Table Header

    Table cell
    Table cell

    Table cell
    Table cell

Body:
border-bottom: 1px solid lightgrey;
border-top: 1px solid lightgrey;

This will assign a top border and a bottom border and keep both, they won't overwrite each other or anything.


问:
HttpClient GetAsync Failure when ARM CPU is Selected
While trying to call a Rest Service, I keep getting the following error when the CPU configuration is set to ARM

An error occurred while sending the request. The text associated with this error code could not be found.The server name or address could not be resolved

Switching to Any CPU or x86 for example, and the call succeeds.

A sample of what the code might look like:

```<code>System.Uri uri = new Uri("http://servername/__/__.svc/ID/123");

using (var client = new System.Net.Http.HttpClient())
       {
         try
            {
              var response = await client.GetAsync(uri);

              if (response.IsSuccessStatusCode)
                {
                    //handle success
                }
                else
                {
                    //handle failure
                }
            }
            catch (HttpRequestException exc)
            {
                throw new HttpRequestException();
            }
        }
</code>```

How to interpret this observation to solve the problem?

Note: App Private Networks (Client & Server) under Capabilities in the Package.appxmanifest is enabled. Calling a service without checking this capability used to cause the same error.

Update with StackTrace

at System.Net.Http.HttpClientHandler.d__86.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Net.Http.HttpClient.d__58.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at ProjectName.Views.MainPage.d__4.MoveNext()

答: Story short, using the server IP address instead of the host/server name, solved the problem. Otherwise, resolving the name might require editing the hosts file as described in here.</p>

Body:
While trying to call a Rest Service, I keep getting the following error when the CPU configuration is set to ARM

An error occurred while sending the request. The text associated with this error code could not be found.The server name or address could not be resolved

Switching to Any CPU or x86 for example, and the call succeeds.

A sample of what the code might look like:

System.Uri uri = new Uri("http://servername/__/__.svc/ID/123");

using (var client = new System.Net.Http.HttpClient())
       {
         try
            {
              var response = await client.GetAsync(uri);

              if (response.IsSuccessStatusCode)
                {
                    //handle success
                }
                else
                {
                    //handle failure
                }
            }
            catch (HttpRequestException exc)
            {
                throw new HttpRequestException();
            }
        }

How to interpret this observation to solve the problem?

Note: App Private Networks (Client & Server) under Capabilities in the Package.appxmanifest is enabled. Calling a service without checking this capability used to cause the same error.

Update with StackTrace

at System.Net.Http.HttpClientHandler.d__86.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Net.Http.HttpClient.d__58.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at ProjectName.Views.MainPage.d__4.MoveNext()


问:
Filter divs based on dropdown select - is there an easy way?
I have a grid made up of divs that have wordpress page IDs as classes, they also have the common class 'set'.

I have a dropdown select that contain each page as an <option> with the page ID as the value.

I want to be able to select a page title in the dropdown menu, and have any corresponding div in the grid with the class 'patient-pageID' only to be visible, and all others hidden.

```<code>$('#filterPatient_dropdown').change(function() {
    var patientID = $("#filterPatient_dropdown option:selected").val();
    $('.set').hide();
    if ($(this).val() == 'patient'+patientID) {
        $(this).show();
    }
});
</code>```

This just hides all the divs when I click on an option.

How can I perform a simple yet effective filter where I click on an option, where the value is the page ID, and it finds the matching class of all divs and only shows these?

答: You're calling .show() on $(this), which in this case is the dropdown and not the div. Try using $('.patient-' + patientID).show();

Body:
I have a grid made up of divs that have wordpress page IDs as classes, they also have the common class 'set'.

I have a dropdown select that contain each page as an <option> with the page ID as the value.

I want to be able to select a page title in the dropdown menu, and have any corresponding div in the grid with the class 'patient-pageID' only to be visible, and all others hidden.

$('#filterPatient_dropdown').change(function() {
    var patientID = $("#filterPatient_dropdown option:selected").val();
    $('.set').hide();
    if ($(this).val() == 'patient'+patientID) {
        $(this).show();
    }
});

This just hides all the divs when I click on an option.

How can I perform a simple yet effective filter where I click on an option, where the value is the page ID, and it finds the matching class of all divs and only shows these?


问:
WPFTookit.Extended - Fails to install
I have followed the steps from several answers on StackOverflow to install the Extended WPF Toolkit Binaries. After downloading, I have attempted to add them to the Toolbox tab, adding a WPF Extend Tookit toolbox, and browsing to the location of the .dll. I answer Yes to the security question, and the progress bar does it's little dance and closes. Yet, I never have any controls show up. What am I missing?</p>

答:
I (finally) found the key step to installing the WPFToolkit.Extended in a related post: Control from WPFToolkit doesn't exist in namespace. This referred to the CodePlex site that had the crucial step: Unblock the .zip file:

(Step) 3. Unblock the ZIP file: Right-click ExtendedWPFToolkit_Binaries.zip -> Properties -> Unblock

Title: WPFTookit.Extended - Fails to install


问:
How can I see what SQL Is doing?
Imagine that I have a database with Name and age and i want to insert a person to that database so I'll do:

```<code>SQL="INSERT INTO Person(Name,Age) VALUES ('" & Name & "'," & Age &")"
</code>```

And in my interface I Insert the Name: Nick and age:25.

How can I see in my interface what SQL is doing for example:

```<code>INSERT INTO Person(Nick,25)
</code>```

PS: Programming this in classic asp. I've seen it done through a simple Response.Write, but I don't remember how it was done.

Hope it was clear to understand, and thank you for all the help

答:
It is just simply this Response.Write(SQL).

On the other hand I strongly suggest you to read about SQL Parameters. Like in here ASP Classic Named Parameter in Paramaterized Query: Must declare the scalar variable

Title: How can I see what SQL Is doing?

Body:
Imagine that I have a database with Name and age and i want to insert a person to that database so I'll do:

SQL="INSERT INTO Person(Name,Age) VALUES ('" & Name & "'," & Age &")"

And in my interface I Insert the Name: Nick and age:25.

How can I see in my interface what SQL is doing for example:

INSERT INTO Person(Nick,25)

PS: Programming this in classic asp. I've seen it done through a simple Response.Write, but I don't remember how it was done.

Hope it was clear to understand, and thank you for all the help


问:
JQuery :not filter question
We can pass :checked or :hidden to :not filter as follows:

```<code>:checkbox:not(:checked)
</code>```

Why cannot we pass p:hidden to :not filter as follows:

```<code>#something:not(p:hidden)
</code>```

Thanks.

答:
You can. If you could not, then either both paragraphs in this example would come out black or both would be blue, and my test shows that the first is blue and the second is black, which is what I would expect.</p>

```<code><!DOCTYPE HTML>
<html lang=en>
<meta charset=utf-8>
<title>Test</title>
<h1>Testing</h1>
<p id="something">testing</p>
<p id="else" style="display: none">testing</p>
<script src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
<script>
$('#something:not(p:hidden)').css('color', 'blue');
$('#else:not(p:hidden)').css('color', 'blue');
$('#else').css('display', 'block');
</script>
</code>```

Title: JQuery :not filter question

Body:
We can pass :checked or :hidden to :not filter as follows:

:checkbox:not(:checked)

Why cannot we pass p:hidden to :not filter as follows:

#something:not(p:hidden)

Thanks.

Body:
You can. If you could not, then either both paragraphs in this example would come out black or both would be blue, and my test shows that the first is blue and the second is black, which is what I would expect.

<!DOCTYPE HTML>
<html lang=en>
<meta charset=utf-8>
<title>Test</title>
<h1>Testing</h1>
<p id="something">testing</p>
<p id="else" style="display: none">testing</p>
<script src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
<script>
$('#something:not(p:hidden)').css('color', 'blue');
$('#else:not(p:hidden)').css('color', 'blue');
$('#else').css('display', 'block');
</script>


问:
cannot set property 'color' of undefined
I'm trying to create a custom error message and styling based on validation (I know about plugins, but the time involved in coordinating the validation plugin with Materialize is too much for a single field).

HTML:

```<code><div class="input-field inline center-align">
  <input id="quantity" name="quantity" type="number" class="">
  <label for="qty" data-error="wrong" data-success="right"
       class="active">Qty</label>
  <span id="qty-error">really?</span>
</div>
</code>```

JS:

```<code>$('#quantity').change(function(){
  var $Qty = $(this).val();
  var $Label = $('#qty-error');
  if ($Qty > 0 && $Qty <= $AvailTix){
      $Label.html('seems reasonable');
      $Label.style.color = '#8e8ef5';
      $(this).addClass('valid');
  } else if ($Qty < 1){
      $Label.html('really?');
      $Label.style.color ='#f96d63';
      $(this).addClass('invalid');
  }
});
</code>```

What's confusing me is that the $Label.html piece is working. It changes the text. But I get this error in the console for the $Label.style.color line:

Uncaught TypeError: Cannot set property 'color' of undefined

答: try $Label.css({color:'#8e8ef5'});

Body:
I'm trying to create a custom error message and styling based on validation (I know about plugins, but the time involved in coordinating the validation plugin with Materialize is too much for a single field).

HTML:

  <input id="quantity" name="quantity" type="number" class="">
  Qty
  really?

JS:

$('#quantity').change(function(){
  var $Qty = $(this).val();
  var $Label = $('#qty-error');
  if ($Qty > 0 && $Qty <= $AvailTix){
      $Label.html('seems reasonable');
      $Label.style.color = '#8e8ef5';
      $(this).addClass('valid');
  } else if ($Qty < 1){
      $Label.html('really?');
      $Label.style.color ='#f96d63';
      $(this).addClass('invalid');
  }
});

What's confusing me is that the $Label.html piece is working. It changes the text. But I get this error in the console for the $Label.style.color line:

Uncaught TypeError: Cannot set property 'color' of undefined

Body: try $Label.css({color:'#8e8ef5'});


问:
Top and bottom borders
I have some code here, this gives me a bottom border, how can I add to it to make it show top and bottom borders?

table.bottomBorder {
  border-collapse: collapse;
}

table.bottomBorder td,
table.bottomBorder th {
  border-bottom: 1px solid lightgrey;
  padding: 10px;
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table class="bottomBorder">
  <tr>
    <th>Table Header</th>
    <th>Table Header</th>
  </tr>
  <tr>
    <td>Table cell</td>
    <td>Table cell</td>
  </tr>
  <tr>
    <td>Table cell</td>
    <td>Table cell</td>
  </tr>
</table></code>```

答:
You missed the th border property, add following css part

```<code>table.bottomBorder tr th {
  text-align: center; /* If you need */
  border-bottom: 1px solid #ddd;
  border-top: 1px solid #ddd;
  padding: 10px;
}
</code>```

table.bottomBorder {
  border-collapse: collapse;
}

table.bottomBorder td,
table.bottomBorder th {
  border-bottom: 1px solid lightgrey;
  padding: 10px;
  text-align: center;
}

table.bottomBorder tr th {
  border-bottom: 1px solid #ddd;
  border-top: 1px solid #ddd;
  padding: 10px;
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table class="bottomBorder">
  <tr>
    <th>Table Header</th>
    <th>Table Header</th>
  </tr>
  <tr>
    <td>Table cell</td>
    <td>Table cell</td>
  </tr>
  <tr>
    <td>Table cell</td>
    <td>Table cell</td>
  </tr>
</table></code>```

Title: Top and bottom borders

Body:
You missed the th border property, add following css part

table.bottomBorder tr th {
  text-align: center; /* If you need */
  border-bottom: 1px solid #ddd;
  border-top: 1px solid #ddd;
  padding: 10px;
}

table.bottomBorder {
  border-collapse: collapse;
}

table.bottomBorder td,
table.bottomBorder th {
  border-bottom: 1px solid lightgrey;
  padding: 10px;
  text-align: center;
}

table.bottomBorder tr th {
  border-bottom: 1px solid #ddd;
  border-top: 1px solid #ddd;
  padding: 10px;
  text-align: center;
}

<table class="bottomBorder">
  <tr>
    <th>Table Header</th>
    <th>Table Header</th>
  </tr>
  <tr>
    <td>Table cell</td>
    <td>Table cell</td>
  </tr>
  <tr>
    <td>Table cell</td>
    <td>Table cell</td>
  </tr>
</table>


问:
Why does SQL query visit all rows and is very slow
The table 'reading' contains readings taken every 40s, for today. The query returns averages for 180s periods. 'time_stamp' is indexed. The query below returns a reasonable number of rows (a few hundred) but visits ALL rows and get slower the bigger the table gets. WHERE clause does not seem to be restricting it to today's rows only.

EXPLAIN SELECT
    DATE_FORMAT(time_stamp, '%Y-%m-%dT%T+00:00') ,
    AVG(temp_c)
FROM reading
WHERE DATE(time_stamp) = CURDATE()
GROUP BY round(UNIX_TIMESTAMP(time_stamp) / 180)

Table schema:
CREATE TABLE reading (
  id bigint(20) NOT NULL AUTO_INCREMENT,
  time_stamp timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  temp_c float NOT NULL,
  pressure_hpa float NOT NULL,
  wind_speed_kt int(11) NOT NULL,
  wind_dir_degree int(11) NOT NULL,
  rain_mm float NOT NULL,
  rain_day_mm float NOT NULL,
  wind_gust_kt int(11) NOT NULL,
  humidity float DEFAULT NULL,
  PRIMARY KEY (id),
  KEY time_stamp (time_stamp),
  KEY time_stamp_idx (time_stamp)
) ENGINE=InnoDB AUTO_INCREMENT=1747097 DEFAULT CHARSET=latin1;

答:
```<code>EXPLAIN SELECT
    DATE_FORMAT(time_stamp, '%Y-%m-%dT%T+00:00') ,
    AVG(temp_c)
FROM reading
WHERE DATE(time_stamp) = CURDATE()
GROUP BY round(UNIX_TIMESTAMP(time_stamp) / 180)
</code>```

When the above query is executed, MySQL optimizer isn't interested in index scan (could be because of cost factor) rather full table scan is initiated and the issue appears to be because of WHERE DATE(time_stamp) = CURDATE().

Having changed your where clause to time_stamp >= CURDATE(), I've seen index being used and less number of rows were fetched shunning full scan.

Hence, your final query will be:

```<code>EXPLAIN SELECT
    DATE_FORMAT(time_stamp, '%Y-%m-%dT%T+00:00') ,
    AVG(temp_c)
FROM reading
WHERE time_stamp >= CURDATE()
GROUP BY round(UNIX_TIMESTAMP(time_stamp) / 180);
</code>```

I suspect date(time_stamp) isn't that efficient with index. Similar topic was discussed here (see ypercube's answer).

The above query can be further improved by choosing an alternate of round(UNIX_TIMESTAMP(time_stamp) / 180) as UNIX_TIMESTAMP(timestamp) doesn't use index. But, I'm not trying furthermore.

Hope this helps!

Body:
EXPLAIN SELECT
    DATE_FORMAT(time_stamp, '%Y-%m-%dT%T+00:00') ,
    AVG(temp_c)
FROM reading
WHERE DATE(time_stamp) = CURDATE()
GROUP BY round(UNIX_TIMESTAMP(time_stamp) / 180)

When the above query is executed, MySQL optimizer isn't interested in index scan (could be because of cost factor) rather full table scan is initiated and the issue appears to be because of WHERE DATE(time_stamp) = CURDATE().

Having changed your where clause to time_stamp >= CURDATE(), I've seen index being used and less number of rows were fetched shunning full scan.

Hence, your final query will be:

EXPLAIN SELECT
    DATE_FORMAT(time_stamp, '%Y-%m-%dT%T+00:00') ,
    AVG(temp_c)
FROM reading
WHERE time_stamp >= CURDATE()
GROUP BY round(UNIX_TIMESTAMP(time_stamp) / 180);

I suspect date(time_stamp) isn't that efficient with index. Similar topic was discussed here (see ypercube's answer).

The above query can be further improved by choosing an alternate of round(UNIX_TIMESTAMP(time_stamp) / 180) as UNIX_TIMESTAMP(timestamp) doesn't use index. But, I'm not trying furthermore.

Hope this helps!


问:
java.upcasting
i have this example:

```<code>class One
{
    public void testOne(){System.out.println("One!!!");}
    public void testTwo(){System.out.println("One!!!");}
}
public class Jenia extends One
{
    static void test(One o) {o.testOne(); o.testTwo();}
    public static void main(String args[])
    {
        test(new One());
    }
}
</code>```

Results:

```<code>One!!!
One!!!
</code>```

ok, no questions.

than, i try modified my code:

only this method:

```<code>public static void main(String args[])
    {
        test(new Jenia());
        }
</code>```

results:

```<code>One!!!
One!!!
</code>```

ok, we have this results because - here upcasting(Jenia-One).

its all ok too, but, modified again:
 in class Jenia override methodtestOne`:

```<code>public void testOne(){System.out.println("Two!!!");}
</code>```

so i have this code:

```<code>class One
{
    public void testOne(){System.out.println("One!!!");}
    public void testTwo(){System.out.println("One!!!");}
}
public class Jenia extends One
{
    public void testOne(){System.out.println("Two!!!");}

    static void test(One o){o.testOne(); o.testTwo();}
    public static void main(String args[])
    {
        test(new Jenia());
    }
}
</code>```

and results:

```<code>Two!!!
One!!!
</code>```

my question: why Two!!! ?? why we not lost override methods?

答:
java overriding here is the tutorial http://download.oracle.com/javase/tutorial/java/IandI/override.html

```<code>public class A {
    void print() {
        System.out.println("A");
    }

    public static void main(String[] args){
        A a1 = new A();
        a1.print(); // A

        A a2 = new B();
        a2.print(); // B ! because it overrides print method

        B b = new B();
        b.print(); // B
    }
}

class B extends A {
    void print() {
        System.out.println("B");
    }
}
</code>```

Title: java.upcasting

Body:
i have this example:

class One
{
    public void testOne(){System.out.println("One!!!");}
    public void testTwo(){System.out.println("One!!!");}
}
public class Jenia extends One
{
    static void test(One o) {o.testOne(); o.testTwo();}
    public static void main(String args[])
    {
        test(new One());
    }
}

Results:

One!!!
One!!!

ok, no questions.

than, i try modified my code:

only this method:

public static void main(String args[])
    {
        test(new Jenia());
        }

results:

One!!!
One!!!

ok, we have this results because - here upcasting(Jenia-One).

its all ok too, but, modified again:
 in class Jenia override methodtestOne`:

public void testOne(){System.out.println("Two!!!");}

so i have this code:

class One
{
    public void testOne(){System.out.println("One!!!");}
    public void testTwo(){System.out.println("One!!!");}
}
public class Jenia extends One
{
    public void testOne(){System.out.println("Two!!!");}

    static void test(One o){o.testOne(); o.testTwo();}
    public static void main(String args[])
    {
        test(new Jenia());
    }
}

and results:

Two!!!
One!!!

my question: why Two!!! ?? why we not lost override methods?

Body:
java overriding here is the tutorial http://download.oracle.com/javase/tutorial/java/IandI/override.html

public class A {
    void print() {
        System.out.println("A");
    }

    public static void main(String[] args){
        A a1 = new A();
        a1.print(); // A

        A a2 = new B();
        a2.print(); // B ! because it overrides print method

        B b = new B();
        b.print(); // B
    }
}

class B extends A {
    void print() {
        System.out.println("B");
    }
}


问:
Swift 3- How to get button in UICollectionViewCell work
I am trying to implement an Edit button inside a cell.

Please refer to image:

What I done so far:

MainController:

```<code>class MainController: UICollectionViewController, UICollectionViewDelegateFlowLayout  {
  let imgCellId = "imgCellId"

  override func viewDidLoad() {
    collectionView?.backgroundColor = .white
    collectionView?.register(ImgItemCell.self, forCellWithReuseIdentifier: imgCellId)
  }

  override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
      let cell = collectionView.dequeueReusableCell(withReuseIdentifier: imgCellId, for: indexPath) as! ImgItemCell
      cell.editButton.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)

      return cell
  }

  func buttonPressed(){
    print("buttonPressed !")
  }

}
</code>```

ImgItemCell:

```<code>import Material

class ImgItemCell: UICollectionViewCell{

   override init(frame: CGRect){
       super.init(frame: frame)

       setupViews()
   }
   ...
   let editButton: RaisedButton = {
       let button = RaisedButton(title: "Edit", titleColor: .black) return button
   }()

  func setupViews(){
     ...
     addSubview(editButton)
     ...
  }

}
</code>```

Result: The button is not clickable. No log is printed when clicking on the button.

In android, I have done this by OnClickListener of button to perform action for each row. How can I do the same in Swift 3?

Solution: (it's working for me)

Hi all thank you for all suggestions, they’re more less the hint for me to come to the solution.

The root cause of my problem is view hierarchy (as @DatForis pointed out)

Explanation: I want a cell contains image and a layout of buttons so that I had view hierarchy as below

```<code>override func setupViews() {
    super.setupViews()

    addSubview(imgView)
    addSubview(buttonLayout)
    buttonLayout.addSubView(buttonList)
            buttonList.addSubview(editButton)
            buttonList.addSubview(shareButton)
  }
</code>```

this hierarchy somehow blocked the click event of button.

Therefore, I changed a bit in hierarchy

```<code>  override func setupViews() {
    super.setupViews()

    addSubview(imgView)
    addSubview(buttonLayout)
            buttonLayout.addSubview(editButton)
            buttonLayout.addSubview(shareButton)
   }
</code>```

and BAM ! it worked like a charm.

In fact, I need a proper explanation about why the hierarchy impact to children view.

By the way, I think most replies here are workable solution, but I selected @DonMag as final answer, because it’s clean and clear with a cool callback to Controller.

But again, my root problem is from view hierarchy.

答:
A very reliable and flexible pattern is to assign a "Callback Closure" to your cell. Put your button action handler inside the cell, and have it "call back" to the view controller.

Here is a basic example (you should be able to implement it with your custom cell with no problem):

```<code>//
//  CViewWithButtonCollectionViewController.swift
//  SWTemp2
//
//  Created by Don Mag on 6/5/17.
//  Copyright © 2017 DonMag. All rights reserved.
//

import UIKit

private let reuseIdentifier = "ImgItemCell"

class ImgItemCell: UICollectionViewCell {

    // this will be our "call back" action
    var btnTapAction : (()->())?

    override init(frame: CGRect){
        super.init(frame: frame)
        setupViews()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupViews()
    }

    let editButton: UIButton = {
        let button = UIButton(type: UIButtonType.system)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.backgroundColor = .white
        button.setTitle("Edit", for: .normal)
        return button
    }()

    func setupViews(){

        // add a button
        addSubview(editButton)

        editButton.centerXAnchor.constraint(equalTo: contentView.centerXAnchor).isActive = true
        editButton.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true

        // add the touchUpInside target
        editButton.addTarget(self, action: #selector(btnTapped), for: .touchUpInside)

    }

    @objc func btnTapped() {
        print("Tapped!")

        // use our "call back" action to tell the controller the button was tapped
        btnTapAction?()
    }

}

class CViewWithButtonCollectionViewController: UICollectionViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        if let layout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout {
            layout.itemSize = CGSize(width: 300, height: 100)
        }

    }

    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 10
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! ImgItemCell

        cell.backgroundColor = .red

        // set a "Callback Closure" in the cell
        cell.btnTapAction = {
            () in
            print("Edit tapped in cell", indexPath)
            // start your edit process here...
        }

        return cell
    }

}
</code>```

Body:
I am trying to implement an Edit button inside a cell.

Please refer to image:

What I done so far:

MainController:

class MainController: UICollectionViewController, UICollectionViewDelegateFlowLayout  {
  let imgCellId = "imgCellId"

  override func viewDidLoad() {
    collectionView?.backgroundColor = .white
    collectionView?.register(ImgItemCell.self, forCellWithReuseIdentifier: imgCellId)
  }

  override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
      let cell = collectionView.dequeueReusableCell(withReuseIdentifier: imgCellId, for: indexPath) as! ImgItemCell
      cell.editButton.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)

      return cell
  }

  func buttonPressed(){
    print("buttonPressed !")
  }

}

ImgItemCell:

import Material

class ImgItemCell: UICollectionViewCell{

   override init(frame: CGRect){
       super.init(frame: frame)

       setupViews()
   }
   ...
   let editButton: RaisedButton = {
       let button = RaisedButton(title: "Edit", titleColor: .black) return button
   }()

  func setupViews(){
     ...
     addSubview(editButton)
     ...
  }

}

Result: The button is not clickable. No log is printed when clicking on the button.

In android, I have done this by OnClickListener of button to perform action for each row. How can I do the same in Swift 3?

Solution: (it's working for me)

Hi all thank you for all suggestions, they’re more less the hint for me to come to the solution.

The root cause of my problem is view hierarchy (as @DatForis pointed out)

Explanation: I want a cell contains image and a layout of buttons so that I had view hierarchy as below

override func setupViews() {
    super.setupViews()

    addSubview(imgView)
    addSubview(buttonLayout)
    buttonLayout.addSubView(buttonList)
            buttonList.addSubview(editButton)
            buttonList.addSubview(shareButton)
  }

this hierarchy somehow blocked the click event of button.

Therefore, I changed a bit in hierarchy

  override func setupViews() {
    super.setupViews()

    addSubview(imgView)
    addSubview(buttonLayout)
            buttonLayout.addSubview(editButton)
            buttonLayout.addSubview(shareButton)
   }

and BAM ! it worked like a charm.

In fact, I need a proper explanation about why the hierarchy impact to children view.

By the way, I think most replies here are workable solution, but I selected @DonMag as final answer, because it’s clean and clear with a cool callback to Controller.

But again, my root problem is from view hierarchy.

Body:
A very reliable and flexible pattern is to assign a "Callback Closure" to your cell. Put your button action handler inside the cell, and have it "call back" to the view controller.

Here is a basic example (you should be able to implement it with your custom cell with no problem):

//
//  CViewWithButtonCollectionViewController.swift
//  SWTemp2
//
//  Created by Don Mag on 6/5/17.
//  Copyright © 2017 DonMag. All rights reserved.
//

import UIKit

private let reuseIdentifier = "ImgItemCell"

class ImgItemCell: UICollectionViewCell {

    // this will be our "call back" action
    var btnTapAction : (()->())?

    override init(frame: CGRect){
        super.init(frame: frame)
        setupViews()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupViews()
    }

    let editButton: UIButton = {
        let button = UIButton(type: UIButtonType.system)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.backgroundColor = .white
        button.setTitle("Edit", for: .normal)
        return button
    }()

    func setupViews(){

        // add a button
        addSubview(editButton)

        editButton.centerXAnchor.constraint(equalTo: contentView.centerXAnchor).isActive = true
        editButton.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true

        // add the touchUpInside target
        editButton.addTarget(self, action: #selector(btnTapped), for: .touchUpInside)

    }

    @objc func btnTapped() {
        print("Tapped!")

        // use our "call back" action to tell the controller the button was tapped
        btnTapAction?()
    }

}

class CViewWithButtonCollectionViewController: UICollectionViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        if let layout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout {
            layout.itemSize = CGSize(width: 300, height: 100)
        }

    }

    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 10
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! ImgItemCell

        cell.backgroundColor = .red

        // set a "Callback Closure" in the cell
        cell.btnTapAction = {
            () in
            print("Edit tapped in cell", indexPath)
            // start your edit process here...
        }

        return cell
    }

}

ContentLicense: CC BY-SA 4.0


问:
Find all tables in database By primaryKey
I'm searching for a query that can retrieve all the tables by the specified key/keys name on a specific database.
Something like this:

```<code>SELECT table_name
FROM   information_Schema.columns
WHERE  column_name='ID_UNICO'
AND    Constraint_Type = 'PRIMARY KEY'
</code>```

I've been searching and the best I could find was:

```<code>SELECT Col.Column_Name from
    INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab,
    INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col
WHERE
    Col.Constraint_Name = Tab.Constraint_Name
    AND Col.Table_Name = Tab.Table_Name
    AND Constraint_Type = 'PRIMARY KEY'
    AND Col.Table_Name = '<your table name>'
</code>```

this retrieves the PK's of a specific table, I want to find table_name BY PK name.

```<code>SELECT table_name
FROM   information_Schema.columns
WHERE  column_name='ID_UNICO'
and    ordinal_position = 1;
</code>```

also found this but this gives me the first column of the table, which doesn't ensure me that it it the PK.

Couldn't find any duplicate either.

答:
You can use this query. Replace 'YOUR_COLUMN_NAME' with your primary key column name.</p>

```<code>SELECT Table_Name
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA + '.' + QUOTENAME(CONSTRAINT_NAME)), 'IsPrimaryKey') = 1
and COLUMN_NAME ='YOUR_COLUMN_NAME'
</code>```

Body:
I'm searching for a query that can retrieve all the tables by the specified key/keys name on a specific database.
Something like this:

SELECT table_name
FROM   information_Schema.columns
WHERE  column_name='ID_UNICO'
AND    Constraint_Type = 'PRIMARY KEY'

I've been searching and the best I could find was:

SELECT Col.Column_Name from
    INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab,
    INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col
WHERE
    Col.Constraint_Name = Tab.Constraint_Name
    AND Col.Table_Name = Tab.Table_Name
    AND Constraint_Type = 'PRIMARY KEY'
    AND Col.Table_Name = '<your table name>'

this retrieves the PK's of a specific table, I want to find table_name BY PK name.

SELECT table_name
FROM   information_Schema.columns
WHERE  column_name='ID_UNICO'
and    ordinal_position = 1;

also found this but this gives me the first column of the table, which doesn't ensure me that it it the PK.

Couldn't find any duplicate either.

Body:
You can use this query. Replace 'YOUR_COLUMN_NAME' with your primary key column name.

SELECT Table_Name
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA + '.' + QUOTENAME(CONSTRAINT_NAME)), 'IsPrimaryKey') = 1
and COLUMN_NAME ='YOUR_COLUMN_NAME'


问:
How to fetch default value in input using angularjs?
Hi all How to get default value in input using angular js?

my plunker please look at my plunker I want to fetch directquestion values are defaults in an input field.

"directquestion": "582c1f4b53cf7fec2ddf282e", i am expecting to fetch directquestion values defaulty in above input field...

if we fetch that ng-model values in an input field, the data's are got a filter.

I want to filter direct question values through the input field....

if anyone knows the solution please help me thanks in advance...

答:
Do you want to select the first result by default?
If that's what you want, try the following

UPDATE: I had worn ng-change instead of ng-init

HTML:

```<code><div ng-repeat="question in questions | filter:directquestion" class="col-md-6" ng-init="selectDirectQuestion($first, question)">
</code>```

CONTROLLER:

```<code>$scope.selectDirectQuestion = function(first, question){
 if(first){
  $scope.directquestion = question.directquestion;
 }
}
</code>```

If it is the first round of ngRepeat, the value will be assigned to the input model

Plunker

Body:
Do you want to select the first result by default?
If that's what you want, try the following

UPDATE: I had worn ng-change instead of ng-init

HTML:

<div ng-repeat="question in questions | filter:directquestion" class="col-md-6" ng-init="selectDirectQuestion($first, question)">

CONTROLLER:

$scope.selectDirectQuestion = function(first, question){
 if(first){
  $scope.directquestion = question.directquestion;
 }
}

If it is the first round of ngRepeat, the value will be assigned to the input model

Plunker


问:
failure in make Prometheus: undefined sort.Slice
I face with an error while building from source. Go version is:

```<code>> go version
go version go1.7.2 linux/amd64
</code>```

The error is:

```<code>prometheus head.go undefined: sort.Slice
</code>```

答: Prometheus needs to be compiled with go 1.8 I'm afraid.  sort.Slice was introduced in that version.

Body:
I face with an error while building from source. Go version is:

> go version
go version go1.7.2 linux/amd64

The error is:

prometheus head.go undefined: sort.Slice