text:
Q: Does Java need closures? I've been reading a lot lately about the next release of Java possibly supporting closures.  I feel like I have a pretty firm grasp on what closures are, but I can't think of a solid example of how they would make an Object-Oriented language "better".  Can anyone give me a specific use-case where a closure would be needed (or even preferred)?

A: Java doesn't need closures, an Object oriented language can do everything a closure does using intermediate objects to store state or do actions (in Java's case inner classes).
But closures are desirable as a feature because they greatly simplify the code and increase readability and as a consequence the maintainability of the code.
I'm no Java specialist but I'm using  C# 3.5 and closures are one of my favorite features of the language, for example take the following statement as an example:
// Example #1 with closures
public IList<Customer> GetFilteredCustomerList(string filter) {
    //Here a closure is created around the filter parameter
    return Customers.Where( c => c.Name.Contains(filter)).ToList();
}

now take an equivalent example that doesn't use closures
//Example #2 without closures, using just basic OO techniques
public IList<Customer> GetFilteredCustomerList(string filter) {
    return new Customers.Where( new CustomerNameFiltrator(filter));
}
...
public class CustomerNameFiltrator : IFilter<Customer> {
    private string _filter;
    public  CustomerNameFiltrator(string filter) {
         _filter = filter;
    }
    public bool Filter(Customer customer) {
        return customer.Name.Contains( _filter);
    }
}

I know this is C# and not Java but the idea is the same, closures are useful for conciseness, and make code shorter and more readable. Behind the scenes, the closures of C# 3.5 do something that's looks very similar to example #2 meaning the compiler creates a private class behind the scenes and passes the 'filter' parameter to it.
Java doesn't need closures to work, as a developer you don't need them either, but, they are useful and provide benefits so that means that they are desirable in a language that is a production language and one of it's goals is productivity.

A:
I've been reading a lot lately about the next release of Java possibly supporting closures. I feel like I have a pretty firm grasp on what closures are, but I can't think of a solid example of how they would make an Object-Oriented language "better."

Well, most people who use the term "closure" actually mean "function object", and in this sense, function objects make it possible to write simpler code in certain circumstances such as when you need custom comparators in a sort function.
For example, in Python:
def reversecmp(x, y):
   return y - x

a = [4, 2, 5, 9, 11]
a.sort(cmp=reversecmp)

This sorts the list a in reverse order by passing the custom comparison functoin reversecmp.  The addition of the lambda operator makes things even more compact:
a = [4, 2, 5, 9, 11]
a.sort(cmp=lambda x, y : y - x)

Java does not have function objects, so it uses "functor classes" to simulate them.  In Java you do the equivalent operation by implementing a custom version of the Comparator class, and passing that to the sort function:
class ReverseComparator implements Comparator {
   public compare(Object x, Object y) {
      return (Integer) y - (Integer) x;
   }

...

List<Integer> a = Arrays.asList(4, 2, 5, 9, 11);
Collections.sort(a, new ReverseComparator());

As you can see, it gives the same effect as closures, but is clumsier and more verbose.  However, the addition of anonymous inner classes obviates most of the pain:
List<Integer> a = Arrays.asList(4, 2, 5, 9, 11);
Comparator reverse = new Comparator() {
   public Compare(Object x, Object y) {
       return (Integer) y - (Integer) x;
   }
}
Collections.sort(a, reverse);

So I would say that the combination of functor classes + anonymous inner classes in Java is sufficient to compensate for the lack of true function objects, making their addition unnecessary.

A: As a Lisp programmer I would wish that the Java community understands the following difference: functions as objects vs. closures.
a) functions can be named or anonymous. But they can also be objects of themselves. This allows functions to be passed around as arguments, returned from functions or stored in data structures. This means that functions are first class objects in a programming language.
Anonymous functions don't add much to the language, they just allow you to write functions in a shorter way.
b) A closure is a function plus a binding environment. Closures can be passed downwards (as parameters) or returned upwards (as return values). This allows the function to refer to variables of its environment, even if the surrounding code is no longer active.
If you have a) in some language, then the question comes up what to do about b)? There are languages that have a), but not b). In the functional programming world a) (functions) and b (functions as closures) is nowadays the norm. Smalltalk had a) (blocks are anonymous functions) for a long time, but then some dialects of Smalltalk added support for b) (blocks as closures).
You can imagine that you get a slightly different programming model, if you add functions and closures to the language.
From a pragmatic view, the anonymous function adds some short notation, where you pass or invoke functions. That can be a good thing.
The closure (function plus binding) allows you for example to create a function that has access to some variables (for example to a counter value). Now you can store that function in an object, access it and invoke it. The context for the function object is now not only the objects it has access to, but also the variables it has access to via bindings. This is also useful, but you can see that variable bindings vs. access to object variables now is an issue: when should be something a lexical variable (that can be accessed in a closure) and when should it be a variable of some object (a slot). When should something be a closure or an object? You can use both in the similar ways. A usual programming exercise for students learning Scheme (a Lisp dialect) is to write a simple object system using closures.
The result is a more complicated programming language and a more complicated runtime model. Too complicated?

A: Java has had closures since 1.1, just in a very cumbersome and limited way.
They are often useful wherever you have a callback of some description. A common case is to abstract away control flow, leaving the interesting code to call an algoritm with a closure that has no external control flow.
A trivial example is for-each (although Java 1.5 already has that). Whilst you can implement a forEach method in Java as it stands, it's far too verbose to be useful.
An example which already makes sense with existing Java is implementing the "execute around" idiom, whereby resource acquisition and release is abstracted. For instance, file open and close can be done within try/finally, without the client code having to get the details right.

A: They don't make an Object-Oriented language better. They make practical languages more practical.
If you're attacking a problem with the OO hammer - represent everything as interactions between objects - then a closure makes no sense. In a class-based OO language, closures are the smoke-filled back rooms where stuff gets done but no one talks about it afterwards. Conceptually, it is abhorrent.
In practice, it's extremely convenient. I don't really want to define a new type of object to hold context, establish the "do stuff" method for it, instantiate it, and populate the context... i just want to tell the compiler, "look, see what i have access to right now? That's the context i want, and here's the code i want to use it for - hold on to this for me 'till i need it".
Fantastic stuff.

A: The most obvious thing would be a pseudo-replacement for all those classes that just have a single method called run() or actionPerformed() or something like that.  So instead of creating a Thread with a Runnable embedded, you'd use a closure instead.  Not more powerful than what we've got now, but much more convenient and concise.
So do we need closures?  No.  Would they be nice to have?  Sure, as long as they don't feel bolted on, as I fear they would be.

