问:
Javascript web server?
Is it possible to build a micro (proof of concept) web server in Javascript?

Has anyone done this before?.

EDIT: Apparently explicit clarification is needed here. The question is ultimately about how to push data from the server to the browser after the initial request made by the browser has been closed. In other words, how to make the browser accept subsequent requests initiated by a server.

Does a javascript based web server need to be installed into the browser, or is there some other method?

答:
You could try "ewsjs is an embedded Web server inside your browser. When developing Ajax-based and single-page-applications, it is often very difficult to test these applications until a Web server is in place. (...)

EWS provides an embedded Web server that looks to your Ajax application as if it is coming from the server. You can put in any logic and fully test out your Ajax application within the browser, without running a server.

EWS supports several key features: Registering handlers for any path, Registering handlers for parametrized paths (like Sinatra routes), Registering a handler for automatic (when no other handler matches), Rewriting of one path to another (like in Apache or nginx), Asynchronous (exactly mimicking true ajax calls)"

on https://github.com/deitch/ewsjs

Title: Javascript web server?


来源: stackexchange

问:
Ajax submit with specific IDs in execute still submits entire form
As far as I understood, specifying IDs in the execute of an f:ajax tag should limit the fields which are posted to the server.

```<code>    <h:form>
        <h:inputText id="one" value="#{manageSettingsBean.testOne}"/>
        <h:inputText id="two" value="#{manageSettingsBean.testTwo}"/>

        <h:commandButton value="Multi test" action="#{maintainEntityAction.multi(manageSettingsBean.testOne, manageSettingsBean.testTwo)}">
            <f:ajax execute="@this one"/>
        </h:commandButton>
    </h:form>
</code>```

In this case, I'd expect that only the first inputText would be submitted.

On examining the form data in Chrome's Network tab, however, I see

j_idt13=j_idt13&j_idt13%3Aone=One&j_idt13%3Atwo=Two&javax.faces.ViewState=-8624538035389330252%3A2147742525648157763&javax.faces.source=j_idt13%3Aj_idt14&javax.faces.partial.event=click&javax.faces.partial.execute=j_idt13%3Aj_idt14%20j_idt13%3Aone&javax.faces.behavior.event=action&javax.faces.partial.ajax=true

Which contains both components, with their default values (of "One" and "Two").

```<code>j_idt13:one=One
j_idt13:two=Two
</code>```

The first component is specified in the javax.faces.partial.execute, so it is the only one that is updated, but both fields do seem to be submitted. I'm doing the partial submit as part of a large form to avoid posting up too much data, but the benefit would appear to be lost if the entire form is still being submitted?

答:
The execute attribute has no relation to the submitting of fields or not. It influences their processing on the server. So in this regard your expectation is wrong and everything behaves as expected.

PrimeFaces has introduced a partialSubmit for this that uses their process attribute (their counterpart of execute) to limit what is actually submitted.

Based on this I created some code for another question <f:ajax render="@none" execute="@this"> and reducing submitted post data size in large form that makes this work on plain JSF as well and at the same time I submitted a feature request to OmniFaces to add the same functionality to the OmniFaces o:form. They improved it a little and added it to the upcoming release which you can already try as a 3.0-SNAPSHOT

ContentLicense: CC BY-SA 3.0

Body:
As far as I understood, specifying IDs in the execute of an f:ajax tag should limit the fields which are posted to the server.

    <h:form>
        <h:inputText id="one" value="#{manageSettingsBean.testOne}"/>
        <h:inputText id="two" value="#{manageSettingsBean.testTwo}"/>

        <h:commandButton value="Multi test" action="#{maintainEntityAction.multi(manageSettingsBean.testOne, manageSettingsBean.testTwo)}">
            <f:ajax execute="@this one"/>
        </h:commandButton>
    </h:form>

In this case, I'd expect that only the first inputText would be submitted.

On examining the form data in Chrome's Network tab, however, I see

j_idt13=j_idt13&j_idt13%3Aone=One&j_idt13%3Atwo=Two&javax.faces.ViewState=-8624538035389330252%3A2147742525648157763&javax.faces.source=j_idt13%3Aj_idt14&javax.faces.partial.event=click&javax.faces.partial.execute=j_idt13%3Aj_idt14%20j_idt13%3Aone&javax.faces.behavior.event=action&javax.faces.partial.ajax=true

Which contains both components, with their default values (of "One" and "Two").

j_idt13:one=One
j_idt13:two=Two

The first component is specified in the javax.faces.partial.execute, so it is the only one that is updated, but both fields do seem to be submitted. I'm doing the partial submit as part of a large form to avoid posting up too much data, but the benefit would appear to be lost if the entire form is still being submitted?


问:
regex url to image in php
I am making a profile page where users can set an url to their profile image. How do I check this with regex for example?</p>

答:
You can use FILTER_VALIDATE_URL.

Look at : parsing url - php, check if scheme exists, validate url regex

ContentLicense: CC BY-SA 2.5

Title: regex url to image in php


问:
How to trigger clean method from model when updating?
When I  save my form I perform validation of data that is defined in my model

```<code>    def clean(self):
    model = self.__class__
    if self.unit and (self.is_active == True)  and model.objects.filter(unit=self.unit, is_terminated = False , is_active = True).exclude(id=self.id).count() > 0:
        raise ValidationError('Unit has active lease already, Terminate existing one prior to creation of new one or create a not active lease '.format(self.unit))
</code>```

How can I trigger same clean method during simple update without a need to duplicate clean logic in my update view?(In my view I just perform update without any form)

```<code>Unit.objects.filter(pk=term.id).update(is_active=False)
</code>```

答:
update don't call the save method of your model and so it's not possible for django to raise ValidationError exceptions in this case.

You need to at least call the full_clean method of your model before doing the update.

Maybe like this ?

```<code>unit = Unit.objects.get(pk=term.id)
unit.is_active = False

try:
    unit.full_clean()
except ValidationError as e:
    # Handle the exceptions here

unit.save()
</code>```

Reference: https://docs.djangoproject.com/en/1.11/ref/models/instances/#validating-objects

Body:
When I  save my form I perform validation of data that is defined in my model

    def clean(self):
    model = self.__class__
    if self.unit and (self.is_active == True)  and model.objects.filter(unit=self.unit, is_terminated = False , is_active = True).exclude(id=self.id).count() > 0:
        raise ValidationError('Unit has active lease already, Terminate existing one prior to creation of new one or create a not active lease '.format(self.unit))

How can I trigger same clean method during simple update without a need to duplicate clean logic in my update view?(In my view I just perform update without any form)

Unit.objects.filter(pk=term.id).update(is_active=False)

Body:
update don't call the save method of your model and so it's not possible for django to raise ValidationError exceptions in this case.

You need to at least call the full_clean method of your model before doing the update.

Maybe like this ?

unit = Unit.objects.get(pk=term.id)
unit.is_active = False

try:
    unit.full_clean()
except ValidationError as e:
    # Handle the exceptions here

unit.save()

Reference: https://docs.djangoproject.com/en/1.11/ref/models/instances/#validating-objects


问:
Laravel: How to update packages in storage/framework
I have removed a package with composer remove and it's now removed from composer.json and composer.lock files and also removed from vendor directory. But I noticed that it's still listed in these two files: storage/framework/packages.php and storage/framework/services.php. How can I update/rebuild these files?

Also, when I run php artisan in the root of my project, I get this error:

[Symfony\Component\Debug\Exception\FatalThrowableError]
    Class 'Morilog\Jalali\JalaliServiceProvider' not found

I searched in all the files of the project and found JalaliServiceProvider still listed only in the two above-mentioned files.

答: Your package is registered in config/app.php. remove the package Morilog\Jalali\JalaliServiceProvider::class</p>


问:
scrapy - scraping a field on next page and then returning to old page
I want to scrape data from the site: http://www.consumercomplaints.in/?search=ecom-express#
I am hoping my request is quite simple and straightforward for the more experienced Scrapy users out there.

Problem: I am trying to scrape data for each review.By data,**I mean main title,subtitle ,username,date and review. ** But what i am not able to get the review ,since for review what i want is to goto the link embedded with the main title and then get the whole review not the brief one on the first page and do this for each review.

My spider class:

```<code>from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.spider import BaseSpider
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import HtmlXPathSelector
from consumercomplaint.items import ConsumercomplaintItem

class MySpider(BaseSpider):
    name = "consumer"
    allowed_domains = ["http://www.consumercomplaints.in"]
    start_urls = ["http://www.consumercomplaints.in/?search=ecom-express&page=11"]

def parse(self, response):
    hxs = HtmlXPathSelector(response)
    titles = hxs.select('//table[@width="100%"]')
    print titles
    items = []
    del(titles[0])
    for i in titles:
        item = ConsumercomplaintItem()
        item ["maintitle"] = i.select('.//a[1]//text()').extract()
        item ["username"] = i.select('.//td[@class="small"]//a[2]/text()').extract()
        item["date"]=i.select('.//td[@class="small"]/text()').extract()
        item["subtitle"]=i.select('.//td[@class="compl-text"]/div/b[1]/text()').extract()
        item["complaint"]=i.select('.//td[@class="compl-text"]/div/text()').extract()
        items.append(item)
    return items
</code>```

My item class:

```<code>from scrapy.item import Item, Field

class ConsumercomplaintItem(Item):
    maintitle = Field()
    username = Field()
    date = Field()
    subtitle = Field()
    complaint = Field()
</code>```

答:
I would do it in two phases:

a)  save partial data into item
b) extract link of the full complaint
c) create a new request and save your item into request.meta
d) yield request

a) extract full complaint
b) extract item from meta
c) save complaint into item's field
d) yield item

```<code>def parse(self, response):
    hxs = HtmlXPathSelector(response)
    titles = hxs.select('//table[@width="100%"]')
    print titles
    items = []
    del(titles[0])
    for i in titles:
        item = ConsumercomplaintItem()
        item ["maintitle"] = i.select('.//a[1]//text()').extract()
        item ["username"] = i.select('.//td[@class="small"]//a[2]/text()').extract()
        item["date"]=i.select('.//td[@class="small"]/text()').extract()
        item["subtitle"]=i.select('.//td[@class="compl-text"]/div/b[1]/text()').extract()

    complaint_link = row.xpath('//complaint/link/a/@href').extract_first()
    complaint_page = response.urljoin(complaint_link)
    request = scrapy.Request(cve_page, callback=self.parse_complaint)
    request.meta['item'] = item
    yield request

def parse_complaint(self, response):
    item = response.meta['item']
    item['complaint'] = response.xpath('/complaint/path/text()').extract_first()
    yield item
</code>```

