text:
Q: X ticks axis in matplotlib Plot Figure
Hello Everyone,
I am trying to plot a graph of contour but in very strange way the x values written in the x axis are not
much to the real x values.
I did not success solving that issue and wonder why this is happening.
I tried changing the x ticks in many different ways but with no success,
Hope someone can help me get out from this situation.
Thanks!
`import numpy as np
import numdifftools as nd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
def Function(x):
    return np.cos(x[0])+np.sin(x[1])+(1/5)*x[0]**2+(1/4)*x[1]**2

def hw10GDstep(f,x0):
    xold=x0[0]
    yold=x0[1]
    grad=nd.Gradient(Function)([xold,yold])
    Xnew=xold-0.2*grad[0]
    Ynew=yold-0.2*grad[1]
    X,Y=np.meshgrid(Xnew,Ynew)
    fval=f(X,Y)
    fval=list(fval)
    return ([Xnew,Ynew],fval[0][0])

def GradienDecent(f,x0):
    numberofiter=0
    xtol=10**-4
    norm=100
    xy=x0
    listofalliter=[]
    while(norm>xtol and numberofiter<1000):
        numberofiter=numberofiter+1
        step=hw10GDstep(f,xy)
        xy=step[0]
        fval=step[1]
        templist=[xy,fval,numberofiter]
        listofalliter.append(templist)
        grad=nd.Gradient(Function)([xy[0],xy[1]])
        norm=np.linalg.norm(grad)
    return (listofalliter)

f=lambda x,y:np.cos(x)+np.sin(y)+(1/5)*x**2+(1/4)*y**2
xlist=np.linspace(-10,10,1000)
ylist=np.linspace(-10,10,1000)
X,Y=np.meshgrid(xlist,ylist)
Z=f(X,Y)
plt.contourf(X,Y,Z,cmap ="bone")
x0_1=[7,7]
x0_2=[-7,-7]
x0_3=[0,-7]

x1=GradienDecent(f,x0_1)
x0_1listofx=[]
x0_1listofy=[]
for i in range(0,len(x1)):
    x0_1listofx.append(x1[i][0][0])
    x0_1listofy.append(x1[i][0][1])
x1iter=x1[len(x1)-1][2]
x1xmin=x1[len(x1)-1][0][0]
x1ymin=x1[len(x1)-1][0][1]
x1zmin=x1[len(x1)-1][1]
xyz1=[x1xmin,x1ymin,x1zmin]

x2=GradienDecent(f,x0_2)
x0_2listofx=[]
x0_2listofy=[]
for i in range(0,len(x2)):
    x0_2listofx.append(x2[i][0][0])
    x0_2listofy.append(x2[i][0][1])
x2iter=x2[len(x2)-1][2]
x2xmin=x2[len(x2)-1][0][0]
x2ymin=x2[len(x2)-1][0][1]
x2zmin=x2[len(x2)-1][1]
xyz2=[x2xmin,x2ymin,x2zmin]

x3=GradienDecent(f,x0_3)
x0_3listofx=[]
x0_3listofy=[]
for i in range(0,len(x3)):
    x0_3listofx.append(x3[i][0][0])
    x0_3listofy.append(x3[i][0][1])
x3iter=x3[len(x3)-1][2]
x3xmin=x3[len(x3)-1][0][0]
x3ymin=x3[len(x3)-1][0][1]
x3zmin=x3[len(x3)-1][1]
xyz3=[x3xmin,x3ymin,x3zmin]

print("For Start Point Of [7,7] Made: "+str(x1iter)+" "+"Iterations, The Minimum Is [X,Y,Z]: "+str(xyz1))
print("For Start Point Of [-7,-7] Made: "+str(x2iter)+" "+"Iterations, The Minimum Is [X,Y,Z]: "+str(xyz2))
print("For Start Point Of [0,-7] Made: "+str(x3iter)+" "+"Iterations, The Minimum Is [X,Y,Z]: "+str(xyz3))
print("The End.")
plt.plot_date(x0_1listofx,x0_1listofy,color='green',markersize=2,label="For Start Point Of [7,7]")
plt.plot_date(x0_2listofx,x0_2listofy,color='blue',markersize=2,label="For Start Point Of [-7,-7]")
plt.plot_date(x0_3listofx,x0_3listofy,color='red',markersize=2,label="For Start Point Of [0,-7]")
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Gradient Descent For F(x,y):")
plt.colorbar()
plt.legend()
plt.show()

A: The plt.plot_date method is for plotting dates. Since your data is numerical, you can change plt.plot_date to plt.plot.
EDIT: to avoid connecting all of the data points together, pass marker='.' and linestyle='None' to the plt.plot method.
import numpy as np
import numdifftools as nd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
def Function(x):
    return np.cos(x[0])+np.sin(x[1])+(1/5)*x[0]**2+(1/4)*x[1]**2

def hw10GDstep(f,x0):
    xold=x0[0]
    yold=x0[1]
    grad=nd.Gradient(Function)([xold,yold])
    Xnew=xold-0.2*grad[0]
    Ynew=yold-0.2*grad[1]
    X,Y=np.meshgrid(Xnew,Ynew)
    fval=f(X,Y)
    fval=list(fval)
    return ([Xnew,Ynew],fval[0][0])

def GradienDecent(f,x0):
    numberofiter=0
    xtol=10**-4
    norm=100
    xy=x0
    listofalliter=[]
    while(norm>xtol and numberofiter<1000):
        numberofiter=numberofiter+1
        step=hw10GDstep(f,xy)
        xy=step[0]
        fval=step[1]
        templist=[xy,fval,numberofiter]
        listofalliter.append(templist)
        grad=nd.Gradient(Function)([xy[0],xy[1]])
        norm=np.linalg.norm(grad)
    return (listofalliter)

f=lambda x,y:np.cos(x)+np.sin(y)+(1/5)*x**2+(1/4)*y**2
xlist=np.linspace(-10,10,1000)
ylist=np.linspace(-10,10,1000)
X,Y=np.meshgrid(xlist,ylist)
Z=f(X,Y)
plt.contourf(X,Y,Z,cmap ="bone")
x0_1=[7,7]
x0_2=[-7,-7]
x0_3=[0,-7]

x1=GradienDecent(f,x0_1)
x0_1listofx=[]
x0_1listofy=[]
for i in range(0,len(x1)):
    x0_1listofx.append(x1[i][0][0])
    x0_1listofy.append(x1[i][0][1])
x1iter=x1[len(x1)-1][2]
x1xmin=x1[len(x1)-1][0][0]
x1ymin=x1[len(x1)-1][0][1]
x1zmin=x1[len(x1)-1][1]
xyz1=[x1xmin,x1ymin,x1zmin]

x2=GradienDecent(f,x0_2)
x0_2listofx=[]
x0_2listofy=[]
for i in range(0,len(x2)):
    x0_2listofx.append(x2[i][0][0])
    x0_2listofy.append(x2[i][0][1])
x2iter=x2[len(x2)-1][2]
x2xmin=x2[len(x2)-1][0][0]
x2ymin=x2[len(x2)-1][0][1]
x2zmin=x2[len(x2)-1][1]
xyz2=[x2xmin,x2ymin,x2zmin]

x3=GradienDecent(f,x0_3)
x0_3listofx=[]
x0_3listofy=[]
for i in range(0,len(x3)):
    x0_3listofx.append(x3[i][0][0])
    x0_3listofy.append(x3[i][0][1])
x3iter=x3[len(x3)-1][2]
x3xmin=x3[len(x3)-1][0][0]
x3ymin=x3[len(x3)-1][0][1]
x3zmin=x3[len(x3)-1][1]
xyz3=[x3xmin,x3ymin,x3zmin]

print("For Start Point Of [7,7] Made: "+str(x1iter)+" "+"Iterations, The Minimum Is [X,Y,Z]: "+str(xyz1))
print("For Start Point Of [-7,-7] Made: "+str(x2iter)+" "+"Iterations, The Minimum Is [X,Y,Z]: "+str(xyz2))
print("For Start Point Of [0,-7] Made: "+str(x3iter)+" "+"Iterations, The Minimum Is [X,Y,Z]: "+str(xyz3))
print("The End.")
plt.plot(x0_1listofx,x0_1listofy,color='green',marker='.',markersize=2,linestyle='None',label="For Start Point Of [7,7]")
plt.plot(x0_2listofx,x0_2listofy,color='blue',marker='.',markersize=2,linestyle='None',label="For Start Point Of [-7,-7]")
plt.plot(x0_3listofx,x0_3listofy,color='red',marker='.',markersize=2,linestyle='None',label="For Start Point Of [0,-7]")
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Gradient Descent For F(x,y):")
plt.colorbar()
plt.legend()
plt.show()


text:
Q: Knockout - readonly model binding from selected item in dropdown I'm having issues with structure of ViewModel in Knockout.
UPDATE
JS Fiddle
END UPDATE
Overview

*

*I would like to return a model from MVC action and use mappings
extension for knockout to create observable from JSON to ViewModel.

*Display items in table were only one field is editable and this
field is dropdown, but it's causing all properties of item to update
values.

*Post model back to MVC Action.

Description
I'm using mapping extension to map JSON model returned from MVC action to knockout model, my model looks like this:
public class SomeClassInput
{
    public string Help { get; set; }
    public IEnumerable<SomeClassItem> Items { get; set; }

    public class SomeClassItem
    {
        public string Code { get; set; }
        public string Location { get; set; }
        public string Easting { get; set; }
        public string Northing { get; set; }
        public string WaterName { get; set; }
        public string WfdCode { get; set; }
    }

    public SomeClassInput()
    {
        Items = new List<SomeClassItem>();
    }
}

Model returned from Action, can contains default data - few items.
I'm using custom serialize settings for JSON, so all PascalCase properties names are transformed to camelCase.
binding is quite straight forward (wrapper around some sort of controller to manage few screens, and dynamic loading of views):
this.model = ko.mapping.fromJS(modelJson);
ko.applyBindings(this.model, this.view.content[0]);

Now in View I have a table:

                [Actions]

                Code

                Location

                Name of Water

                WFD Code

                <button class="btn" data-bind="click: table.addRow">Add new Storm Water Overflow</button>

this is not working example - so labels can be spans or whatever is needed.
$parent.table | table - wraps all actions around tables, like adding a row, removing, moving up and down. this works.
Only one cell will be editable – Code. Code will be a dropdown that is initialized by some ajax code in background returning all possible codes and meta-data connected to item - this call is executed before model ko.applyBindings. Result of ajax call will be looking almost like model:
[ {
  name: 'some_name_of_code',
  code: 'GUID',
  location: 'some_place',
  easting: '435',
  northing: '345',
  waterName: 'some_name',
  wfdCode: 'some_code'

}, {
//..
}]

Whenever user select an item from Code dropdown, all the properties should be displayed and mapped to model. this.model.items[0].easting will and should return a value.
So when user will click save, I could unwrap model and post it as JSON to MVC action.
update
just in case, as all my knockouts view model are manage by controller there is a std. way of posting model back to server, fragment responsible for it:
save: function () {
    var that = this,
        model = ko.mapping.toJS(this.model);

    delete model.help;

    logger.log(this.id + ' SAVE event executing');

    return $.ajax({
        type: 'POST',
        url: this.saveUri,
        data: JSON.stringify(model),
        contentType: 'application/json; charset=utf-8',
        success: function() {
            logger.log(that.id + ' SAVE event executed and finished with success, cleaning up dirty flag');

            that.model.tracker().markCurrentStateAsClean();
        }
    });
}

end update
Question
I'm not sure how to achieve what I want without writing lots of custom functions that will set a data – from model returned by action to view model, and from what we have on the view to model that will be posted back to server.
Any help will be appreciated.
UPDATE
JS Fiddle
END UPDATE

A: Here's the working fiddle.
http://jsfiddle.net/madcapnmckay/wgRdj/
Found a couple of things. First your initial viewmodel creation wasn't using any mapping
configuration so this line.
var viewModel = ko.mapping.fromJS(jsonModel);

Created anonymous objects instead of objects of type Item. I changed this to.
var viewModel = ko.mapping.fromJS(jsonModel, {
    items: {
       create: function (options) {
           return new Item(options.data);
       }
    }
});

Secondly your incoming json has copies of every piece of data from the code object. In order to get the options binding to correctly select the value you would have to be referencing the same exact object instance since js will not be able to tell two objects apart even with identical values. There are a number of ways this could have been done but inorder to keep your existing json structure I simply changed the binding to refrence just the codeid instead of the whole object and made the other item values derive from that.
function Item(config) {
   var self = this;
   this.code = ko.observable(config.code);

   var value = ko.computed(function() {
        if (this.code()) {
            // find the code in the list
            return ko.utils.arrayFirst(viewModel.codes(),
                 function (c) {
                     return c.code == self.code();
                 });
        }
        return null;
   }, this);

   var getValue = function(name) {
       if (value()) {
           return value()[name];
       }
       return "";
   }

   this.location = ko.computed(function() {
       return getValue("location");
   }, this);

   this.easting = ko.computed(function() {
       return getValue("easting");
   }, this);

   this.northing = ko.computed(function() {
       return getValue("northing");
   }, this);

   this.waterName = ko.computed(function() {
       return getValue("waterName");
   }, this);

   this.wfdCode = ko.computed(function() {
       return getValue("wfdCode");
   }, this);
}

This has the advantage of only needing the id being passed in the json initially.
Hope this helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: onChange in form_dropdown codeigniter not work i try to submit a form without submit button with javascript but not work. My code is:
<?php echo form_dropdown('week_id',$weeklist,'onChange="submitform();"','class ="form-control selectpicker" data-style="btn-danger"'); ?>

and the js is:
<script type="text/javascript">
 function submitform() {
 document.autosubmit.submit();
 }

The name and the id of the form is autosubmit. Also i will try to put the week_id inside the function but not work too. Any suggestions? Thanks in advnace.

A: If you're going to use an ID:
document.querySelector('#autosubmit').submit();

If you just want to target the form, you need to use the name="" attribute, not the id="" attribute, something like this:
document.forms['autosubmit'].submit();


text:
Q: GAE Java Flexible env 502 bad gateway Just migrated to app engine flexible env for a java app which was running fine on standard env till now for last 3 years.
Encountered 502 bad gateway for a servlet call. Here is the short description -
http://----.appspot.com/carSearch?
Similar servlets returning same data (JSON) work fine but this does not.
 Tried using OutpoutStream / PrintWriter but none of them worked.
The only difference from other servlets is I am saving the data in session and  then returning it. Cloudflare confirmed the issue as caused by origin server.

A: I had a similar issue. It turns out that I have a root javax.servlet.Filter which blocks calls to internal AppEngine URLs. I solved it like this:
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException
{
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) resp;

    String path = request.getRequestURI();

    if(path.startsWith("/_ah/")) // bypass AppEngine internal requests
    {
        chain.doFilter(request, response);
        return;
    }

    // ...
}


text:
Q: How to setup multiple https-capable subdomains in MAMP Pro? I can set them up one-by-one with self-signed certs, but it's not practical for how many subdomains I'm working with.
Is there an easier way to do this?

A: Easiest is to use a wildcard certificate signed by a recognized authority. That also makes the certificates valid and validatable which is not the case for self signed certificates.
A wildcard certificate costs a fee for the signing service. Some 20 Euros a year currently. And you obviously have to go through a verification process, typically per telephone. The Let's Encrypt certificates are great, but they do not offer wildcard certificates. You certainly can automate the creation of their certificates by scripting, though, if you are willing to invest effort into that.
I personally used startssl in the past. Their portal is a bit difficult to use, but things work, and I failed to find anything comparable if it comes to prices. You need their "level 2" for a wildcard certificate, the free certificates are always for a single host name only. Each wildcard certificate will cost extra, obviously, but similar obviously you can use a single wildcard certificate with all host names within a given domain name which is what you are looking for I think.


text:
Q: DRF Create queryset by adding foreign key queryset into it I want to get foreign data(Child model) into Parent Model queryset.
I am able to add foreign data into Parent data but it is JSON. I want to convert that JSON into queryset because get_queryset() returns model/queryset.
I googled a lot but unable to find anything helpful.
class Parent(models.Model):
    parent_name = models.TextField()
    child = models.ForeignKey(Child, related_name="+", on_delete=models.CASCADE, null=True)

class Child(models.Model):
    child_name = models.TextField()

class ParentViewSet(viewsets.ModelViewSet):
    queryset = Parent.objects.all()
    serializer_class = ParentInfoSerializer
    filter_backends = (filters.DjangoFilterBackend,)
    filter_fields = ['parent_name']

   def get_queryset(self):
        response = []
        parent_name = self.request.GET.getlist("parent_name")[0]#
        parent_queryset =
              Parent.objects.filter(parent_name=parent_name)
        for par_queryset in parent_queryset:
            parent_result = self.serializer_class(phy_queryset).data
            child_id = physician_info_result["child"]
            child_instance = Child.objects.get(pk=child_id)
            child_result = ChildSerializer(child_instance).data
            parent_result["child"] = child_result
            response.append(parent_result)
       return response

URL -
http://localhost:9000/api/parent?parent_name=xyz

Response output is:
[{
    "parent_name": "xyz",
    "child": [{
        "id": 1
        "child_name": "abc"
    }]
}]
But above output it is JSON which I don't want. I want output into queryset/model.
NOTE: Queryset output should contain foreign queryset.

A: You could just replace the default field for child to child serializer and it'll work like you want.
class ParentSerializer(models.Model):
    child = ChildSerializer()

     class Meta:
         models = Parent
         fields = ('parent_name', 'child')

And you also don't need to override the get_queryset method.


text:
Q: When does usercontrol visible property affect its children? I have a ASP.NET userControl that contains other controls.
Sometimes, when changing the visible property of the usercontrol, it does change the visible value of its children, but sometimes it doesn't.
I thought it depended on the moment the property was changed during the page life cycle, cause it seemed to work well when changed in the Page_PreRender event, but I got a case when it didn't work.
Any idea, on how I could affect the visibility of all the controls of the user control just through the visible property of this one? I don't want to make a loop through all the children to set their visbile property.
Thanks

A: It never "affects" its children. Setting a parent to false does not change the Visible property of a child. However, when the page is rendered, if ANY parent object is set to false, none of the children will be rendered. The Visible property of a child will still show as true while going through the rendering process and debugging, but it will never render.


text:
Q: Unable to autowire RestTemplate for unit test I have a service which uses an autowired instance of RestTemplate like below
@Service
class SomeAPIService {
    private RestTemplate restTemplate;

    SomeAPIService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
        this.restTemplate.setRequestFactory(HttpUtils.getRequestFactory());
    }
}

Everything runs fine in non-test environment. But when I try to run following unit test in test profile, it starts complaining about unable to autowire rest template.
@RunWith( SpringJUnit4ClassRunner.class )
@SpringBootTest(classes = MyApplication.class, webEnvironment = RANDOM_PORT, properties = "management.port:0")
@ActiveProfiles(profiles = "test")
@EmbeddedPostgresInstance(flywaySchema = "db/migration")
public abstract class BaseTest {
}

@SpringBootTest(classes = SomeAPIService.class)
public class SomeAPIServiceTest extends BaseTest {
    @Autowired
    SomeAPIService someAPIService;

    @Test
    public void querySomeAPI() throws Exception {
        String expected = someAPIService.someMethod("someStringParam");
    }
}

Following is the detailed exception -

Caused by:
  org.springframework.beans.factory.UnsatisfiedDependencyException:
  Error creating bean with name 'someAPIService': Unsatisfied dependency
  expressed through constructor parameter 0; nested exception is
  org.springframework.beans.factory.NoSuchBeanDefinitionException: No
  qualifying bean of type 'org.springframework.web.client.RestTemplate'
  available: expected at least 1 bean which qualifies as autowire
  candidate. Dependency annotations: {}

Any clues?

A: Following helped me get the correct dependencies autowired. The solution is to also include RestTemplate.class in list of classes given to SpringBootTest.
@SpringBootTest(classes = {RestTemplate.class, SomeAPIService.class})
class SomeAPIService {
    @Autowired
    SomeAPIService someAPIService;

    @Test
    public void querySomeAPI() throws Exception {
        String expected = someAPIService.someMethod("someStringParam");
    }
}

@Emre answer was helpful in guiding me towards the final solution.

A: You are trying to autowire SomeAPIService without satisfying its dependencies. You should inject Rest Template to SomeAPIService. But you are getting NoSuchBeanDefinitionException for Rest Template.
Take a look how to inject it :
How to autowire RestTemplate using annotations

A: Alternative answer would be - to use TestRestTemplate
From official docs >>>
TestRestTemplate can be instantiated directly in your integration tests, as shown in the following example:
public class MyTest {

    private TestRestTemplate template = new TestRestTemplate();

    @Test
    public void testRequest() throws Exception {
        HttpHeaders headers = this.template.getForEntity(
                "https://myhost.example.com/example", String.class).getHeaders();
        assertThat(headers.getLocation()).hasHost("other.example.com");
    }

}

Alternatively, if you use the @SpringBootTest annotation with WebEnvironment.RANDOM_PORT or WebEnvironment.DEFINED_PORT, you can inject a fully configured TestRestTemplate and start using it. If necessary, additional customizations can be applied through the RestTemplateBuilder bean.


text:
Q: How to give blue outline to edit text android? i have an edit text view , i want its border to be of blue color , only its border or outline to be blue  not the complete edit text view .How to get blue border?Please help

A: You can use a shape drawable as a background for the edit text view. You can define it in an xml file in the res/drawable folder:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@android:color/transparent" />
    <stroke
        android:width="1dp"
        android:color="#0000ff" />
</shape>

If you want to make the background variable depending on whether the edit text view has focus, etc., you can use the above as one element of a state list drawable.


text:
Q: C# size of a linked list (source code) I'm in my second year in computer science. Our teacher asked us to implement the class MyLinkedList (even tough it exists by default in C#) to improve our programming skills (Algorithms).
I was able to implement a good part of the code and test it, but I was not able to implement the function that returns the size of the linked list.
This is what I've done to far :
class MyLinkedList
{

    class Element
    {
        public float value;
        public Element next;
    }

    Element first;

    public MyLinkedList()
    {
        first = null;
    }

    public void add(float x)
    {
        Element e = new Element();
        e.value = x;
        e.next = first;
        first = e;
    }

    public float get(int i)
    {
        if (first == null)
        {
            throw new Exception("Empty list...no elements inside");
        }
        Element tmp = first;
        for (int j = 0; j < i; ++j)
        {
            tmp = tmp.next;
            if (tmp == null)
            {
                throw new Exception("...");
            }
        }
        return tmp.value;
    }

    public int size()
    {
        // I'm completely lost on that one, I have no clue on how
        // doing it.
    }

}

class MainClass
{
    public static void Main(string[] args)
    {
        //To test the code

        MyLinkedList l = new MyLinkedList();
        l.add(3);
        l.add(5);
        l.add(8);
        Console.WriteLine(l.get(0));
        Console.WriteLine(l.get(1));
        Console.WriteLine(l.get(4));
    }
}

A: I am not at my development machine, so I haven't tried this:
public int Count()
{
     int count = 0;
     Element e = first
     while(e != null)
     {
          ++count;
          e =e.next;
     }
     return count;
}

That is the kinnd of thing you need.

A: try this code:
 public int size()
{
     Element tmp = first;
     int cnt =0;
     while(temp != null)
     {
         cnt++;
         temp = temp.next
     }
      return cnt;

}

A: Why don't you use a field to keep track of the size? You can increment it when adding elements and decrement it on removing.
class MyLinkedList
{
    int size = 0;

    public void add(float x)
    {
        size++;
        ....
    }

    public void remove(float x)
    {
        size--;
        ...
    }

    public int size()
    {
        return size;
    }

It's only an idea.. of course you have to check whether you have really added or removed the element. eg: you are trying to remove an element that is not in the list). Doing like that you can avoid to calculate the size everytime the size method is  called.


text:
Q: Extrude, or, make 2d SVG path into 3d I am wondering if anyone has heard of some javascript which can take a simple SVG path that took maybe 30 seconds to create in illustrator or something and convert it into something that looks 3d. There is an extrude function in illustrator which does this. It is also called polling in sketchUp.
I am using Raphael.js now, but am open to other suggestions. A simple solution would be to make a copy of the path and move it a couple pixels down and to the right and give it a darker color behind the original path, but I am looking for something that might have a little more shading.
Thanks!

A: There is always a possibility to use three.js for extruding the path for use in webGL in browser:
http://alteredqualia.com/three/examples/webgl_text.html#D81F0A21010#23a
(More samples here:http://stemkoski.github.io/Three.js/)
It uses js-fonts and parses the path commands on them, extrudes the paths and renders the scene. In the same way it should be possible to take an SVG path and extrude it. Raphael has Raphael.parsePathString() which gives you the path segments as an array of individual segments. If you first convert the path commands to cubic curves using Raphael.path2curve() and Raphael._pathToabsolute(), you have only only one segment type so you can use three.js:s BEZIER_CURVE_TO command. If you have transformations applied on the path (which is usually the case in Illustrator export) you can flatten them using function from here: https://stackoverflow.com/a/13102801/1691517.
One possible starting point is here (click the fiddle of the answer):
Extruding multiple polygons with multiple holes and texturing the combined shape
Three.js supports few path commands, but have not tested all of them (
http://threejsdoc.appspot.com/doc/three.js/src.source/extras/core/Path.js.html, see below).

THREE.PathActions = {

    MOVE_TO: 'moveTo',
    LINE_TO: 'lineTo',
    QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
    BEZIER_CURVE_TO: 'bezierCurveTo',       // Bezier cubic curve
    CSPLINE_THRU: 'splineThru',             // Catmull-rom spline
    ARC: 'arc'                              // Circle

};

I have used a custom rather complex function to polygonize SVG path, so was no need to rely to other commands than moveto and lineto.
The downside is of course rather low support level for webGL, 31-53%: http://caniuse.com/webgl

Other more cross-browser solution is this SVG3d library if lesser quality and slowness is not an issue:
http://debeissat.nicolas.free.fr/svg3d.php
https://code.google.com/p/svg3d/

A: I think this resource could be helpful to you, he uses d3 to generate 2D visualization and then uses d3-threeD to extrude.

A: Sounds like you want to use svg filters. Webplatform.org has a pretty good tutorial about that. Scroll down a bit and you'll find some lighting filters that looks like 3d.
Raphaël doesn't support filters though, so either you'll need to extend it, or just use svg directly.


text:
Q: Typescript const reusing property values to define new properties Is there a way I can reuse the property value defined in an const object in Typescript to define other new properties in the same object?
Something like this:
const TEST = {
  "a1": "world",
  "a2": "hello",
  "a3": this.a1
};

console.log(TEST.a3); logs undefined right now.

A: No, because TEST isn't defined yet then.
For example, if you try this:
const TEST = {
  "a1": "world",
  "a2": "hello",
  "a3": TEST["a3"]
};

You'll get:

Error: Block-scoped variable 'TEST' used before its declaration

You can do this:
const TEST = {
  "a1": "world",
  "a2": "hello"
} as { a1: string, a2: string, a3: string };

TEST.a3 = TEST.a1;

(code in playground)


text:
Q: Asking the user for input until they give a valid response I am writing a program that accepts user input.
#note: Python 2.7 users should use `raw_input`, the equivalent of 3.X's `input`
age = int(input("Please enter your age: "))
if age >= 18:
    print("You are able to vote in the United States!")
else:
    print("You are not able to vote in the United States.")

The program works as expected as long as the the user enters meaningful data.
Please enter your age: 23
You are able to vote in the United States!

But it fails if the user enters invalid data:
Please enter your age: dickety six
Traceback (most recent call last):
  File "canyouvote.py", line 1, in <module>
    age = int(input("Please enter your age: "))
ValueError: invalid literal for int() with base 10: 'dickety six'

Instead of crashing, I would like the program to ask for the input again. Like this:
Please enter your age: dickety six
Sorry, I didn't understand that.
Please enter your age: 26
You are able to vote in the United States!

How do I ask for valid input instead of crashing or accepting invalid values (e.g. -1)?

A: The simplest way to accomplish this is to put the input method in a while loop. Use continue when you get bad input, and break out of the loop when you're satisfied.
When Your Input Might Raise an Exception
Use try and except to detect when the user enters data that can't be parsed.
while True:
    try:
        # Note: Python 2.x users should use raw_input, the equivalent of 3.x's input
        age = int(input("Please enter your age: "))
    except ValueError:
        print("Sorry, I didn't understand that.")
        #better try again... Return to the start of the loop
        continue
    else:
        #age was successfully parsed!
        #we're ready to exit the loop.
        break
if age >= 18:
    print("You are able to vote in the United States!")
else:
    print("You are not able to vote in the United States.")

Implementing Your Own Validation Rules
If you want to reject values that Python can successfully parse, you can add your own validation logic.
while True:
    data = input("Please enter a loud message (must be all caps): ")
    if not data.isupper():
        print("Sorry, your response was not loud enough.")
        continue
    else:
        #we're happy with the value given.
        #we're ready to exit the loop.
        break

while True:
    data = input("Pick an answer from A to D:")
    if data.lower() not in ('a', 'b', 'c', 'd'):
        print("Not an appropriate choice.")
    else:
        break

Combining Exception Handling and Custom Validation
Both of the above techniques can be combined into one loop.
while True:
    try:
        age = int(input("Please enter your age: "))
    except ValueError:
        print("Sorry, I didn't understand that.")
        continue

    if age < 0:
        print("Sorry, your response must not be negative.")
        continue
    else:
        #age was successfully parsed, and we're happy with its value.
        #we're ready to exit the loop.
        break
if age >= 18:
    print("You are able to vote in the United States!")
else:
    print("You are not able to vote in the United States.")

Encapsulating it All in a Function
If you need to ask your user for a lot of different values, it might be useful to put this code in a function, so you don't have to retype it every time.
def get_non_negative_int(prompt):
    while True:
        try:
            value = int(input(prompt))
        except ValueError:
            print("Sorry, I didn't understand that.")
            continue

        if value < 0:
            print("Sorry, your response must not be negative.")
            continue
        else:
            break
    return value

age = get_non_negative_int("Please enter your age: ")
kids = get_non_negative_int("Please enter the number of children you have: ")
salary = get_non_negative_int("Please enter your yearly earnings, in dollars: ")

Putting It All Together
You can extend this idea to make a very generic input function:
def sanitised_input(prompt, type_=None, min_=None, max_=None, range_=None):
    if min_ is not None and max_ is not None and max_ < min_:
        raise ValueError("min_ must be less than or equal to max_.")
    while True:
        ui = input(prompt)
        if type_ is not None:
            try:
                ui = type_(ui)
            except ValueError:
                print("Input type must be {0}.".format(type_.__name__))
                continue
        if max_ is not None and ui > max_:
            print("Input must be less than or equal to {0}.".format(max_))
        elif min_ is not None and ui < min_:
            print("Input must be greater than or equal to {0}.".format(min_))
        elif range_ is not None and ui not in range_:
            if isinstance(range_, range):
                template = "Input must be between {0.start} and {0.stop}."
                print(template.format(range_))
            else:
                template = "Input must be {0}."
                if len(range_) == 1:
                    print(template.format(*range_))
                else:
                    expected = " or ".join((
                        ", ".join(str(x) for x in range_[:-1]),
                        str(range_[-1])
                    ))
                    print(template.format(expected))
        else:
            return ui

With usage such as:
age = sanitised_input("Enter your age: ", int, 1, 101)
answer = sanitised_input("Enter your answer: ", str.lower, range_=('a', 'b', 'c', 'd'))

Common Pitfalls, and Why you Should Avoid Them
The Redundant Use of Redundant input Statements
This method works but is generally considered poor style:
data = input("Please enter a loud message (must be all caps): ")
while not data.isupper():
    print("Sorry, your response was not loud enough.")
    data = input("Please enter a loud message (must be all caps): ")

It might look attractive initially because it's shorter than the while True method, but it violates the Don't Repeat Yourself principle of software development. This increases the likelihood of bugs in your system. What if you want to backport to 2.7 by changing input to raw_input, but accidentally change only the first input above? It's a SyntaxError just waiting to happen.
Recursion Will Blow Your Stack
If you've just learned about recursion, you might be tempted to use it in get_non_negative_int so you can dispose of the while loop.
def get_non_negative_int(prompt):
    try:
        value = int(input(prompt))
    except ValueError:
        print("Sorry, I didn't understand that.")
        return get_non_negative_int(prompt)

    if value < 0:
        print("Sorry, your response must not be negative.")
        return get_non_negative_int(prompt)
    else:
        return value

This appears to work fine most of the time, but if the user enters invalid data enough times, the script will terminate with a RuntimeError: maximum recursion depth exceeded. You may think "no fool would make 1000 mistakes in a row", but you're underestimating the ingenuity of fools!

A: Why would you do a while True and then break out of this loop while you can also just put your requirements in the while statement since all you want is to stop once you have the age?
age = None
while age is None:
    input_value = input("Please enter your age: ")
    try:
        # try and convert the string input to a number
        age = int(input_value)
    except ValueError:
        # tell the user off
        print("{input} is not a number, please enter a number only".format(input=input_value))
if age >= 18:
    print("You are able to vote in the United States!")
else:
    print("You are not able to vote in the United States.")

This would result in the following:
Please enter your age: *potato*
potato is not a number, please enter a number only
Please enter your age: *5*
You are not able to vote in the United States.

this will work since age will never have a value that will not make sense and the code follows the logic of your "business process"

A: Use try-except to handle the error and repeat it again:
while True:
    try:
        age = int(input("Please enter your age: "))
        if age >= 18:
            print("You are able to vote in the United States!")
        else:
            print("You are not able to vote in the United States.")
    except Exception as e:
        print("please enter number")

A: Building upon Daniel Q's and Patrick Artner's excellent suggestions,
here is an even more generalized solution.
# Assuming Python3
import sys

class ValidationError(ValueError):  # thanks Patrick Artner
    pass

def validate_input(prompt, cast=str, cond=(lambda x: True), onerror=None):
    if onerror==None: onerror = {}
    while True:
        try:
            data = cast(input(prompt))
            if not cond(data): raise ValidationError
            return data
        except tuple(onerror.keys()) as e:  # thanks Daniel Q
            print(onerror[type(e)], file=sys.stderr)

I opted for explicit if and raise statements instead of an assert,
because assertion checking may be turned off,
whereas validation should always be on to provide robustness.
This may be used to get different kinds of input,
with different validation conditions.
For example:
# No validation, equivalent to simple input:
anystr = validate_input("Enter any string: ")

# Get a string containing only letters:
letters = validate_input("Enter letters: ",
    cond=str.isalpha,
    onerror={ValidationError: "Only letters, please!"})

# Get a float in [0, 100]:
percentage = validate_input("Percentage? ",
    cast=float, cond=lambda x: 0.0<=x<=100.0,
    onerror={ValidationError: "Must be between 0 and 100!",
             ValueError: "Not a number!"})

Or, to answer the original question:
age = validate_input("Please enter your age: ",
        cast=int, cond=lambda a:0<=a<150,
        onerror={ValidationError: "Enter a plausible age, please!",
                 ValueError: "Enter an integer, please!"})
if age >= 18:
    print("You are able to vote in the United States!")
else:
    print("You are not able to vote in the United States.")

A: def validate_age(age):
    if age >=0 :
        return True
    return False

while True:
    try:
        age = int(raw_input("Please enter your age:"))
        if validate_age(age): break
    except ValueError:
        print "Error: Invalid age."

A: Functional approach or "look mum no loops!":
from itertools import chain, repeat

prompts = chain(["Enter a number: "], repeat("Not a number! Try again: "))
replies = map(input, prompts)
valid_response = next(filter(str.isdigit, replies))
print(valid_response)

Enter a number:  a
Not a number! Try again:  b
Not a number! Try again:  1
1

or if you want to have a "bad input" message separated from an input prompt as in other answers:
prompt_msg = "Enter a number: "
bad_input_msg = "Sorry, I didn't understand that."
prompts = chain([prompt_msg], repeat('\n'.join([bad_input_msg, prompt_msg])))
replies = map(input, prompts)
valid_response = next(filter(str.isdigit, replies))
print(valid_response)

Enter a number:  a
Sorry, I didn't understand that.
Enter a number:  b
Sorry, I didn't understand that.
Enter a number:  1
1

How does it work?

*

*
prompts = chain(["Enter a number: "], repeat("Not a number! Try again: "))

This combination of itertools.chain and itertools.repeat will create an iterator
which will yield strings "Enter a number: " once, and "Not a number! Try again: " an infinite number of times:
for prompt in prompts:
    print(prompt)

Enter a number:
Not a number! Try again:
Not a number! Try again:
Not a number! Try again:
# ... and so on

*replies = map(input, prompts) - here map will apply all the prompts strings from the previous step to the input function. E.g.:
for reply in replies:
    print(reply)

Enter a number:  a
a
Not a number! Try again:  1
1
Not a number! Try again:  it doesn't care now
it doesn't care now
# and so on...

*We use filter and str.isdigit to filter out those strings that contain only digits:
only_digits = filter(str.isdigit, replies)
for reply in only_digits:
    print(reply)

Enter a number:  a
Not a number! Try again:  1
1
Not a number! Try again:  2
2
Not a number! Try again:  b
Not a number! Try again: # and so on...

And to get only the first digits-only string we use next.

Other validation rules:

*

*String methods: Of course you can use other string methods like str.isalpha to get only alphabetic strings, or str.isupper to get only uppercase. See docs for the full list.

*Membership testing:
There are several different ways to perform it. One of them is by using __contains__ method:
from itertools import chain, repeat

fruits = {'apple', 'orange', 'peach'}
prompts = chain(["Enter a fruit: "], repeat("I don't know this one! Try again: "))
replies = map(input, prompts)
valid_response = next(filter(fruits.__contains__, replies))
print(valid_response)

Enter a fruit:  1
I don't know this one! Try again:  foo
I don't know this one! Try again:  apple
apple

*Numbers comparison:
There are useful comparison methods which we can use here. For example, for __lt__ (<):
from itertools import chain, repeat

prompts = chain(["Enter a positive number:"], repeat("I need a positive number! Try again:"))
replies = map(input, prompts)
numeric_strings = filter(str.isnumeric, replies)
numbers = map(float, numeric_strings)
is_positive = (0.).__lt__
valid_response = next(filter(is_positive, numbers))
print(valid_response)

Enter a positive number: a
I need a positive number! Try again: -5
I need a positive number! Try again: 0
I need a positive number! Try again: 5
5.0

Or, if you don't like using dunder methods (dunder = double-underscore), you can always define your own function, or use the ones from the operator module.

*Path existance:
Here one can use pathlib library and its Path.exists method:
from itertools import chain, repeat
from pathlib import Path

prompts = chain(["Enter a path: "], repeat("This path doesn't exist! Try again: "))
replies = map(input, prompts)
paths = map(Path, replies)
valid_response = next(filter(Path.exists, paths))
print(valid_response)

Enter a path:  a b c
This path doesn't exist! Try again:  1
This path doesn't exist! Try again:  existing_file.txt
existing_file.txt

Limiting number of tries:
If you don't want to torture a user by asking him something an infinite number of times, you can specify a limit in a call of itertools.repeat. This can be combined with providing a default value to the next function:
from itertools import chain, repeat

prompts = chain(["Enter a number:"], repeat("Not a number! Try again:", 2))
replies = map(input, prompts)
valid_response = next(filter(str.isdigit, replies), None)
print("You've failed miserably!" if valid_response is None else 'Well done!')

Enter a number: a
Not a number! Try again: b
Not a number! Try again: c
You've failed miserably!

Preprocessing input data:
Sometimes we don't want to reject an input if the user accidentally supplied it IN CAPS or with a space in the beginning or an end of the string. To take these simple mistakes into account we can preprocess the input data by applying str.lower and str.strip methods. For example, for the case of membership testing the code will look like this:
from itertools import chain, repeat

fruits = {'apple', 'orange', 'peach'}
prompts = chain(["Enter a fruit: "], repeat("I don't know this one! Try again: "))
replies = map(input, prompts)
lowercased_replies = map(str.lower, replies)
stripped_replies = map(str.strip, lowercased_replies)
valid_response = next(filter(fruits.__contains__, stripped_replies))
print(valid_response)

Enter a fruit:  duck
I don't know this one! Try again:     Orange
orange

In the case when you have many functions to use for preprocessing, it might be easier to use a function performing a function composition. For example, using the one from here:
from itertools import chain, repeat

from lz.functional import compose

fruits = {'apple', 'orange', 'peach'}
prompts = chain(["Enter a fruit: "], repeat("I don't know this one! Try again: "))
replies = map(input, prompts)
process = compose(str.strip, str.lower)  # you can add more functions here
processed_replies = map(process, replies)
valid_response = next(filter(fruits.__contains__, processed_replies))
print(valid_response)

Enter a fruit:  potato
I don't know this one! Try again:   PEACH
peach

Combining validation rules:
For a simple case, for example, when the program asks for age between 1 and 120, one can just add another filter:
from itertools import chain, repeat

prompt_msg = "Enter your age (1-120): "
bad_input_msg = "Wrong input."
prompts = chain([prompt_msg], repeat('\n'.join([bad_input_msg, prompt_msg])))
replies = map(input, prompts)
numeric_replies = filter(str.isdigit, replies)
ages = map(int, numeric_replies)
positive_ages = filter((0).__lt__, ages)
not_too_big_ages = filter((120).__ge__, positive_ages)
valid_response = next(not_too_big_ages)
print(valid_response)

But in the case when there are many rules, it's better to implement a function performing a logical conjunction. In the following example I will use a ready one from here:
from functools import partial
from itertools import chain, repeat

from lz.logical import conjoin

def is_one_letter(string: str) -> bool:
    return len(string) == 1

rules = [str.isalpha, str.isupper, is_one_letter, 'C'.__le__, 'P'.__ge__]

prompt_msg = "Enter a letter (C-P): "
bad_input_msg = "Wrong input."
prompts = chain([prompt_msg], repeat('\n'.join([bad_input_msg, prompt_msg])))
replies = map(input, prompts)
valid_response = next(filter(conjoin(*rules), replies))
print(valid_response)

Enter a letter (C-P):  5
Wrong input.
Enter a letter (C-P):  f
Wrong input.
Enter a letter (C-P):  CDE
Wrong input.
Enter a letter (C-P):  Q
Wrong input.
Enter a letter (C-P):  N
N

Unfortunately, if someone needs a custom message for each failed case, then, I'm afraid, there is no pretty functional way. Or, at least, I couldn't find one.

A: Good question! You can try the following code for this. =)
This code uses ast.literal_eval() to find the data type of the input (age). Then it follows the following algorithm:

*

*Ask user to input her/his age.
1.1. If age is float or int data type:

*

*Check if age>=18. If age>=18, print appropriate output and exit.

*Check if 0<age<18. If 0<age<18, print appropriate output and exit.

*If age<=0, ask the user to input a valid number for age again, (i.e. go back to step 1.)
1.2. If age is not float or int data type, then ask user to input her/his age again (i.e. go back to step 1.)

Here is the code.
from ast import literal_eval

''' This function is used to identify the data type of input data.'''
def input_type(input_data):
    try:
        return type(literal_eval(input_data))
    except (ValueError, SyntaxError):
        return str

flag = True

while(flag):
    age = raw_input("Please enter your age: ")

    if input_type(age)==float or input_type(age)==int:
        if eval(age)>=18:
            print("You are able to vote in the United States!")
            flag = False
        elif eval(age)>0 and eval(age)<18:
            print("You are not able to vote in the United States.")
            flag = False
        else: print("Please enter a valid number as your age.")

    else: print("Sorry, I didn't understand that.")

A: Though the accepted answer is amazing. I would also like to share a quick hack for this problem. (This takes care of the negative age problem as well.)
f=lambda age: (age.isdigit() and ((int(age)>=18  and "Can vote" ) or "Cannot vote")) or \
f(input("invalid input. Try again\nPlease enter your age: "))
print(f(input("Please enter your age: ")))

P.S. This code is for python 3.x.

A: Using Click:
Click is a library for command-line interfaces and it provides functionality for asking a valid response from a user.
Simple example:
import click

number = click.prompt('Please enter a number', type=float)
print(number)

Please enter a number:
 a
Error: a is not a valid floating point value
Please enter a number:
 10
10.0

Note how it converted the string value to a float automatically.
Checking if a value is within a range:
There are different custom types provided. To get a number in a specific range we can use IntRange:
age = click.prompt("What's your age?", type=click.IntRange(1, 120))
print(age)

What's your age?:
 a
Error: a is not a valid integer
What's your age?:
 0
Error: 0 is not in the valid range of 1 to 120.
What's your age?:
 5
5

We can also specify just one of the limits, min or max:
age = click.prompt("What's your age?", type=click.IntRange(min=14))
print(age)

What's your age?:
 0
Error: 0 is smaller than the minimum valid value 14.
What's your age?:
 18
18

Membership testing:
Using click.Choice type. By default this check is case-sensitive.
choices = {'apple', 'orange', 'peach'}
choice = click.prompt('Provide a fruit', type=click.Choice(choices, case_sensitive=False))
print(choice)

Provide a fruit (apple, peach, orange):
 banana
Error: invalid choice: banana. (choose from apple, peach, orange)
Provide a fruit (apple, peach, orange):
 OrAnGe
orange

Working with paths and files:
Using a click.Path type we can check for existing paths and also resolve them:
path = click.prompt('Provide path', type=click.Path(exists=True, resolve_path=True))
print(path)

Provide path:
 nonexistent
Error: Path "nonexistent" does not exist.
Provide path:
 existing_folder
'/path/to/existing_folder

Reading and writing files can be done by click.File:
file = click.prompt('In which file to write data?', type=click.File('w'))
with file.open():
    file.write('Hello!')
# More info about `lazy=True` at:
# https://click.palletsprojects.com/en/7.x/arguments/#file-opening-safety
file = click.prompt('Which file you wanna read?', type=click.File(lazy=True))
with file.open():
    print(file.read())

In which file to write data?:
         # <-- provided an empty string, which is an illegal name for a file
In which file to write data?:
 some_file.txt
Which file you wanna read?:
 nonexistent.txt
Error: Could not open file: nonexistent.txt: No such file or directory
Which file you wanna read?:
 some_file.txt
Hello!

Other examples:
Password confirmation:
password = click.prompt('Enter password', hide_input=True, confirmation_prompt=True)
print(password)

Enter password:
 ······
Repeat for confirmation:
 ·
Error: the two entered values do not match
Enter password:
 ······
Repeat for confirmation:
 ······
qwerty

Default values:
In this case, simply pressing Enter (or whatever key you use) without entering a value, will give you a default one:
number = click.prompt('Please enter a number', type=int, default=42)
print(number)

Please enter a number [42]:
 a
Error: a is not a valid integer
Please enter a number [42]:

42

A: Try this one:-
def takeInput(required):
  print 'ooo or OOO to exit'
  ans = raw_input('Enter: ')

  if not ans:
      print "You entered nothing...!"
      return takeInput(required)

      ##  FOR Exit  ##
  elif ans in ['ooo', 'OOO']:
    print "Closing instance."
    exit()

  else:
    if ans.isdigit():
      current = 'int'
    elif set('[~!@#$%^&*()_+{}":/\']+$').intersection(ans):
      current = 'other'
    elif isinstance(ans,basestring):
      current = 'str'
    else:
      current = 'none'

  if required == current :
    return ans
  else:
    return takeInput(required)

## pass the value in which type you want [str/int/special character(as other )]
print "input: ", takeInput('str')

A: Use "while" statement till user enter a true value and if the input value is not a number or it's a null value skip it and try to ask again and so on.
In example I tried to answer truly your question. If we suppose that our age is between 1 and 150 then input value accepted, else it's a wrong value.
For terminating program, the user can use 0 key and enter it as a value.

Note: Read comments top of code.

# If your input value is only a number then use "Value.isdigit() == False".
# If you need an input that is a text, you should remove "Value.isdigit() == False".
def Input(Message):
    Value = None
    while Value == None or Value.isdigit() == False:
        try:
            Value = str(input(Message)).strip()
        except Exception:
            Value = None
    return Value

# Example:
age = 0
# If we suppose that our age is between 1 and 150 then input value accepted,
# else it's a wrong value.
while age <=0 or age >150:
    age = int(Input("Please enter your age: "))
    # For terminating program, the user can use 0 key and enter it as an a value.
    if age == 0:
        print("Terminating ...")
        exit(0)

if age >= 18 and age <=150:
    print("You are able to vote in the United States!")
else:
    print("You are not able to vote in the United States.")

A: I am a big fan of Unix philosophy "Do one thing and do it well". Capturing user input and validating it are two separate steps:

*

*prompting the user for input with get_input until the input is ok

*validating using a validator function that can be passed to get_input
It can be kept as simple as (Python 3.8+, with  the walrus operator):
def get_input(
    prompt="Enter a value: ",
    validator=lambda x: True,
    error_message="Invalid input. Please try again.",
):
    while not validator(value := input(prompt)):
        print(error_message)
    return value

def is_positive_int(value):
    try:
        return int(value) >= 0
    except ValueError:
        return False

if __name__ == "__main__":
    val = get_input("Give a positive number: ", is_positive_int)
    print(f"OK, thanks for {val}")

Sample run:
Give a positive number: -5
Invalid input. Please try again.
Give a positive number: asdf
Invalid input. Please try again.
Give a positive number:
Invalid input. Please try again.
Give a positive number: 42
OK, thanks for 42

In Python < 3.8 you could use get_input like this:
def get_input(
    prompt="Enter a value: ",
    validator=lambda x: True,
    error_message="Invalid input. Please try again.",
):
    while True:
        value = input(prompt)
        if validator(value):
            return value
        print(error_message)

You might also handle KeyboardInterrupt and print a friendly exit message before terminating the application. A counter can be used to limit the allowed retries if desired.

A: So, I was messing around with something similar to this recently, and I came up with the following solution, which uses a way of getting input that rejects junk, before it's even checked in any logical way.
read_single_keypress() courtesy https://stackoverflow.com/a/6599441/4532996
def read_single_keypress() -> str:
    """Waits for a single keypress on stdin.
    -- from :: https://stackoverflow.com/a/6599441/4532996
    """

    import termios, fcntl, sys, os
    fd = sys.stdin.fileno()
    # save old state
    flags_save = fcntl.fcntl(fd, fcntl.F_GETFL)
    attrs_save = termios.tcgetattr(fd)
    # make raw - the way to do this comes from the termios(3) man page.
    attrs = list(attrs_save) # copy the stored version to update
    # iflag
    attrs[0] &= ~(termios.IGNBRK | termios.BRKINT | termios.PARMRK
                  | termios.ISTRIP | termios.INLCR | termios. IGNCR
                  | termios.ICRNL | termios.IXON )
    # oflag
    attrs[1] &= ~termios.OPOST
    # cflag
    attrs[2] &= ~(termios.CSIZE | termios. PARENB)
    attrs[2] |= termios.CS8
    # lflag
    attrs[3] &= ~(termios.ECHONL | termios.ECHO | termios.ICANON
                  | termios.ISIG | termios.IEXTEN)
    termios.tcsetattr(fd, termios.TCSANOW, attrs)
    # turn off non-blocking
    fcntl.fcntl(fd, fcntl.F_SETFL, flags_save & ~os.O_NONBLOCK)
    # read a single keystroke
    try:
        ret = sys.stdin.read(1) # returns a single character
    except KeyboardInterrupt:
        ret = 0
    finally:
        # restore old state
        termios.tcsetattr(fd, termios.TCSAFLUSH, attrs_save)
        fcntl.fcntl(fd, fcntl.F_SETFL, flags_save)
    return ret

def until_not_multi(chars) -> str:
    """read stdin until !(chars)"""
    import sys
    chars = list(chars)
    y = ""
    sys.stdout.flush()
    while True:
        i = read_single_keypress()
        _ = sys.stdout.write(i)
        sys.stdout.flush()
        if i not in chars:
            break
        y += i
    return y

def _can_you_vote() -> str:
    """a practical example:
    test if a user can vote based purely on keypresses"""
    print("can you vote? age : ", end="")
    x = int("0" + until_not_multi("0123456789"))
    if not x:
        print("\nsorry, age can only consist of digits.")
        return
    print("your age is", x, "\nYou can vote!" if x >= 18 else "Sorry! you can't vote")

_can_you_vote()

You can find the complete module here.
Example:
$ ./input_constrain.py
can you vote? age : a
sorry, age can only consist of digits.
$ ./input_constrain.py
can you vote? age : 23<RETURN>
your age is 23
You can vote!
$ _

Note that the nature of this implementation is it closes stdin as soon as something that isn't a digit is read. I didn't hit enter after a, but I needed to after the numbers.
You could merge this with the thismany() function in the same module to only allow, say, three digits.

A: You can always apply simple if-else logic and add one more if logic to your code along with a for loop.
while True:
     age = int(input("Please enter your age: "))
     if (age >= 18)  :
         print("You are able to vote in the United States!")
     if (age < 18) & (age > 0):
         print("You are not able to vote in the United States.")
     else:
         print("Wrong characters, the input must be numeric")
         continue

This will be an infinite loo and you would be asked to enter the age, indefinitely.

A: Below code may help.
age=(lambda i,f: f(i,f))(input("Please enter your age: "),lambda i,f: i if i.isdigit() else f(input("Please enter your age: "),f))
print("You are able to vote in the united states" if int(age)>=18 else "You are not able to vote in the united states",end='')

If you want to have maximum tries, say 3, use below code
age=(lambda i,n,f: f(i,n,f))(input("Please enter your age: "),1,lambda i,n,f: i if i.isdigit() else (None if n==3 else f(input("Please enter your age: "),n+1,f)))
print("You are able to vote in the united states" if age and int(age)>=18 else "You are not able to vote in the united states",end='')

Note: This uses recursion.

A: Use isdigit() to check if a string represents a valid integer.
You could use a recursive function.
def ask():
    answer = input("Please enter amount to convert: ")
    if not answer.isdigit():
        print("Invalid")
        return ask()

    return int(answer)

Gdp = ask()

Or a while loop
while True:
    answer = input("Please enter amount to convert: ")
    if not answer.isdigit():
        print("Invalid")
        continue

    Gbp = int(answer)

A: While a try/except block will work, a much faster and cleaner way to accomplish this task would be to use str.isdigit().
while True:
    age = input("Please enter your age: ")
    if age.isdigit():
        age = int(age)
        break
    else:
        print("Invalid number '{age}'. Try again.".format(age=age))

if age >= 18:
    print("You are able to vote in the United States!")
else:
    print("You are not able to vote in the United States.")

A: You can write more general logic to allow user to enter only specific number of times, as the same use-case arises in many real-world applications.
def getValidInt(iMaxAttemps = None):
  iCount = 0
  while True:
    # exit when maximum attempt limit has expired
    if iCount != None and iCount > iMaxAttemps:
       return 0     # return as default value

    i = raw_input("Enter no")
    try:
       i = int(i)
    except ValueError as e:
       print "Enter valid int value"
    else:
       break

    return i

age = getValidInt()
# do whatever you want to do.

A: You can make the input statement a while True loop so it repeatedly asks for the users input and then break that loop if the user enters the response you would like. And you can use try and except blocks to handle invalid responses.
while True:

    var = True

    try:
        age = int(input("Please enter your age: "))

    except ValueError:
        print("Invalid input.")
        var = False

    if var == True:
        if age >= 18:
                print("You are able to vote in the United States.")
                break
        else:
            print("You are not able to vote in the United States.")

The var variable is just so that if the user enters a string instead of a integer the program wont return "You are not able to vote in the United States."

A: One more solution for using input validation using a customized ValidationError and a (optional) range validation for integer inputs:
class ValidationError(ValueError):
    """Special validation error - its message is supposed to be printed"""
    pass

def RangeValidator(text,num,r):
    """Generic validator - raises 'text' as ValidationError if 'num' not in range 'r'."""
    if num in r:
        return num
    raise ValidationError(text)

def ValidCol(c):
    """Specialized column validator providing text and range."""
    return RangeValidator("Columns must be in the range of 0 to 3 (inclusive)",
                          c, range(4))

def ValidRow(r):
    """Specialized row validator providing text and range."""
    return RangeValidator("Rows must be in the range of 5 to 15(exclusive)",
                          r, range(5,15))

Usage:
def GetInt(text, validator=None):
    """Aks user for integer input until a valid integer is given. If provided,
    a 'validator' function takes the integer and either raises a
    ValidationError to be printed or returns the valid number.
    Non integers display a simple error message."""
    print()
    while True:
        n = input(text)
        try:
            n = int(n)

            return n if validator is None else validator(n)

        except ValueError as ve:
            # prints ValidationErrors directly - else generic message:
            if isinstance(ve, ValidationError):
                print(ve)
            else:
                print("Invalid input: ", n)

column = GetInt("Pleased enter column: ", ValidCol)
row = GetInt("Pleased enter row: ", ValidRow)
print( row, column)

Output:
Pleased enter column: 22
Columns must be in the range of 0 to 3 (inclusive)
Pleased enter column: -2
Columns must be in the range of 0 to 3 (inclusive)
Pleased enter column: 2
Pleased enter row: a
Invalid input:  a
Pleased enter row: 72
Rows must be in the range of 5 to 15(exclusive)
Pleased enter row: 9

9, 2

A: Persistent user input using recursive function:
String
def askName():
    return input("Write your name: ").strip() or askName()

name = askName()

Integer
def askAge():
    try: return int(input("Enter your age: "))
    except ValueError: return askAge()

age = askAge()

and finally, the question requirement:
def askAge():
    try: return int(input("Enter your age: "))
    except ValueError: return askAge()

age = askAge()

responseAge = [
    "You are able to vote in the United States!",
    "You are not able to vote in the United States.",
][int(age < 18)]

print(responseAge)

A: You can try to convert it to a integer, but ask the user to repeat if it doesn't work.
while True:
    age = input('Please enter your age: ')
    try:
        age_int = int(age)
        if age_int >= 18:
            print('You can vote in the United States!')
        else:
            print('You cannot vote in the United States.')
        break
    except:
        print('Please enter a meaningful answer.')

The while loop runs as long as the user has not inputted a meaningful answer, but breaks if it makes sense.


text:
Q: Apply background color for all page, including navigation bar in Shiny On the code bellow I tried to stablish a background color in all my Shiny UI page but I couldnt do this for the Navigation Bar:
library(shiny)
ui <- fluidPage(

    setBackgroundColor(
        color = c("#F7FBFF", "#2171B5"),
        gradient = "linear",
        direction = c("bottom","left")
    ),

titlePanel("Titulo"),

navbarPage(

title = h1('Métodos'),
    tabPanel(h1('Painel Geral')),
                 tabPanel(h1('Painel Geral')),
                          tabPanel(h1('Painel Geral')),
                                   tabPanel(h1('Painel Geral'))))

server <- function(input, output) {

}

shinyApp(ui = ui, server = server)

As you can see the navbar still gray. How can I change for the entire page?
Also how can I change it using the .css file?
I tried all the divs but didnt work.
Any help?
Many thanks

A: Use this CSS:
library(shinyWidgets)
library(shiny)

css <- "
.navbar-default {
  background-color: inherit;
  border: none;
}
"

ui <- fluidPage(
  tags$head(tags$style(css)),
  setBackgroundColor(
    color = c("#F7FBFF", "#2171B5"),
    gradient = "linear",
    direction = c("bottom","left")
  ),
  ......

If you don't want to use shinyWidgets::setBackgroundColor, use this css:
css <- "
body {
  min-height: 100%;
  width:100%;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
  position: absolute;
  background: -moz-linear-gradient(to bottom left, #F7FBFF, #2171B5) fixed;
  background: -webkit-linear-gradient(to bottom left, #F7FBFF, #2171B5) fixed;
  background: -ms-linear-gradient(to bottom left, #F7FBFF, #2171B5) fixed;
  background: -o-linear-gradient(to bottom left, #F7FBFF, #2171B5) fixed;
  background: linear-gradient(to bottom left, #F7FBFF, #2171B5) fixed;
}
.navbar-default {
  background-color: inherit;
  border: none;
}
"


text:
Q: How to make jqGrid have two different pagers? I can get two pagers in jqGrid, one is on top, and one is on the bottom.
But I want to make the top pager show recordText on left, and the bottom pager show navigator buttons on the left.
The reason I want this is my grid is too wide, I don't want to use scrollbar to get the recordText or navigator buttons.

A: here this will help you...you can have two pagers one at top and one at bottom and based on your requirements you can hide a few things from pager.
Unable to position pager (navigation bar) above jqGrid


text:
Q: How to retrieve custom field values from JIRA with C#? There are some default values present in the custom field called "PLACE" which has LONDON,PARIS etc.. How can i retrieve these ( London , paris ) from JIRA SOAP API in C#. JIRA- JIRA 4.0 and C# - .net framework 4.0.

A: You can use the XML-RPC to do that, if you're not set on the SOAP API. Python Code sample (can change to C#):
#!/usr/bin/python

# Refer to the XML-RPC Javadoc to see what calls are available:
# http://docs.atlassian.com/software/jira/docs/api/rpc-jira-plugin/latest/com/atlassian/jira/rpc/xmlrpc/XmlRpcService.html

import xmlrpclib

# Jira connction info
#server = 'http://212.29.248.203:8080/rpc/xmlrpc'
server = 'https://your.jira.com/rpc/xmlrpc'
user = 'user'
password = 'password'
filter = '10302'
customfieldID = "customfield_10417"

s = xmlrpclib.ServerProxy(server)
auth = s.jira1.login(user, password)

# get list of issues
issues = s.jira1.getIssuesFromFilter(auth, filter)
for issue in issues:
        # get open since time
        for customFields in issue['customFieldValues']:
                if customFields['customfieldId'] == customfieldID :
                        print "found field!"+  customFields['values']


text:
Q: why use a dictionary if a List combined with Tuples offers way more flexibility? new to Python, trying to learn how to use dictionaries, but honestly don't see the point, you're limited to 2 pairs whereas if I just make a list with Tuples I get far more flexibility
in the code below I made a list of superheroes, where u can look it up by
Name(Batman), Identity (Bruce Wayne) or Universe (DC)
can't do that on a dictionary (you're limited to pairs of 2) so why would I ever need a dictionary?
Superheroes = [('Batman','Bruce Wayne','DC'),('Spiderman','Peter Parker','Marvel'),('Superman','Clark Kent','DC'),('Ironman','Tony Stark','Marvel'),('Green Arrow','Oliver Queen','DC')]
user_selection = input()

for (name,identity,universe) in Superheroes:
  if name==user_selection or identity == user_selection or universe == user_selection:
    print('Hero:' + name + '\nSecret Identity:' + identity + '\nUniverse:'+ universe)
  else:
    continue

A: Most uses of dictionaries don't require searching for a match in both the keys and values. You design your data structure so that the item you normally need to look up is the dictionary key.
For instance, if you have data with ingredients in recipes, you would almost always be looking it up by the dish that you're cooking. So you make that the key and you can get all the ingredients with a single lookup instead of searching the entire list.
If you occasionally need to find something in the value, you can still iterate through the dictionary using dict.entries(). If you need to look up by different components frequently you can make multiple dictionaries that all refer to the same values using different keys.


text:
Q: How to find nearest set of radio button and clear them

        <input type="radio" name="q31:1_answer" value="0" <?php echo ($quiz_answer1=='0' )? 'checked': ''?> id="q31:1_answer0">
        a. <break>

        <input type="radio" name="q31:1_answer" value="1" <?php echo ($quiz_answer1=='1' )? 'checked': ''?> id="q31:1_answer1">
        b. <br>

        <input type="radio" name="q31:1_answer" value="2" <?php echo ($quiz_answer1=='2' )? 'checked': ''?> id="q31:1_answer2">
        c.  <lb>

    <button type='button' name='clear' onclick=javascript:clear_me(this);>Clear</button>

        <input type="radio" name="q105:2_answer" value="0" id="q105:2_answer0" <?php echo ($quiz_answer4=='0' )? 'checked': ''?> >
        a. Home Tool Markup Language

        <input type="radio" name="q105:2_answer" value="1" id="q105:2_answer1" <?php echo ($quiz_answer4=='1' )? 'checked': ''?>>
        b. Hyper Text Markup Language

        <input type="radio" name="q105:2_answer" value="2" id="q105:2_answer2" <?php echo ($quiz_answer4=='2' )? 'checked': ''?>>
        c. Hyperlinks and Text Markup Language

    <button type='button' name='clear' onclick=javascript:clear_me();>Clear</button>

I have two sets of Radio buttons and clear button with each one set,I want to clear the nearest set of radio button
on clicking the clear button.I first tried with clearing with single set of radio button by the following code
which works.
function clear_me()
{
$('input:radio').attr("checked", false);
}

But then later I wrote a script to find nearest one and clear it,which didnt work.
In the below code I am trying to find out name of the input element and then clear it,name is going to dynamic so I can't hard code it.
function clear_me()
{
var elementName =  $(this).closest('.answer').closest('.r0').closest('input').attr('name');
var ele = document.getElementsByName(elementName);
    for(var i=0;i<ele.length;i++)
        ele[i].checked = false;
}

Can anyone please help me in writing a script to do the expected work ?

A: You were close to solution, Use .closest() to traverse up to answer element, then use .find() to target the child :radio element then set its checked property using .prop() method.
$(this).closest('.answer').find(':radio').prop('checked', false)

As you are using jQuery, I would recommend to use unobtrusive event handler
$('button[name=clear]').on('click', function() {
    $(this).closest('.answer').find(':radio').prop('checked', false)
});

$('button[name=clear]').on('click', function() {
  $(this).closest('.answer').find(':radio').prop('checked', false)
});

    <input type="radio" name="q31:1_answer" value="0">
    a. <break>

    <input type="radio" name="q31:1_answer" value="1">
    b. <br>

    <input type="radio" name="q31:1_answer" value="2">
    c.  <lb>

  <button type='button' name='clear'>Clear</button>

    <input type="radio" name="q105:2_answer" value="0" id="q105:2_answer0">
    a. Home Tool Markup Language

    <input type="radio" name="q105:2_answer" value="1" id="q105:2_answer1">
    b. Hyper Text Markup Language

    <input type="radio" name="q105:2_answer" value="2" id="q105:2_answer2">
    c. Hyperlinks and Text Markup Language

  <button type='button' name='clear'>Clear</button>


text:
Q: Force to show a window from a process started with SW_HIDE as STARTUPINFO? I want to create/show a window from a DLL, but this DLL is loaded from a process which was created with STARTUPINFOW::wShowWindow set to SW_HIDE before. Unfortunately I can't change any of the code which creates the process:
STARTUPINFOW startupInfo;
memset(&startupInfo, 0, sizeof(startupInfo));
startupInfo.cb = sizeof(startupInfo);
startupInfo.dwFlags = STARTF_USESHOWWINDOW;
startupInfo.wShowWindow = SW_HIDE;
PROCESS_INFORMATION processInfo;
memset(&processInfo, 0, sizeof(processInfo));

CreateProcessW(NULL, getCommand(), NULL, NULL, FALSE, 0, NULL, getWorkingDir(), &startupInfo, &processInfo);

I'm creating the window normally using Win32 api:
ZeroMemory(&wc, sizeof(WNDCLASSEX));
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = WindowProcRouter;
wc.hbrBackground = (HBRUSH)COLOR_WINDOW;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.lpszClassName = L"Window";
RegisterClassEx(&wc);
DWORD dwStyle = WS_CAPTION | WS_MINIMIZEBOX | WS_SYSMENU;
RECT WindowRect;
WindowRect.left = (long)0;
WindowRect.right = (long)width;
WindowRect.top = (long)0;
WindowRect.bottom = (long)height;
AdjustWindowRect(&WindowRect, dwStyle, FALSE);
HWND handle = CreateWindowEx(0,
      wc.lpszClassName,
      L"Title",
      dwStyle,
      0, 0,
      WindowRect.right - WindowRect.left,
      WindowRect.bottom - WindowRect.top,
      nullptr,
      nullptr,
      wc.hInstance,
      (void*) this);
ShowWindow(handle, SW_SHOW);
SetFocus(handle);

But the window is not shown; only if I launch the parent process manually (so the STARTUPINFO code from the first code-snippet is never executed).
The only solutions I know about are either changing the code which creates the process or creating a entirely new process (without SW_HIDE as STARTUPINFO) inside my DLL.
So I was wondering if there is any way to force showing the window, even that the parent process is using SW_HIDE as STARTUPINFO::wShowWindow?

A: The STARTUPINFO value is only used the first time a process calls ShowWindow(), so if you call it a second time your window will be shown.


text:
Q: How to get multiple selected values of select box in laravel? I have a html form which has a select list box from which you can select multiple values because its multiple property is set to multiple. Consider form method is 'POST' but i have this error:

(Array to string conversion)

The html code for the form is as follows:
<body>
<form action="{{route('info.create')}}" method="post">
  <select name="ary[]" multiple="multiple">
    <option value="Option 1"> Option 1 </option>
    <option value="Option 2"> Option 2 </option>
    <option value="Option 3"> Option 3 </option>
    <option value="Option 4"> Option 4 </option>
    <option value="Option 5"> Option 5 </option>
  </select>
  <input type="submit">
</form>
</body>

I want to post the selected values in select list box on info.create page. So how i do to fix this error please?
My controller code is :
$info=new Info();
$info->Risques=$request['ary'];

A: I'm not a laravel dev, but you'll need to loop through the select list as
if(!empty($_POST['ary'])){
    foreach($_POST['ary'] as $value){
        echo $value;
    }
}

do a dd($_POST['ary']) #to see what it outputs

A: It is a typecasting issue in the Model upon calling the create method or Eloquent.
You need to add a variation of the following to your model:
    /**
     * Typecast for protection.
     *
     * @var array
     */
    protected $casts = [
        'ary' => 'array',  // ary being your column name
    ];

And if you want to see what the request is sending in your method in your controller you can do
$data = $request->all();
dd($data);

That is assuming your method is using the Request class Request $request


text:
Q: Retrieve data from a bookmark Could you please let me know how can i retrieve data from a ms-word document bookmark dynamically, using c#.
The information online regarding this has not been useful..
i have tried the below code:
 private void btnBookmark_Click(object sender, EventArgs e)
    {
        object missing = Type.Missing;
        try
        {

            string wordOutputPath="D:\\RC Docs\\Template\\WordDocumentName";

            objWordDoc = objWord.Documents.Open(wordOutputPath.ToString(), false, false, ref missing,
                                                ref missing, ref missing, ref missing, ref missing,
                                                ref missing, ref missing, ref missing, true,
                                                ref missing, ref missing, ref missing, ref missing);

            //how to retrieve the bookmarks from the document-code has to be written here

             objWordDoc.Close();
        }

A: I think that you need something like:
foreach (Bookmark bk in objWordDoc.Bookmarks)
 {
    string s = bk.Range.Text;
    bk.Range.Text = s + "asd";
 }

A: Im able to retrieve the data from the bookmark of one document and insert it into a other document...but the format of the text is changing....
ex:
if i add some colour,font in the source document bookmark....the same format is not copied into the target documents bookmark...only the text is copied...


text:
Q: Home Networking Cable and equipment choice I wanted to rewire parts of my home, and got across the Cat Standards. However, when trying to shop for Cat6a, I almost always only come across Cat7 cables.
Why is that the case ? Where can I get good Cat6a cable to put through walls, and also from the outlet to pcs as well as patchcables ?
I also heard that some people said that Cat7 is not compatible with RJ45 and Cat6a Patchpanels. Has someone experience with this ?

A: Cat6a supports 10Gbit Ethernet at runs of up to 100 meters. This is on the market today and is being well-received by the market and isn't going away.
Cat7 is still a big question mark. It remains to be seen if equipment that requires it will make it to market and be well received, or if the market will skip over it to something even better. There's also no market consensus on connectors and other installation best practices as far as I can tell.
So, if the cost of Cat7 cable doesn't bother you, pull Cat7 but terminate it like Cat6a for now, and if the market ever adopts Cat7, you (or the future owner of your home) will be thrilled to discover you don't have to pull new cable, you maybe just have to re-terminate the cable you pulled back in 2020.


text:
Q: How do you convert a Date into a ActiveSupport::TimeWithZone with a particular timezone? I have a Date object like this:
>> the_date
=> Tue, 12 Jun 2012

>> the_date.class
=> Date

And a timezone stored as a string:
>> tz = "Pacific Time (US & Canada)"
=> "Pacific Time (US & Canada)"

And I'm looking to generate an ActiveSupport::TimeWithZone at midnight of the given date in the given timezone (not midnight of the given date in utc, then converted to the given timezone). The best way I've found to do this so far is exceedingly ugly:
>> the_time = ActiveSupport::TimeZone.new(tz).parse(the_date.to_s)
=> Tue, 12 Jun 2012 00:00:00 PDT -07:00

>> the_time.class
=> ActiveSupport::TimeWithZone

There's got to be a better way to generate this! Anyone know how to do this?

A: Not really much better, but different than your solution:
the_date.to_time.in_time_zone
#=> Mon, 11 Jun 2012 22:00:00 UTC +00:00

the_date.to_time.in_time_zone(tz)
#=> Mon, 11 Jun 2012 15:00:00 PDT -07:00

Time.zone = tz
#=> "Pacific Time (US & Canada)"

the_date.to_time.in_time_zone
#=> Mon, 11 Jun 2012 15:00:00 PDT -07:00

the_date.to_time.in_time_zone.end_of_day
#=> Mon, 11 Jun 2012 23:59:59 PDT -07:00

(the_date.to_time.in_time_zone + 1.day).beginning_of_day
#=> Tue, 12 Jun 2012 00:00:00 PDT -07:00


text:
Q: Before corruption, "(node)-[r:player*]->()" query was working fine, but not after importing corrupted fix data some months ago my neo4j data corrupted after fixing corrupted data. I imported in neo4j. Data are working fine. All queries are working fine.
The problem is that while I search data by relationship by * like in
(node)-[r:player*]->()

at times, query executing continues and I am not getting any output. After some time the query goes in lock level.
before the corruption (node)-[r:player*]->() query was working fine. That problem occurred after importing corrupted fix data.


text:
Q: Allowing website user to browse a server folder A simple HTML code snippet allows you to browse your own files:
<input type="file" value="Browse">
<input type="submit" value="Submit">

But how do I let the user browse server folders, and only particular ones therein? (I'd hate to have someone deleting my root...)
I've done some searching around, but immediate search terms like "user browse server directory" return scanty references.


text:
Q: $T\colon \mathbb R^2 \rightarrow \mathbb R^2$ be a linear transformation with $T(x)=0$ for all $x$ such that $||x||=1.$ I came across the following problem that says:

Let $T\colon \mathbb R^2 \rightarrow \mathbb R^2$ be a linear transformation. Assume that  $T(x)=0$ for all  $x$ such that $||x||=1.$ Then, which of the following options is correct

*

*$T \equiv 0$

*$T$ is onto

*The dimension of the kernel of $T$ is $1$

*The dimension of the range of $T$ is $1$

I do not know how to progress with the problem and in particular how to use the fact that $\|x\|=1.$ Can someone point me in the right direction? Thanks in advance for your time.
EDIT:As David Mitra suggested,we see that $T(0,1)=T(1,0)=0.$ And so from here.I can conclude that dim(ker $T$)=$2$. So the dimension of range of $T=0$. So,option $2,3,4$ can not be true.So the only option left which is  $T \equiv 0$ is true.Am I right? Please comment.

A: Hint: $$T(x)=T\left(\|x\|\cdot\frac{x}{\|x\|}\right)=\|x\|T\left(\frac{x}{\|x\|}\right).$$

A: By linearity, any transformation is determined by its action on a basis. The conditions of your problem allow you to conclude that $T(1,0)=T(0,1)=(0,0)$ as David pointed out. So, you have only one one option that is valid, as you have chosen. But, what does it mean if $Ker(T)$ has dimension 2 and the domain of your transformation has dimension 2? The earlier information allows you to conclude option (1) directly.


text:
Q: python cumulative sum of triples? My data is:
li = [('a', 10, 'b'), ('b', 12, 'c'), ('c', 5, 'd'), ('b', 2, 'e')]

a is the start.
The execution should be as:
a = 0
b = a + 10
c = b + 12
d = c + 5
e = b + 2

S in the end:
a=0 b=10 c=22 d=27 e=12

I thought about using trees and recursion to calculate, but I'm at a loss and don't know how to write these codes.

A: Using a defaultdict will make this task pretty simple:
from collections import defaultdict

res = defaultdict(int)
for source, operand, target in li:
    res[target] = res[source] + operand

for key,val in res.items():
    print(key, "=", val)

Will give:
a = 0
b = 10
c = 22
d = 27
e = 12

A: You need direct access to your variables in namespace?
from sys import modules

main = modules["__main__"]

li=[('a',10,'b'),('b',12,'c'),('c',5,'d'),('b',2,'e')]

a = 0
for var_1, num, var_2 in li:
    setattr(main, var_2, getattr(main, var_1) + int(num))

print(f"a={a}", f"b={b}", f"c={c}", f"d={d}", f"e={e}", sep='\n')

output:
a=0
b=10
c=22
d=27
e=12


text:
Q: Proving no real solutions Please read the question before marking as duplicate; this is proving there are NO SOLUTIONS OUTSIDE THE INTERVAL.

Given that:
$x^3−3x+3=\sin(x)$ show that there are no real solutions outside the
  interval $[−3,−2]$

am not trying to prove there is a solution; this has been done with intermediate value theorem; proving no real solutions outside interval

A: By derivation, the LHS has extrema at $x=\pm1$, namely $(-1,5)$ and $(1,1)$. We also have the points $(-3,-15)$ and $(-2,1)$.
We can write the following variation table:
$$\begin{array}&x&-\infty&-3&-2&-1&1&\infty\\LHS&-\infty&-15&1&5&1&\infty\end{array}$$
This proves that the LHS remains out of $[-1,1]$ outside $[-3,-2]$, except maybe at $x=1$. But then $\sin 1<1$ and there is no solution.

A: Nice! How's question 3c doing for you?
Essentially what you want to do is find the critical points and prove that the local minimum does not occur below the x-axis.
You would find the critical points by deriving f(x) to get f^(1)(x) = 3x^2-3-cos(x).
You know that -1<=cos(x)<=1, so in order for f^(-1)(x) to equal 0, the component |3x^2-3|<=1. Solving this, x<= sqrt(4/3), and x>=-sqrt(4/3)
Find the derivative of both, use either first or second derivative principals to determine nature, and check endpoints to see if they are strictly increasing, or strictly decreasing.
Simple...ish


text:
Q: Building URL in CodeIgniter I'm basically trying to grab everything after the 4th segment in the URL, however there is no fixed number of segments. Here is my attempt but for some reason $url is always 0 rather than the string I am looking for. Any suggestions?
$url = '';
for ($counter = 4; $counter <= $this->uri->total_segments(); $counter++) {
    $url += $this->uri->slash_segment($counter);
}
echo $url;

A: Try this:
$segs = $this->uri->segment_array(); // get all segments
$my_segs = $segs[3]; // get segments starting from four

foreach ($my_segs as $segment)
{
  echo $segment;
  echo '<br />';
}

Also to concatenate strings, use a dot not plus sign eg:
$url .= $this->uri->slash_segment($counter);

A: You can simplify that code like so:
echo implode('/', array_slice($this->uri->segment_array(), 3));

That will get everything after and including the 4th parameter.


text:
Q: Querying nested data from a Firebase Realtime database to populate a ListView I'm trying to populate a ListView using a query that will retrieve all GroupVaccinations that have a boolean value equal to false i.e. allVaccinated = false. The database is structured like so: allVaccinated is the condition I'm looking to use
The following code is what I've tried but nothing is being rendered:
     databaseReferenceGV = FirebaseDatabase.getInstance().getReference("groupVaccinations");
            groupVaccinationList = new ArrayList<>();
    groupVaccinationList.clear();

        BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {

            switch (item.getItemId()) {

                case R.id.navigation_vaccinations:
                    listView.setAdapter(null);
                    groupVaccinationList.clear();
                    Query toDoVaccinationQuery = databaseReferenceGV.orderByChild("groupVaccinationID/allVaccinated").equalTo(false);
                    toDoVaccinationQuery.addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                            for(DataSnapshot groupVaccinationSnapshot : dataSnapshot.getChildren()) {
                                for (DataSnapshot vaccinationSnapshot : groupVaccinationSnapshot.getChildren()) {
                                    GroupVaccination groupVaccination = vaccinationSnapshot.getValue(GroupVaccination.class);
                                    groupVaccinationList.add(groupVaccination);
                                }
                            }
                            AllGroupVaccinationList groupVaccinationInfoAdapter = new AllGroupVaccinationList(ActivityToDoDoses.this, groupVaccinationList);
                            listView.setAdapter(groupVaccinationInfoAdapter);
                        }

                        @Override
                        public void onCancelled(@NonNull DatabaseError databaseError) {
                            throw databaseError.toException();

                        }
                    });

                    return true;
                case R.id.navigation_doses:
                    //other action
            }
            return false;
        }
    };

I'm not quite sure how to query a firebase database so any help is welcomed! Thanks!

A: You cannot use the following query:
databaseReferenceGV.orderByChild("groupVaccinationID/allVaccinated").equalTo(false);

Since between the groupVaccinationID node and the allVaccinated property, there are two more children: -LXiM ... BX9x and -LZk5 ... j8Vz. To solve this, you can iterate the DataSnapshot objects twice using getChildren() method (as you already do) but in this case, only the following query is required:
databaseReferenceGV = FirebaseDatabase.getInstance().getReference("groupVaccinations");

Then create an if statement client side:
if(!groupVaccination.getAllVaccinated()) {
    groupVaccinationList.add(groupVaccination);
}

Or you can change your database structure to allow a query based only on a single dynamic node.


text:
Q: Renaming attributes/fields in shapefile attribute table using QGIS I would like to rename some fields in my attribute table:

Like rename "XRF_N3"in something else. It seems quite a easy issue but I don't find any information about how can I do that.

A: No need for plugins since QGIS v3.12. There is now something called the Rename field tool — special thanks to ndawson for building the tool.
Procedure

*

*Locate the top-most menu bar

*Go to Processing › Toolbox

*In the Processsing Toolbox, go to Vector Table › Rename field

*The Rename Field window will be opened like so:

*Select the Input layer that has the attribute table

*Select the Field to rename (field that you want to rename)

*Type the New field name

*Click Run

A: Since QGIS 2.16 you no longer need a plugin to do this - you can double click a field name in a shapefile from the vector layer properties window and rename (set the layer as editable first)

A: Since 2.16, you can edit field names in the layer properties when editing is enabled:

Renaming is possible using Table Manager plugin (http://plugins.qgis.org/plugins/tablemanager/)

A: if anyone is having any difficulty finding the Table manager button, for me it was located here:

A: You can use Refactor Fields from processing toolbox. It will create a new layer as output having the new names you defined. Besides that, this tool also allows to change field types, field order and other stuff. You can also rename more than one field at once.

This algorithm allows editing the structure of the attributes table of
a vector layer. Fields can be modified in their type and name, using a
fields mapping. The original layer is not modified. A new layer is
generated, which contains a modified attribute table, according to the
provided fields mapping. Rows in orange have constraints in the
template layer from which these fields were loaded. Treat this
information as a hint during configuration. No constraints will be
added on an output layer nor will they be checked or enforced by the
algorithm.


text:
Q: SQLiteDataAdapter Fill exception I'm trying to use the OleDb CSV parser to load some data from a CSV file and insert it into a SQLite database, but I get an exception with the OleDbAdapter.Fill method and it's frustrating:

An unhandled exception of type
  'System.Data.ConstraintException'
  occurred in System.Data.dll
Additional information: Failed to
  enable constraints. One or more rows
  contain values violating non-null,
  unique, or foreign-key constraints.

Here is the source code:
public void InsertData(String csvFileName, String tableName)
{
    String dir = Path.GetDirectoryName(csvFileName);
    String name = Path.GetFileName(csvFileName);

    using (OleDbConnection conn =
        new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
        dir + @";Extended Properties=""Text;HDR=No;FMT=Delimited"""))
    {
        conn.Open();
        using (OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM " + name, conn))
        {
            QuoteDataSet ds = new QuoteDataSet();
            adapter.Fill(ds, tableName); // <-- Exception here
            InsertData(ds, tableName); // <-- Inserts the data into the my SQLite db
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        SQLiteDatabase target = new SQLiteDatabase();
        string csvFileName = "D:\\Innovations\\Finch\\dev\\DataFeed\\YahooTagsInfo.csv";
        string tableName = "Tags";
        target.InsertData(csvFileName, tableName);

        Console.ReadKey();
    }
}

The "YahooTagsInfo.csv" file looks like this:
tagId,tagName,description,colName,dataType,realTime
1,s,Symbol,symbol,VARCHAR,FALSE
2,c8,After Hours Change,afterhours,DOUBLE,TRUE
3,g3,Annualized Gain,annualizedGain,DOUBLE,FALSE
4,a,Ask,ask,DOUBLE,FALSE
5,a5,Ask Size,askSize,DOUBLE,FALSE
6,a2,Average Daily Volume,avgDailyVolume,DOUBLE,FALSE
7,b,Bid,bid,DOUBLE,FALSE
8,b6,Bid Size,bidSize,DOUBLE,FALSE
9,b4,Book Value,bookValue,DOUBLE,FALSE

I've tried the following:

*

*Removing the first line in the CSV file so it doesn't confuse it for real data.

*Changing the TRUE/FALSE realTime flag to 1/0.

*I've tried 1 and 2 together (i.e. removed the first line and changed the flag).

None of these things helped...
One constraint is that the tagId is supposed to be unique.  Here is what the table look like in design view:

Can anybody help me figure out what is the problem here?
Update:
I changed the HDR property from HDR=No to HDR=Yes and now it doesn't give me an exception:
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dir + @";Extended Properties=""Text;HDR=Yes;FMT=Delimited""");

I assumed that if HDR=No and I removed the header (i.e. first line), then it should work... strangely it didn't work. In any case, now I'm no longer getting the exception.
The new problem arose here: SQLiteDataAdapter Update method returning 0

A: First thing: IMO emplacing keys and constraints on a transport structure such as your dataset is a bad idea.
Use a transaction and let the target db throw if it wants.
Second: have you examined the ds to ensure the csv is getting loaded? VS has a dataset debug visualizer built in - simply set a break point after the ds is loaded and hover over the variable name, click the little down-arrow and select the appropriate visualizer.
Third: I don't think that you are generating an insert command. Just before you call update, check the InsertCommand.CommandText..
var cmdText = sqliteAdapter.InsertCommand.CommandText;

I think you will find that it is empty.
This is the source of the SQLiteDataAdapter ctor that ultimately gets called. Note that no command builder is employed. You need to explicitly set the InserCommand property on the SQLiteDataAdapter, perhaps by using a SQLiteCommandBuilder?
public SQLiteDataAdapter(string commandText, SQLiteConnection connection)
{
    this.SelectCommand = new SQLiteCommand(commandText, connection);
}

A: I changed the HDR property from HDR=No to HDR=Yes and now it doesn't give me an exception anymore... here is what the connection string looks like:
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dir + @";Extended Properties=""Text;HDR=Yes;FMT=Delimited""");

I assumed that if HDR=No and I removed the header (i.e. first line), then it should work... the only way to get rid of the exception if HDR=No is if I remove the constraints by calling ds.EnforceConstraints = false;
In any case, now I'm no longer getting the exception. If anybody can explain why this is happening, then please do tell.


text:
Q: Sample weights in XGBClassifier I am using Scikit-Learn XGBClassifier API with sample weights. If I multiply sample weights by 2, I get totally different results with exact same parameters and random_state, I am expecting that If we multiply/divide sample weight with a constant, results should not change. Do you have any suggestion?

A: What you describe, while somewhat unusual it is not unexpected if we do not optimise our XGBoost routine adequately. Your intuition though is correct: "results should not change".
When we change the scale of the sample weights, the sample weights change the deviance residuals associated with each data point; i.e. the use of different sample weights' scale, results in our GBM to train on a different sample per se. When performing gradient boosting iteration, the residuals that serve as leaf weights are multiplied by that sample weights. Therefore the fit themselves are different especially during the first few iterations of XGBoost.
Usually the difference in the fit due to different sample weights' scale is not substantial and will ultimately smooth out but it can noticeable (especially during the first iterations).
# Using Python 3.6.9 // xgboost 0.90
import pandas as pd
import numpy as np
from xgboost import XGBRegressor
import xgboost as xgb

w=np.array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1])
w_2=w*2
X=pd.DataFrame([13.36, 5.35, 0.26, 84.16, 24.67, 22.26, 18.02, 14.20, 61.66, 57.26])
y=pd.DataFrame([37.54, 14.54, -0.72, 261.19, 76.90, 67.15, 53.89, 43.48, 182.60, 179.44])
X_test=pd.DataFrame([0.5])

xgb_model=XGBRegressor(n_estimators=100, learning_rate=1,
                       objective='reg:squarederror', subsample=1, reg_lambda=0.1)

xgb_model.fit(X, y, sample_weight=w)
print(xgb_model.predict(X_test, ntree_limit=5))
# [-0.65936375]
print(xgb_model.predict(X_test))
# [-0.71998453]

xgb_model.fit(X, y, sample_weight=w_2)
print(xgb_model.predict(X_test, ntree_limit=5))
#[-0.76515234]
print(xgb_model.predict(X_test))
# [-0.7199712]

As we can see, using either the initial "unit weights" w or their scaled version w_2 returns effectively the same estimate (~0.7199...) when we optimise "enough" (e.g. after doing 100 iterations).  Nevertheless, when we are starting the first estimates can be substantially different (-0.6593... against -0.7651...). (Notice the observed behaviour is a bit version dependant. I played with XGBoost ver. 1.0.1 and the difference tapers off very quickly at about ntree_limit=4.)
If we observe substantial difference between the estimates of two boosters where the only difference is the scale of the sample weights, this is primarily indicative of two things:

*

*we have not optimised the boosters adequately so they have not yet reach a steady state. We need to optimise further (e.g. have more iterations).

*we have over-fitted our samples so the boosters interpreter the differences in the scaling of sample weights as material difference. We need to regularise more strongly (e.g. have higher regularisation parameters reg_alpha and reg_lambda).