A: When closures finally arrive in Java, I will gleefully get rid of all my custom comparator classes.
myArray.sort( (a, b) => a.myProperty().compareTo(b.myProperty() );

...looks a helluva lot better than...
myArray.sort(new Comparator<MyClass>() {
   public int compare(MyClass a, MyClass b) {
      return a.myProperty().compareTo(b.myProperty();
   }
});

A: A few people have said, or implied, that closures are just syntactic sugar - doing what you could already do with anonymous inner classes and making it more convenient to pass parameters in.
They are syntactic sugar in the same sense that Java is syntactic sugar for assembler (that "assembler" could be bytecode, for sake of argument). In other words they raise they level of abstraction, and this is an important concept.
Closures promote the concept of the function-as-object to a first class entity - one that increases the expressiveness of code, rather than cluttering it with even more boilerplate.
An example that's close to my heart has already been mentioned by Tom Hawtin - implementing the Execute Around idiom, which is just about the only way to get RAII into Java. I wrote a blog entry on exactly that subject a couple of years ago when I first heard closures might be coming.
Ironically, I think the very reason that closures would be good for Java (more expressiveness with less code) may be what rattles many Java advocates. Java has a mindset of "spell everything out the long way". That and the fact that closures are a nod towards a more functional way of doing things - which I also see as a Good Thing, but may water down the pure OO message that many in the Java community hold dear.

A: I have been thinking a lot about the topic of this very interesting question in
the last few days. First of all, if I have understood correctly, Java already has
some basic notion of closures (defined through anonymous classes) but the new feature
that is going to be introduced is the support for closures based on anonymous functions.
This extension will definitely make the language more expressive but I am not sure
if it really fits with the rest of the language.
Java has been designed as an object-oriented language with no support for functional programming: Will the new semantics be easy to understand? Java 6 does not even have functions, will Java 7 have anonymous functions but no "normal" functions?
My impression is that as new programming styles or paradigms like functional
programming become more popular, everyone wants to use them in their
favourite OOP language. This is understandable: one wants to continue to use
a language they're familiar with while adopting new features. But in this way
a language can become really complex and lose coherence.
So my attitude at the moment is to stick to Java 6 for OOP (I hope Java 6 will still
be supported for a while) and, in case I really get interested in doing OOP + FP,
to take a look at some other language like Scala (Scala was defined to be multi-
paradigm from the beginning and can be well integrated with Java) rather than switching
to Java 7.
I think Java owes its success to the fact that it combines a simple language with very
powerful libraries and tools, and I do not think that new features like closures will
make it a better programming language.

A: Now that JDK8 is about to be released there is more information available that can enrich the answers to this question.
Bria Goetz, language architect at Oracle, has published a series of papers (yet drafts) on the current state of lambda expressions in Java. It does also cover closures as they are planning to release them in the upcoming JDK, which should be code complete around January 2013 and should be released around midyear 2013.

*

*The State of Lambda: in the first page or two this article attempts to answer the question presented here. Although I still found it short in arguments, but is is full of examples.

*The State of Lambda - Libraries Edition: this is also very interesting because it covers advantages like lazy evaluation and parallelism.

*The Translation of Lambda Expressions: which basically explains the desugaring process done by the Java compiler.

A: As a java developer who is trying to teach themselves lisp in an attempt to become a better programmer, I would say that I would like to see the Josh Block proposal for closures implemented.  I find myself using anonymous inner classes to express things like what to do with each element of a list when aggregating some data.  To would be nice to represent that as a closure, instead of having to create an abstract class.

A: Closures in an imperative language (examples: JavaScript, C#, the forthcoming C++ refresh) are not the same as anonymous inner classes. They need to be able to capture modifiable references to local variables. Java's inner classes can only capture local final variables.
Almost any language feature can be criticised as non-essential:

*

*for, while, do are all just syntactic sugar over goto/if.

*Inner classes are syntactic sugar over classes with a field pointing to the outer class.

*Generics are syntactic sugar over casts.

Exactly the same "non-essential" argument should have blocked the inclusion of all the above features.

A: I suppose for supporting core functional programming concepts, you need closures. Makes the code more elegant and composable with the support for closures. Also, I like the idea of passing around lines of code as parameters to functions.

A: There are some very useful 'higher order functions' which can do operations on lists using closures. Higher order functions are functions having 'function objects' as parameters.
E.g. it is a very common operation to apply some transformation to every element in a list. This higher order function is commonly called 'map' or 'collect'. (See the *. spread operator of Groovy).
For example to square each element in a list without closures you would probably write:
List<Integer> squareInts(List<Integer> is){
   List<Integer> result = new ArrayList<Integer>(is.size());
   for (Integer i:is)
      result.add(i*i);
   return result;
}

Using closures and map and the proposed syntax, you could write it like that:
is.map({Integer i => i*i})

(There is a possible performance problem here regarding boxing of primitive types.)
As explained by Pop Catalin there is another higher order function called 'select' or 'filter': It can be used to get all the elements in a list complying to some condition. For example:
Instead of:
void onlyStringsWithMoreThan4Chars(List<String> strings){
   List<String> result = new ArrayList<String>(str.size()); // should be enough
   for (String str:strings)
      if (str.length() > 4) result.add(str);
   return result;
}

Instead you could write something like
strings.select({String str => str.length() > 4});

using the proposal.
You might look at the Groovy syntax, which is an extension of the Java language to support closures right now. See the chapter on collections of the Groovy User Guide for more examples what to do with closures.
A remark:
There is perhaps some clarification needed regarding the term 'closure'. What I've shown above are strictly spoken no closures. They are just 'function objects'.
A closure is everything which can capture - or 'close over' - the (lexical) context of the code surrounding it. In that sense there are closures in Java right now, i.e. anonymous classes:
Runnable createStringPrintingRunnable(final String str){
    return new Runnable(){
       public void run(){
          System.out.println(str); // this accesses a variable from an outer scope
       }
    };
}

A: Java Closure Examples

A: Not only that benjismith, but I love how you can just do...
myArray.sort{ it.myProperty }
You only need the more detailed comparator you've shown when the natural language comparison of the property doesn't suit your needs.
I absolutely love this feature.

A: What about readability and maintainability...one-liner closures are harder to understand and debug, imo
Software has looong life and you can get people with rudimentary knowledge of the language to maintain it...So spread out logic better than one-liners for easy maintenance...You generally don't have a software star looking after software after its release...

A: You might want to look at Groovy, a language that's mostly compatible with Java, and runs on the JRE, but supports Closures.

A: The lack of binding in anonymous function [i.e. if the variables (and method arguments if there is an enclosing method) of the outer context are declared final then they are available but not otherwise], I don't quite understand what that restriction actually buys.
I use "final" profusely anyways. So, if my intent was to use the same objects inside the closure, I would indeed declare those objects final in the enclosing scope. But what would be wrong in letting the "closure [java a.i.c.]" just get a copy of the reference as if passed via a constructor (well that in fact is how it is done).
If the closure wants to overwrite the reference, so be it; it will do so without changing the copy that the enclosing scope sees.
If we argue that that would lead to unreadable code (e.g. maybe it's not straight-forward to see what the object reference is at the time of the constructor call for the a.i.c.), then how about at least making the syntax less verbose? Scala? Groovy?


text:
Q: List all HTML files in a directory python code not working I am trying to list all HTML files in a directory using os.walk  but it returning none instead of file names
Here is my code
def read_dirctory():
    matches = []
    for root, dirnames, filenames in os.walk('/home/akallararajappan/www.mangalam.com/agriculture'):
        for filename in fnmatch.filter(filenames, '*.html'):
            matches.append(os.path.join(root, filename))
   return matches

What is the problem here ?  I am using Ubuntu 12.04. I have 1000 html files in the directory
output:
[]

A: Something like this should work. BTW there are a already a couple of questions like this.
def read_directory():
    matches =[]
    directory = '/home/akallararajappan/www.mangalam.com/agriculture'
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.endswith('.html'):
                matches.append(os.path.join(root, file))
    return matches

redpajama_set_name: RedPajamaStackExchange


text:
Q: Displaying an array of JPanels in a JPanel I'm somewhat new to Swing, and I've been having a problem with trying to display an array of JPanels inside a JPanel.
The program adds Student objects to an arraylist in the Driver class based off information inputted by the user, and then is supposed to display that information on separate JPanels in the studentPane JPanel, but they never show up after the information is put in.
The first thing I tried was having the Student class return a JPanel by making a method called getInfoPane which returns a JPanel created in the student class with all its necessary info, and then calling:
studentPane.add(students.get(x).getInfoPane());

But that didn't work. Ive also tried making the Student class extend JPanel, adding the student's info to that panel, and then trying to add it to the studentPane JPanel in the Driver class, which doesn't display either.
Currently, I'm trying having a separate arraylist of JPanels called StudentInfo, and adding the students with this code:
for(int x=0; x<Integer.parseInt(numberField.getText()); x++) {
     studentInfo.add(new JPanel ());    //add new JPanel to array
     studentInfo.get(x).add(new JLabel (students.get(x).toString()));  //add info from Student
     studentPane.add(studentInfo.get(x));  //add JPanel with student info to main Student JPanel
}

with the toString method being overridden to return a string with the info inputted into the the Student class. This method hasn't worked either. I have checked to make sure the Student class is receiving the information put in, and it prints out fine. I have also tried to directly add components, like a JLabel, to the studentPane in the Driver class but, but it wouldn't work. After a little testing I found that strings were the only thing that would show up on the studentPane. This has lead me to think that the problem deals with something other than passing a JPanel from another class. I have viewed many other questions with similar problems, but haven't been able to make the solutions work for my program.
So far here is the relevant code from my program:
public class Driver extends JFrame {

     private Container contentPane;
     ArrayList<Student> students = new ArrayList<Student>();
     private JPanel studentPane = new JPanel();
     ArrayList<JPanel> studentInfo = new ArrayList<JPanel>();

     public static void main(String[] args) {
          EventQueue.invokeLater(new Runnable() {
               public void run() {
                    try {
                         Driver frame = new Driver();
                         frame.setVisible(true);
                    } catch (Exception e) {
                         e.printStackTrace();
                    }
               }
           });
     }

     public Driver() {
          contentPane = this.getContentPane();

          profiles.add(addStudentProfiles);         // this chunk has the user input student info and tries to add it to studentPane
          addStudentProfiles.addActionListener(new ActionListener() {
               public void actionPerformed(ActionEvent e) {
                    JOptionPane.showMessageDialog(null, number, "Number to create", JOptionPane.INFORMATION_MESSAGE );
                    if(numberField.getValue() != null) {
                         for(int x=0; x<Integer.parseInt(numberField.getText()); x++) {
                              while(nameField.getText().equals("") || workEthicField.getText().equals("")) {
                                   JOptionPane.showMessageDialog(null, studentInputs, "New Student", JOptionPane.PLAIN_MESSAGE);
                                   if(nameField.getText().equals("") || workEthicField.getText().equals(""))
                                        JOptionPane.showMessageDialog(null, "Error. Please fill out all of the fields");
                              }
                              students.add(new Student(nameField.getText(), Integer.parseInt(workEthicField.getText()), (String)(major1Field.getSelectedItem())));
                              nameField.setText(""); workEthicField.setValue(null);
                         }
                         for(int x=0; x<Integer.parseInt(numberField.getText()); x++) {
                              studentInfo.add(new JPanel ());
                              studentInfo.get(x).add(new JLabel (students.get(x).toString()));
                              studentPane.add(studentInfo.get(x));
                         }
                         numberField.setValue(null);
                    }
               }
          });

          setContentPane(contentPane);
          contentPane.setLayout(null);

          studentPane.setBorder(BorderFactory.createTitledBorder(BorderFactory.createMatteBorder(3, 3, 3, 3, Color.black), "Students", TitledBorder.CENTER, TitledBorder.CENTER));
          studentPane.setLocation(350, 0);
          studentPane.setSize(300, (int)getBounds().getHeight()-62);
          studentPane.setBackground(Color.lightGray);
          studentPane.setVisible(true);
          contentPane.add(studentPane);
     }
}

And here is the Student class:
public class Student {

     private String name, major;
     private int workEthic;
     private String info = "";

     public Student(String name, int workEthic, String major) {

          this.name = name;
          this.workEthic = workEthic;
          this.major = major;

          info = name+ "\n" +major+ "\n" +workEthic;
     }

     public String toString() {
          return info;
     }
}

So basically, I am just wondering why the program won't display JPanels (or components), in the studentPane JPanel (which is inside the the overall contentPane container), and what would be the correct method for doing so. Any help would be greatly appreciated, since I have been stuck on this problem for awhile now.

A: Don't use a null layout on your content pane. Let the content pane take all the space that is available to the frame.

I found that strings were the only thing that would show up on the studentPane.

That statement makes absolutely no sense. A String is not a Component and can't be added to a JPanel. Your code currently adds a JLabel containing the toString() representation of your panel.
The general code for dynamically adding components to a visible GUI is:
panel.add(...);
panel.revalidate(); // invoke layout manager
panel.repaint(); paint all components

By default component have a size of (0, 0), so until you invoke the layout manager, there is nothing to paint.


text:
Q: Querying Geospatial data in Athena database, getting rows in range of 5 miles from specified coordinates I have database table Building with these columns: name, lat, lng
How can I get all Buildings in range of 5 miles from specified coordinates, for example these:
-84.38653999999998
33.72024
?
https://docs.aws.amazon.com/athena/latest/ug/geospatial-functions-list.html

A: It is rather unnecessary complicated in Athena, because

*

*it only supports Geometry (i.e. planar or Cartesian) objects, but does not support Geography objects (on Earth's sphere).

*it only supports single WGS84 projection and thus does not have ST_TRANSFORM that would allow you to use other projections.

In systems that support Geography, you would just construct two geography points, and checked whether they are within 5 miles using ST_DWithin. E.g. in BigQuery:
... WHERE ST_DWithin(ST_GeogPoint(lon, lat), ST_GeogPoint(clon, clat), 5 * 1609.34)

In systems that support various projections, you would chose a suitable equidistant projection and work within it.
Athena has rather rudimentary GIS support, so you would need to either

*

*Don't use any of their geospatial functions, just use Haversine formula directly, see e.g.
https://stackoverflow.com/questions/27928/calculate-distance-between-two-latitude-longitude-points-haversine-formula, or

*if you are OK with impresize results - use Athena's ST_Distance method with suitable angular distance (but that will stretch the circle in West-East direction).

Update: Athena 2 has to_spherical_geography function that should make it much simpler.

A: The distance or radius value of the ST_BUFFER is a function of what units you are using for the geometry. If you are using a projected value, such as
EPSG:3857, Web Mercator coordinate system popularized by Google, then your value would be in meters. So 5 miles would be about 8000 meters.
But -84.38653 33.72024  are long/lat values, so they are geographic (angular) rather than geometric(planar). Maybe think slices of an orange vs a 2D x/y plane? That means that for this work you need to know what decimal degree value approximates 5 miles at your current position on the planet. That's because DD to meters varies as a function of where you are North/South or latitude. At the equator it is about 111320 meters per DD. so to get 5 miles would be about 8046.72/111320 = .072284 DD.
see:
https://en.wikipedia.org/wiki/Decimal_degrees
Try this in the Athena query editor.
SELECT ST_GEOMETRY_TO_TEXT(ST_BUFFER(ST_GEOMETRY_FROM_TEXT('POINT (-84.38653 33.72024)'),.072284))
Then past the result into something like
https://clydedacruz.github.io/openstreetmap-wkt-playground/


text:
Q: Symfony 4 Regex, find a pattern that excludes email check from url check I have a Symfony form that has fields that should let users write emails but not URLs.
I am currently using this regex:
return new Regex(
        [
            'pattern' => '((http|https|ftp|ftps)://)?([a-zA-Z0-9\-]*\.)+[a-zA-Z0-9]{2,4}(/[a-zA-Z0-9=.?&-]*)?',
            'match'   => false,
            'message' => $this->translator->trans('form.field.urlNotAllowed', ['%label%' => $label])
        ]
    );

This regex matches all URLs, but also match emails for validation.
What I want to do is excluding emails from validation and match only URLs.
My code:
/**
 * @param RegistrationFormField $field
 * @param string $key
 * @param array $validationAttributes
 * @return Regex
 */
public function getUrlNotAllowedConstraint($field, $key, &$validationAttributes)
{
    $event = $field->getRegistrationForm()->getEvent();

    $label = /** @Ignore */
    $this->translator->trans($field->getLabel(), [], 'custom') ?: $this->getDefaultLabelName($event, $key);

    $validationAttributes['data-validation'][] = 'url_not_allowed';

    return new Regex(
        [
            'pattern' => '((http|https|ftp|ftps)://)?([a-zA-Z0-9\-]*\.)+[a-zA-Z0-9]{2,4}(/[a-zA-Z0-9=.?&-]*)?',
            'match'   => false,
            'message' => $this->translator->trans('form.field.urlNotAllowed', ['%label%' => $label])
        ]
    );
}

Any help?
I have created the CustomSequentically Constraint:
namespace App\Form\Validator;

use Symfony\Component\Validator\Constraints\Composite as
ConstraintsComposite;

/**
* Use this constraint to sequentially validate nested
constraints.
* Validation for the nested constraints collection will stop at
first violation.
*
* @Annotation
* @Target({"CLASS", "PROPERTY", "METHOD", "ANNOTATION"})
*
*/
class CustomSequentially extends ConstraintsComposite
{
    public $constraints = [];

    public function getDefaultOption()
    {
        return 'constraints';
    }

    public function getRequiredOptions()
    {
        return ['constraints'];
    }

    protected function getCompositeOption()
    {
        return 'constraints';
    }

    public function getTargets()
    {
        return [self::CLASS_CONSTRAINT, self::PROPERTY_CONSTRAINT];
    }
}

And the CustomSequentiallyValidator Class:
namespace App\Form\Validator;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;

class CustomSequentiallyValidator extends ConstraintValidator
{
    /**
     * {@inheritdoc}
     */
    public function validate($value, Constraint $constraint)
    {
        if (!$constraint instanceof CustomSequentially) {
            throw new UnexpectedTypeException($constraint, CustomSequentially::class);
        }

        $context = $this->context;

        $validator = $context->getValidator()->inContext($context);

        $originalCount = $validator->getViolations()->count();

        foreach ($constraint->constraints as $c) {
            if ($originalCount !== $validator->validate($value, $c)->getViolations()->count()) {
                break;
            }
        }
    }
}

And used the constraint like this:
    $constraints = new CustomSequentially([
        'constraints' => [
             new Regex([
                'pattern' => '/((http|https|ftp|ftps):\/\/)?((?!@)[a-zA-Z0-9\-]*\.)+[a-zA-Z0-9]{2,4}(\/[a-zA-Z0-9=.?&-]*)?/',
                'match'   => false,
                'message' => $this->translator->trans('form.field.urlNotAllowed', ['%label%' => $label])
            ]),
            new Regex([
                'pattern' => '/[@]/',
                'match'   => true,
                'message' => 'It is an email'
            ]),
        ],
    ]);
    return $constraints;

Now, if I write a URL or an email both are not passing the validation(a simple text is passing).

A: This will allow any string but if it is a URL it will check with regex. If it detects a URL it will then see if it is an email address by checking if the URL contains the @ symbol and allow it.
Improve or iterate on for your needs as you see fit.
The Constraint
namespace App\Validator;

use Symfony\Component\Validator\Constraint;

class NoUrl extends Constraint
{
    public $urlMessage = 'This looks like a URL, this is not valid.';
}

The Validator
namespace App\Validator;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Exception\UnexpectedValueException;

class NoUrlValidator extends ConstraintValidator
{

    public function validate($url, Constraint $constraint)
    {
        if (!$constraint instanceof NoUrl) {
            throw new UnexpectedTypeException($constraint, NoUrl::class);
        }

        if (null === $url || '' === $url) {
            return;
        }

        if (!is_string($url)) {
            throw new UnexpectedValueException($url, 'string');
        }

        if (preg_match('/((http|https|ftp|ftps):\/\/)?([a-zA-Z0-9\-]*\.)+[a-zA-Z0-9]{2,4}(\/[a-zA-Z0-9=.?&-]*)?/', trim($url))) {
            // str_contains() is PHP 8+, use strpos() for PHP <8
            // String contains an @ symbol so just return as it must be an email address. You can add more checks if needed yourself.
            if (str_contains($url, '@')) {
                return;
            }

            $this->context->buildViolation($constraint->urlMessage)->addViolation();
        }
    }
}

In Your Form
...
use App\Validator\NoUrl;

class YourFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('yourfield', TextType::class, array(
                'constraints' => array(
                    new NoUrl()
                )
            ))
...


text:
Q: Grid search with cross validation: should I keep a separate test set? There is a lot of information on using cross validation and grid search, and there is also confusion about the test set in this situation.
I have a labeled data set that I am using to build a predictive model. I will perform a model selection across a family of models (SVC, NB, random forests, boosting etc.) and then do parameter tuning using grid search.
However, I could not find a definitive answer about whether I need to keep a separate test set for estimating out-of-sample performance.
This is my intended plan:

*

*set aside the test set (and not touch it until the very end to avoid data contamination)

*on the remaining data: perform grid search for all models and estimate their performance using k-fold cross validation

*select the best model from each family of models and test their out-of-sample performance using the test set

*report results

However, there are several challenges that I am not sure how to deal with:

*

*The data set is rather small: around 550 points for 30 variables

*The data set is noisy and I was told that I could get
significantly different results for the same exact model with the same hyper-parameters on different random splits of data
and that is a big challenge

Given these two challenges, I have three questions:

*

*Does my 4-step procedure seem right?

*How do I deal with the second challenge of inconsistent performance?

*Due to the small size of data, what should be the size of the test set and how many fold is it better to have in the cross-validation step?

A: To answer your first question: Yes, it does seem right. However, I want to mention another option:
My advice would be to split the data into three sets, even if there are not many data. One set for training, one for validation and one for testing with 50% of the data in the training data and 25% in each of the others, randomly drawn from the whole data. In your case this would mean 275 points in the training set, 138 in validation and 137 in test.
The training set will then be used to find the models. The validation set will then be used for the cross-validation. Such an out-of-sample cross validation will lessen the risk of model overfitting. Afterwards you could possibly select the best two or three models from each family. Finally, the test set will tell you how well your models generalize.
Nevertheless, the approach you described is fine as well.
Let's move to your second question. This risk is always present. The above approach with the three sets will lessen the risk a bit. However, if you want to drastically lessen the risk of finding too different models after each resampling of sets, collection of new data will be very helpful. Depending on the methods you use, it might also be helpful to look for methods which are robust against uncertainty in the data. For example, for linear regression there exist some ways to make the objective function robust against uncertainty.
If you decide to use only two sets, then I would recommend using 75% for training data and 25% for test data. Concerning the part of the third question about how many folds you should use, I want to point you to this answer here.

A: for the most part i disagree with yukiJ... please read on.
1) procedure almost OK. however, note that you can report the out of sample performance for all models. however, if you then choose the best model based on these numbers, the out of sample performance is again contaminated (you use it for learning the best model family). so I suggest you choose the best model overall using your described procedure, and use your test set then to estimate the performance of the best model. but of course it depends on your interest, are you interested in the performance of the best model (then you should take my suggestion), however if you are interested in the performance of all model families and if you do not nececarily care about the best performance, then your approach is perfect.
2 & 3) I would use nested cross validation. what does this mean?
you make folds for your dataset. lets say 10 fold cross validation. use 5 if it takes too long.
now for each fold, do the following. you construct a trainset and testset. since im telling you for the first fold, lets call them train1, and test1. so you have obtained 2 sets from the complete dataset.
now, you are going to make 10 folds in the dataset train1. so essentially, now you perform cross validation on train1 to determine the best model overall, or the best model from each model family. so in words:
use train1, and for the first fold of train1: make 2 datasets, train1_1 and test1_1 (note, train1_1 is contained in train1, and so iss test1_1). train all models on train1_1 and evaluate them all on test1_1.
then you go to the second fold, so from train1 you make two new datasets train1_2 and test1_2. (note they both are contained in train1).
do the same and evaluate on test1_2.
etc. etc.
then at the end you have evaluated them 10 times, using the dataset train1. now you find the best performing model of each model family (by averaging all test scores), or simply the best model overall (by averaging all test scores). you have to store which model performs the best on the dataset train1 ;). now you have the best performing models, you evaluate them on the still unused testset test1. (remember, test1 is NOT contained in train1).
now you repeat the same for the second fold of the complete dataset. so you form a dataset train2, test2. you again create the following datasets from train2:
train2_1, test2_1
train2_2, test2_2,
...
train2_10, test2_10,
etc. repeat the same procedure. you get the best performing models (which may be different models then you found from the dataset train1! so thats why you need to store which model(s) perform the best). once you have the best performing models, evaluate on test2.
etc. etc. repeat
so in the end, you get this 10 times:
fold 1: model X performed best with out of sample performance Z1
fold 2: model A performed best with ...                       Z2
...
fold 10: model X performed best with ....                     Z10.
using this method, you get most out of your data. why?

*

*you see if there is large variance. does the optimal model really depend on the fold, or is it always the same? in the first case the model might be overfitting on the fold. in the latter case you should be happy since the model is performing consistently good, indicating it really does generalize well!

*you get the variance of the out of sample performance of the model.

*by reusing the data in this way, you do not contaminate folds, yet you get to use your data multiple times.

*also, choosing the best model using this way is more robust, since you use averaged test scores to choose models, so in this way you also avoid overfitting during model selection.
if you get large variance numbers you should of course still watch out. you could indeed make plots of the gridsearch in the intermediate model selection steps to see whether or not model selection makes any sense, or maybe your grid is way too small or much too large.
if the variance numbers are also very nice, you can also instead of averaging them, you can do the following. lets say you have 2 models, and 4 folds:
         fold 1     fold 2     fold 3  fold 4
model A  2          3          5       2      avg: 3
model B  2.2        3.2        3       2.2    avg: 2.65

lets say that for this performance measure, higher is better.
you see on average, model A performs better (looking at the average score).
however, for 3 / 4 folds, model B performs better than model A.
thus you might say that model B was simply unlucky.
so for choosing the best model, you can also use majority voting using the test score. here B would get 3 votes (since it performs the best 3 times) and A gets 1 vote. so after this model selection step, you will select model B.
this can be useful if you have high variance. since by averaging you loose a lot of information (since model A and B use the same folds in each cross val step - pay attention that you do use the same folds!) if you use the same folds in each step, you can directly compare these numbers (fold1, fold2).
to reduce variance, you can repeat the whole above procedure again. simply choose new random cross validation folds, and repeat everything. then you can also get a better idea of whether or not your results are robust.
3) typically, more folds are better, but they are a big computational burden, thats why people typically use only 5 or 10 folds. keep in mind with my above described procedure it will take 100 train + test sets! (10 x 10 = 100).
there is one downside. if you use more folds, variance of your performance on the test set will increase. since the test set is smaller, you average over less samples. however, at least when you have more folds your training set is bigger, and the model will typically perform better (or closer to the performance you would get if you would use all samples for training).
in the end what matters most is your preference. do you want an accurate estimate of the generalization performance? use less folds, big test sets, your estimate will be closer to the real number. however, the bigger your test set, the worse your model will perform since you have less training samples. so you are not reaching your full potential. so instead, i suggest my method, where you have small test sets, but you average performance of the test sets ;).
if I were you, I would look into how to run your computations in parallel, since it will save you a lot of time. at least be sure to save your results during the process if it takes long, so if you have a crash you do not have to start from scratch.
i did not have a lot of time writing and formatting my answer, please forgive me. if anything is unclear let me know and i will get back to you.
PS: for your case I would use a fairly complex model (assuming classification) I would go for KNN (1 parameter) or SVM with RBF kernel (2 parameters). for regression, perhaps looking into robust regression makes sense, but it depends on your performance measure. lets say you measure performance using MSE, I would simply use regular linear regression plus regularization (L2, L1) and perhaps a kernel (polynomial, RBF).