Body:
I want to scrape data from the site: http://www.consumercomplaints.in/?search=ecom-express#
I am hoping my request is quite simple and straightforward for the more experienced Scrapy users out there.

Problem: I am trying to scrape data for each review.By data,**I mean main title,subtitle ,username,date and review. ** But what i am not able to get the review ,since for review what i want is to goto the link embedded with the main title and then get the whole review not the brief one on the first page and do this for each review.

My spider class:

from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.spider import BaseSpider
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import HtmlXPathSelector
from consumercomplaint.items import ConsumercomplaintItem

class MySpider(BaseSpider):
    name = "consumer"
    allowed_domains = ["http://www.consumercomplaints.in"]
    start_urls = ["http://www.consumercomplaints.in/?search=ecom-express&page=11"]

def parse(self, response):
    hxs = HtmlXPathSelector(response)
    titles = hxs.select('//table[@width="100%"]')
    print titles
    items = []
    del(titles[0])
    for i in titles:
        item = ConsumercomplaintItem()
        item ["maintitle"] = i.select('.//a[1]//text()').extract()
        item ["username"] = i.select('.//td[@class="small"]//a[2]/text()').extract()
        item["date"]=i.select('.//td[@class="small"]/text()').extract()
        item["subtitle"]=i.select('.//td[@class="compl-text"]/div/b[1]/text()').extract()
        item["complaint"]=i.select('.//td[@class="compl-text"]/div/text()').extract()
        items.append(item)
    return items

My item class:

from scrapy.item import Item, Field

class ConsumercomplaintItem(Item):
    maintitle = Field()
    username = Field()
    date = Field()
    subtitle = Field()
    complaint = Field()

Body:
I would do it in two phases:

a)  save partial data into item
b) extract link of the full complaint
c) create a new request and save your item into request.meta
d) yield request

a) extract full complaint
b) extract item from meta
c) save complaint into item's field
d) yield item

def parse(self, response):
    hxs = HtmlXPathSelector(response)
    titles = hxs.select('//table[@width="100%"]')
    print titles
    items = []
    del(titles[0])
    for i in titles:
        item = ConsumercomplaintItem()
        item ["maintitle"] = i.select('.//a[1]//text()').extract()
        item ["username"] = i.select('.//td[@class="small"]//a[2]/text()').extract()
        item["date"]=i.select('.//td[@class="small"]/text()').extract()
        item["subtitle"]=i.select('.//td[@class="compl-text"]/div/b[1]/text()').extract()

    complaint_link = row.xpath('//complaint/link/a/@href').extract_first()
    complaint_page = response.urljoin(complaint_link)
    request = scrapy.Request(cve_page, callback=self.parse_complaint)
    request.meta['item'] = item
    yield request

def parse_complaint(self, response):
    item = response.meta['item']
    item['complaint'] = response.xpath('/complaint/path/text()').extract_first()
    yield item

ContentLicense: CC BY-SA 4.0


问:
Why template is getting compiled four times in angular 4?
I am calling a function from inside an angular template (interpolation), strangely the function is getting invoked four times !!

I do know how change detection works in angular, as I understood change-detection process kickstarts if binding value gets updated.

In this scenario, I am not binding / changing any thing as such..

var i = 0;

@Component({
  selector: 'my-app',
  template: `

{{ parentCounter() }}

  `,
})
export class App {
  name:string;
  constructor() {

  }

  parentCounter(){
    alert(`${++i} called`);
    return 5;
  }
}```

Ref: https://plnkr.co/edit/pta0s0nzcsLdTsjCtb3D?p=preview

Note: Template got compiled four times before the async event

答:
As stated in the previous answer comments there are two calls each time as you can see in the pictures to check that the value hasn't changed due to subsequent calls (idempotent test).  The first set of 2 calls is initiated from the bootstrap/initial parsing of the page, the second pair of calls is triggered as the result of the readystatechange event firing off and the automatic zone/async handler triggering a view update.

Also just to add this is really going to be insignificant.  Performance issues arise from pages that have components typically in repeaters with tons of data bindings leading to pages with 10s of thousands of data bindings (and then people complain that it is slow :) )  Check out the timeline and chrome profiling tools they are invaluable, also to dig into this myself I used a debugger keyword and the call stack to see what was going on in general.

Body:
I am calling a function from inside an angular template (interpolation), strangely the function is getting invoked four times !!

I do know how change detection works in angular, as I understood change-detection process kickstarts if binding value gets updated.

In this scenario, I am not binding / changing any thing as such..

var i = 0;

@Component({
  selector: 'my-app',
  template: `

{{ parentCounter() }}

  `,
})
export class App {
  name:string;
  constructor() {

  }

  parentCounter(){
    alert(`${++i} called`);
    return 5;
  }
}

Ref: https://plnkr.co/edit/pta0s0nzcsLdTsjCtb3D?p=preview

Note: Template got compiled four times before the async event


问:
Function composition, tuples and unpacking
(disclaimed: not a Python kid, so please be gentle)

I am trying to compose functions using the following:

```<code>def compose(*functions):
  return functools.reduce(lambda acc, f: lambda x: acc(f(x)), functions, lambda x: x)
</code>```

which works as expected for scalar functions. I'd like to work with functions returning tuples and others taking multiple arguments, eg.

```<code>def dummy(name):
  return (name, len(name), name.upper())

def transform(name, size, upper):
  return (upper, -size, name)

# What I want to achieve using composition,
# ie. f = compose(transform, dummy)
transform(*dummy('Australia'))
=> ('AUSTRALIA', -9, 'Australia')
</code>```

Since dummy returns a tuple and transform takes three arguments, I need to unpack the value.

How can I achieve this using my compose function above? If I try like this, I get:

```<code>f = compose(transform, dummy)
f('Australia')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in <lambda>
  File "<stdin>", line 2, in <lambda>
TypeError: transform() takes exactly 3 arguments (1 given)
</code>```

Is there a way to change compose such that it will unpack where needed?

答:
This one works for your example but it wont handle just any arbitrary function - it will only works with positional arguments and (of course) the signature of any function must match the return value of the previous (wrt/ application order) one.

```<code>def compose(*functions):
    return functools.reduce(
        lambda f, g: lambda *args: f(*g(*args)),
        functions,
        lambda *args: args
        )
</code>```

Note that using reduce here, while certainly idiomatic in functional programming, is rather unpythonic. The "obvious" pythonic implementation would use iteration instead:

```<code>def itercompose(*functions):
    def composed(*args):
        for func in reversed(functions):
            args = func(*args)
        return args
    return composed
</code>```

Edit:

You ask "Is there a way to make have a compose function which will work in both cases" - "both cases" here meaning wether the functions returns an iterable or not (what you call "scalar functions", a concept that has no meaning in Python).

Using the iteration-based implementation, you could just test if the return value is iterable and wrap it in a tuple ie:

```<code>import collections

def itercompose(*functions):
    def composed(*args):
        for func in reversed(functions):
            if not isinstance(args, collections.Iterable):
                args = (args,)
            args = func(*args)
        return args
    return composed
</code>```

but this is not garanteed to work as expected - actually this is even garanteed to NOT work as expected for most use cases. There are a lot of builtin iterable types in Python (and even more user-defined ones) and just knowing an object is iterable doesn't say much about it's semantic.

For example a dict or str are iterable but in this case should obviously be considered a "scalar". A list is iterable too, and how it should be interpreted in this case is actually just undecidable without knowing exactly what it contains and what the "next" function in composition order expects - in some cases you will want to treat it as a single argument, in other cases ase a list of args.

IOW only the caller of the compose() function can really tell how each function result should be considered - actually you might even have cases where you want a tuple to be considered as a "scalar" value by the next function. So to make a long story short: no, there's no one-size-fits-all generic solution in Python. The best I could think of requires a combination of result inspection and manual wrapping of composed functions so the result is properly interpreted by the "composed" function but at this point manually composing the functions will be both way simpler and much more robust.

FWIW remember that Python is first and mostly a dynamically typed object oriented language so while it does have a decent support for functional programming idioms it's obviously not the best tool for real functional programming.

Body:
(disclaimed: not a Python kid, so please be gentle)

I am trying to compose functions using the following:

def compose(*functions):
  return functools.reduce(lambda acc, f: lambda x: acc(f(x)), functions, lambda x: x)

which works as expected for scalar functions. I'd like to work with functions returning tuples and others taking multiple arguments, eg.

def dummy(name):
  return (name, len(name), name.upper())

def transform(name, size, upper):
  return (upper, -size, name)

# What I want to achieve using composition,
# ie. f = compose(transform, dummy)
transform(*dummy('Australia'))
=> ('AUSTRALIA', -9, 'Australia')

Since dummy returns a tuple and transform takes three arguments, I need to unpack the value.

How can I achieve this using my compose function above? If I try like this, I get:

f = compose(transform, dummy)
f('Australia')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in <lambda>
  File "<stdin>", line 2, in <lambda>
TypeError: transform() takes exactly 3 arguments (1 given)

Is there a way to change compose such that it will unpack where needed?

Body:
This one works for your example but it wont handle just any arbitrary function - it will only works with positional arguments and (of course) the signature of any function must match the return value of the previous (wrt/ application order) one.

def compose(*functions):
    return functools.reduce(
        lambda f, g: lambda *args: f(*g(*args)),
        functions,
        lambda *args: args
        )

Note that using reduce here, while certainly idiomatic in functional programming, is rather unpythonic. The "obvious" pythonic implementation would use iteration instead:

def itercompose(*functions):
    def composed(*args):
        for func in reversed(functions):
            args = func(*args)
        return args
    return composed

Edit:

You ask "Is there a way to make have a compose function which will work in both cases" - "both cases" here meaning wether the functions returns an iterable or not (what you call "scalar functions", a concept that has no meaning in Python).

Using the iteration-based implementation, you could just test if the return value is iterable and wrap it in a tuple ie:

import collections

def itercompose(*functions):
    def composed(*args):
        for func in reversed(functions):
            if not isinstance(args, collections.Iterable):
                args = (args,)
            args = func(*args)
        return args
    return composed

but this is not garanteed to work as expected - actually this is even garanteed to NOT work as expected for most use cases. There are a lot of builtin iterable types in Python (and even more user-defined ones) and just knowing an object is iterable doesn't say much about it's semantic.

For example a dict or str are iterable but in this case should obviously be considered a "scalar". A list is iterable too, and how it should be interpreted in this case is actually just undecidable without knowing exactly what it contains and what the "next" function in composition order expects - in some cases you will want to treat it as a single argument, in other cases ase a list of args.

IOW only the caller of the compose() function can really tell how each function result should be considered - actually you might even have cases where you want a tuple to be considered as a "scalar" value by the next function. So to make a long story short: no, there's no one-size-fits-all generic solution in Python. The best I could think of requires a combination of result inspection and manual wrapping of composed functions so the result is properly interpreted by the "composed" function but at this point manually composing the functions will be both way simpler and much more robust.

FWIW remember that Python is first and mostly a dynamically typed object oriented language so while it does have a decent support for functional programming idioms it's obviously not the best tool for real functional programming.


问:
How can I enable my button on checked the checkbox
```<code>function addHeadCol(row, dindex) {
    var td = document.createElement('TD');
    td.setAttribute("class", "bs-checkbox print_hide");
    var chk = document.createElement("input");
    chk.setAttribute("data-index", dindex);
    chk.name = "btSelectItem";
    chk.type = "checkbox";
    td.appendChild(chk);
    row.appendChild(td);
}
</code>```

This code creating checkboxes dynamically. I want to enable a button on checked the checkbox?

答:
Please find working solution below:

function display() {
  alert('hello!');
}

function addHeadCol(row, dindex) {
  var td = document.createElement('TD');
  td.setAttribute("class", "bs-checkbox print_hide");
  var chk = document.createElement("input");
  chk.setAttribute("data-index", dindex);
  chk.name = "btSelectItem";
  chk.className = "chk"
  chk.type = "checkbox";
  chk.addEventListener("change", function(e) {
    checkboxes = document.getElementsByClassName('chk');
    var disableButton = true;
    for (var i = 0; i < checkboxes.length; i++) {
      if (checkboxes[i].checked) {
        disableButton = false;
      }
    }
    document.getElementById("btn").disabled = disableButton;
  });
  td.appendChild(chk);
  row.appendChild(td);
}

addHeadCol(document.getElementById('row1'), 1)
addHeadCol(document.getElementById('row2'), 2)
addHeadCol(document.getElementById('row3'), 3)
addHeadCol(document.getElementById('row4'), 4)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr id="row1"></tr>
  <tr id="row2"></tr>
  <tr id="row3"></tr>
  <tr id="row4"></tr>
</table>
<button id="btn" disabled onclick="display()">Click Me!</button></code>```

Body:
function addHeadCol(row, dindex) {
    var td = document.createElement('TD');
    td.setAttribute("class", "bs-checkbox print_hide");
    var chk = document.createElement("input");
    chk.setAttribute("data-index", dindex);
    chk.name = "btSelectItem";
    chk.type = "checkbox";
    td.appendChild(chk);
    row.appendChild(td);
}

This code creating checkboxes dynamically. I want to enable a button on checked the checkbox?

Body:
Please find working solution below:

function display() {
  alert('hello!');
}

function addHeadCol(row, dindex) {
  var td = document.createElement('TD');
  td.setAttribute("class", "bs-checkbox print_hide");
  var chk = document.createElement("input");
  chk.setAttribute("data-index", dindex);
  chk.name = "btSelectItem";
  chk.className = "chk"
  chk.type = "checkbox";
  chk.addEventListener("change", function(e) {
    checkboxes = document.getElementsByClassName('chk');
    var disableButton = true;
    for (var i = 0; i < checkboxes.length; i++) {
      if (checkboxes[i].checked) {
        disableButton = false;
      }
    }
    document.getElementById("btn").disabled = disableButton;
  });
  td.appendChild(chk);
  row.appendChild(td);
}

addHeadCol(document.getElementById('row1'), 1)
addHeadCol(document.getElementById('row2'), 2)
addHeadCol(document.getElementById('row3'), 3)
addHeadCol(document.getElementById('row4'), 4)

<table>
  <tr id="row1"></tr>
  <tr id="row2"></tr>
  <tr id="row3"></tr>
  <tr id="row4"></tr>
</table>
<button id="btn" disabled onclick="display()">Click Me!</button>


问:
How to iterate through json object and form a new object with concatenated values using Javascript?
I have been working on  api which gives data in JSON object and i have no control with it at all. I need to pull data on select box. I have managed to populate it but it allows single value binding only. ie firstName or lastName or middleName and not both. Here is my current JSON Object:

```<code>.employeesList = [
  {
    id: 1,
    firstName: 'firstName',
    middleName: 'middleName',
    lastName: 'lastName',
  },
  {
    id: 2,
    firstName: 'firstName2',
    middleName: 'middleName2',
    lastName: 'lastName2',
  },
  {
    id: 3,
    firstName: 'firstName3',
    middleName: 'middleName3',
    lastName: 'lastName3',
  },
  {
    id: 4,
    firstName: 'firstName4',
    middleName: 'middleName4',
    lastName: 'lastName4',
  },
  {
    id: 5,
    firstName: 'firstName5',
    middleName: 'middleName5',
    lastName: 'lastName5',
  }
]
</code>```

I would like to merge firstName, middleName and lastName in each data and form a new JSON Object having only ids and fullNames like so:

```<code>.employeesList = [
  {
    id: 1,
    fullName: 'firstName MiddleName LastName'
  },
  {
    id: 2,
    fullName: 'firstName2 MiddleName2 LastName2'
  },
  {
    id: 3,
    fullName: 'firstName3 MiddleName3 LastName3'
  },
  {
    id: 4,
    fullName: 'firstName4 MiddleName4 LastName4'
  },
  {
    id: 5,
    fullName: 'firstName5 MiddleName5 LastName5'
  }
]
</code>```

How can i achieve that using Javascript?

答:
var employeesList = [ {
    id: 1,
    firstName: 'firstName',
    middleName: 'middleName',
    lastName: 'lastName',
  },
  {
    id: 2,
    firstName: 'firstName2',
    middleName: 'middleName2',
    lastName: 'lastName2',
  },
  {
    id: 3,
    firstName: 'firstName3',
    middleName: 'middleName3',
    lastName: 'lastName3',
  },
  {
    id: 4,
    firstName: 'firstName4',
    middleName: 'middleName4',
    lastName: 'lastName4',
  },
  {
    id: 5,
    firstName: 'firstName5',
    middleName: 'middleName5',
    lastName: 'lastName5',
  }
]

employeesList.map((obj) => {
  obj["fullName"] = obj["firstName"] + " " + obj["middleName"] + " "  +obj["lastName"];
  delete obj["firstName"];
  delete obj["middleName"];
  delete obj["lastName"];
  console.log(obj)
});```

Body:
I have been working on  api which gives data in JSON object and i have no control with it at all. I need to pull data on select box. I have managed to populate it but it allows single value binding only. ie firstName or lastName or middleName and not both. Here is my current JSON Object:

.employeesList = [
  {
    id: 1,
    firstName: 'firstName',
    middleName: 'middleName',
    lastName: 'lastName',
  },
  {
    id: 2,
    firstName: 'firstName2',
    middleName: 'middleName2',
    lastName: 'lastName2',
  },
  {
    id: 3,
    firstName: 'firstName3',
    middleName: 'middleName3',
    lastName: 'lastName3',
  },
  {
    id: 4,
    firstName: 'firstName4',
    middleName: 'middleName4',
    lastName: 'lastName4',
  },
  {
    id: 5,
    firstName: 'firstName5',
    middleName: 'middleName5',
    lastName: 'lastName5',
  }
]

I would like to merge firstName, middleName and lastName in each data and form a new JSON Object having only ids and fullNames like so:

.employeesList = [
  {
    id: 1,
    fullName: 'firstName MiddleName LastName'
  },
  {
    id: 2,
    fullName: 'firstName2 MiddleName2 LastName2'
  },
  {
    id: 3,
    fullName: 'firstName3 MiddleName3 LastName3'
  },
  {
    id: 4,
    fullName: 'firstName4 MiddleName4 LastName4'
  },
  {
    id: 5,
    fullName: 'firstName5 MiddleName5 LastName5'
  }
]

How can i achieve that using Javascript?


问:
How to submit a form on page load without clicking submit button?
Is there a way to make a form submit "onload" without clicking a
submit button with PHP? i saw some ways to make it with Javascript, but i love php and id like to make it with php.

For example:

```<code><form action="https://xxxxxx.com/yyy.php" method="post" id="foo">
<input type="hidden" name="LoginEmail" value="user [at] domain.com">
<input type="hidden" name="LoginPassword" value="mycleartextpassword">
<input type="submit" name="Authenticate" value="Login">
<input type="hidden" name="Action" value="1" >
</form>
</code>```

I can make it with javascript:

```<code><form id="foo"> .... < /form>

<script type="text/javascript">
    function myfunc () {
        var frm = document.getElementById("foo");
        frm.submit();
    }
    window.onload = myfunc;
</script>
</code>```

Well, Can we make same thing with PHP? Could you please kindly share your ideas and advices?

Thank you.

答:
it is by using jquery ajax.

```<code>$(document).ready(function(){..........your code goes here........});
</code>```

if you prefer jquery replay me i wll give you the help

Body:
Is there a way to make a form submit "onload" without clicking a
submit button with PHP? i saw some ways to make it with Javascript, but i love php and id like to make it with php.

For example:

<form action="https://xxxxxx.com/yyy.php" method="post" id="foo">
<input type="hidden" name="LoginEmail" value="user [at] domain.com">
<input type="hidden" name="LoginPassword" value="mycleartextpassword">
<input type="submit" name="Authenticate" value="Login">
<input type="hidden" name="Action" value="1" >
</form>

I can make it with javascript:

<form id="foo"> .... < /form>

Well, Can we make same thing with PHP? Could you please kindly share your ideas and advices?

Thank you.

Body:
it is by using jquery ajax.

$(document).ready(function(){..........your code goes here........});

if you prefer jquery replay me i wll give you the help


问:
Limit image, title, and story height in cardview
I started from https://startbootstrap.com/template-overviews/4-col-portfolio/. I made some changes and got to this:

Images are provided externally and I have no control over their sizes. What I want to achieve is that all images should take 25% of the row height. Aspect ratio should be maintained so the width of the image can be decreased, the column width should remain the same. All titles should take maximum 50% (text trimmed if too long) and the remainder is filled with content text (text trimmed again).

I'm completely new to bootstrap and tried to influence the image height with by adding

```<code>.card-img-top {
  height: 25%;
}
</code>```

But that doesn't seem to do anything.

Can anyone advise? If possible I would prefer to not have to go into sass for now since I have no experience with this.

Edit: the complete code is here: https://github.com/JefPatat/ProjectX

答:
With easy html like:

```<code><div class="row">
    <div class="image">
        <img src="">
    </div>
    <div class="title">
       this is the tittle short
    </div>
    <div class="txt">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi u
    </div>