text:
Q: Ask siri to set alarm silently? Is it possible to set an alarm with my voice to siri, receive confirmation, but not have her speak back?
Is there a technique I can use to do this with all commands?

A: Settings > Siri & Search > Voice Feedback
Your choices are :-

*

*Always On

*Control with Ring Switch

*Hands-Free Only
So really to prevent her answering, you'd need the 2nd option & the ring switch off.
The info in the pref itself says this will only work if you don't use Hey Siri - you will have to use the double-click to wake her.
The alternative is to turn the ringer right down, Siri volume is tied to that. I haven't tested how that will affect an alarm though. It might be somewhat self-defeating.


text:
Q: How to count the vehicles if boundingRect touch the line Below is the code i am trying:
    def mouse_drawing(event, x, y, flags, params):
    global point1, point2, drawing
    if event == cv2.EVENT_LBUTTONDOWN:
        if drawing is False:
            drawing = True
            point1 = (x, y)
        else:
            drawing = False
    elif event == cv2.EVENT_MOUSEMOVE:
        if drawing is True:
            point2 = (x, y)

    cap = cv2.VideoCapture("new2.asf")
    cv2.namedWindow("App", cv2.WINDOW_FREERATIO)
    cv2.setMouseCallback("App", mouse_drawing)
    fgbg = cv2.createBackgroundSubtractorMOG2()
    kernel = np.ones((5, 5), np.uint8)