</div>
</code>```

you could use this CSS:

```<code>.row {/*------This is your column-*/
   height:600px; /*------The height of your columns-*/
   width:200px; /*------The width of your columns-*/
   border:1px solid black; /*------basic style-*/
   float:left; /*------layout-*/
   margin-right:10px; /*------basic style-*/
   overflow:hidden; /*------to avoid the rest of your text, if long, to overflow-*/
}
.image {
   height:25%;/*------Fixed height-*/
   position:relative;  /*------needed to adapt the image with code below-*/
}
.image img {
   position:absolute;
    top:0;
    left:0;
    right:0;
    bottom:0;
    margin:auto;
    max-width:100%;
    max-height:100%;/*------all this img properties will center the image whatever size, keeping aspect ratio-*/
}
.title {
  font-size:16px;/*------style-*/
  color:blue;/*------style-*/
  max-height:25%;/*------So, as you said, max 25% of container-*/
  overflow:hidden;/*------trimming text if more than 25% height-*/
}
.txt {
does not requiered anything special but styles. Will take the rest of the height avalaible
}
</code>```

As an example:

* {box-sizing:border-box;}
.row {
   height:600px;
   width:200px;
   border:1px solid black;
   float:left;
   margin-right:10px;
   overflow:hidden;
}
.image {
   height:25%;
   position:relative;
}
.image img {
   position:absolute;
    top:0;
    left:0;
    right:0;
    bottom:0;
    margin:auto;
    max-width:100%;
    max-height:100%;
}
.title {
  font-size:16px;
  color:blue;
  max-height:25%;
  overflow:hidden;
}
.txt {

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
    <div class="image">
        <img src="http://html.crunchpress.com/tulip/images/blog/blog-img-3.jpg" alt="">
    </div>
    <div class="title">
      this is the tittle short
    </div>
    <div class="txt">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi u
    </div>
</div>
<div class="row">
    <div class="image">
        <img src="http://www.imgworlds.com/wp-content/themes/IMG/img/phase3/welcome/hulk.png" alt="">
    </div>
    <div class="title">
      this is the tittle lon gthis is the tittle long this is the tittle long this is the tittle long this is the tittle lonle lon gthis is the tittle long this is the tittle long this is the tittle long this is the tittle longle lon gthis is the tittle long this is the tittle long this is the tittle long this is the tittle longg
    </div>
    <div class="txt">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magnre magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laboruma aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
    </div>
</div></code>```

EDITED AFTER FIRST COMMENT BELOW

Ok. To adapt it to your pure bootstrap I make this FIDDLE for you with boostrap loaded.

notice that I just paste this html INSIDE "portfolio-item" container:

```<code><div class="image">
            <img src="">
        </div>
        <div class="title">
           this is the tittle short
        </div>
        <div class="txt">
          Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi u
        </div>
</code>```

This CSS at the end of css sheet:

```<code>.row {
   height:800px;
}
.portfolio-item {
  height:100%;
}
.image {
   height:25%;
   position:relative;
}
.image img {
   position:absolute;
    top:0;
    left:0;
    right:0;
    bottom:0;
    margin:auto;
    max-width:100%;
    max-height:100%;
}
.title {
  font-size:16px;
  color:blue;
  max-height:25%;
  overflow:hidden;
}
</code>```

Carefull as css classes ´row´ and ´portfolio-item´ are from bootstrap so you may modifi all the project. Better to add your opwn class with the properties above.

Body:
I started from https://startbootstrap.com/template-overviews/4-col-portfolio/. I made some changes and got to this:

Images are provided externally and I have no control over their sizes. What I want to achieve is that all images should take 25% of the row height. Aspect ratio should be maintained so the width of the image can be decreased, the column width should remain the same. All titles should take maximum 50% (text trimmed if too long) and the remainder is filled with content text (text trimmed again).

I'm completely new to bootstrap and tried to influence the image height with by adding

.card-img-top {
  height: 25%;
}

But that doesn't seem to do anything.

Can anyone advise? If possible I would prefer to not have to go into sass for now since I have no experience with this.

Edit: the complete code is here: https://github.com/JefPatat/ProjectX

Body:
With easy html like:

<div class="row">
    <div class="image">
        <img src="">
    </div>
    <div class="title">
       this is the tittle short
    </div>
    <div class="txt">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi u
    </div>
</div>

you could use this CSS:

.row {/*------This is your column-*/
   height:600px; /*------The height of your columns-*/
   width:200px; /*------The width of your columns-*/
   border:1px solid black; /*------basic style-*/
   float:left; /*------layout-*/
   margin-right:10px; /*------basic style-*/
   overflow:hidden; /*------to avoid the rest of your text, if long, to overflow-*/
}
.image {
   height:25%;/*------Fixed height-*/
   position:relative;  /*------needed to adapt the image with code below-*/
}
.image img {
   position:absolute;
    top:0;
    left:0;
    right:0;
    bottom:0;
    margin:auto;
    max-width:100%;
    max-height:100%;/*------all this img properties will center the image whatever size, keeping aspect ratio-*/
}
.title {
  font-size:16px;/*------style-*/
  color:blue;/*------style-*/
  max-height:25%;/*------So, as you said, max 25% of container-*/
  overflow:hidden;/*------trimming text if more than 25% height-*/
}
.txt {
does not requiered anything special but styles. Will take the rest of the height avalaible
}

As an example:

* {box-sizing:border-box;}
.row {
   height:600px;
   width:200px;
   border:1px solid black;
   float:left;
   margin-right:10px;
   overflow:hidden;
}
.image {
   height:25%;
   position:relative;
}
.image img {
   position:absolute;
    top:0;
    left:0;
    right:0;
    bottom:0;
    margin:auto;
    max-width:100%;
    max-height:100%;
}
.title {
  font-size:16px;
  color:blue;
  max-height:25%;
  overflow:hidden;
}
.txt {

}

<div class="row">
    <div class="image">
        <img src="http://html.crunchpress.com/tulip/images/blog/blog-img-3.jpg" alt="">
    </div>
    <div class="title">
      this is the tittle short
    </div>
    <div class="txt">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi u
    </div>
</div>
<div class="row">
    <div class="image">
        <img src="http://www.imgworlds.com/wp-content/themes/IMG/img/phase3/welcome/hulk.png" alt="">
    </div>
    <div class="title">
      this is the tittle lon gthis is the tittle long this is the tittle long this is the tittle long this is the tittle lonle lon gthis is the tittle long this is the tittle long this is the tittle long this is the tittle longle lon gthis is the tittle long this is the tittle long this is the tittle long this is the tittle longg
    </div>
    <div class="txt">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magnre magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laboruma aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
    </div>
</div>

EDITED AFTER FIRST COMMENT BELOW

Ok. To adapt it to your pure bootstrap I make this FIDDLE for you with boostrap loaded.

notice that I just paste this html INSIDE "portfolio-item" container:

<div class="image">
            <img src="">
        </div>
        <div class="title">
           this is the tittle short
        </div>
        <div class="txt">
          Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi u
        </div>

This CSS at the end of css sheet:

.row {
   height:800px;
}
.portfolio-item {
  height:100%;
}
.image {
   height:25%;
   position:relative;
}
.image img {
   position:absolute;
    top:0;
    left:0;
    right:0;
    bottom:0;
    margin:auto;
    max-width:100%;
    max-height:100%;
}
.title {
  font-size:16px;
  color:blue;
  max-height:25%;
  overflow:hidden;
}

Carefull as css classes ´row´ and ´portfolio-item´ are from bootstrap so you may modifi all the project. Better to add your opwn class with the properties above.


答:
```<code>newList = employeesList.map((empl) => {
    return {
        id: empl.id, fullName: empl.firstName + ' ' + empl.middleName + ' ' + empl.lastName}
    }
)
</code>```

Title: How to iterate through json object and form a new object with concatenated values using Javascript?


问:
Javascript : How to enable stopPropagation?
With object.stopPropagation() I can stop event bubbling but how can I re-enable it?

Is there a pre defined function in js something like object.startPropagation?

EDIT:

The Problem is that the JS remembers if you click on the "object" than stop Event Bubbling always even after I don't want it, so I would like to stop it:

```<code>document.getElementById("object").onclick = function(e){
    if(e && e.stopPropagation) {
        e.stopPropagation();
    } else {
          e = window.event;
          e.cancelBubble = true;
    }
}
</code>```

答:
It doesn't remember the value at all. The event e is new each time onclick is fired. The problem is you're always cancelling the event bubbling:

```<code>if(foo) {
    e.stopPropagation();
} else {
    e.cancelBubble = true;
}
</code>```

e.stopPropagation is the W3C method
of preventing event bubbling.

e.cancelBubble is the Microsoft
method to prevent event bubbling.

They're both the same. So you're cancelling bubbling of events every time. More reading here.

You'll need to change your method so that it only cancels bubbling if your criteria are met:

```<code>document.getElementById("object").onclick = function(e) {

    if(e && e.stopPropagation && someCriteriaToStopBubbling === true)
    {
        e.stopPropagation();
    }
    else if (someCriteriaToStopBubbling === true)
    {
          e = window.event;
          e.cancelBubble = true;
    }
}
</code>```

UPDATE:
Bear in mind that in your current code, if (e && e.stopPropagation) will always be true if the browser supports stopPropagation. If it goes into the second brace for cancelBubble, it will not remember the value last set. See this fiddle.

Basically, to summarise, in your code you're cancelling propagation every time after every click. You have to put some criteria into the function to determine whether or not to cancel the propagation up the element hierarchy.

Body:
With object.stopPropagation() I can stop event bubbling but how can I re-enable it?

Is there a pre defined function in js something like object.startPropagation?

EDIT:

The Problem is that the JS remembers if you click on the "object" than stop Event Bubbling always even after I don't want it, so I would like to stop it:

document.getElementById("object").onclick = function(e){
    if(e && e.stopPropagation) {
        e.stopPropagation();
    } else {
          e = window.event;
          e.cancelBubble = true;
    }
}

Body:
It doesn't remember the value at all. The event e is new each time onclick is fired. The problem is you're always cancelling the event bubbling:

if(foo) {
    e.stopPropagation();
} else {
    e.cancelBubble = true;
}

e.stopPropagation is the W3C method
of preventing event bubbling.

e.cancelBubble is the Microsoft
method to prevent event bubbling.

They're both the same. So you're cancelling bubbling of events every time. More reading here.

You'll need to change your method so that it only cancels bubbling if your criteria are met:

document.getElementById("object").onclick = function(e) {

    if(e && e.stopPropagation && someCriteriaToStopBubbling === true)
    {
        e.stopPropagation();
    }
    else if (someCriteriaToStopBubbling === true)
    {
          e = window.event;
          e.cancelBubble = true;
    }
}

UPDATE:
Bear in mind that in your current code, if (e && e.stopPropagation) will always be true if the browser supports stopPropagation. If it goes into the second brace for cancelBubble, it will not remember the value last set. See this fiddle.

Basically, to summarise, in your code you're cancelling propagation every time after every click. You have to put some criteria into the function to determine whether or not to cancel the propagation up the element hierarchy.


问:
Questions about moving to Git on VSTS?
We've been using TFS for many years but are considering moving to VSTS, possibly with a switch to Git (our company was taken over recently and the new owners use Git). I've been having a quick play with GitHub (not VSTS), and have a few questions...

Local repo

I'm struggling to get my head around the idea of first having to commit to a local repo then to the server. It seems like an unnecessary extra step, and I'm not sure what the benefits are?

Branching

Git recommends creating a branch each time you want to develop a new feature or fix a bug. Our team might churn out dozens of new features in a sprint, so I'm a bit concerned about the resulting explosion of branches, the overhead of managing them, and the possible confusion/mistakes that could result. I realise you can delete a branch when you've done with it, but it's still an unwanted overhead and I know our devs will forget to clean up after themselves!

With TFS we commit changes straight to the master (dev) branch, and the only time we create a branch is when releasing a new version of the product. We'll create a "Release_1.0" branch for example, and the only time we would work on this is to fix a bug (then merge it back into "dev").

We obviously don't have to follow the "Git way", but I'm wondering what the pros and cons are of this workflow?

Work Items

Am I right in saying that work items can be associated with a Git "commit"? Is it nicely integrated like it is with TFS, or is it more of an after-thought/hack approach? I don't want this sort of thing to become a hindrance to our devs.

Builds

We're still running TFS2012, and have customised our build processes (e.g. to update version numbers in AssemblyInfo.cs, run StyleCop, create an InnoSetup script, etc). This may or may not be specific to Git, but is it still possible to manage and customise builds in VSTS? I'm assuming builds run on the VSTS servers, therefore there would be some cost involved for their CPU time?

答:
The idea of creating local commits is not an overhead but a feature which allows you to do anything while working locally. You can create/amend/delete commits as long as you haven't pushed them. It gives you the flexibility which I am sure you will love once you get accustomed.

Branches in git are cheap. You will probably maintain a master branch and some of the releases branches. Apart from that whenever you want to develop some feature, you will create a new branch out of master, commit your changes, push the changes to server and create a pull request and then merge it back to master and delete the branch. VSTS allows easily deleting branches when it is merged. Git also has the option of deleting all the branches which are merged to master. To take your bug fixes to master or releases branches, you can use the git cherry pick feature which has first class support in VSTS UI.

Yes, there is first class support for linking work items to commits and pull requests.

Yes, you can customize your build however you want. Git is only a version control system. Your build pipeline can remain the same.

Title: Questions about moving to Git on VSTS?


问:
Opengl/glsl/lwjgl either 2d or 3d, not both?
So I'm trying to render a basic overlay onto my 3D scene, and currently I can either have the 3D scene or the 2D overlay, I cant work out how to get both

In my main method, where render is called, I moved specific render functions to manager classes, so in the main render I call :

```<code>        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glEnable(GL_DEPTH_TEST);
        glEnable(GL_COLOR_MATERIAL);

        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();

        glOrtho(-aspect, aspect, -1, 1, -10, 10);

        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();

        material.setColour(new Vector3f(1,1,1));
        sLight.getPointLight().setPosition(camera.getPosition());
        sLight.setDirection(camera.getForward());

        DayCycle.getInstance().update(Time.getDelta());

        shader.updateUniforms(transform.getTransformation(), transform.getProjectedTransformation(), material);
        //material is a wrapper class for textures and specular value etc
        //transform is a matrix wrapper for getting projected transformations, taking the camera position when its created
        WorldManager.renderAll(true); //true denotes yes to wireframe mode

        InterfaceManager.renderAll();

        glfwSwapBuffers(window);
        glfwPollEvents();
</code>```

If i comment out WorldManager.renderAll(), I get the little 2d square in the right part of the screen, If i dont comment it, I get the world render but no little square

WorldManager.renderAll()

```<code>    public static void renderAll(boolean wireframeMode)
    {
    RendererUtils.setWireframeMode(wireframeMode);

    for (String s : chunks.keySet())
    {
        Chunk actingChunk = chunks.get(s);

        Transform transform = new Transform();
        Shader shader = PhongShader.getInstance();
        transform.setTranslation(new Vector3f(actingChunk.getLocation().getX() * (Chunk.ChunkSize),0.0f, actingChunk.getLocation().getY() * (Chunk.ChunkSize)));
        transform.setScale(1.0f, 50f, 1.0f);
        shader.updateUniforms(transform.getTransformation(), transform.getProjectedTransformation(), actingChunk.getMaterial());
        shader.bind();

        actingChunk.getMesh().draw();
        //transform.setRotation(new Vector3f(0,0,0));
    }
    }
</code>```

InterfaceManager.renderAll()

```<code>    public static void renderAll()
{
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    glOrtho(0, width, 0, height, -10, 10);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    glDisable(GL_CULL_FACE);
    glDisable(GL_DEPTH_TEST);
    RendererUtils.setWireframeMode(false);
    for (Interface i : interfaces)
    {
        Transform transform = new Transform();
        transform.setTranslation(new Vector3f(0,0,0));
        InterfaceShader.getInstance().updateUniforms(transform.getProjectedTransformation());
        InterfaceShader.getInstance().bind();

        i.getMesh().draw();
    }
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);
}
</code>```

When I have WorldManager.renderAll() uncommented, i get a nice sea of triangles (as its meant to look) but no 2D square
With it commented, I get a nice little square where its meant to be and nothing else

Shaders are here : https://pastebin.com/xWaWhQHy because I felt this post was getting too long to have them inlined

What's my problem? I cant figure out where it is

Edit : If i've missed any pertinent code, tell me and i'll upload it to a pastebin

Edit 2 : updated my code here to reflect that i'd removed a shader in interfaceManager to actually get a square to draw at all : https://pastebin.com/pHHDsCvF for the shader code

Edit 3 : Ive determined it's something to do with my interface shaders, If i use PhongShader instead of InterfaceShader then it works exactly how I wanted it to

答:
I can suggest you to modify the code this way:

```<code>  WorldManager.renderAll(true); //true denotes yes to wireframe mode

  glClear(GL_DEPTH_BUFFER_BIT);
  InterfaceManager.renderAll();
</code>```

This way you will clear depth buffer before rendering 2d interface.

Body:
So I'm trying to render a basic overlay onto my 3D scene, and currently I can either have the 3D scene or the 2D overlay, I cant work out how to get both

In my main method, where render is called, I moved specific render functions to manager classes, so in the main render I call :

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glEnable(GL_DEPTH_TEST);
        glEnable(GL_COLOR_MATERIAL);

        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();

        glOrtho(-aspect, aspect, -1, 1, -10, 10);

        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();

        material.setColour(new Vector3f(1,1,1));
        sLight.getPointLight().setPosition(camera.getPosition());
        sLight.setDirection(camera.getForward());

        DayCycle.getInstance().update(Time.getDelta());

        shader.updateUniforms(transform.getTransformation(), transform.getProjectedTransformation(), material);
        //material is a wrapper class for textures and specular value etc
        //transform is a matrix wrapper for getting projected transformations, taking the camera position when its created
        WorldManager.renderAll(true); //true denotes yes to wireframe mode

        InterfaceManager.renderAll();

        glfwSwapBuffers(window);
        glfwPollEvents();

If i comment out WorldManager.renderAll(), I get the little 2d square in the right part of the screen, If i dont comment it, I get the world render but no little square

WorldManager.renderAll()

    public static void renderAll(boolean wireframeMode)
    {
    RendererUtils.setWireframeMode(wireframeMode);

    for (String s : chunks.keySet())
    {
        Chunk actingChunk = chunks.get(s);

        Transform transform = new Transform();
        Shader shader = PhongShader.getInstance();
        transform.setTranslation(new Vector3f(actingChunk.getLocation().getX() * (Chunk.ChunkSize),0.0f, actingChunk.getLocation().getY() * (Chunk.ChunkSize)));
        transform.setScale(1.0f, 50f, 1.0f);
        shader.updateUniforms(transform.getTransformation(), transform.getProjectedTransformation(), actingChunk.getMaterial());
        shader.bind();

        actingChunk.getMesh().draw();
        //transform.setRotation(new Vector3f(0,0,0));
    }
    }

InterfaceManager.renderAll()

    public static void renderAll()
{
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    glOrtho(0, width, 0, height, -10, 10);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    glDisable(GL_CULL_FACE);
    glDisable(GL_DEPTH_TEST);
    RendererUtils.setWireframeMode(false);
    for (Interface i : interfaces)
    {
        Transform transform = new Transform();
        transform.setTranslation(new Vector3f(0,0,0));
        InterfaceShader.getInstance().updateUniforms(transform.getProjectedTransformation());
        InterfaceShader.getInstance().bind();

        i.getMesh().draw();
    }
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);
}

When I have WorldManager.renderAll() uncommented, i get a nice sea of triangles (as its meant to look) but no 2D square
With it commented, I get a nice little square where its meant to be and nothing else

Shaders are here : https://pastebin.com/xWaWhQHy because I felt this post was getting too long to have them inlined

What's my problem? I cant figure out where it is

Edit : If i've missed any pertinent code, tell me and i'll upload it to a pastebin

Edit 2 : updated my code here to reflect that i'd removed a shader in interfaceManager to actually get a square to draw at all : https://pastebin.com/pHHDsCvF for the shader code