while True:
    ret, frame = cap.read()
    frame = cv2.resize(frame,None,fx=scaling_factorx,fy=scaling_factory,interpolation=cv2.INTER_AREA)
    imgray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
    fgmask1 = cv2.GaussianBlur(imgray, (7,7), 0)

    fgmask = fgbg.apply(fgmask1)

    if point1 and point2:
        cv2.line(frame, point1, point2, (0, 255, 0), 3)

    contours, hierarchy = cv2.findContours(fgmask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    try:
        hierarchy = hierarchy[0]
    except:
        hierarchy = []

    for contour, hier in zip(contours, hierarchy):
        (x, y, w, h) = cv2.boundingRect(contour)
        if w > 80 and h > 80:
            cv2.rectangle(frame, (x,y), (x+w,y+h), (0, 255, 0), 2)

    cv2.imshow("App", frame)

How to write a image of a vehicle with cv2.imwrite which is reached the line, the line which is drawn as manually.  And  the vehicles are having the rectangular boxes that's fine But some vehicles having more than one box. One vehicle should be have only one rectangular box. And that should be saved if reached the line, rest of vehicles should not to be saved. Please let me know the solution.

A: First, you need to group intersecting rectangles into one.

*

*You do so by checking the intersection area between each pair of rectangles.

*If the intersection area is larger than a pre-defined heuristic ratio of the small rectangle area then the smaller rectangle should be removed. For example, intersection_area / smaller_rect_area > 0.75

*Please check this answer for the rectangles intersection.

Second, to check that a rectangle has passed the line:

*

*Use your points to find the parameters for the general line formula: ax + by + c = 0

*For each frame, plug the rectangle center coordinates in the formula and keep track of the sign of the result.

*If the sign of the result changes that means that the rectangle center has passed the line.


text:
Q: How do I add an "add Image" button to the right side of my Gallery view? I have used the Gallery widget to display a set of pictures, but would like to add an image at the end with an OnClickListener that will allow me to add further images to my list.
How can I add something to the right side of a Gallery View?
Will putting the Gallery and a button inside a HorizontalScrollView work?  Or is there a better way to do this?

A: One way I see doing this:
In your adapter you should override the method getCount() and set it so that it return the number of images you wish to display + 1.
In your getView/bindView/newView (depending on which adapter you used) you should check to see if the position you are inflating is == getCount() - 1. if so, you should inflate a view that contains your "Add new image" button. Then you just need to attach your onClick listener to that button and handle the insertion of new images

A:
Will putting the Gallery and a button inside a HorizontalScrollView work? Or is there a better way to do this?

*

*probably not. There is no way for the views to differentiate which touch events should go to the gallery and which to the HorizontalScrollView.

You need to set your Gallery width to be something less than FILL_PARENT, then you can put the ImageButton to the right of it with android:layout_toRightOf="@id/galleryId"
That way both will be on the screen, the "add" button will always be shown and the gallery will be able to scroll to reveal all of the images that are contained in it.


text:
Q: Reset Windows Spotlight I am using Windows Spotlight on the lock screen of my Windows 10 laptop, and I have accidently liked some photos, and the keep coming up. is there a way to 'change your mind' about a photo, or just reset the whole thing?

A: I was also frustrated by this very same issue with the Windows Spotlight Lockscreen image on Windows 10.
Being unable to "change your mind" after having previously selected either "I want more" or "Not a fan" is a real pain. I've described below what worked for me. It may not be a full solution, especially if Microsoft change the way Spotlight works, but for now it seems to be a good enough work around.
WARNING: This involves changing values in the Windows Registry so be warned that it is generally considered a dangerous practice if you're not sure of what you're doing. Proceed at your own risk. Don't hold me liable if you break your machine.
The basic idea is that the current lockscreen image is stored at the following registry path:
HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Lock Screen\Creative

*

*Open the Windows Registry

*Follow the registry path:
HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Lock Screen\Creative

*Find the key "CreativeJson" and double click on it. The 'Edit String' dialog will open.

*

*Go to the 'Value data' field. It contains a rather long json string with parameters affecting how the lockscreen image operates.

*Start scrolling through the json string from the very left and you'll find a lot of key-value pairs in there including: "creativeId", "placementId", "impressionToken" among others. (These are not very useful for what we need, but i've pointed them out just as a check-point to see if you're on the right track)

*The important ones for this process start approaching when you see "onHover", "onPositiveFeedback", "onNegativeFeedback" and the one that will solve our problems 'feedbackProvided'.

*If you've previously given feedback it will have  value of "true". If you have not it will be "false". So in our case where we want to change the decision we made, it should already read "true", so it will involve changing the value from "true" to "false".

*Change this particular value and it should read now "feedbackProvided":false (NB: Don't change anything else. The entire rest of the string should remain the same)

*Once you've done this click "Ok" and you can close the registry.

*If you lock your screen now the current image should now allow you to make a choice again.

Note: As this registry path holds the settings for the current lock screen image, several parameters will obviously change when the Windows decides to change the lock screen for you. I think among these many parameters they have some sort of "Time-to-Live" for the current lockscreen.
Note2: The location of where the images are stored is also found at the registry path mentioned above, but at the Registry Key "HotspotImageFolderPath". On most Win 10 machines at the moment, the default should be:
C:\Users\[USERNAME]\AppData\Local\Packages\Microsoft.Windows.ContentDeliveryManager_cw5n1h2txyewy\ LocalState\Assets
Update: Here is a Powershell script to update the feedback flag:
$creativeJson = (Get-ItemProperty 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Lock Screen\Creative').CreativeJson | ConvertFrom-Json
$creativeJson.cdm.feedbackEvents.feedbackProvided = $false
New-ItemProperty -Path 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Lock Screen\Creative' -Name CreativeJson -Value ($creativeJson | ConvertTo-Json -Depth 100 -Compress) -Force

A: I just encountered the same issue as described by Blazinator. And note: This is after having previously been able to view and edit the string..
However I can inform that THE STRING IS ACTUALLY THERE! It is just invisible, for some reason: But you can highlight and copy it: Here's how:

*

*Press the [home] key to place the cursor at the start of the string.

*then press both the [shift] + [end] keys to highlight the whole
string (you can't see it's highlighted but it is).

*Press [ctrl]+[c] (or right-click and select "copy" from the menu").

Then you can paste the whole string to notepad and edit it there (Note: It'll be a good idea to de-select Word Wrap in the "Format" menu, or it might spur in some carriage return chars). And when done editing then copy and paste the whole string back (make sure to overwrite or delete the original (invisible) content).
In response to the original post, however: The "feedbackProvided" part of the string, reads "false" even though I have clicked the "like".. So my alternative solution for now is to simply replace the image file with a different image of the same filename. - Here's how:

*

*Find the image file in the folder specified in Note 2 above and
copy it to a convenient location.

*The images are .jfif format; simply add .jfif as extension and open
with some graphics program. (Tip: if you copy all the images and add
the .jfif extension to them all then you can easily spot which one
it is).

*Then paste a different image over it and save.

*Then remove the .jfif extension again, and copy it back to the
images folder, thus overwriting the original file.

That'll work too.


text:
Q: skypeforlinux Ubuntu package says File has unexpected size (2471 != 2457). Mirror sync in Progress? When I am running apt get update in Ubuntu mate 18.04 the following things happens
Err:10 https://repo.skype.com/deb stable/main amd64 Packages
File has unexpected size (2248 != 2481). Mirror sync in progress? [IP: 104.89.123.202 443]
Hashes of expected file:
 - Filesize:2481 [weak]
 - SHA512:97a1cc8c9c71d68e35b37c9ef33a85859bbabb482b482a71c70d657cc9464210fce0a1afda11dd5c8275071b60291324dac9b0a39979542cef326a14e09be5fc
 - SHA256:27a18eb994515c58706b3516b1430d5cdb4a3030fc95fc4c17a6e712f00f808b
 - SHA1:8dedefb9caea4b2f69fac16419494805e8c87a76 [weak]
 - MD5Sum:67e1b981d511902b109dc6bfd54ce30d [weak]
Release file created at: Mon, 24 Sep 2018 12:21:19 +0000

And the following when reading the packages.
Reading package lists... Done
E: Failed to fetch https://repo.skype.com/deb/dists/stable/main/binary-amd64/Packages.bz2  File has unexpected size (2471 != 2457). Mirror sync in progress? [IP: 23.58.225.224 443]
   Hashes of expected file:
    - Filesize:2457 [weak]
    - SHA512:58f0d8f3255a5cc7f28a3a1270ff655e187c9cae212391a570b6c3512c20852549a0f706c9df7ccd1be7cc3ce791547c2c6dcdf44021425756c1d824995be14a
    - SHA256:bcd5e58ed12bf52cd8a16d947b9209f4292d339dc11898f8ebe501106b5dc311
    - SHA1:d534917678932e9320d80da96c4f1b2c6dbf478c [weak]
    - MD5Sum:2a9e2b845f1b29d8ee10ec10de46686d [weak]
   Release file created at: Mon, 24 Sep 2018 11:56:19 +0000
E: Some index files failed to download. They have been ignored, or old ones used instead.

From here I can see the problem is in skypeforlinux package, but I can't find a way to solve it.

A: Deleting the skype repository list using worked for me:
rm -rf /etc/apt/sources.list.d/skype-stable.list*

It was automatically installed when unpacking official deb obtained from https://www.skype.com/en/get-skype. You don't need to remove skype application though.


text:
Q: Protocols: Why is @ObjC required for conformance checking and optional requirements? The Swift documentation says the following about protocols:

You can check for protocol conformance only if your protocol is marked
  with the @objc attribute, as seen for the HasArea protocol above. This
  attribute indicates that the protocol should be exposed to Objective-C
  code and is described in Using Swift with Cocoa and Objective-C. Even
  if you are not interoperating with Objective-C, you need to mark your
  protocols with the @objc attribute if you want to be able to check for
  protocol conformance.
Note also that @objc protocols can be adopted only by classes, and not
  by structures or enumerations. If you mark your protocol as @objc in
  order to check for conformance, you will be able to apply that
  protocol only to class types.

and

Optional protocol requirements can only be specified if your protocol
  is marked with the @objc attribute. Even if you are not interoperating
  with Objective-C, you need to mark your protocols with the @objc
  attribute if you want to specify optional requirements.
Note also that @objc protocols can be adopted only by classes, and not
  by structures or enumerations. If you mark your protocol as @objc in
  order to specify optional requirements, you will only be able to apply
  that protocol to class types.

Why cannot pure Swift protocols (non-@objc) be checked for conformance. Why don't they have optional requirements? Can anybody guess the underlying language design reason?
I expect that at some undetermined (probably far away) time in the future Apple will slowly reimplement and replace Cocoa and CocoaTouch with libraries programmed purely in Swift. At that time, if we wan't to avoid using any Obj-C related stuff, should we avoid using optional protocol requirements and protocol checks conformance in our code?
If so, what's Swift's idiomatic way of achieving similar patterns without using @objc? (E.g., a delegate with optional methods.)

For example, this simple use case cannot be implemented with non-@objc protocols (and Printable, DebugPrintable and Streamable are non-@objc:
import UIKit

let firstName = "John"
let lastName = "Appleseed"
let age = 33
let height = 1.74

let values: [Any] = [firstName, lastName, age, height]
let stringifiedValues = [String]()

for value in values
{
    if let pritanbleValue = value as? Printable
    {
        stringifiedValues.append(value.description)
    }
    else if let debugPrintableValue = value as? DebugPrintable
    {
        stringifiedValues.append(value.debugDescription)
    }
    else if let streamableValue = value as? Streamable
    {
        var string = ""
        streamableValue.writeTo(&string)
        stringifiedValues.append(string)
    }
    // etc.
    else
    {
        stringifiedValues.append("[NoStringRepresentation]")
    }
}

A: Swift probably does not include enough runtime type information to check for protocol conformance. Protocols are really only a compile-time thing, and ObjC includes extra tables in the built product that aren't strictly necessary for running the program to allow determining conformance. Since @objc has to turn a class/protocol into something that ObjC understands, objects declared with this attribute get the additional metadata and probably other adapter data structures so ObjC won't notice they're not real ObjC.
The recommendation from Apple in ObjC has always been to check for the presence of individual methods, and not to look at the class or protocol, to permit duck typing and enable use of proxy objects. My guess is that this is the reason why the designers of Swift felt it was OK to leave out protocol runtime data in the default case, to encourage proper detection of features of a class.
As to how to use it: For the case of a protocol you're apparently supposed to use the ? operator (which checks both whether the object exists and that it implements the given method). I don't know if the same works for system API, but given it's an ObjC class in that case, you can just call foo.respondsToSelector("doFoo:").

A: jckarter, an Apple employee, said the following on an Apple Developer Forums' thread:

This is a limitation of Swift's runtime. We intend to remove this restriction in a future release.


text:
Q: Is there a way to bet more than 9999 medals? In the coliseum, you can bet on monster fights.
With the results of your bets, you can get an engine that does not consume gas (giving infinite gas)
Thing is, that engine is 3.7 million medals (from memory, can't see the exact number), so even if you bet and win the max amount every time, it's gonna be a while. The counter only has 4 digits, making the max bet 9999 medals.
Is there a way to upgrade and make bigger bets and advance faster?

A: There's no way to bet more than 9999 medals at a time.
You simply have to grind through the colosseum a lot in order to get the rewards you want.


text:
Q: Change Website Overall Size On HTML or CSS, how can I change the overall website size? When I use CTRL+WheelDown to 80% on the browser, it looks perfect but how can I do this on HTML or CSS files to make it default?

A: You can do this with CSS:
html{ zoom: 80%; }

A: 1.You can use CSS attributes such as height-size and width-size. You can make a class with these attributes with values in percentage or pixels (your choice). Later use this class in div to apply conditions to content in division block.
2.You can also use Bootstrap. As it has a responsive class which makes it easier and efficient.


text:
Q: Android ListView is not scrolling I have one ListView in  the tabhost. Everything works fine but the ListView doesn't scroll properly.
Here's my XML Layout:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<!-- As the main content view, the view below consumes the entire
     space available using match_parent in both dimensions. -->
<FrameLayout
    android:id="@+id/content_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

   <TabHost
    android:id="@+id/tabhost"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >
        </TabWidget>

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <LinearLayout
                android:id="@+id/liner"
                android:layout_marginTop="50dp"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical" >

                <ListView
                    android:layout_width="match_parent"
                    android:id="@+id/listView11"
                    android:layout_height="wrap_content" />

            </LinearLayout>

        </FrameLayout>

    </LinearLayout>
</TabHost>

</FrameLayout>

<ListView
    android:id="@+id/left_drawer"
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:choiceMode="singleChoice"
    android:divider="@android:color/transparent"
    android:dividerHeight="0dp"
    android:background="#111"/>

Here's the JAVA class:
    public  class NotFragment extends Fragment {
    MyCustomAdapter myAdapter = new MyCustomAdapter();
    ListView listView;
    public static final String SecimId = "planet_number";

    public NotFragment() {
        // Empty constructor required for fragment subclasses
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        final View rootView = inflater.inflate(R.layout.yemeklistesi, container, false);
        int secim = getArguments().getInt(SecimId);
        String Title = Gunler[secim];
     // get the listview
        TabHost mytabhost =(TabHost) rootView.findViewById(R.id.tabhost);
        mytabhost.setup();
        //listView = (ListView)rootView.findViewById(R.id.listInclude);
        TabSpec spec;
        spec = mytabhost.newTabSpec("yemekhane");
        spec.setContent(R.id.liner);
        spec.setIndicator("Yemekhane");
        listView = (ListView)findViewById(R.id.listView11);
        prepareData("Yemekhane");
        mytabhost.addTab(spec);
        mytabhost.addTab(mytabhost.newTabSpec("sosyaltesisler").setIndicator("Sosyal Tesisler").setContent(R.id.liner));
        mytabhost.addTab(mytabhost.newTabSpec("turuncusalon").setIndicator("Turuncu Salon").setContent(R.id.liner));

        // Listview Group click listener
        mytabhost.setOnTabChangedListener(new OnTabChangeListener() {

            @Override
            public void onTabChanged(String tabId) {
                // TODO Auto-generated method stub

                if(tabId=="sosyaltesisler"){
                    prepareData("Sosyal Tesisler");
                }else if(tabId=="yemekhane"){
                    prepareData("Yemekhane");
                }else if(tabId=="turuncusalon"){
                    prepareData("Turuncu Salon");
                }
            }
        });
        getActivity().setTitle(Title);
        return rootView;
    }
    private void prepareData(String Birim) {
        // TODO Auto-generated method stub
        int gunId = getArguments().getInt(SecimId);
        List<String> liste = new ArrayList<String>();
        for(int i = 0; i<yemek.length;i++){
            if(yemek[i].getBirim().compareTo(Birim)==0 && yemek[i].getGun().compareTo(Gunler[gunId]) ==0 ){
                liste.add(yemek[i].getAd()+"-"+yemek[i].getOgunAdi());
            }
    }
        Menu = new String[liste.size()];
        liste.toArray(Menu);
        myAdapter = new MyCustomAdapter();
        for(int i=0;i<Menu.length;i++){
            if(myAdapter.checkSeparator(Menu[i].split("-")[1])){
                myAdapter.addSeparatorItem(Menu[i].split("-")[1]);
            }
            myAdapter.addItem(Menu[i].split("-")[0]);
        }
        listView.setAdapter(myAdapter);

   }
}`

And my CustomAdapter:
private class MyCustomAdapter extends BaseAdapter {

    private static final int TYPE_ITEM = 0;
    private static final int TYPE_SEPARATOR = 1;
    private static final int TYPE_MAX_COUNT = TYPE_SEPARATOR + 1;

    private ArrayList<String> mData = new ArrayList<String>();
    private LayoutInflater mInflater;

    private TreeSet<Integer> mSeparatorsSet = new TreeSet<Integer>();

    public MyCustomAdapter() {
        mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public void addItem(final String item) {
        mData.add(item);
        notifyDataSetChanged();
    }

    public void addSeparatorItem(final String item) {
        mData.add(item);
        // save separator position
        mSeparatorsSet.add(mData.size() - 1);
        notifyDataSetChanged();
    }

    @Override
    public int getItemViewType(int position) {
        return mSeparatorsSet.contains(position) ? TYPE_SEPARATOR : TYPE_ITEM;
    }

    @Override
    public int getViewTypeCount() {
        return TYPE_MAX_COUNT;
    }

    public int getCount() {
        return mData.size();
    }

    public String getItem(int position) {
        return mData.get(position);
    }
    public boolean checkSeparator(String Separator){
        for(int i=0;i<getCount();i++){
            int type = getItemViewType(i);
            if(type ==TYPE_SEPARATOR && getItem(i).compareTo(Separator)==0){
                return false;
            }
        }
        return true;
    }
    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        int type = getItemViewType(position);
        System.out.println("getView " + position + " " + convertView + " type = " + type);
        if (convertView == null) {
            holder = new ViewHolder();
            switch (type) {
                case TYPE_ITEM:
                    convertView = mInflater.inflate(R.layout.item1, null);
                    holder.textView = (TextView)convertView.findViewById(R.id.text);
                    break;
                case TYPE_SEPARATOR:
                    convertView = mInflater.inflate(R.layout.item2, null);
                    holder.textView = (TextView)convertView.findViewById(R.id.textSeparator);
                    break;
            }
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder)convertView.getTag();
        }
        holder.textView.setText(mData.get(position));
        return convertView;
    }`enter code here`

}

`
Can someone please give me an advice?


text:
Q: Обьединить два DeleteByQueryRequestBuilder в один Можно ли, используя Java API, совместить два запроса на удаление?
Пробую сделать так:
DeleteByQueryRequestBuilder requestBuilder = new DeleteByQueryRequestBuilder(client.getClient(), DeleteByQueryAction.INSTANCE)
    .setQuery(QueryBuilders.boolQuery().must(matchQuery("leftId", leftId())).must(matchQuery("rightId", rightId())))
    .setQuery(QueryBuilders.boolQuery().must(matchQuery("leftId", rightId())).must(matchQuery("rightId", leftId())));

requestBuilder.get();

Но выполняется только один запрос - последний запрос.

A: Нет нельзя, в билдере один запрос перетирается на другой, из за этого и выполняется последний.


text:
Q: Using postMessage to extension background page I'm trying to send a CryptoKey (generated by SubtleCrypto.generateKey()) object from a contentscript to the background page of a webextension.
When using chrome.runtime.sendMessage to send the object, it is lost, as CryptoKey is not stringifyable (see also this question). Using window.postMessage to transfer the key to another window does work, as this method uses structured cloning..
Is there something similar to postMessage to send data that is not stringifyable to the background page of a webextension?

A: Thanks to the comment by @wOxxOm I solved it by creating a web accessible resource with this code:
window.addEventListener("message", receiveMessage, false);

function receiveMessage(event) {
  chrome.extension.getBackgroundPage().postMessage(event.data, "*");
}

This is triggered by the contentscript like that:
let iframe = document.createElement('iframe');
iframe.setAttribute('src', chrome.extension.getURL('webaccessible/index.html'));
iframe.addEventListener("load", () => {
  iframe.contentWindow.postMessage(data);
})

While data is an object that contains the CryptoKey.
This data is received in the background script just like you normally would receive such messages:
window.addEventListener('message',(event) => {
  console.log(event);
});


text:
Q: How can I compare elements from a list of lists in Python I have a list of lists of strings and I would like to obtain the largest string on each inner list and store them into another list. For example:
tableData = [['apples','bananas','oranges','cherries'],
            ['Alice','Bob','Carol','David'],
            ['dogs','cats','moose','goose']]

widths = [0] * len(tableData)

I want to store in widths[0], the width of the longest string in tableData[0], in widths[1] the width of the longest string in tableData[1], and so on. How can I compare the length of the words in order to get the greater?
The only way I thought is doing this:
for f in range(len(tableData)):
    for c in range(len(tableData[1])):
        max = len(tableData[f][c])
        if max < len(tableData[f][c+1]):
            max = len(tableData[f][c+1])
    widths[f] = max

A: widths = [len(max(lst, key=len)) for lst in tableData]

For your list of lists called tableData, this gives:
[8, 5, 5]

Explanation:
[max(lst, key=len) for x in tableData] gives you a list containing the longest string of each nested list. Using len(), one then obtains the lengths of these.
The same result can be achieved using:
widths = [len(sorted(lst, key=len)[-1]) for lst in tableData]

Where sorted(lst, key=len) will sort the elements of each list by length, from shortest to longest. Using [-1] one can then obtain the last value of each list, i.e. the longest strings. len()will then compute their lengths.

A: Don't worry about initializing widths. List comprehensions are your friends here.
# creates a list of lists of word lengths
lengths_of_words = [[len(word) for word in x] for x in tableData]

# finds the max length for each list
widths = [max(y) for y in lengths_of_words]

Could also be shortened to
widths = [max([len(word) for word in x]) for x in tableData]

This is the old, incorrect answer if people would like to learn from my mistake:
widths = [len(max(x)) for x in tableData]


text:
Q: KeyError: How to exclude certain parts when a part of the serializer is empty I have this piece in my serializer which is using a nested serializer field. When i try to submit my form it will return a KeyError if I don't add anything inside "assigned facilities". I tried adding an else statement but that doesn't seem to be helping. The debugger is actually complaining about line two when the field is empty so how do i exclude it when there is no data submited in assigned_facilities field? I`m already using required=False, allow_null=True inside the serializer.
    def create(self, validated_data):
        assigned_facilities = validated_data.pop("assigned_facilities")
        instance = Lead.objects.create(**validated_data)

        for item in assigned_facilities:
            instance.leadfacility.create(**item)

        else:
            print("No Facilities Added!")

        return instance

A: You can add default value in pop function, so it wont raise keyerror
    def create(self, validated_data):
        assigned_facilities = validated_data.pop("assigned_facilities", [])
        instance = Lead.objects.create(**validated_data)

        for item in assigned_facilities:
            instance.leadfacility.create(**item)

        else:
            print("No Facilities Added!")

        return instance


text:
Q: Migrating from Webpack 1.x to 2.x In Webpack 1.x I used to do the following on regular basis:
require.ensure([ './mod2.js' ], ( require ) => {
    setTimeout(() => {
        // some later point in time, most likely through any kind of event
        var data = require( './mod2.js' ); // actual evaluating the code
    },1100);
}, 'myModule2');

With this technique, we were able to transfer a webpack-bundle over the wire, but evaluate the actual contents (the JavaScript code) from that bundle at some later point in time. Also, using require.ensure we could name the bundle, in this case myModule2, so we could see the name / alias when bundling happened executing webpack.
In Webpack 2.x, the new way to go is using System.import. While I love receiving a Promise object now, I have two issues with that style. The equivalent of the above code would look like:
System.import( './mod2.js' ).then( MOD2 => {
    // bundle was transferred AND evaluated at this point
});

*

*How can we split the transfer and the evaluation now?

*How can we still name the bundle?

The Webpack documentation on Github says the following:

Full dynamic requires now fail by default
A dependency with only an expression (i. e. require(expr)) will now
  create an empty context instead of an context of the complete
  directory.
Best refactor this code as it won't work with ES6 Modules. If this is
  not possible you can use the ContextReplacementPlugin to hint the
  compiler to the correct resolving.

I'm not sure if that plays a role in this case. They also talk about code splitting in there, but it's pretty briefly and they don't mention any of the "issues" or how to workaround.

A: tl;dr: System.resolve and System.register do most of what you want. The rest of this answer is why require.ensure cannot and how System.import calls the others.
I think ES6 modules prevent this for working well, although following it through the relevants specs is tricky, so I may be totally wrong.
That said, let's start with a few references:

*

*the WhatWG module loader

*the ES6 specification on modules (§15.2)

*the CommonJS module specification

*the fantastic 2ality article on ES6 modules
The first reference explains more behavior, although I'm not entirely sure how normatize it is. The latter explains the implementation details on the JS side. Since no platforms implement this yet, I don't have references for how it actually work in real life, and we'll have to rely on the spec.
The require that has been available in webpack 1.x is a mashup of the CommonJS and AMD requires. The CommonJS side of that is described in ref#3, specifically the "Module Context" section. Nowhere does that mention require.ensure, nor does the AMD "specification" (such as it is), so this is purely an invention of webpack. That is, the feature was never real, in the sense of being specified somewhere official and fancy looking.
That said, I think require.ensure conflicts with ES6 modules. Calling System.import should invoke the import method from a Loader object. The relevant section in ref#2 does not lay that out explicitly, but §10.1 does mention attaching a loader to System.
The Loader.prototype.import method is not terribly involved, and step 4 is the only one that interests us:

*Return the result of transforming Resolve(loader, name, referrer) with a fulfillment handler that, when called with argument key, runs the following steps:

*

*Let entry be EnsureRegistered(loader, key).

*Return the result of transforming LoadModule(entry, "instantiate") with a fulfillment handler that, when called, runs the following steps:

*

*Return EnsureEvaluated(entry).

The flow is resolve-register-load-evaluate, and you want to break between load and evaluate. Note, however, that the load stage calls LoadModule with stage set to "instantiate". That implies and probably requires the module has already been translated via RequestTranslate, which does much of the heavy parsing as it tries to find the module's entry point and so on.
This has already done more work than you want, from the sounds of it. Since the basics of module loading require a known entry point, I don't think there's a way to avoid parsing and partially evaluating the module with the calls exposed from System. You already knew that.
The problem is that System.import can't possibly know -- until after parsing -- whether the module is an ES6 module that must be evaluated or a webpack bundle that could be deferred. The parsing must be done to figure out if we need to parse, leading to a chicken-and-egg problem.
Up to this point, we've been following the path from System.import through the Loader. The import call is dictating what stage of import we're at, assuming you want to go through the full end-to-end loading process. The underlying calls, like Loader.prototype.load, provide fine grained control over those stages.
I'm not sure how you would invoke the first two stages (fetch and translate), but if you were able to translate and register a module, later calls should simply evaluate and return it.
If the spec is accurate, this should be exposed (in supporting implementations) through the System.loader property and would have the methods you need to call. There are large parts of the flow you don't have access to, so I would suggest not doing this and instead setting up your code so nothing significant runs when a module is loaded. If that's not possible, you need to recreate the flow up through registering but stop shy of evaluation.


text:
Q: process.env vs app.get('env') on getting the express.js environment So, in my node.js 5.2.0 / express.js 4.2.0 I can do
if (app.get('env') === 'development') {
  app.use(//etc

or
var env = process.env.NODE_ENV || 'development';
if (env === 'development') {
  app.use(//etc

So process.env.NODE_ENV and app.get('env') both get the environment's value. Is there any significant difference besides the syntax?
Thanks

A: There is no significant difference.
Express app.get('env') returns 'development' if NODE_ENV is not defined. So you don't need the line to test its existence and set default.


text:
Q: Yarn module not found: when I execute yarn mix in my project, i got this error:
ERROR in ./resources/js/app.js 1:0-22
Module not found: Error: Can't resolve './bootstrap' in '/Users/xxx/Sites/localhost/xxx/resources/js'

The bootstrap folder exists. Does anyone know what's wrong?
App.js:
require('./bootstrap');

import Alpine from 'alpinejs';

window.Alpine = Alpine;

Alpine.start();


text:
Q: Trouble with data merge I'm having a hard time getting data from my code into the template using the c# library.
I have a template setup that I added a text box to using the online template edit tool.  I'm trying to update the value of that text box with it's Data Label.  Could I get a c# example of this?
This is the snippet from my current code:
Text name = new Text();
name.TabLabel = "Data Label";
name.Value = "My Name";
tRole.Tabs = new EnvelopeRecipientTabs();
tRole.Tabs.TextTabs = new List<Text>();
tRole.Tabs.TextTabs.Add(name);

List<TemplateRole> rolesList = new List<TemplateRole>() { tRole };
envDef.TemplateRoles = rolesList;

I have tried some of the comments and questions and this is what I have now:
C#
//define signer
TemplateRole signer1 = new TemplateRole();
signer1.Name = "John Doe";
signer1.Email = "BOB@AOL.COM";
signer1.RoleName = "Owner";

//populate envelope object
EnvelopeDefinition envelopeDefinition = new EnvelopeDefinition();
envelopeDefinition.TemplateId = "bd417d79-2a0b-4d76-8970-e2d18451c2f5";
envelopeDefinition.Status = "created";
envelopeDefinition.EmailSubject = "eSign";

//create text tab object
Text text1 = new Text();
text1.TabLabel = "FullName";
text1.Value = "EP";

//apply tab to signer
signer1.Tabs = new Tabs();
signer1.Tabs.TextTabs = new List<Text>();
signer1.Tabs.TextTabs.Add(text1);

//apply signer
List<TemplateRole> templateroles = new List<TemplateRole>() { signer1 };
envelopeDefinition.TemplateRoles = templateroles;

// execute it
EnvelopesApi envelopesApi = new EnvelopesApi();
EnvelopeSummary envelopeSummary = await envelopesApi.CreateEnvelopeAsync(account.accountId, envelopeDefinition);
return envelopeSummary.EnvelopeId;

JSON
POST https://demo.docusign.net:7801/restapi/v2/accounts/4794997/envelopes

TraceToken: fe59bc72-61f3-4c07-9eeb-0d53d558437a
Timestamp: 2018-05-21T18:36:48.4260253Z

Content-Length: 255
Content-Type: application/json
Connection: Keep-Alive
Accept: application/json
Host: demo.docusign.net
X-DocuSign-SDK: C#
X-DocuSign-Authentication: {"Username":"[omitted]", "Password":"[omitted]", "IntegratorKey":"[omitted]"}
x-ms-request-root-id: dba2cd44-40b5e3581ae1a62d
x-ms-request-id: |dba2cd44-40b5e3581ae1a62d.2.
Request-Id: |dba2cd44-40b5e3581ae1a62d.2.
X-SecurityProtocol-Version: TLSv1.2
X-SecurityProtocol-CipherSuite: ECDHE-RSA-AES256-GCM-SHA384
x-forwarded-for: 24.1.74.183

{"emailSubject":"eSign With Payment From API","status":"created","templateId":"bd417d79-2a0b-4d76-8970-e2d18451c2f5","templateRoles":[{"email":"BOB@AOL.COM","name":"John Doe","roleName":"Owner","tabs":{"textTabs":[{"tabLabel":"FullName","value":"EP"}]}}]}
201 Created
Content-Type: application/json; charset=utf-8
X-DocuSign-TraceToken: fe59bc72-61f3-4c07-9eeb-0d53d558437a

{
  "envelopeId": "13fb444c-79cc-43bb-b6d4-3a6241c84ebc",
  "uri": "/envelopes/13fb444c-79cc-43bb-b6d4-3a6241c84ebc",
  "statusDateTime": "2018-05-21T18:36:46.9570000Z",
  "status": "created"
}

Data Label https://i.stack.imgur.com/Lo1dx.jpg
Recipient https://i.stack.imgur.com/ZtrNH.jpg

A: The name.TabLabel property needs to exactly match the label used in your template. So, for example, if your tag was set up like this:

you would use name.TabLabel = "Text1";. Setting name.Value = "My Name"; would then populate that tag with 'My Name', assuming your template is being referenced and your signer is mapped to the template role.
Code sample for sending from a template with tags populated follows. This assumes the signer role name is "Signer 1" and the tag label is "Text 1"
        //define signer
        TemplateRole signer1 = new TemplateRole();
        signer1.Name = "Example User";
        signer1.Email = "user@example.com";
        signer1.RoleName = "Signer 1";

        //populate envelope object
        EnvelopeDefinition envelopeDefinition = new EnvelopeDefinition();
        envelopeDefinition.TemplateId = "xxx-yyy-zzz"; // Replace with template ID
        envelopeDefinition.Status = "created"; //generates draft instead of immediately sending

        //create text tab object
        Text text1 = new DocuSign.eSign.Model.Text();
        text1.TabLabel = "Text1";
        text1.Value = "Example Text";

        //apply tab to signer
        signer1.Tabs = new Tabs();
        signer1.Tabs.TextTabs = new List<DocuSign.eSign.Model.Text>();
        signer1.Tabs.TextTabs.Add(text1);

        //apply signer
        List<TemplateRole> templateroles = new List<TemplateRole>() { signer1 };
        envelopeDefinition.TemplateRoles = templateroles;

        //create EnvelopesApi object
        EnvelopesApi template = new EnvelopesApi(apiClient.Configuration);

        //execute envelope generation
        EnvelopeSummary response = template.CreateEnvelope(accountId, envelopeDefinition);

A: You are creating envelope in the created status, and Signer will not be able to see the dataLabel value for a draft envelope as Signer does not have access to the envelope for a draft envelope. You need to create/update envelope with the sent status, once Signer starts the signing ceremony then he/she will be seeing the pre-populated text tab value.


text:
Q: Failing ant.junit in gradle build I'm writing a Gradle task that delegates to ant.junit. (Yes, this is what I want to do).
I can't get the build to fail when the tests fail.
// this will fail
task breakit << {
    ant.property(name: "broken", value: "!")
    ant.fail(if: 'broken')
}

// this doesn't fail, even though running JUnit against java.lang.String fails.
task breakit << {
    ant.junit(failureproperty: 'broken') { test(name: 'java.lang.String') }
    ant.fail(if: 'broken')
}

The behaviour should be the same in both calls to ant.fail. The property broken should be set, but in the second version it isn't. The build responds with:
:breakit
[ant:junit] TEST java.lang.String FAILED

BUILD SUCCESSFUL

Using haltonfailure: 'yes' doesn't work either - the build is still successful.
How can I fail the build on broken tests?

A: Which version of gradle are you using? With version 2.2.1,
ant.junit(printsummary: 'on', showoutput: 'yes', haltonfailure: 'no', failureproperty: 'failed', errorproperty: 'errored') {
}

ant.fail(if: 'failed')
ant.fail(if: 'errored')

does work for me. You can even confirm that by trying this simple code:
ant.failed = 'true'
ant.fail(if: 'failed')


text:
Q: guardar en variables los elementos de una respuesta xml Como grabar elementos de lista de un xml?
es decir tengo la respuesta que me regea varios elementos y esos elementos guardarlo en variables?
ejemplo:
For Each nd As Xml.XmlNode In record
   rec= New Response()
   rec.nombre = nd.Item("Nombre").InnerText
   rec.direccion = nd.Item("dir").InnerText
   rec.factura = nd.Item("folio").InnerText
   resp.ListaRecord.Add(rec)
Next

algo así

A: Hay una clase denominada Document o XmlDocument en Vb para trabajar con xml. Podrías cargar el xml con algo asi:
 Dim xml = new Document
 Xml.loadxml(tu xml aquí)
 Dim nodes as xmlnodes=xml.selectnodes("tu ruta xpath               aquí")
 For i=0 to nodes.count - 1
 Variable=nodes(i)

 Next

Disculpa, hace tiempo que no trabajo con Vb. Ahora trabajo con c#. Espero sea de ayuda..


text:
Q: How do you refresh a form to populate with database change, smoother than .Hide / .Show? I have a combo box that displays the change on a complete refresh of the form, but the new one ends up changing location and is not a smooth transition as you would expect. As I update the information in text boxes and use save button, I want the form to clear and combo box to populate with new data saved in my database. Here is my code now that works, but not the way I like.
      finally
            {
                con.Close();
                frmBooks mainForm = new frmBooks();
                mainForm.Show();
                this.Hide();
            }

It seems like it would be very simple to either lock the location to .Show() in the same location or some use of .Refresh(), but I have failed at getting that to work. I am using VS 2010.

A:  frmBooks mainForm = new frmBooks();
 mainForm.Show(); --- > Show new Form and
 this.Hide(); --> Hide Current open form

Maybe you can put your combobox loading and clearing of fields on a method and call it anywhere on your events.
pivate void refreshForm()
{

 //you dsource
 cmbox.DataSource = youredsource
 cmbox.DisplayMember = "YouTableColumn";

 textbox.text = string.Empty()
 //anything you want to clear

}

something like this:
     finally
        {
            con.Close();
           //refresh combo box and clear fields on form
           refreshForm();
        }

Regards


text:
Q: Android strange behavior on https response I've lost my sunday trying to understand what is going wrong with my https calls. This is my code to make a call to a https rest service:
String url = AppUtils.env.getValue()+"announcementsservice/getYears";
    StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {

        @Override
        public void onResponse(String jsonResponse) {

            AnnouncementsResponse response = (AnnouncementsResponse)
                        AppUtils.convertJsonResponse(AnnouncementsResponse.class, jsonResponse);

            arrayAdapter.clear();
            arrayAdapter.setNotifyOnChange(false);
            for (Integer year : response.getYears()) {
                arrayAdapter.add(String.valueOf(year));
            }
            arrayAdapter.setNotifyOnChange(true);
            arrayAdapter.notifyDataSetChanged();

        }

    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {

            VolleyLog.d("tag", "Error: " + error.getMessage());
            Toast.makeText(getApplicationContext(), "Error while loading ... ", Toast.LENGTH_SHORT).show();

        }

    });

I'm using volley to call the service and gson to parse the response. I've tried the code on a nexus 4 simulator and all is working fine. Then I tried to install the app on a Vernee physical device (os 5.1 sdk 22) via usb and all is working fine. Then I tried to install the app via google play store (alpha testing) on the same Vernee device and the code throws a null pointer exception. I tried everything to understand the problem but the only thing I understood is that the response is arriving, but there is an error converting it with gson:
java.lang.NullPointerException: Attempt to invoke interface method     'java.util.Iterator java.util.List.iterator()' on a null object reference

This is the response (same on simulator and physical device):
{
  "result": 1,
  "announcementsList": null,
  "years": [2018]
}

I'm becoming crazy!
Thanks in advance

A: One of the reasons which may cause such problem is Proguard !
When you debug an app, the model are as the same as you see. So Gson model is the same as server response and everything works fine. But when you build the Apk it become obfuscated. so the class names and parameters change. that why when you want to parse it with GSON it can't understand and the result of that is null.
what you should do is to tell the progurad to prevent changing your models which you used in GSON serializing. add this line to your proguard rules:
-keep class com.test.app.models.** { *; }

Instead of com.test.app.models enter the package name of the repository where all your models in it

A: Only possible problem I can think of is your pro guard is truncating variable name.
So put  @SerializedName("years")@Expose  above your variable years


text:
Q: Contradiction of uniqueness I'm endeavouring to prove that $\forall m,n\in \mathbb{N}:m\ne 0 \wedge n\ne 0\implies m\cdot n\ne 0$.
Preliminary definitions If $x$ and $y$ are natural numbers.

*

*$x<y\iff \exists c\in \mathbb{N};\ c\ne 0: x+c=y$
Remark It's provable that such a number $c$ in definition $1$ is unique.
Proof. We'll prove its contrapositive, \begin{align*}m\cdot n=0\implies m=0\vee n=0\tag{$a$}\end{align*}Let $p,q,r$ be propositions. From the tauotlogies $p\vee q\equiv \sim p\implies q$ and $ p\implies (q\implies r)\equiv (p\wedge q)\implies r$ we may notice that $(a)$ is logically equivalent to show \begin{align*}m\cdot n=0\wedge m\ne 0\implies n=0\end{align*} which is what we'll show instead of $(a)$. To do so, let $m$ and $n$ be arbitrarily chosen natural numbers. If $m\ne 0$, then $m>0$ because $m\in \mathbb{N}$ ($\forall x\in \mathbb{N}:x\ge 0$). So by hypothesis, we know $m>m\cdot n$. Meaning there is a unique natural number, say $p$, different from $0$ such that $m\cdot n+p=m$ or simply there is a unique \begin{align*}p\in \mathbb{N};\ p\ne 0: p=m\tag{$b$}\end{align*} because $m\cdot n=0$. But given that $p$ is unique and $m$ is any natural number $p=m$ is an absurd. Hence, $(a)$ is true because its logical equivalent is vacuously true.
My question. In this context, is $p=m$ a contradiction because of the uniquess of $p$?
Remark Assume $0\in \mathbb{N}$


text:
Q: How can I partially compare two strings with wildcard in C? I need to compare two strings, one of which uses "?" wildcard.
If the pattern is e?lo and string is hello, the comparison function should return true.
I was thinking of using a recursive method, but it apparently only works when the matching is cover the entire input string. What is the correct solution?
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#define MAX 100

bool WildCmp(char *pattern, char *string);

int main(void)
{
  char pattern[MAX];
  char string[MAX];

  printf("What is the pattern?\n");
  fgets(pattern, MAX, stdin);
  printf("What is the string?\n");
  fgets(string, MAX, stdin);

  if(WildCmp(pattern, string))
    printf("Match Found\n");
  else
    printf("Match Not Found");

  return 0;
}

bool WildCmp(char *pattern, char *string)
{
  if (*pattern=='\0' && *string=='\0')
    return true;

  if (*pattern != '\0' && *pattern != *string)
    return WildCmp(pattern, string+1);

  if (*pattern=='?' || *pattern==*string)
    return WildCmp(pattern+1,string+1);

  if (*pattern=='*')
    return WildCmp(pattern+1,string) || WildCmp(pattern,string+1);

  return false;
}


text:
Q: Typescript Omit seems to transform an union into an intersection I have this type
type Cartesian = { kind: 'cartesian'; x: number; y: number; }
type Polar = { kind: 'polar'; angle: number; distance: number }
type Movement = { name: string } & (Cartesian | Polar);

that I can use like this
const move = (movement: Movement) => { /* whatever */ };
move({ name: 'top right', kind: 'cartesian', x: 10, y: 10 });
move({ name: 'left', kind: 'polar', angle: Math.PI, distance: 10 });

but for some reason, I can't use it like this
const unnamedMove = (unnamedMovement: Omit<Movement, 'name'>) => {
    move({ name: 'default', ...unnamedMovement })
}

because TS throws a 2345:
Argument of type '{ kind: "cartesian" | "polar"; name: string; }' is not assignable to parameter of type 'Movement'.
  Type '{ kind: "cartesian" | "polar"; name: string; }' is not assignable to type '{ name: string; } & Polar'.
    Type '{ kind: "cartesian" | "polar"; name: string; }' is missing the following properties from type 'Polar': angle, distance

I don't understand this.
If I am not mistaken Omit<Movement, 'name'> should be equivalent to the union type Cartesian | Polar, which would make { name: 'default', ...unnamedMovement } a Movement, and all things should work.
However, it looks like TS infers Omit<Movement, 'name'> as if it was the union type Cartesian & Polar, thus the error.
Is it a bug or a mistake from my part?
playground link

A: You probably want Distributive conditional types. From the docs
When conditional types act on a generic type, they become distributive when given a union type.
This means that you can declare something like this
type DOmit<T, K extends string> = T extends any
  ? Omit<T, K>
  : never;

and then use it like this
const unnamedMove = (unnamedMovement: DOmit<Movement, "name">) => {
    move({ name: 'default', ...unnamedMovement })
}

Playground here


text:
Q: Can I sync Ubuntu One contacts with my Android device? Am I able to sync contacts from my android device with Ubuntu One or is it only with Ubuntu desktop for now?

A: No you are only able to sync files, contacts for Android devices will be coming soon. Unfortunately its just syncing between Desktops (like you said) and via the website
Hope i helped, heres the website if you want to check: https://one.ubuntu.com/services/


text:
Q: Using CMAKE and QT everybody!
It's my first time using both Cmake and Qt and I'm having some trouble. This probably is some newb quest and is more related to linux than cmake and Qt, but I'm not sure.
I'm trying compile ScanTailor (https://github.com/scantailor/scantailor), but when I type cmake ., I get the following output

-- Boost version: 1.55.0
  -- Found unsuitable Qt version "" from NOTFOUND
  -- Configuring incomplete, errors occurred!
  See also "/home/Igor/Documentos/github/scantailor/CMakeFiles/CMakeOutput.log".
  See also "/home/Igor/Documentos/github/scantailor/CMakeFiles/CMakeError.log".

I have installed Qt4, the path is /lib64/qt4 , but how I tell that to cmake?
Thank you for reading.