Edit 3 : Ive determined it's something to do with my interface shaders, If i use PhongShader instead of InterfaceShader then it works exactly how I wanted it to

Body:
I can suggest you to modify the code this way:

  WorldManager.renderAll(true); //true denotes yes to wireframe mode

  glClear(GL_DEPTH_BUFFER_BIT);
  InterfaceManager.renderAll();

This way you will clear depth buffer before rendering 2d interface.


问:
java.io.FileNotFoundException: /storage/emulated/0/Notes/fact50Result.txt: open failed ENOENT (No such file or directory)
I am trying to export the results of a factorial calculation in a txt file.
I found this code that looked quite straight forward from this article here.
However I'm getting the error on the title. What am I doing wrong?

I have typed this into the manifest:

```<code> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</code>```

And this is my code related to saving:

```<code>    public void save(View v) {
     if(numOnRAM!=-1) {
         EditText text = (EditText) findViewById(R.id.resultTextBox);
         String data = text.getText().toString();
         generateNoteOnSD(this,"fact"+numOnRAM+"Results.txt", data);
     }
}

public void generateNoteOnSD(Context context, String sFileName, String sBody) {
    try {
        File root = new File(Environment.getExternalStorageDirectory(), "Notes");
        if (!root.exists()) {
            root.mkdirs();
        }
        File gpxfile = new File(root, sFileName);
        FileWriter writer = new FileWriter(gpxfile);
        writer.append(sBody);
        writer.flush();
        writer.close();
        Toast.makeText(context, "File "+sFileName+" saving success!", Toast.LENGTH_LONG).show();

    } catch (IOException e) {
        e.printStackTrace();
        Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();//After adding this
//toast message did I realise the error thar occurs.

    }
}
</code>```

答:
I think you have to request permission on runtime. Please check the code below:</p>

```<code> final private int REQUEST_CODE_ASK_PERMISSIONS = 123;

      private void requestPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ) {
            ActivityCompat
                    .requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_ASK_PERMISSIONS);
        }
    }

        @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_ASK_PERMISSIONS:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Permission Granted
                    Toast.makeText(MainActivity.this, "Permission Granted", Toast.LENGTH_SHORT)
                            .show();
                } else {
                    // Permission Denied
                    Toast.makeText(MainActivity.this, "Permission Denied", Toast.LENGTH_SHORT)
                            .show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
</code>```

Body:
I am trying to export the results of a factorial calculation in a txt file.
I found this code that looked quite straight forward from this article here.
However I'm getting the error on the title. What am I doing wrong?

I have typed this into the manifest:

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

And this is my code related to saving:

    public void save(View v) {
     if(numOnRAM!=-1) {
         EditText text = (EditText) findViewById(R.id.resultTextBox);
         String data = text.getText().toString();
         generateNoteOnSD(this,"fact"+numOnRAM+"Results.txt", data);
     }
}

public void generateNoteOnSD(Context context, String sFileName, String sBody) {
    try {
        File root = new File(Environment.getExternalStorageDirectory(), "Notes");
        if (!root.exists()) {
            root.mkdirs();
        }
        File gpxfile = new File(root, sFileName);
        FileWriter writer = new FileWriter(gpxfile);
        writer.append(sBody);
        writer.flush();
        writer.close();
        Toast.makeText(context, "File "+sFileName+" saving success!", Toast.LENGTH_LONG).show();

    } catch (IOException e) {
        e.printStackTrace();
        Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();//After adding this
//toast message did I realise the error thar occurs.

    }
}

Body:
I think you have to request permission on runtime. Please check the code below:

 final private int REQUEST_CODE_ASK_PERMISSIONS = 123;

      private void requestPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ) {
            ActivityCompat
                    .requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_ASK_PERMISSIONS);
        }
    }

        @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_ASK_PERMISSIONS:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Permission Granted
                    Toast.makeText(MainActivity.this, "Permission Granted", Toast.LENGTH_SHORT)
                            .show();
                } else {
                    // Permission Denied
                    Toast.makeText(MainActivity.this, "Permission Denied", Toast.LENGTH_SHORT)
                            .show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }


问:
How to get user's IP address in a bot with node.js?
I am writing a bot in node.js. May I know how can I insert code to console.log the IP address of message sender please? I need the IP address to perform some auto-log in.

Many Thanks!!

答:
To get the Ip address of your User

```<code>    var app = require('express')();

    app.get("/ip", (req, res) => {
      console.log(req.ip) // "::ffff:127.0.0.1" ::ffff: is a subnet prefix for IPv4 (32 bit)
      let ip = req.ip.split(':');
      console.log(ip[3]);
       res.json(ip[3]);  // ==> 127.0.0.1 You can Get Your Ip address only
    });
app.listen(3003);
</code>```

Body:
To get the Ip address of your User

    var app = require('express')();

    app.get("/ip", (req, res) => {
      console.log(req.ip) // "::ffff:127.0.0.1" ::ffff: is a subnet prefix for IPv4 (32 bit)
      let ip = req.ip.split(':');
      console.log(ip[3]);
       res.json(ip[3]);  // ==> 127.0.0.1 You can Get Your Ip address only
    });
app.listen(3003);


问:
How to generate plists from rails models?
I'm rather new at ruby (on rails) and I can't figure this one out;

What is the best way to serialize objects to plist in rails?

I'm using the plist library from rubyforge.

And I have nested_attributes:

```<code>class Deck
deck has_many :cards
accepts_nested_attributes_for :cards

class Card
belongs_to :deck
</code>```

I've tried in the deck controller to do this:

```<code>format.plist { render :plist => @deck.to_plist }
</code>```

But I don't get the cards...

Similar in xml, I can do this:

```<code>format.xml  { render :xml => @deck.to_xml(:include => :cards) }
</code>```

And get the desired output.

Can anyone help or point me in the right direction?

答:
Have you registred the mime type in your environment.rb ?

```<code>Mime::Type.register "text/plist", :plist
</code>```

this could help http://blog.willj.net/2010/01/25/generating-a-plist-file-in-rails/

bye

Body:
I'm rather new at ruby (on rails) and I can't figure this one out;

What is the best way to serialize objects to plist in rails?

I'm using the plist library from rubyforge.

And I have nested_attributes:

class Deck
deck has_many :cards
accepts_nested_attributes_for :cards

class Card
belongs_to :deck

I've tried in the deck controller to do this:

format.plist { render :plist => @deck.to_plist }

But I don't get the cards...

Similar in xml, I can do this:

format.xml  { render :xml => @deck.to_xml(:include => :cards) }

And get the desired output.

Can anyone help or point me in the right direction?

Body:
Have you registred the mime type in your environment.rb ?

Mime::Type.register "text/plist", :plist

this could help http://blog.willj.net/2010/01/25/generating-a-plist-file-in-rails/

bye


问:
HTMLElement focus() method Uncaught TypeError
I have come across an issue which i feel is rather odd though I'm still learning javascript. I want to do some calculations only when a value for a state is set, if the state isn't set then I want the form field focused.

Now the issue is that the code below doesn't work

```<code>document.getElementById('cart-hplus').addEventListener('submit', estimateTotal);

function estimateTotal(event) {
    event.preventDefault();

    var state = document.getElementById('s-state').value;
    if (state === '') {
        alert("Please choose your preferred shipping state.");

        state.focus();
    }
}
</code>```

Uncaught TypeError: state.focus is not a function

But this works but i don't think it's good habit declaring a variable then using the document object again inside my if statement

```<code>function estimateTotal(event) {
    event.preventDefault();

    var state = document.getElementById('s-state').value;
    if (state === '') {
        alert("Please choose your preferred shipping state.");

        document.getElementById('s-state').focus();
    }
}
</code>```

What is wrong with the first code?

答:
You are not making a distinction between the state input control and the state value. You are going to need to use 2 variables:

```<code>function estimateTotal(event) {
    event.preventDefault();
    var state = document.getElementById('s-state');
    var stateValue = state.value;
    if (stateValue === '') {
        alert("Please choose your preferred shipping state.");
        state.focus();
    }
}
</code>```

Also, the way you have it is fine. There is nothing wrong with referencing the object twice.

Body:
I have come across an issue which i feel is rather odd though I'm still learning javascript. I want to do some calculations only when a value for a state is set, if the state isn't set then I want the form field focused.

Now the issue is that the code below doesn't work

document.getElementById('cart-hplus').addEventListener('submit', estimateTotal);

function estimateTotal(event) {
    event.preventDefault();

    var state = document.getElementById('s-state').value;
    if (state === '') {
        alert("Please choose your preferred shipping state.");

        state.focus();
    }
}

Uncaught TypeError: state.focus is not a function

But this works but i don't think it's good habit declaring a variable then using the document object again inside my if statement

function estimateTotal(event) {
    event.preventDefault();

    var state = document.getElementById('s-state').value;
    if (state === '') {
        alert("Please choose your preferred shipping state.");

        document.getElementById('s-state').focus();
    }
}

What is wrong with the first code?

Body:
You are not making a distinction between the state input control and the state value. You are going to need to use 2 variables:

function estimateTotal(event) {
    event.preventDefault();
    var state = document.getElementById('s-state');
    var stateValue = state.value;
    if (stateValue === '') {
        alert("Please choose your preferred shipping state.");
        state.focus();
    }
}

Also, the way you have it is fine. There is nothing wrong with referencing the object twice.


问:
Java SimpleDateFormat for time zone with a colon separator?
I have a date in the following format: 2010-03-01T00:00:00-08:00

I have thrown the following SimpleDateFormats at it to parse it:

```<code>private static final SimpleDateFormat[] FORMATS = {
        new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"), //ISO8601 long RFC822 zone
        new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz"), //ISO8601 long long form zone
        new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"), //ignore timezone
        new SimpleDateFormat("yyyyMMddHHmmssZ"), //ISO8601 short
        new SimpleDateFormat("yyyyMMddHHmm"),
        new SimpleDateFormat("yyyyMMdd"), //birthdate from NIST IHE C32 sample
        new SimpleDateFormat("yyyyMM"),
        new SimpleDateFormat("yyyy") //just the year
    };
</code>```

I have a convenience method that uses those formats like so:

```<code>public static Date figureOutTheDamnDate(String wtf) {
    if (wtf == null) {
        return null;
    }
    Date retval = null;
    for (SimpleDateFormat sdf : FORMATS) {
        try {
            sdf.setLenient(false)
            retval = sdf.parse(wtf);
            System.out.println("Date:" + wtf + " hit on pattern:" + sdf.toPattern());
            break;
        } catch (ParseException ex) {
            retval = null;
            continue;
        }
    }

    return retval;
}
</code>```

It seems to hit on the pattern yyyyMMddHHmm but returns the date as Thu Dec 03 00:01:00 PST 2009.

What is the correct pattern to parse this date?

UPDATE: I don't NEED the time zone parsing. I don't anticipate having time sensitive issues moving between zones, but how would I get the "-08:00" zone format to parse????

Unit test:

```<code>@Test
public void test_date_parser() {
    System.out.println("\ntest_date_parser");
    //month is zero based, are you effing kidding me
    Calendar d = new GregorianCalendar(2000, 3, 6, 13, 00, 00);
    assertEquals(d.getTime(), MyClass.figureOutTheDamnDate("200004061300"));
    assertEquals(new GregorianCalendar(1950, 0, 1).getTime(), MyClass.figureOutTheDamnDate("1950"));
    assertEquals(new GregorianCalendar(1997, 0, 1).getTime(),  MyClass.figureOutTheDamnDate("199701"));
    assertEquals(new GregorianCalendar(2010, 1, 25, 15, 19, 44).getTime(),   MyClass.figureOutTheDamnDate("20100225151944-0800"));

    //my machine happens to be in GMT-0800
    assertEquals(new GregorianCalendar(2010, 1, 15, 13, 15, 00).getTime(),MyClass.figureOutTheDamnDate("2010-02-15T13:15:00-05:00"));
    assertEquals(new GregorianCalendar(2010, 1, 15, 18, 15, 00).getTime(), MyClass.figureOutTheDamnDate("2010-02-15T18:15:00-05:00"));

    assertEquals(new GregorianCalendar(2010, 2, 1).getTime(), MyClass.figureOutTheDamnDate("2010-03-01T00:00:00-08:00"));
    assertEquals(new GregorianCalendar(2010, 2, 1, 17, 0, 0).getTime(), MyClass.figureOutTheDamnDate("2010-03-01T17:00:00-05:00"));
}
</code>```

Output from unit test:

```<code>test_date_parser
Date:200004061300 hit on pattern:yyyyMMddHHmm
Date:1950 hit on pattern:yyyy
Date:199701 hit on pattern:yyyyMM
Date:20100225151944-0800 hit on pattern:yyyyMMddHHmmssZ
Date:2010-02-15T13:15:00-05:00 hit on pattern:yyyy-MM-dd'T'HH:mm:ss
Date:2010-02-15T18:15:00-05:00 hit on pattern:yyyy-MM-dd'T'HH:mm:ss
Date:2010-03-01T00:00:00-08:00 hit on pattern:yyyy-MM-dd'T'HH:mm:ss
Date:2010-03-01T17:00:00-05:00 hit on pattern:yyyy-MM-dd'T'HH:mm:ss
</code>```

答:
You can use X in Java 7.

https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

```<code>static final SimpleDateFormat DATE_TIME_FORMAT =
        new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

static final SimpleDateFormat JSON_DATE_TIME_FORMAT =
        new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");

private String stringDate = "2016-12-01 22:05:30";
private String requiredDate = "2016-12-01T22:05:30+03:00";

@Test
public void parseDateToBinBankFormat() throws ParseException {
    Date date = DATE_TIME_FORMAT.parse(stringDate);
    String jsonDate = JSON_DATE_TIME_FORMAT.format(date);

    System.out.println(jsonDate);
    Assert.assertEquals(jsonDate, requiredDate);
}
</code>```

Body:
I have a date in the following format: 2010-03-01T00:00:00-08:00

I have thrown the following SimpleDateFormats at it to parse it:

private static final SimpleDateFormat[] FORMATS = {
        new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"), //ISO8601 long RFC822 zone
        new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz"), //ISO8601 long long form zone
        new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"), //ignore timezone
        new SimpleDateFormat("yyyyMMddHHmmssZ"), //ISO8601 short
        new SimpleDateFormat("yyyyMMddHHmm"),
        new SimpleDateFormat("yyyyMMdd"), //birthdate from NIST IHE C32 sample
        new SimpleDateFormat("yyyyMM"),
        new SimpleDateFormat("yyyy") //just the year
    };

I have a convenience method that uses those formats like so:

public static Date figureOutTheDamnDate(String wtf) {
    if (wtf == null) {
        return null;
    }
    Date retval = null;
    for (SimpleDateFormat sdf : FORMATS) {
        try {
            sdf.setLenient(false)
            retval = sdf.parse(wtf);
            System.out.println("Date:" + wtf + " hit on pattern:" + sdf.toPattern());
            break;
        } catch (ParseException ex) {
            retval = null;
            continue;
        }
    }

    return retval;
}

It seems to hit on the pattern yyyyMMddHHmm but returns the date as Thu Dec 03 00:01:00 PST 2009.

What is the correct pattern to parse this date?

UPDATE: I don't NEED the time zone parsing. I don't anticipate having time sensitive issues moving between zones, but how would I get the "-08:00" zone format to parse????

Unit test:

@Test
public void test_date_parser() {
    System.out.println("\ntest_date_parser");
    //month is zero based, are you effing kidding me
    Calendar d = new GregorianCalendar(2000, 3, 6, 13, 00, 00);
    assertEquals(d.getTime(), MyClass.figureOutTheDamnDate("200004061300"));
    assertEquals(new GregorianCalendar(1950, 0, 1).getTime(), MyClass.figureOutTheDamnDate("1950"));
    assertEquals(new GregorianCalendar(1997, 0, 1).getTime(),  MyClass.figureOutTheDamnDate("199701"));
    assertEquals(new GregorianCalendar(2010, 1, 25, 15, 19, 44).getTime(),   MyClass.figureOutTheDamnDate("20100225151944-0800"));

    //my machine happens to be in GMT-0800
    assertEquals(new GregorianCalendar(2010, 1, 15, 13, 15, 00).getTime(),MyClass.figureOutTheDamnDate("2010-02-15T13:15:00-05:00"));
    assertEquals(new GregorianCalendar(2010, 1, 15, 18, 15, 00).getTime(), MyClass.figureOutTheDamnDate("2010-02-15T18:15:00-05:00"));

    assertEquals(new GregorianCalendar(2010, 2, 1).getTime(), MyClass.figureOutTheDamnDate("2010-03-01T00:00:00-08:00"));
    assertEquals(new GregorianCalendar(2010, 2, 1, 17, 0, 0).getTime(), MyClass.figureOutTheDamnDate("2010-03-01T17:00:00-05:00"));
}

Output from unit test:

test_date_parser
Date:200004061300 hit on pattern:yyyyMMddHHmm
Date:1950 hit on pattern:yyyy
Date:199701 hit on pattern:yyyyMM
Date:20100225151944-0800 hit on pattern:yyyyMMddHHmmssZ
Date:2010-02-15T13:15:00-05:00 hit on pattern:yyyy-MM-dd'T'HH:mm:ss
Date:2010-02-15T18:15:00-05:00 hit on pattern:yyyy-MM-dd'T'HH:mm:ss
Date:2010-03-01T00:00:00-08:00 hit on pattern:yyyy-MM-dd'T'HH:mm:ss
Date:2010-03-01T17:00:00-05:00 hit on pattern:yyyy-MM-dd'T'HH:mm:ss

Body:
You can use X in Java 7.

https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

static final SimpleDateFormat DATE_TIME_FORMAT =
        new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

static final SimpleDateFormat JSON_DATE_TIME_FORMAT =
        new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");

private String stringDate = "2016-12-01 22:05:30";
private String requiredDate = "2016-12-01T22:05:30+03:00";

@Test
public void parseDateToBinBankFormat() throws ParseException {
    Date date = DATE_TIME_FORMAT.parse(stringDate);
    String jsonDate = JSON_DATE_TIME_FORMAT.format(date);

    System.out.println(jsonDate);
    Assert.assertEquals(jsonDate, requiredDate);
}


问:
Can .NET's System.Console be configured to print Right To Left?
After overcoming the issues in printing non-ascii characters described here, I wonder if is it possible to configure the console to print Right-To-Left ?

I am now playing with Visual Studio T4 templating, wanted to see for my self the outcome of trying to automatically generate Enums out of database look up tables - and for that I wanted to test myself in this console application I am writing for this purpose.

Obviously, as a workaround, printing the following helps me:

```<code>new string(str.ToCharArray().Reverse().ToArray())
</code>```

But does the console support RTL printing ?

答:
If you also want to print your strings aligned to the right side of the screen in addition to have it rendered in a reversed manner (RTL), use this:

```<code>private static void WriteLineRtl(string input)
{
  Console.CursorLeft = Console.WindowWidth - input.Length;
  for (int i = input.Length - 1; i >= 0; i--)
      Console.Write(input[i]);
}
</code>```

Example:

```<code>using static System.Console;

class Program
{
  static void Main(string[] args)
  {
    WriteLineRtl("שלום,");
    WriteLineRtl("בהמשך לשיחתנו הטלפונית,");
    WriteLineRtl("רציתי להודיע שהכל בסדר.");
    WriteLineRtl("שלום ולהתראות!");

    Read();
  }

  static void WriteLineRtl(string input)
  {
    CursorLeft = WindowWidth - input.Length;
    for (int i = input.Length - 1; i >= 0; i--)
      Write(input[i]);
  }
}
</code>```

Output:

Body:
After overcoming the issues in printing non-ascii characters described here, I wonder if is it possible to configure the console to print Right-To-Left ?

I am now playing with Visual Studio T4 templating, wanted to see for my self the outcome of trying to automatically generate Enums out of database look up tables - and for that I wanted to test myself in this console application I am writing for this purpose.

Obviously, as a workaround, printing the following helps me:

new string(str.ToCharArray().Reverse().ToArray())

But does the console support RTL printing ?

Body:
If you also want to print your strings aligned to the right side of the screen in addition to have it rendered in a reversed manner (RTL), use this:

private static void WriteLineRtl(string input)
{
  Console.CursorLeft = Console.WindowWidth - input.Length;
  for (int i = input.Length - 1; i >= 0; i--)
      Console.Write(input[i]);
}

Example:

using static System.Console;

class Program
{
  static void Main(string[] args)
  {
    WriteLineRtl("שלום,");
    WriteLineRtl("בהמשך לשיחתנו הטלפונית,");
    WriteLineRtl("רציתי להודיע שהכל בסדר.");
    WriteLineRtl("שלום ולהתראות!");

    Read();
  }

  static void WriteLineRtl(string input)
  {
    CursorLeft = WindowWidth - input.Length;
    for (int i = input.Length - 1; i >= 0; i--)
      Write(input[i]);
  }
}

Output:


问:
Undo local commit in Git
I know this question has been asked thousands of time and I tried all solutions and none worked.

I committed to my local 2-3 files and now I want to undo the commit. How can I do that: This is also the first ever commit.

```<code>git reset HEAD^
fatal: ambiguous argument 'HEAD^': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'
</code>```

UPDATE:

```<code>git reset --soft HEAD~1
fatal: ambiguous argument 'HEAD~1': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'
</code>```

UPDATE 2:

```<code>git reset --hard HEAD~1
fatal: ambiguous argument 'HEAD~1': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'
</code>```

答:
if it's your first commit then there is nothing to revert to. there is no state that git knows before this commit.

Maybe you can edit the commit with https://www.atlassian.com/git/tutorials/rewriting-history

Otherwise you can delete the .git Folder in your Directory and start again with git init

Title: Undo local commit in Git

Body:
I know this question has been asked thousands of time and I tried all solutions and none worked.

I committed to my local 2-3 files and now I want to undo the commit. How can I do that: This is also the first ever commit.

git reset HEAD^
fatal: ambiguous argument 'HEAD^': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'

UPDATE:

git reset --soft HEAD~1
fatal: ambiguous argument 'HEAD~1': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'

UPDATE 2:

git reset --hard HEAD~1
fatal: ambiguous argument 'HEAD~1': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'


问:
Handling positions in FirebaseRecyclerAdapter
I have fiddled with the FirebaseRecyclerAdapter for quite some time now. It's really a great tool to populate a custom list/recycler view very fast with all of its features. However, one thing that I would like to ask is how to handle positions of items inside the adapter itself.

So for example, I want to mimic this small feature that WhatsApp has in their chats.

So, in a group chat setting, if a person sends more than one consecutive message in a row, the display name of that particular person will be invisible.

The logic behind it according to my understanding: if the person who sends the message is the same for (position - 1), then I will just make the EditText invisible for (position). This is, of course, to prevent a very long stream of text with minimum amounts of repetitive information.

Let's say the JSON tree from Firebase database is as follows.

```<code>{
  "messages" : {
    "pushed_id_1" : {
      "message_sender" : "AppleJuice",
      "message_text" : "Are you free?"
    },
    "pushed_id_2" : {
      "message_sender" : "AppleJuice",
      "message_text" : "On Saturday I mean..."
    }
  }
}
</code>```

The FirebaseRecyclerAdapter would look like this.

```<code>FirebaseRecyclerAdapter<Message, MessageViewHolder> adapter = new FirebaseRecyclerAdapter<Message, MessageViewHolder>(Message.class, R.layout.message_item, MessageViewHolder.class, myRef) {

            @Override
            protected void populateViewHolder(MyBookingsViewHolder viewHolder, Booking model, int position) {
                viewHolder.messageSender.setText(model.getMessage_sender());
                viewHolder.messageText.setText(model.getMessage_text());

                //put some code here to implement the feature that we need
            }
        };
        messages_recycler_menu.setAdapter(adapter);
</code>```

The furthest I have gone is to use getItemCount() method in the FirebaseRecyclerAdapter, but I am still unable to achieve the feature that mimics that of Whatsapp's that I was talking about previously.

Is there a method that can achieve this? Or am I missing something very important in this example?

答:
As discussed in comments:

Let's suppose I received message and stored sender's name in constant String that should be static constant in some class i.e. AppConstants so that It can be accessed everywhere therefore after that:

in populateViewHolder or in your message receiver do something like this:

```<code>if (TextUtils.isEqual(storedSender,model.getMessage_sender())){
        viewHolder.messageSender.setVisiblity(View.GONE)
       }
    else{
        // do your normal flow
        viewHolder.messageSender.setVisiblity(View.VISIBLE);
    storedSender = model.getMessage_sender();
    }
</code>```

In this way automatically the last message's sender's name will be updated , this is exactly what you were trying to achieve by adapter position!

Body:
I have fiddled with the FirebaseRecyclerAdapter for quite some time now. It's really a great tool to populate a custom list/recycler view very fast with all of its features. However, one thing that I would like to ask is how to handle positions of items inside the adapter itself.

So for example, I want to mimic this small feature that WhatsApp has in their chats.

So, in a group chat setting, if a person sends more than one consecutive message in a row, the display name of that particular person will be invisible.

The logic behind it according to my understanding: if the person who sends the message is the same for (position - 1), then I will just make the EditText invisible for (position). This is, of course, to prevent a very long stream of text with minimum amounts of repetitive information.

Let's say the JSON tree from Firebase database is as follows.

{
  "messages" : {
    "pushed_id_1" : {
      "message_sender" : "AppleJuice",
      "message_text" : "Are you free?"
    },
    "pushed_id_2" : {
      "message_sender" : "AppleJuice",
      "message_text" : "On Saturday I mean..."
    }
  }
}

The FirebaseRecyclerAdapter would look like this.

FirebaseRecyclerAdapter<Message, MessageViewHolder> adapter = new FirebaseRecyclerAdapter<Message, MessageViewHolder>(Message.class, R.layout.message_item, MessageViewHolder.class, myRef) {

            @Override
            protected void populateViewHolder(MyBookingsViewHolder viewHolder, Booking model, int position) {
                viewHolder.messageSender.setText(model.getMessage_sender());
                viewHolder.messageText.setText(model.getMessage_text());

                //put some code here to implement the feature that we need
            }
        };
        messages_recycler_menu.setAdapter(adapter);

The furthest I have gone is to use getItemCount() method in the FirebaseRecyclerAdapter, but I am still unable to achieve the feature that mimics that of Whatsapp's that I was talking about previously.

Is there a method that can achieve this? Or am I missing something very important in this example?

Body:
As discussed in comments:

Let's suppose I received message and stored sender's name in constant String that should be static constant in some class i.e. AppConstants so that It can be accessed everywhere therefore after that:

in populateViewHolder or in your message receiver do something like this:

if (TextUtils.isEqual(storedSender,model.getMessage_sender())){
        viewHolder.messageSender.setVisiblity(View.GONE)
       }
    else{
        // do your normal flow
        viewHolder.messageSender.setVisiblity(View.VISIBLE);
    storedSender = model.getMessage_sender();
    }

In this way automatically the last message's sender's name will be updated , this is exactly what you were trying to achieve by adapter position!


问:
Locking a file while copying using Commons IO
I am using the Apache Commons IO:

```<code>     FileUtils.copyFileToDirectory(srcFile, destDir)
</code>```

How do I make Windows lock the destination file during copy? Windows locks the file correctly if I use:

```<code>      Runtime.getRuntime().exec(
      "cmd /c copy /Y \"" + srcFile.getCanonicalPath() + "\" \""
          + destDir.getCanonicalPath() + "\"").waitFor();
</code>```

Notes:
The contention is not with the local program, but an external one. The file is being copied to a remote system. The remote system is processing the file before it completes the copy. Because the systems are Windows, the normal copy locks the file and blocks the external program from access.

答:
Java doesn't natively support file locking.

If contention for the file is coming from within your program, perhaps you need to build additional synchronization on top of the file copy to make sure concurrent writes don't clobber one another.  However, if the contention is coming from somewhere external to your software then there isn't much you can do.  You can try writing the file to a temporary directory and then renaming it since the rename is more or less atomic (depending on the filesystem).

It would help to have more information on why you need to lock the file in the first place.

The contention is not with the local
  program, but an external one. The file
  is being copied to a remote system.
  The remote system is processing the
  file before it completes the copy.
  Because the systems are Windows, the
  normal copy locks the file and blocks
  the external program from access.

In that case, you should try writing to a temporary file and then renaming it when the file is fully copied.  File renames are atomic operations (on a non networked filesystem) so it should work for you.

OwnerDisplayName: Joshua

Body:
I am using the Apache Commons IO:

     FileUtils.copyFileToDirectory(srcFile, destDir)

How do I make Windows lock the destination file during copy? Windows locks the file correctly if I use:

      Runtime.getRuntime().exec(
      "cmd /c copy /Y \"" + srcFile.getCanonicalPath() + "\" \""
          + destDir.getCanonicalPath() + "\"").waitFor();

Notes:
The contention is not with the local program, but an external one. The file is being copied to a remote system. The remote system is processing the file before it completes the copy. Because the systems are Windows, the normal copy locks the file and blocks the external program from access.

LastEditorDisplayName: Joshua

OwnerDisplayName: Kevin

LastEditorDisplayName: Kevin


问:
NSString memory leak when parsing xml
am writing an application that parses some xml and creates a dictionary of the element names and their values using the below key methods:

```<code>- (void)parserDidStartDocument:(NSXMLParser *)parser{
    foundCharacters = [[NSMutableString alloc] init];
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    if (accumulator) {
        [foundCharacters appendString:string];
    }
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {

    if ([foundCharacters length] != 0) {

                    [parsedContent setObject:[foundCharacters copy] forKey:elementName];

                }
}
</code>```

The leak occurs in the occurs on the "[parsedContent setObject:[foundCharacters copy] forKey:elementName];" line, I can't work out a way to overcome this.

Any insights would be much appreciated.

Edit:

The memory leak only occurs if the request to parse is called more than once

I've also tried "[[foundCharacters copy] autorelease]" but no to avale

答:
In your parserDidStartDocument: you alloc/init a mutable string, but I don't see code where you dispose of this string again. You need to release the string again, for example in the parserDidEndDocument: method.

The memory leak is reported later probably because this is the last place where the variable was actually referenced.

Title: NSString memory leak when parsing xml

Body:
am writing an application that parses some xml and creates a dictionary of the element names and their values using the below key methods:

- (void)parserDidStartDocument:(NSXMLParser *)parser{
    foundCharacters = [[NSMutableString alloc] init];
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    if (accumulator) {
        [foundCharacters appendString:string];
    }
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {

    if ([foundCharacters length] != 0) {

                    [parsedContent setObject:[foundCharacters copy] forKey:elementName];

                }
}

The leak occurs in the occurs on the "[parsedContent setObject:[foundCharacters copy] forKey:elementName];" line, I can't work out a way to overcome this.

Any insights would be much appreciated.

Edit:

The memory leak only occurs if the request to parse is called more than once

I've also tried "[[foundCharacters copy] autorelease]" but no to avale