text:
Q: Permanently blocking a page/URL out of Google Analytics I have a question about filtering / segments in Google Analytics for a unique scenario with one of my clients. I essentially want to block a page URL forever out of analytics --- never see it counted page views, top pages, etc. What is the best way to do that?
Developers added a widget to my client's website which uses an iframe URL from their domain. This iframe is on 30+ different URLs which makes this URL seem like it is the #1 top page which is severely skewing their analytics. I am told there is no other way to do it - especially with the budget/scope of work - which means I need to find the best way to filter this out of Google Analytics reporting.
For instance, I am looking at "Behavior - Overview" - this iframe URL is #1. I know I can click into "view full report" and from there hit advanced and exclude this page to get the real results.
However, is there a top-level filter that can be permanently activated to block this page so you do not have to do the advanced filtering every time you are in Google Analytics?
Thank you for your help!

A: Just to confirm, your issue is this:
https://support.google.com/analytics/answer/1012049?hl=en
"Inflated number of pageviews"
If you just want to block it, would this not work?
In GA, go to Admin -> Filters -> Create new filter -> Custom -> Exclude by Request URL -> use the URI that you refer to.
I'd be interested to know if that works!


text:
Q: Converting WebDriver.current_url into string in python Im currently trying to get a webpage url converted into a string so that it could be put into a html format
  for x in range(3):

        wDriver.get('https://www.example.com/')
        sTitle = wDriver.find_element_by_xpath('/html[1]/body[1]/div[1]/main[1]/div[4]/div[1]/div[1]/div[1]/div[1]/div['+str(i)+']/div[1]/div[1]/h2[1]/a[1]')
        sTitle.click()
        link = wDriver.current_url
        sHeader = wDriver.find_element_by_class_name('c-page-title')
        print(sHeader.text + ' ' + link)
        i=i+1
        newLink = str(link)
        time.sleep(2)

        sReturn = sReturn + '
'+sHeader+'
'

The error code I get is
"TypeError: can only concatenate str (not "WebElement") to str"

A: link = wDriver.current_url

current_url returns a string, so link is already a string. You do not need to explicitly convert to string again.
The reason why you are getting this exception
"TypeError: can only concatenate str (not "WebElement") to str"

is cause when you look here
sReturn = sReturn + '
'+sHeader+'
'

newLink is a string, so no issue with that, but sHeader is a web element. That is what causing the issue.
Please use .text to extract the text :
sReturn = sReturn + '
'+sHeader.text+'
'

or in case for any reason you would like to have it stored in a variable then use :
sHeader = wDriver.find_element_by_class_name('c-page-title').text
sReturn = sReturn + '
'+sHeader+'
'

redpajama_set_name: RedPajamaStackExchange


text:
Q: Como borrar el archivo sobrante después de unir dos archivos? Tengo que realizar el siguiente ejercicio, debo crear 2 archivos y escribir cosas en su interior, aprox 2 lineas de texto en cada uno y a continuación debo crear un 3er fichero y copiar todas las lineas de los dos anteriores ficheros en el 3ero y borrar los dos anteriores, yo consigo crear correctamente el 3er fichero y que se introduzcan los datos, pero solo se me borra el primer fichero, el segundo sigue estando en la carpeta como sería esto ?
adjunto codigo:
public static void combinarFichero(String directorio,String ficherorUno, String ficheroDos) throws IOException {

            //llamo a los metodos de insertar fichero

            //creo variables para cada una de las rutas que voy a usar

           //llamo dos buffreader y les asigno un nombre y llamo un buffered reader

            //creo 3 clases file y les asigno una ruta

            //si no existen los file 1 y 2 previamente creados se crean y nos avisa si existen o no.

            //creamos el 3er fichero

            try {
               //a los 2 buffreader se le asigna el file con su ruta y al file reader lo mismo

                copiar(buffWrite, buffRead);
                copiar(buffWrite, buffReadDos);

            }
            catch(IOException e) {
                System.out.println("Error: "+ e.getMessage());
            }
            finally {
                if(buffWrite != null)
                    buffWrite.close();
                if(buffRead != null)
                    buffRead.close();

                new File(RutaOriginalDos).delete(); //elimina los dos primeros archivos que hemos creado
                new File(RutaOriginal).delete();
            }
    }

    private static void copiar(BufferedWriter bw, BufferedReader br) throws IOException{

        String linea=br.readLine();
        while(linea!=null){

            bw.write(linea);

            linea=br.readLine();
        }

}

A: Después de crear el archivo puedes eliminarlos archivos usando el método delete():
  ...
  f3.createNewFile();
  ...
  //Elimina archivos.
  f1.delete();
  f2.delete();
  ...

Me refiero a que realices esto en tu finally:
    finally {
        if(buffWrite != null)
            buffWrite.close();
        if(buffRead != null)
            buffRead.close();
        if(buffReadDos != null)
            buffReadDos.close();

        //new File(RutaOriginalDos).delete();
        //new File(RutaOriginal).delete();
        //Elimina archivos.
        f1.delete();
        f2.delete();
    }

A:

yo consigo crear correctamente el 3er fichero y que se introduzcan los datos, pero solo se me borra el primer fichero, el segundo sigue estando en la carpeta como sería esto

El problema radica en este bloque de código:
finally
{
    if(buffWrite != null)
        buffWrite.close();
    if(buffRead != null)
        buffRead.close();

    new File(RutaOriginalDos).delete();
    new File(RutaOriginal).delete();
}

Se te olvidó cerrar los recursos de buffReadDos.
Es decir, el código debería ser así:
finally
{
    if(buffWrite != null)
        buffWrite.close();
    if(buffRead != null)
        buffRead.close();
    if(buffReadDos != null)
        buffReadDos.close();

    new File(RutaOriginalDos).delete();
    new File(RutaOriginal).delete();
}

Si no cierras los recursos, no podrás eliminar el segundo archivo y el método delete retornará false.
Lo puedes comprobar con este código de ejemplo:
public class Program
{
    public static void main(String[] args) throws IOException
    {
        File f = new File("nombres.txt");

        var b = new BufferedReader(new FileReader("nombres.txt"));

        System.out.println(f.delete());
    }

}

Resultado en pantalla:
false


text:
Q: Get Data from Inline with Admin.User Model I am trying to use an 'augmentation' table with the Admin.User Model to store additional data related to that user/login.
Here is my admin.py
class UserProfileInline(admin.StackedInline):
    model = AppUserProfile
    can_delete = False
    verbose_name_plural = 'profile'

# Define a new User admin
class UserAdmin(BaseUserAdmin):
    inlines = (UserProfileInline,)

# Re-register UserAdmin
admin.site.unregister(User)
admin.site.register(User, UserAdmin)

Here is my models.py
class AppUserProfile(models.Model):
    user = models.ForeignKey(User, on_delete=models.DO_NOTHING)
    usr_tpid = models.CharField(max_length=20)
    usr_cstid = models.CharField(max_length=20)
    db_table = 'app_user_profile'

Here is my views.py where I'm trying to get the usr_cstid from the login value.
def login_view(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            print(request.POST)
            username = form.cleaned_data['userName']
            password = form.cleaned_data['password']
            userInfo = AppUserProfile.objects.all().filter(user=username)
            print(username)
            print(userInfo)
            user = authenticate(username=username, password=password)
            if user is not None:
                login(request, user)
                groups = [x.name for x in user.groups.all()]
                full_info = User.objects.all().filter(username=username)
                user_info = User.objects.all().filter(username=username).values('first_name')
                print(full_info)
                request.session['first_name'] = user_info[0]['first_name']
                request.session['user_group'] = groups[0]
                # print(user_info, groups)
                # return render(request, template_name='landingPage.html', context={'user': first_name})
                if 'Administrator' in groups:
                    # return render(request, template_name='adm_landing_page.html', context={'user': first_name})
                    return redirect('AdminPortal:adm_landing_page')
                if 'Supplier' in groups:
                    # return HttpResponseRedirect(reverse('adm_landing_page', args=(), kwargs={'user': username}))
                    return render(request, template_name='supplier_landing_page.html', )
                    # return redirect('SupplierPortal:supplier_landing_page')

            else:
                form = LoginForm()
    else:
        form = LoginForm()

    return render(request, 'registration/login.html', {'form': form})

However I'm getting the following error:
ValueError: invalid literal for int() with base 10: 'supplier_ad'

It seems this is the line causing the error:
    userInfo = AppUserProfile.objects.all().filter(user=username)

I am not sure what I have wrong, or how to link back to those values.

A: Not sure what are you trying to achieve with this but you cannot filter user object by username string  rather by user object or users id or you could do something like this
userInfo = AppUserProfile.objects.all().filter(user__username=username)

If you are expecting one  AppUserProfile instance use get() instead of filter()
Also I am not seeing what exactly you are trying to achieve as when you login your user it is always accessible with request.user and depending on relation you could get resulting profile for instance assuming OneToOne relationship request.user.profile


text:
Q: Multiple GLSurfaceView moving at the same time I am facing an strange issue not sure why this is happening.
I have a Java based Activity which has a LinearLayout. This LinearLayout consists of two GLSurfaceView. All the associated methods of GLSurfaceView like OnDraw, SurfaceChanged etc are moving call down to JNI layer. Inside the JNI layer I am drawing a cube using OpenGLES. I have also created a touch listener and have associated it with first GLSurfaceView. Once I get a touch event I move the call to JNI layer and randomly rotate the first cube.
Problem is when I rotate my first cube both the cubes rotates at exactly same angle. I have debugged this issue for last four hours and I am pretty sure there is nothing wrong in my logic. But for some unknown reason when I make change in one GLSurfaceView other cube changes automatically.
Any ideas? Similar issues? Guess?
Update
I am using same context i.e. my activity for both GLSurfaceView. Basically I have a class inside C++ which draws cube through opengles. Now I am successfully creating two cubes and displaying them simultaneously. Both cubes have different texture on them which I am passing via Java layer. My c++ class has a method which randomly rotates the cube. Problem is if I call method of one cube to rotate it other automatically rotates at same angle no make what I do.

A: Without your code, I'd guess you are initializing your GLSurfaceView's using the same context. When sharing a context changing one will change the other because they will share the same GL10 instance in the Renderer. I don't program in android, but in general you'd use multiple "viewports" to display different things.

A: Say that your first GLSurfaceView is on the first left side of your screen, and the second is on the second right half. One idea is to check what side the coordinates x, y of the motionEvent belongs to. And then pass rotation and translation accordingly.

A: Issue solved there was one logical mistake in my code
Sorry for inconvenience


text:
Q: Why are the identities of two diffrent Integer Pyobjects same in VSCode? a=543
b=543

print(id(a),id(b))
print(a is b)

I am a Python newbie and my understanding of the above code is that

*

*a = 543 => Since 543 is not in the small integer cache range of -5 to 256, a new pyobject of type integer with value 543 is created and the name/label a is given to that pyobject

*b = 543 => a new pyobject of type integer with value 543 is AGAIN created and the name/label b is given to that pyobject

*Since a and b refer to two different objects, their identities are different and thus id(a)==id(b) must return False
Below is the snapshot of running the above code using Python interpreter in terminal. And the result is what I expected
run in python interpreter
But the same code when ran through VS Code is returning same id for both a and b and id(a)==id(b) as True
run in VS Code
Is my understanding that a different object is created every time incorrect?

*

*If yes, why is it behaving that way with Python interpreter?

Or is just VSCode doing something that I don't understand yet?


text:
Q: Returning the value of one element of an object in an array of objects in Vue Using the map method I am creating a new array (updated) from an existing array (data) and looking up a third array (members) using a Vue getter and it's working fine if I want to return the member object as below...
const updated = data.map(el => ({
      ...el,
      memberId: getters.members.find(m => m.accountKey === el.dataKey)
    }))

However, when I try to return just the member object id, by adding '.id' below, I get an type error ""TypeError: Cannot read properties of undefined (reading 'id')"
const updated = data.map(el => ({
      ...el,
      memberId: getters.members.find(m => m.accountKey === el.dataKey).id
    }))

I need to return the id not the entire member object

A: I don't know why you are trying to use array.find
but if you are trying to get the find or filter from an array.
It's better to use array.filter. Because array.find will return only the 1st value of the element that it match. If there are multiple matches it will ignore the the rest.
const array = [{name:'user1', id: 1}, {name:'user2', id: 2}];

const result = array.filter(person => person.name === 'user1');

console.log(result)


text:
Q: Eclipse Svn synchronizing Not working? Problems reported while synchronizing SVNStatusSubscriber. 0 of 1 resources were synchronized.
An error occurred synchronizing /MedxBilingSchedularPro: Error getting status for resource P/MedxBilingSchedularPro org.apache.subversion.javahl.ClientException: Previous operation has not finished; run 'cleanup' if it was interrupted
Error getting status for resource P/MedxBilingSchedularPro org.apache.subversion.javahl.ClientException: Previous operation has not finished; run 'cleanup' if it was interrupted
org.apache.subversion.javahl.ClientException: Previous operation has not finished; run 'cleanup' if it was interrupted
org.apache.subversion.javahl.ClientException: Previous operation has not finished; run 'cleanup' if it was interrupted

A: Read the error message. It provides a clear instruction:

Previous operation has not finished; run 'cleanup' if it was
  interrupted

Therefore, clean up your project's working copy. If you can't or don't know how to do it through Eclipse by some reason, run svn cleanup from the command line.
Read SVNBook | Sometimes You Just Need to Clean Up.


text:
Q: How do I place two JMenuItems adjacent to each other? My Code:
JMenuBar bar = new JMenuBar();
JMenu menu = new JMenu("Edit circle");
JMenuItem help = new JMenuItem("Help");
JMenuItem exit = new JMenuItem("Exit");

bar.add(menu);
bar.add(help);
bar.add(exit);

Output of the JMenuBar:

I want the output to be something like this:

What do I need to do in order to get the expected output?

A: you cannot add JMenuItem in JMenuBar.
so try this.. it'll work..
    JMenuBar bar = new JMenuBar();
    JMenu menu1 = new JMenu("Edit circle");
    JMenu help = new JMenu("Help");
    JMenu exit = new JMenu("Exit");
    bar.add(menu1);
    bar.add(help);
    bar.add(exit);
    exit.addMenuListener(new MenuListener() {

        @Override
        public void menuSelected(MenuEvent e) {
            System.out.println("Exiting");
        }

        @Override
        public void menuDeselected(MenuEvent e) {
        }

        @Override
        public void menuCanceled(MenuEvent e) {
        }
    });

you cannot add ActionListener to JMenu. use MenuListener..
reference from this...


text:
Q: Reporting GLMMs I have read several excellent resources (e.g., Bolker, 2009, Thiele, 2012)  on what should be reported, what is missing in the current research using Generalized linear mixed models, but I still have few questions...
I managed to fit a model using glmer (binomial family with logit link). Compared several different models, and choose the one that seems to be the best fit. The outcome variable is binary (0/1). Fixed effects are 5 continuous variables and 2 factors (graded/not_graded and yes/no). Students within a course was defined as a random effect.
The question is rather simple - what is the association between the five continuous variables and the outcome, and what is the effect of the two factors?
Are there any general guidelines what should be reported in the research paper in order to answer such a research question? I've seen a lot of statistics, graphs, everything... but I simply want to summarize a model in a table or two with a few simple graphs.


text:
Q: How to stop Asynctask from Timer? I am trying to stop Asynctask from Timer but it is not stopping.
Here is code where I schedule the timerTask(asynctask)
public void CreateTimer(){
    timer =new Timer();
    timerTask = new MyTimertask();
    timer.schedule(timerTask,5000,2000);
}

A: The documentation for TimerTask doesn't seem to have the schedule method. You can cancel an AsyncTask with cancel(true).
Maybe instead you could use a CountdownTimer or a new Thread?
With CountdownTimer:
CountDownTimer cdt = new CountDownTimer(5000, 1000) {
        @Override
        public void onTick(long l) {}

        @Override
        public void onFinish() {
            cancel();//Cancel CountdownTimer
            cancel(true);// Cancel Asynctask
        }
    };
    cdt.start();

With Thread:
Thread thread = new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    Thread.sleep(5000);
                    cancel(true);//Cancel Asynctask
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        };
thread.start();

A: Async task can be cancelled at any time by invoking cancel(boolean). More information can be found here.
It would be helpful if you post your code to give a more precise answer.


text:
Q: Why does the billiard multiprocessing module require the "if __name__=='__main__'" line? If I have the following code:
def f():
    print 'ok!'
    import sys
    sys.exit()

if __name__=='__main__':
    import billiard
    billiard.forking_enable(0)
    p = billiard.Process( target=f)
    p.start()
    while p.is_alive():
        pass

The script behaves as expected, printing "ok!" and ending. But if I omit the if __name__=='__main__': line and de-indent the following lines, my machine (OS X) goes crazy, continually spawning tons of Python processes until I killall Python. Any idea what's going on here?
(To those marking this as a duplicate, note that while the other question asks the purpose of  if __name__=='__main__' generally, I'm specifically asking why failure to use it here causes dramatically unexpected behaviour)

A: You're disabling fork support with the line:
billiard.forking_enable(0)

That means that the library will need to spawn (instead of fork) your child process, and have it re-import the __main__ module to run f, just like Windows does. Without the if __name__ ... guard, re-importing the __main__ module in the children will also mean re-running your code that creates the billiard.Process, which creates an infinite loop.
If you leave fork enabled, the re-import in the child process isn't necessary, so everything works fine with or without the if __name__ ... guard.


text:
Q: How to learn all these client-side tricks that are used on the Web today? I want to learn JavaScript nicely and become very good at it. I want to form a systematic learning plan before I start reading the books. Don't want to end up wasting my time reading the wrong books.
I want to learn from books that will teach me enough to be able to learn all the things that are commonly used in today's websites.
For example, if you look at this website
http://rethrick.com/#
His page source doesn't show the full content of the web page. How does he do all those animated transition effects?
How do I learn all that stuff? Please help me. I want to learn all that stuff. Which book should I start reading?
Another example is the Stack Exchange websites. For instance, the Writers website itself. When you hover over the Questions link on the top or any of such links, it displays a yellow background highlight. How do they do that?
Where do I learn all these tricks? I see two options:
a) Look up the web on an ad hoc basis when you need to learn some trick.
But I don't like this technique.
OR
b) Systematically learn and read some books. I will read all the books if I have to. Please tell me what technologies other than JavaScript are at use to do these things.
And if it is just JavaScript, what books will teach me the level of JavaScript that Google employees and FogCreek and StackExchange employees use.

A:
And if it is just JavaScript, what books will teach me the level of JavaScript that Google employees and FogCreek and StackExchange employees use.

This is the easiest to answer: none. Yes, get started with Danny Goodman's tome or JavaScript: The Good Parts if you have some programming experience and want a quick intro, but both will only get you started. I mean, I'm sure they had some textbooks they read in college, but it's kind of like asking what books made pro athletes so good, or what book you read to get good at guitar.
It's maybe 10% textual material and 90% constant practice -- finding new problems to solve and figuring out how to solve them.
EDIT
I don't intend to imply that avoiding books is admirable, merely that experience is the best teacher, and that a theoretical understanding is only a means to an end: practical understanding. Books are absolutely necessary here; I'm mostly disputing the connection between books and the kind of expertise that lands you a high-flying job. For a perhaps more relevant example, imagine language learners. You can study the textbooks all you'd like, but absent experience you'll stutter like a first-year student. (Even if, for example, you can recite correctly the grammatical differences of some construction better than a native speaker.)
So no, don't just copypasta and come to SO when things break. But do start early in your reading, and the mistakes you make (rather than some script you copied) are often the best teachers.

A: HTML5Rocks is a great resource, they show you some newer features and have code samples.
http://www.html5rocks.com/

A: Take a nice project and start implementing it. Read books, search internet as you go.
So go make a clone of http://rethrick.com/


text:
Q: Is "next" optional in "next Friday"?
You must submit your assignments by next Monday at the latest.

Is "next" optional in the above sentence? I think by "by Monday" should be clear enough and "next" is redundant.

A: It is impossible to say whether you can remove next from next Monday without additional context. It may make no difference, but it may make no difference because both are equally weak.
Next Monday itself can be ambiguous, as to whether it is referring to Monday next week or the week after that. Monday alone would pose the same problem if you are at a point in the week where next Monday and this Monday would differ, and adds the possibility that Monday or this Monday refers to this past Monday rather than this coming Monday.
Even further, if you're referring to something occurring over multiple weeks, you must also distinguish between references to fixed dates and references to points in the cycle, in which case it might not just be this Monday or next Monday, but the next Monday.
You don't indicate why you want the shorter form, but do remember that language is not software, or logic. Redundancy is neither inherently erroneous nor inefficient. The language is full of idiomatic pleonasms from advance warning to water hydrant that some people may dislike, but which most others accept without any thought.

A: This is something that confuses native English speakers as it is often used in two different ways.  Whenever someone tells me something like "next Monday" I always have to ask if they are referring to this-coming Monday (i.e. the closest Monday) or the Monday following the closest Monday.  This is because some people think the closest Monday is the so-called "this Monday" and the following is the so-called "next Monday".
Anyhow, to answer your question, yes, It's optional.

A: As noted in other answers, there is potential for ambiguity in the meaning of next. Hence, it is usually best when dealing with important matters, and especially in written communications, to use a specific date.
When speaking I might say

Your assignments must be submitted by next Monday, the 23rd July.

making my meaning clear. In writing I would use the slightly more formal:

Your assignments must be submitted by Monday 23rd July.


text:
Q: Jquery dropdown switching issue http://jsfiddle.net/dyHD7/
Basically I am trying to make it so that when user hovers over text, it switches to dropdown, and when user selects a option or hovers outside the dropdown, it switches back to the text. Any ideas how to achieve this?

A: You can use the method change(), update status_txt with the changed value.
HTML

                Unpaid

            <select name="status[]">
                <option selected="" value="0">Unpaid</option>
                <option value="Paid">Paid</option>
                <option value="Cancelled">Cancelled</option>
                <option value="Void">Void</option>
            </select>

JQuery
$(".sudiptaDD").live("mouseenter",function(){
    $(".status_txt",this).slideUp(200);
$(".status_dd",this).slideDown(200);
$('select').change(function(){
        var value = $(this).val();
        $('.status_txt span').html(value);
    });

}).live("mouseleave",function(){
    $(".status_dd",this).slideUp(200);
    $(".status_txt",this).slideDown(200);
 });

Fiddle

A: Check this It is not much smooth but I think working as u want
http://jsfiddle.net/dk76h/
Click on text and when dropdown will come use keyboard arrow keys to select value and press enter and then remove mouse from it.
I know it is quite tedious but If u can improve it give the link


text:
Q: paginate a subquery in flask This is an abbreviated version of the problem posted in Strange paginate behaviour when paginating a subquery in flask.
I need to paginate the result of the following query and display the results:
sub = db.session.query(Magazine).join(Magazine.subscribers).filter(User.id == 2).subquery()
subscribers = db.session.query(User).select_from(sub).join(Magazine.subscribers)

and I try to do it with the following code:
page=request.args.get('page', 1, type=int)
friends=subscribers.paginate(page, 3, False)
next_url=url_for('index', page=friends.next_num) if friends.has_next else None
prev_url=url_for('index', page=friends.prev_num) if friends.has_prev else None
return render_template("index.html", title="My friends", friends=friends.items, next_url=next_url, prev_url=prev_url)

This gives a weird result. To start with it returns only 2 results when 3 are asked and friends.has_next is false when it should be true (there are more items in the databse). In Strange paginate behaviour when paginating a subquery in flask there are more details and also a test I run. I am suspecting the error comes from the subquery. Am I missing something obvious??!!!
In the following example I work with some "fake" data in a flask shell:
>>> sub = db.session.query(Magazine).join(Magazine.subscribers).filter(User.id == 2).subquery()
>>> subscribers = db.session.query(User).select_from(sub).join(Magazine.subscribers)
>>> friends=subscribers.paginate(1, 3, False)
>>> subscribers.all()
[<User 2>, <User 3>, <User 4>, <User 5>, <User 6>]
>>> friends.items
[<User 2>, <User 3>]
>>> friends.has_next
False
>>> friends.has_prev
False

Any insights?

A: You can use sqlalchemy_paginator. Check out this link for detailed example.
from sqlalchemy_paginator import Paginator
query = session.query(MyModel)
paginator = Paginator(query, 5)
for page in paginator:
    print "page number of current page in iterator", page.number
    print "this is a list that contains the records of current page", page.object_list


text:
Q: Dapper List Parameter rejected by Postgres I have a List<Guid> (also tried it with a plain array) that I would like to use in a query. Dapper generates the SQL and substitutes the parameters for numbered params correctly. However, PG complains about the syntax at the list parameter. No further details are given. Copying the generated SQL and substituting the numbers with actual values (adding parens to the list param), the query works.
Here's the offending clause in the generated SQL:
WHERE (
    names.tenant = $1
    AND scan_results.tenant = $1
    AND scan_results.scan IN $2
)

The original statement string for Dapper is this:
WHERE (
    file_names.tenant = @tenantId
    AND scan_results.tenant = @tenantId
    AND scan_results.scan IN @validScans
)

The query is executed using con.Query like this:
con.Query(stmt, new
{
    tenantId = tenant.Id,
    validScans = tenant.LatestScans // .ToArray()
});

The exact Postgres error is:
ERROR:  syntax error at or near "$2" at character ...

A: Turns out I had some misconceptions about both PGSQL and Dapper. First, parens are needed around the parameter, and second, I need to use ANY, not IN.
So the correct SQL looks like this: AND scan_results.scan = ANY (@validScans)


text:
Q: No division in numerical differentiaton algorithm I am trying to understand an algorithm that evaluates the speed of a moving element. The position sensors are sampled with varying but rather big speed (from 16MSPS to 24MSPS) and the speed is calculated as a simple difference between the last two values.
The formula for the speed is then v = f(x_(n+1)) - f(x_n) , and according to all numerical approaches i was expectingv = (f(x+h) - f(x)) / h
I don't really understand why the division is omitted. Under what circumstances can the division be ignored?
This system is implemented on a FPGA.

A: It can be ignored when h is 1 as divide by 1 is a no-op.

A: Thanks to many comments I was able to understand the problem:
The unit calculating the speed doesn't need to know the time period. By subtracting the next sampled value from the previous one, it produces output values. These values represent a function, that is is linearly dependent on the speed. One way to understand this is, that this output is  kind of 'speed without units'. The output can be than further manipulated (oversampled, undersampled) to achieve desired signal quality.
To able to determine the speed in some exact units (like m/s) at least the sampling frequency has to be given. In case of rotational movement also other constants are needed, such as the radius of the axis where the sensor is mounted, etc. This happens at some later point.


text:
Q: MLFlow Projects throw JSONDecode error when run I'm trying to get MLFlow Projects to run using the MLFlow CLI and its following the tutorial leads to an error.  For any project I try to run from the CLI, I get the following error
Traceback (most recent call last):
  File "/home/rbc/.local/bin/mlflow", line 11, in <module>
    sys.exit(cli())
  File "/home/rbc/.local/lib/python3.6/site-packages/click/core.py", line 764, in __call__
    return self.main(*args, **kwargs)
  File "/home/rbc/.local/lib/python3.6/site-packages/click/core.py", line 717, in main
    rv = self.invoke(ctx)
  File "/home/rbc/.local/lib/python3.6/site-packages/click/core.py", line 1137, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "/home/rbc/.local/lib/python3.6/site-packages/click/core.py", line 956, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/home/rbc/.local/lib/python3.6/site-packages/click/core.py", line 555, in invoke
    return callback(*args, **kwargs)
  File "/home/rbc/.local/lib/python3.6/site-packages/mlflow/cli.py", line 139, in run
    run_id=run_id,
  File "/home/rbc/.local/lib/python3.6/site-packages/mlflow/projects/__init__.py", line 230, in run
    storage_dir=storage_dir, block=block, run_id=run_id)
  File "/home/rbc/.local/lib/python3.6/site-packages/mlflow/projects/__init__.py", line 88, in _run
    active_run = _create_run(uri, experiment_id, work_dir, entry_point)
  File "/home/rbc/.local/lib/python3.6/site-packages/mlflow/projects/__init__.py", line 579, in _create_run
    active_run = tracking.MlflowClient().create_run(experiment_id=experiment_id, tags=tags)
  File "/home/rbc/.local/lib/python3.6/site-packages/mlflow/tracking/client.py", line 101, in create_run
    source_version=source_version
  File "/home/rbc/.local/lib/python3.6/site-packages/mlflow/store/rest_store.py", line 156, in create_run
    response_proto = self._call_endpoint(CreateRun, req_body)
  File "/home/rbc/.local/lib/python3.6/site-packages/mlflow/store/rest_store.py", line 66, in _call_endpoint
    js_dict = json.loads(response.text)
  File "/usr/lib/python3.6/json/__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.6/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.6/json/decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Here's an example of the type of command I'm using to start the run, which comes directly from the tutorial
mlflow run https://github.com/mlflow/mlflow#examples/sklearn_elasticnet_wine -m databricks -c cluster-spec.json --experiment-id 72647065958042 -P alpha=2.0 -P l1_ratio=0.5

I've traced the error to something involving MLFLow returning empty when it tries to start a run but I can successfully run MLFlow experiments using the Databricks environment I'm connecting to so I'm not sure where the problem is, I'm running MLFlow 0.9.1 on Ubuntu 18.04

A: not sure if you have solved your issue, but here is how I fixed it:

*

*the databricks-cli work with the following config without problem:
host = https://xxx.databricks.net/?o=<org_id>
token=dapixxx

*but mlflow not quit happy about that, change it to:
host = https://xxx.databricks.net
username = token
password = dapixxx


text:
Q: Loop over the properties of member variable for conditional check in MVEL Member variable categories must have MAIN type and url.
Stream
boolean mainCatImage=categories.stream()
   .anyMatch(categories -> categories.getType()
   .equals("MAIN") && StringUtils.isNotBlank(categories.getUrl()));

I have rewritten the same usign MVEL. The below works, but is there any way to do it in other way with less code in MVEL?
MVEL
mainCatImage = false;
foreach (cat : input.categories) {
   if(cat.type == 'MAIN' && cat.url!=empty){
        mainCatImage = true;
    }
}
    mainCatImage;


text:
Q: How to find all the matched patterns in a variable and writing them to output and a newline character every of matched string? I have a string variable as
$variable

and I have a pattern as like:
/<OPTION [^>]*>\D*([^<]+)/g

How can I print all the matched strings inside that variable and writing to console a newline character - \n after every matched string with Perl?

A: I recommend the use of TreeBuilder to parse HTML. You will gain performance if use XPath or the look_down() function.
By the way:
my @arr = $variable =~ /<OPTION [^>]*>D*([^<]+)/g;
for(0 .. @arr - 1) {
    print $arr[$_] . "\n";
}

A: You should use a module for processing HTML data. If you insist on doing it The Wrong Way:
print join("\n", $variable =~ /<OPTION [^>]*>\D*([^<]+)/g), "\n";


text:
Q: ABP Framework API Scope I cloned MicroserviceDemo solution, before run project PublicWebsite.Host, I commented below code in PublicWebSiteHostModule.cs, but why PublicWebsite.Host still can access PublicWebSiteGateway, ProductService and BloggingService? In my view, I think app only access to required scopes. (Other hand, comment or don't comment below code, PublicWebsite.Host still run correctly. Sorry for my English).
Thanks you!
            context.Services.AddAuthentication(options =>
                {
                    options.DefaultScheme = "Cookies";
                    options.DefaultChallengeScheme = "oidc";
                })
                .AddCookie("Cookies", options =>
                {
                    options.ExpireTimeSpan = TimeSpan.FromDays(365);
                })
                .AddOpenIdConnect("oidc", options =>
                {
                    options.Authority = configuration["AuthServer:Authority"];
                    options.ClientId = configuration["AuthServer:ClientId"];
                    options.ClientSecret = configuration["AuthServer:ClientSecret"];
                    options.RequireHttpsMetadata = false;
                    options.ResponseType = OpenIdConnectResponseType.CodeIdToken;
                    options.SaveTokens = true;
                    options.GetClaimsFromUserInfoEndpoint = true;
                    options.Scope.Add("role");
                    options.Scope.Add("email");
                    options.Scope.Add("phone");

                    //options.Scope.Add("PublicWebSiteGateway");
                    //options.Scope.Add("ProductService");
                    //options.Scope.Add("BloggingService");

                    options.ClaimActions.MapAbpClaimTypes();
                });


text:
Q: Adding custom information to CSPROJ files As part of our development life cycle we have a number of process that we run against the C# source in our projects.
The processes are driven off a GUI that currently reads the *.csproj file to find the source files used within the project. This works fine.
We now have a new requirement to provide some validation processes that require a call out to a web-service. The web-service needs to be provided with some credentials that are project specific. Ideally we could enter and store these credentials within the *.csproj file but I don't see a means of extending it - is there?
We don't really want to introduce a new config. file just for these settings if we can help it. Is it possible to store information like this is the *.csproj file, if not is there any other place to put it.
thanks

A: VS projects support "project extensions". These are custom data stored directly in csproj/vbproj files. You can very easily read and write them even from VS. For example, the following VS macro writes such custom setting:
Dim proj As Project = DirectCast(DTE.ActiveSolutionProjects(0), Project)
proj.Globals.VariableValue("MySettingName1") = "My value1"
proj.Globals.VariablePersists("MySettingName1") = True

The following reads it back:
proj.Globals.VariableValue("MySettingName1").ToString

And the code in csproj file looks like:
  <ProjectExtensions>
    <VisualStudio>
      <UserProperties MySettingName1="My value1" />
    </VisualStudio>
  </ProjectExtensions>

Of course, this is persisted and will not be overwritten by VS.

A: The .csproj file is basically an MSBuild file, as such you can extend it with custom values. If you right-click on a project in Visual Studio and choose "Unload Project", the project will "grey out" and you can then right-click again and choose Edit [ProjectFileName].csproj. You can then add something similar to the following:
<PropertyGroup Label="Custom">
  <Badger>1</Badger>
</PropertyGroup>

This should be persisted when the project is modified (i.e. files added/removed) and you can retrieve the values from the file, using the method of your choice.

A: I know you dismiss it but the most obvious, and probably recommended, place is in the config file.  Albeit encrypted.
One config file per project does for most cases and is not a large overhead imho.


text:
Q: SQL Row_Number() and Linq record count different I have two bits of code doing basically the same thing but the results are different. I am trying to get the index number of a record from an ordered list in the database, and then skip/take some results.
Linq method:
int index = db.users.OrderByDescending(o => o.TotalScore)
              .ToList()
              .FindIndex(f => f.UserId == User.UserId);
               // returns 557

SQL method:
WITH IndexedUsers AS (
  SELECT UserId,
     ROW_NUMBER() OVER (ORDER BY TotalScore desc) AS 'RowNumber'
  FROM [User]
)
SELECT RowNumber
FROM IndexedUsers
WHERE UserId = @userId
//Returns 559

Stumped at the difference here. I dont want to be calling ToList on the user collection from the database, i am just using it for testing purposes. I would expect the results to be 1 out with the FindIndex method being 0 based. Any ideas why the values aren't the same?


text:
Q: Study some topological properties of $I^{\aleph_0}\times I^2/M$ I've been solving some problems from my Topology course, and I'm unable to finish this one:

Given $I^{\aleph_0}$ the Hilbert cube, and given $Y=I^2/M$ the
quotient space where $M=\{(0,0),(1,0),(0,1),(1,1)\}$.

*

*Prove that $X=I^{\aleph_0}\times Y$ is $T_1$, compact and path connected.

*Prove that given $f:X\to\mathbb R$ continuous map, $\exists a,b\in\mathbb{R}$ s.t. $a\leq b$ >  and $f(X)=[a,b]$ (assuming that $\mathbb R$ has the usual topology).

The work I've done:
Question 1

*

*Compact: since $I^{\aleph_0}$ and $I^2$ are topological cubes, they're compact. $Y$ is then also compact because it's the continuous and surjective image of a compact (for being a quotient space). Hence $X$ is compact because it's product of compact spaces.

*Path connected: using an analogous reasoning as the one used for compactness (cubes are path connected, quotient of path connected is path connected, and product of path connected is path connected) it follows that $X$ is path connected.

*$T_1$: here's where I have difficulties in this question. I know cubes are $T_2$ and also that they're $T_4$ (normal + $T_1$). I would be able to prove that $Y$ is normal since the quotient map defined is closed (easy to see because $M$ is finite, hece closed for cubes being $T_1$, and if the subset below is closed then the quotient application is also closed), but still proving that $Y$ is normal does not seem useful to prove that $X$ is $T_1$. I'm probably forgetting some characterisation property that may turn this prove into a trivial one (since using the definition in a space as complicated as this one seems unachievable and clearly not the exercise's intention), but right now I don't know how to prove it.

So here's my first question: How can I prove this space $X$ is $T_1$? Which characterisation am I forgetting?
Question 2
For this second one, I assume I've proven the first.

*

*From my course notes, I know a result that tells me that if $X$ a non-empty compact space, then a continuous map $f:X\to\mathbb R$ is bounded.

*I also know that the continuous image of a path connected space is also path connected, and a subset of usual $\mathbb R$ is path connected if and only if it's an interval. Considering also that it's bounded, then we conclude $\exists a,b\in\mathbb R$ s.t. $f(X)$ is of one of the following forms: $(a,b)$, $(a,b]$, $[a,b)$ or $[a,b]$.

*The continuous and surjective image of a compact set is compact. If I consider $f:X\to f(X)\subset \mathbb R$, it's clearly continuous and surjective, hence we conclude $f(X)$ is compact, and since it's a subspace of usual $\mathbb R$ then it's closed and bounded. From the 4 different types of interval that $f(X)$ could be as seen in the previous point, the only one closed is $[a,b]$.
So from this reasoning I can finnaly conclude $f(X)=[a,b]$ for some $a,b\in\mathbb R$, $a\leq b$. I feel this prove is correct but maybe I jumped into a wrong conclusion somewhere midway. So my second question is : Is my solution for the second question of the exercise correct? If not, where did I made a mistake?
My biggest issue with this problem is proving $X$ is $T_1$ in question 1, for question 2 I just want to check if my proof is correct. Any help ot hint will be appreciated, thanks in advance.

A: *

*The preimage of any point by the quotient map is a subset of at most four points, and therefore a closed set. Thus, every point in the quotient is closed.

*$X$ is compact, path connected and non-empty, therefore the image of $f$ must be a non-empty, compact and connected subset of $\Bbb R$, id est an inteval in the form $[a,b]$ for some $a\le b$. Personally, I would just say that connected subsets of $\Bbb R$ are intervals and that compact subsets of $\Bbb R$ have a maximum and a minimum, but your work doesn't seem incorrect.


text:
Q: Showing notification to user at specific time, but it appears every time when i closed or open my application? The full scenario is I am trying to show notification according to user selected time for that I am using a TimePickerDialog, BroadcastReceiver class and a Service class, every thing is working fine notification also appears at specific times, but the problem is when I open and close the application every time notification comes.

Activity.java

Intent myIntent = new Intent(ReminderActivity.this, MyBreakfastReciver.class);
System.out.println("getting Breakfast Reminder");
pendingIntent = PendingIntent.getBroadcast(ReminderActivity.this, 0, myIntent,0);

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());

//bTimePart1 and bTimePart2 is the time choosen by user through time picker
calendar.set(Calendar.HOUR_OF_DAY, bTimePart1 );
calendar.set(Calendar.MINUTE, bTimePart2);

AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);

BroadcastReciever

public class MyBreakfastReciver extends BroadcastReceiver
{

    @Override
    public void onReceive(Context context, Intent intent)
    {
        Intent service1 = new Intent(context, MyBreakfastAlarmService.class);
        context.startService(service1);

    }

}

Reciever class

 private void showNotification(Context context) {
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(context)
        .setSmallIcon(R.drawable.notificationlogo)
        .setContentTitle("DietGuru")
        .setAutoCancel(true)
        .setContentText("You haven't logged your BreakFast for today.")
        .setSubText("Would you like to do it now?");

        // Creates an explicit intent for an Activity in your app
        Intent resultIntent = new Intent(context, CalorieMainActivity.class);

        // The stack builder object will contain an artificial back stack for the
        // started Activity.
        // This ensures that navigating backward from the Activity leads out of
        // your application to the Home screen.
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
        // Adds the back stack for the Intent (but not the Intent itself)
        stackBuilder.addParentStack(CalorieMainActivity.class);

        // Adds the Intent that starts the Activity to the top of the stack
        stackBuilder.addNextIntent(resultIntent);

        resultPendingIntent =
                stackBuilder.getPendingIntent(
                        0,
                        PendingIntent.FLAG_CANCEL_CURRENT
                        );
        mBuilder.setContentIntent(resultPendingIntent);

        //mBuilder.setContentIntent(resultPendingIntent);
        mBuilder.setDefaults(Notification.DEFAULT_ALL);

        NotificationManager mNotificationManager =
                (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        // mId allows you to update the notification later on.

        mNotificationManager.notify(1, mBuilder.build());

    }

I just want to stop my notification when I open and close my application.

A: If your time time selection is before ur current time then Alaram fire event so try to check if time is before current time then add day so Alaram fire event on next day with given time, Check below example with fire notifiaction 8 a.m on each day :
 Calendar calendar = Calendar.getInstance();
 calendar.setTimeInMillis(System.currentTimeMillis());
 // Set the alarm's trigger to next day if set alAram after 8 a.m.
 if(calendar.get(Calendar.HOUR_OF_DAY)>8){
       calendar.add(Calendar.DAY_OF_MONTH,1);
 }
 // Set the alarm's trigger time to 8:00 a.m.
 calendar.set(Calendar.HOUR_OF_DAY, 8);
 calendar.set(Calendar.MINUTE,0);
 calendar.set(Calendar.SECOND,0);


text:
Q: socket.io web client not working I recently met the socket world with socket.io and node.js
I found this server example online: https://gist.github.com/creationix/707146
I created a first client on iOS and i receive and dispatch messages, the same as telnet client, next I would like to create a second client with socket.io to receive the messages on the browser too.
I tried the example in the howto: http://socket.io/#how-to-use but with these examples the client is not even recognized!
Where am I wrong? Where do I start?
The server code:
// Load the TCP Library
net = require('net');

// Keep track of the chat clients
var clients = [];

// Start a TCP Server
net.createServer(function (socket) {

// Identify this client
socket.name = socket.remoteAddress + ":" + socket.remotePort

// Put this new client in the list
clients.push(socket);

// Send a nice welcome message and announce
socket.write("Welcome " + socket.name + "\n");
broadcast(socket.name + " joined the chat\n", socket);

// Handle incoming messages from clients.
socket.on('data', function (data) {
broadcast(socket.name + "> " + data, socket);
});

// Remove the client from the list when it leaves
socket.on('end', function () {
clients.splice(clients.indexOf(socket), 1);
broadcast(socket.name + " left the chat.\n");
});

// Send a message to all clients
function broadcast(message, sender) {
clients.forEach(function (client) {
  // Don't want to send it to sender
  if (client === sender) return;
  client.write(message);
});
// Log it to the server output too
process.stdout.write(message)
}

}).listen(5000);

// Put a friendly message on the terminal of the server.
console.log("Chat server running at port 5000\n");

The client code:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
 });
</script>

Thanks a lot.

A: I know its late, and you probably solved the issue but the server is listening on port 5000.
Your client is connecting to port 80.
Change the clinet code to:
   <script src="/socket.io/socket.io.js"></script>
   <script>
   var socket = io.connect('http://localhost:5000');
   socket.on('news', function (data) {
   console.log(data);
   socket.emit('my other event', { my: 'data' });
    });
   </script>


text:
Q: Set position of image in a window using pygtk Is it possible to set the position of an image using pygtk?
import pygtk
import gtk

class Example:
    self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
    self.image = gtk.Image()
    self.image.set_from_file("example.png")
    # Position goes here (it should, shouldn't it?)
    self.window.add(self.image)
    self.image.show()
    self.window.fullscreen()
    self.window.show_all()

A: GTK lays widgets out based on relative alignments and padding, not absolute pixel positions. Instances of gtk.Image have properties xalign, xpad, yalign, ypad that can be used to position the widget if the parent has more space than is needed.
For example
self.image.xalign = 0.5
self.image.yalign = 0.5

would center the image in the window
self.image.xalign = 0
self.image.yalign = 0

would place the image in the upper left
self.image.xalign = 1
self.image.yalign = 1

would place the image in the bottom right
If you really want to deal with fixed positions then you need to use the gtk.Fixed widget. It allows to specify an explicit position when adding a child through the method put(child, x, y). Heed the warning in the documentation, though, that it's a bad idea and will make for a broken UI.


text:
Q: Declaring indexes together or separately, what is the difference? I'm having trouble with huge datasets in mysql and I'm exploring lots of different ways to index. Can anyone tell me what the difference is if I declare several indexes together
ALTER TABLE `db`.`test` ADD INDEX `someindex` (field1, field2, field3);

Rather than declaring them separately?
ALTER TABLE `db`.`test` ADD INDEX `f1` (field1), ADD INDEX `f2` (field2);

Why would one want to declare them together or separately?

A: Databases can typically only use one index per query, so assuming that all three columns are in your 'where' clause, you would want the single, compound index.
However, compound indexes can only be used partially from left to right, so if you have another query on, say, just field1, then the compound index will still be used. But, for a query with only field2 in the 'where' clause, that index cannot be used, and you will need an index that is either just on field2, or one which is compound, but starts with field2.
This is explained in detail in the [MySQL documentation]

A: I teach MySQL training classes, and when discussing multi-column indexes, I use an analogy to a telephone book.  A telephone book is basically an index on last name, then first name.  So the sort order is determined by which "column" is first.  Searches fall into a few categories:

*

*If you look up people whose last name is Smith, you can find them easily because the book is sorted by last name.

*If you look up people whose first name is John, the telephone book doesn't help because the Johns are scattered throughout the book.  You have to scan the whole telephone book to find them all.

*If you look up people with a specific last name Smith and a specific first name John, the book helps because you find the Smiths sorted together, and within that group of Smiths, the Johns are also found in sorted order.

If you had a telephone book sorted by first name then by last name, the sorting of the book would assist you in the above cases #2 and #3, but not case #1.
That explains cases for looking up exact values, but what if you're looking up by ranges of values?  Say you wanted to find all people whose first name is John and whose last name begins with 'S' (Smith, Saunders, Staunton, Sherman, etc.).  The Johns are sorted under J within each last name, but if you want all Johns for all last names starting with S, the Johns are not grouped together.  They're scattered again, so you end up having to scan through all the names with last name starting with 'S'.  Whereas if the telephone book were organized by first name then by last name, you'd find all the Johns together, then within the Johns, all the S last names would be grouped together.
So the order of columns in a multi-column index definitely matters.  One type of query may need a certain column order for the index.  If you have several types of queries, you might need several indexes to help them, with columns in different orders.
For more details and examples, see my presentation How to Design Indexes, Really. Or watch my presentation on video.

To clarify when to use a single-column index vs. a multi-column index, consider if you are using your phone book to look up a person by the combination of last name and first name. For example "Sarah Smith."
If you had two phone books, one organized by last name and the other organized by first name, you could search the last name book for "Smith" and search the first name book for "Sarah" and then somehow find the intersection of the two results. MySQL sometimes tries to do this with the index merge algorithm.
It would be better to search one index, if it's sorted by both last name and first name, like a real phone book. Then the search finds the subset of the book for "Smiths" and within that subset, it can efficiently search for "Sarahs" because the subset is sorted by first name.


text:
Q: @NotNull annotation is not working in Spring boot application Below is my DTO class.
public class AbstractDTO extends BaseDTO {

    private Integer createdBy;

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = DATE_FORMAT)
    @NotNull(message = "createdDate may not be null")
    private LocalDateTime createdDate;

    private Integer lastModifiedBy;
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = DATE_FORMAT)
    private LocalDateTime lastModifiedDate;

    private Boolean isActive;

    // getter & setters
}

Here I am trying to annotate createdDate field as @NotNull but is it not working. It is allowing in request body and after executing the service in postman not getting any error.
I have tried below options but no luck.
1) Tried to add maven dependency.
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

2) Tried to annotate DTO class as @Validated
3) Tried to annotate createdDate field @Valid with @NotNull but still not luck.
Please help me out with this issue.

A: You have an endpoint with some request body like;
@RestController
public class TheController {

    @PostMapping(path = "/doSomething", consumes = "application/json", produces = "application/json")
    public void post(@Valid @RequestBody AbstractDTO request) {
        //code
    }
}

You need to have @Valid annotation for the request object. Only with this you'd have validation enabled for AbstractDTO for /doSomething endpoint.
Check here, for more in depth details

A: Have you got the right import ?
I use import javax.validation.constraints.NotNull;

A: Your DTO class is correct. You have to use @Valid annotation.
For example :
@Controller
public class Controller {

    @PostMapping("/")
    public String checkPersonInfo(@Valid AbstractDTO abstractDTO, BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {
            return "some-page";
        }
        return "some-other-page";
    }
}

Refer to this Spring Boot Example On Validating Form Input  for reference.
Why to use @Valid annotation ?
This allows you to validate the set of constraints applied on the data members of a class.

However, if you have XML based configuration in your project, then you have to add this below in the applicationContext.xml given below. (Source : here)
<bean
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="webBindingInitializer">
        <bean
            class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
            <property name="validator" ref="validator" />
        </bean>
    </property>
</bean>

    <bean id="validator"
        class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
    </bean>

A: Description

*

*In my case, I define 1 parent class A has 3 sub class B, C, D such as:

public A {   private B bCommand;   private C cCommand;   private D
dCommand; }

*I annotated @NotNull, @NotBlank for some fields in 3 sub class.
In Controller, I have put @Valid for function like that:

@PostMapping() public ResponseEntity create(@RequestBody @Valid A
command){ }

Solution

*

*I put @Valid for sub class which has field(s) need to check constraint.

*Example:
Class B, C have some fields which have constraint like not null

public A {  @Valid   private B bCommand;  @Valid   private C cCommand;
private D dCommand; }


text:
Q: Ruby - how to test method using minitest I have this class:
require 'yaml'

class Configuration
  class ParseError < StandardError; end

  attr_reader :config

  def initialize(path)
    @config = YAML.load_file(path)
  rescue => e
    raise ParseError, "Cannot open config file because of #{e.message}"
  end

  def method_missing(key, *args, &block)
    config_defines_method?(key) ? @config[key.to_s] : super
  end

  def respond_to_missing?(method_name, include_private = false)
    config_defines_method?(method_name) || super
  end

  private

  def config_defines_method?(key)
    @config.has_key?(key.to_s)
  end
end

how do I write test for methods: method_missing, respond_to_missing?, config_defines_method?
I have some understanding about unit testing but when it comes to Ruby im pretty new.
So far i have tried this:
def setup
  @t_configuration = Configuration.new('./config.yaml')
end

def test_config_defines_method
  @t_configuration.config[:test_item] = "test"
  assert @t_configuration.respond_to_missing?(:test_item)
end

Im not sure if im testing it right, because when i run rake test it gives me this:

NoMethodError: private method `respond_to_missing?' called for #

If there is no clear way how to solve this, can anyone direct me to a place where similar tests are written? So far Ive only found hello world type of test examples which are not helping much in this case.

A: As mentioned in the documentation for #respond_to_missing?, you do not want to call the method directly. Instead, you want to check that the object responds to your method. This is done using the #respond_to? method:
assert @t_configuration.respond_to?(:test_item)


text:
Q: Can we know the installation order of features that are being installed with the msi Can we know the installation order of features that are being installed with the msi.
And also the exact time taken for which each feature to get installed completely?

A: MSI doesn't install files/components/features in a deterministic order.  Instead it determines what need to be installed/replaced/removed  and then executes them like such:
StopServices
RemoveServices
RemoveRegistry
RemoveFiles
RemoveFolders
CreateFolders
CopyFiles
WriteRegistry
CreateServices
StartServices
For some of these nothing may be needed depending on whether it's a first time install, final uninstall or maintenance transaction such as feature change, repair or upgrade.
Within any given type of resources (say folders, files, registry or services ) it is generally non-deterministic in which order they will be installed.
Finally  MSI only predicts (costs) disk space needed it makes no calculations on how long something will take.


text:
Q: Reverse Iteration of an STL Algorithm I have a function that is being called with 2 pointers for arguments, the beginning and and ending of an array. My function will search from the end pointer to the beginning pointer for an element that matches a condition.
If I was trying to iterate forward I could do this with find_if but I need to iterate in reverse. Does the STL have any provision for this?
Note: I can easily do this in a for loop. What I'm looking for is a more elegant solution.

A: Yes, it is called std::reverse_iterator. An example:
template<typename RandomAccessIterator>
void reverse_sort(RandomAccessIterator begin, RandomAccessIterator end) {
    typedef std::reverse_iterator<RandomAccessIterator> r_iter_t;
    std::sort(r_iter_t(end), r_iter_t(begin));
}

int main() {
    int arr[] = { 1, 2, 3 };
    reverse_sort(std::begin(arr), std::end(arr));
    for(auto i : arr) std::cout << i << "\n";
}

gives
3
2
1


text:
Q: Visual Studio 2019 How do I choose Clang to be the toolchain? I want to create a Visual Studio project, compile with Clang and run on Windows.
I was trying to following this guide:
https://devblogs.microsoft.com/cppblog/clang-llvm-support-in-visual-studio/
But after an introduction to installation it suddenly mentions CMake.
So far I have:

*

*Installed VS2019 (choosing Clang tools for Windows option)

*Created an Empty C++ project

How do I now instruct my project to use Clang?

A: In each project's "Properties" pop-up, select "LLVM (clang-cl)" as the "Platform Toolset" to use, as shown below:

If you don't see this option, then you (probably) need to add more of the 'optional' Clang-related components, via your Visual Studio Installer (select "Modify" and list "Individual Components"):

You'll need the "Clang-cl for v142 build tools..." at the very least.


text:
Q: Customizing WP FlexSlider plugin - removing prev/next side panels I'm wondering if there is a way to either a) reduce the width of the prev/next sides of the slider or b) remove these two panels entirely but keep the arrows in place to cycle through the slides? (These elements seem to be ul.flex-direction-nav.)
I've tried
ul.flex-direction-nav { display:none; } to no avail.
Slider can be viewed as used in this theme - http://themeforest.net/item/serene-magazine-wordpress-theme/5663537

A: the styles it is using are more specific than the ones you're trying to override them with.
To remove completely:
#featured-slider .flex-direction-nav { display:none; }

then you'll need to remove the padding from #featured-slider:
#featured-slider { padding:none; }

if you're testing in firebug you will need to scroll once you add these styles for the plugin's jquery to show the adjustments correctly.

To re-size:
you need to adjust the width of the next/prev slides, the width of the link, the positioning of the arrows, and the positioning of the circles around the arrows. example of 100px wide:
<!-- next/prev slide width -->
#featured-slider { padding-left:100px; padding-right:100px; }

<!-- link width -->
#featured-slider .flex-direction-nav a { width:100px; }

<!-- circle position -->
#featured-slider .flex-direction-nav a:after { left:30px; }

<!-- arrow position -->
#featured-slider .flex-direction-nav a:before { left:36px; }

hope that helps.

A: Flexslider actually already has default settings to control wether navigation is displayed or not. In your JS, where you call flexslider, try something like:
$('.your-flex-element').flexslider({
 controlNav: false;
 directionNav: false;
});


text:
Q: Shortcut is not triggering in WPF window The following code is working for usercontrols but not in the Mainwindows. Setting Focusable="True" for the mainwindow.
<Window.InputBindings>
  <KeyBinding Modifiers="Ctrl" Key="S" Command="{Binding SaveCommand}" />
</Window.InputBindings>

    private ICommand _saveCommand;
    public ICommand SaveCommand
    {
        get
        {
            if (_saveCommand == null)
            {
                _saveCommand = new RelayCommand(
                    param => this.SaveObject(),
                    param => this.CanSave()
                );
            }
            return _saveCommand;
        }
    }

    private bool CanSave()
    {
        return (Project != null);
    }

    private void SaveObject()
    {
        // Code here
    }

A: Got fixed by using the below code from the link.
Keyboard shortcuts in WPF
public YourWindow() //inside any WPF Window constructor
{
   ...
   //add this one statement to bind a new keyboard command shortcut
   InputBindings.Add(new KeyBinding( //add a new key-binding, and pass in your command object instance which contains the Execute method which WPF will execute
      new WindowCommand(this)
      {
         ExecuteDelegate = TogglePause //REPLACE TogglePause with your method delegate
      }, new KeyGesture(Key.P, ModifierKeys.Control)));
   ...
}
Create a simple WindowCommand class which takes an execution delegate to fire off any method set on it.
public class WindowCommand : ICommand
{
    private MainWindow _window;
//Set this delegate when you initialize a new object. This is the method the command will execute. You can also change this delegate type if you need to.
public Action ExecuteDelegate { get; set; }

//You don't have to add a parameter that takes a constructor. I've just added one in case I need access to the window directly.
public WindowCommand(MainWindow window)
{
    _window = window;
}

//always called before executing the command, mine just always returns true
public bool CanExecute(object parameter)
{
    return true; //mine always returns true, yours can use a new CanExecute delegate, or add custom logic to this method instead.
}

public event EventHandler CanExecuteChanged; //i'm not using this, but it's required by the interface

//the important method that executes the actual command logic
public void Execute(object parameter)
{
    if (ExecuteDelegate != null)
    {
        ExecuteDelegate();
    }
    else
    {
        throw new InvalidOperationException();
    }
}

}


text:
Q: errorCallback not catching exception in child when thrown in apex call promise I have a web component (lwc) with a child component that makes an imperative server call. When an exception is thrown by the server the parent component is not catching it in the errorCallback. The parent errorCallback is working when the child throws from other parts of the code.
I'm ok to work around this and trigger an event to notify the parent but I wonder if this is expected behaviour?
pseudocode
   /* parent.html */
  <template>
   <c-child></c-child>
  </template>

/* parent.js */
import { LightningElement} from 'lwc';
export default class child extends LightningElement {
  errorCallback(err){
   console.log('parent error handler', err);
 }
}

/* child.html */
<template>
</template>

/* child.js */
import { LightningElement } from 'lwc';
import getDataFromServer from '@salesforce/apex/apexController.getData';

export default class child extends LightningElement {
 serverCall(){
  getDataFromServer()
        .then((data) => {
            // process success
        })
        .catch((error) => {
            console.error(error);
            throw error?.body?.message;
        });
    }
 }
}

I expected the console output to be 'parent error handler' but what I get is 'uncaught in promise'.

A: Yes, this is expected behavior. It's a feature of Promises, not LWC specifically. You have to first somehow "break out" of the Promise before you can throw a catchable exception. Something like the following should work:
  error;
  throwError() {
    setTimeout(() => {
      throw this.error;
    });
  }
  serverCall() {
    getDataFromServer()
      .then((data) => {
        // process success
      })
      .catch((error) => {
        this.error = error;
        this.throwError();
      });
  }

The setTimeout breaks us out of the Promise, and we're free to throw the error. Note, however, that the stack trace will show that the error came from throwError, not the original serverCall, so you might need to store additional information about the problem.


text:
Q: How to enable zoom for all the webViews text font in UIPageViewController I am creating one page view controller based application in portrait mode only, where i am loading multiple html pages in UIWebView. Inside the web view have zoom in and zoom out functionality. when i click on the zoom button only the current page gets zoomed. I want that all the web view text fonts to be same. I am trying but not getting output properly.
here is my code....
   - (void)viewDidLoad
   {
      [super viewDidLoad];

     zoomButtonPressed = NO;
     buttonPressed = NO;

     //Instantiate the model array
     self.htmlArray = [[NSMutableArray alloc] init];

     NSString *path;
     NSBundle *bundle = [NSBundle mainBundle];

       for (int index = 1; index <= 94 ; index++)
        {
          path = [bundle pathForResource:[NSString stringWithFormat:@"p_%d",index]
          ofType:@"html"];
         [self.htmlArray addObject:path];
        }

       //Step 1
       //Instantiate the UIPageViewController.
       self.pageViewController = [[UIPageViewController alloc]
       initWithTransitionStyle:UIPageViewControllerTransitionStylePageCurl

       navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal
       options:nil];

       //Step 2:
       //Assign the delegate and datasource as self.
       self.pageViewController.delegate = self;
       self.pageViewController.dataSource = self;

       //Step 3:
       //Set the initial view controllers.
       ContentViewController *contentViewController = [[ContentViewController alloc]
       initWithNibName:@"ContentViewController_iPad" bundle:nil];

       contentViewController.strURL = [self.htmlArray objectAtIndex:0];

       NSArray *viewControllers = [NSArray arrayWithObject:contentViewController];

       [self.pageViewController setViewControllers:viewControllers
       direction:UIPageViewControllerNavigationDirectionForward animated:NO
       completion:nil];

       //Step 4:
       //Add the pageViewController as the childViewController
       [self addChildViewController:self.pageViewController];

       //Add the view of the pageViewController to the current view
       [self.view addSubview:self.pageViewController.view];

       [self.pageViewController didMoveToParentViewController:self];

       //Step 5:
       // set the pageViewController's frame as an inset rect.
       CGRect pageViewRect;

       pageViewRect = CGRectMake(5, 201, 745, 834);
       pageViewRect = CGRectInset(pageViewRect, 12.0, 73.0);

       self.pageViewController.view.frame = pageViewRect;

      //Step 6:
      self.view.gestureRecognizers = self.pageViewController.gestureRecognizers;
     }

     #pragma mark - UIPageViewControllerDataSource Methods

     - (UIViewController *)pageViewController:(UIPageViewController *)pageViewController
     viewControllerBeforeViewController:(UIViewController *)viewController
     {

       NSUInteger currentIndex = [self.htmlArray indexOfObject:[(ContentViewController
       *)viewController strURL]];
          if(currentIndex == 0)
          {
             return nil;
          }
     ContentViewController *contentViewController = [[ContentViewController alloc]
     init];
     contentViewController.strURL = [self.htmlArray objectAtIndex:currentIndex - 1];

     buttonPressed = NO;

     if (currentIndex % 2 == 0) {
        content=contentViewController;
     }
     else {
        content1=contentViewController;
     }

     if (zoomButtonPressed)
     {
        [self setTextZooming];
     }

    return contentViewController;
   }

    - (UIViewController *)pageViewController:(UIPageViewController *)pageViewController
    viewControllerAfterViewController:(UIViewController *)viewController
   {

      NSUInteger currentIndex = [self.htmlArray indexOfObject:[(ContentViewController
      *)viewController strURL]];
      if(currentIndex == self.htmlArray.count-1)
      {
        return nil;
      }

      ContentViewController *contentViewController = [[ContentViewController alloc]
      init];
      contentViewController.strURL = [self.htmlArray objectAtIndex:currentIndex + 1];

      buttonPressed = NO;

      if (currentIndex % 2 == 0) {
         content=contentViewController;
      }
      else {
         content1=contentViewController;
      }

      if (zoomButtonPressed)
      {
         [self setTextZooming];
      }

    return contentViewController;
   }

   #pragma mark - UIPageViewControllerDelegate Methods

   - (UIPageViewControllerSpineLocation)pageViewController:(UIPageViewController
   *)pageViewController
               spineLocationForInterfaceOrientation:(UIInterfaceOrientation)orientation
   {

    if(UIInterfaceOrientationIsPortrait(orientation))
     {
    //Set the array with only 1 view controller
    UIViewController *currentViewController = [self.pageViewController.viewControllers
    objectAtIndex:0];

    NSArray *viewControllers = [NSArray arrayWithObject:currentViewController];
    [self.pageViewController setViewControllers:viewControllers
    direction:UIPageViewControllerNavigationDirectionForward animated:YES
    completion:NULL];

    //Important- Set the doubleSided property to NO.
    self.pageViewController.doubleSided = NO;

    //Return the spine location
    return UIPageViewControllerSpineLocationMin;
  }
  else
   {
     NSArray *viewControllers = nil;
     ContentViewController *currentViewController =
     [self.pageViewController.viewControllers objectAtIndex:0];

    NSUInteger currentIndex = [self.htmlArray indexOfObject:[(ContentViewController
    *)currentViewController strURL]];

       if(currentIndex == 0 || currentIndex %2 == 0)
         {
        UIViewController *nextViewController = [self
        pageViewController:self.pageViewController
        viewControllerAfterViewController:currentViewController];

        viewControllers = [NSArray arrayWithObjects:currentViewController,
        nextViewController, nil];
         }
       else
         {
            UIViewController *previousViewController = [self
            pageViewController:self.pageViewController
            viewControllerBeforeViewController:currentViewController];

            viewControllers = [NSArray arrayWithObjects:previousViewController,
            currentViewController, nil];
         }

       //Now, set the viewControllers property of UIPageViewController
        [self.pageViewController setViewControllers:viewControllers
        direction:UIPageViewControllerNavigationDirectionForward animated:YES
        completion:NULL];

     return UIPageViewControllerSpineLocationMid;
     }
   }

   -(void) setTextZooming
   {
     if (!buttonPressed){
     content.webView.scrollView.scrollEnabled = YES;
     content1.webView.scrollView.scrollEnabled = YES;
     int fontSize = 120;
     NSString *string = [[NSString alloc]
     initWithFormat:@"document.getElementsByTagName('body')
     [0].style.webkitTextSizeAdjust= '%d%%'", fontSize];
     [content.webView stringByEvaluatingJavaScriptFromString:string];
     [content1.webView stringByEvaluatingJavaScriptFromString:string];
     buttonPressed=YES;
     zoomButtonPressed = YES;
    }
    else{
     content.webView.scrollView.scrollEnabled = NO;
     content1.webView.scrollView.scrollEnabled = NO;
     int fontSize = 97;
     NSString *string = [[NSString alloc]
     initWithFormat:@"document.getElementsByTagName('body')
     [0].style.webkitTextSizeAdjust= '%d%%'", fontSize];
     [content.webView stringByEvaluatingJavaScriptFromString:string];
     [content1.webView stringByEvaluatingJavaScriptFromString:string];
     buttonPressed=NO;
     zoomButtonPressed = NO;
    }
   }

  // When user clicks on zoom button.
  -(IBAction)zoomBtnPressed:(id)sender
  {
     [self setTextZooming];
  }

A: I found the problem:
In UIPageViewController delegate methods
      - (UIViewController *)pageViewController:(UIPageViewController *)pageViewController
        viewControllerAfterViewController:(UIViewController *)viewController

      - (UIViewController *)pageViewController:(UIPageViewController *)pageViewController
        viewControllerBeforeViewController:(UIViewController *)viewController

The problem was before returning my view controller i am directly setting the font increasing method. The method "setTextZooming" is calling, but it will never work because transaction (animation) in progress. So set animated:NO or use this..
     if (zoomButtonPressed)
     {
         [self performSelector:@selector(setTextZooming) withObject:nil afterDelay:0.4];
     }

This works for me...


text:
Q: Appending div's in angular I'm new to angular and I'm trying to do the following:
I have li's inside one ul . Suppose I have 15 li's and I want to append a div after the 4th li and 12th li.
How can I do that in angular?
Here's what my code looks like:

....

 ...

The li's are placed as follows: Initially only  7 li's are visible. If more are to be seen "show more" is hit and more 7 li's will be visible.
li1 li2
li3 li4  **li5**
li6  li7

Show more

li8 li9 li10

li11 li12 **li13**

li14 li15

In place of li5 and li13 I want to append two separate div's with different id's. Is there any easy way to do it?

  This will be in li5 position ie next to li4

  This will be in li13 position ie next to li12

A: You can do this using ng-repeat-start combined with ng-repeat-end along with a conditional ng-if to check index.
Will use limitTo filter to set how many to show and start point. For demo it just toggles the start at 0 or 7...leave it to you to add better logic
HTML

{{item.item}}

Change Start

JS
 $scope.start =0;

 $scope.toggleStart = function(){
     $scope.start = $scope.start === 0 ? 7 :0;
 }

DEMO

A: The ideal way would be to preprocess your data within the controller, map it to an array that has all your states covered:
var stories = [
    {story: storyData, visible: true, div: false},
    {story: storyData, visible: true, div: false},
    {story: storyData, visible: true, div: false},
    {story: storyData, visible: true, div: false},
    {story: storyData, visible: true, div: true},
    ...
];

$scope.stories = stories;

Then in the view you can easily iterate using entry in stories, and use triggers like ng-show="entry.div" to alternate between div vs. non-div, ng-show="entry.visible" to alternate between visible-immediately vs. when show-more is clicked.
You can have a button trigger $scope.showMore(), which could process this data to switch state of visible from false to true on the next n records, starting at the first record that is hidden.


text:
Q: What does $('') mean in JavaScript?
Possible Duplicate:
What is the meaning of "$" sign in javascript

I've encountered a code in JavaScript that looks like this:
$('svg circle').tipsy({
    gravity: 'w',
    html: true,
    title: function() {
      return 'Color: ';
    }
});

What does $('') mean here?

A: This is from using the jQuery library, which is used to standardize JavaScript usage between browsers and make accessing elements and other common tasks much, much easier. It is not a part of JavaScript itself, except insofar as $ is an acceptable name for a function or variable.

A: Usually when you encounter $(), that means the developer is using a javascript library, such as jQuery.
The $ symbol is the namespace for those libraries.  All the functions they define begin with $., such as $.get().  Passing the id of an html tag like this: $("#myId") will give you a jQuery object representing that node.

A: This is the shorted initializing function for jQuery or zeptojs
$("selector").method();

It can also mean an shorten for document.getElementById if the framework is used:
$('myId'); // document.getElementById("myId");

The plugin tipsy is used witch creates tooltips on hover.


text:
Q: Define code sections in sql managment studio I have a very long script in sql. I'm working with SSMS 2012 and sql servr 2012.
The sturctre is somewhere like this:
--Loans_Group
--2013
create view Loans_2013
(
select * from X where yr=2013
)
go

--2014
create view Loans_2014
(
select * from X where yr=2014
)
go
--2015
create view Loans_2015
(
select * from X where yr=2015
)
go
--2016
create view Loans_2016
(
select * from X where yr=2016
)
go
--2017
create view Loans_2017
(
select * from X where yr=2017
)
go

--Credit scoring Group

--2013
create view CS
(
select * from Y where yr=2013
)
go

--2014
create view CS where yr=2014
(
select * from Y
)
go

--2015
create view CS
(
select * from Y where yr=2015
)
go

--2016
create view CS where yr=2016
(
select * from Y
)
go

--2017
create view CS where yr=2017
(
select * from Y
)
go

create view Loans_Join as (
select * from Loans_2013
union
select * from Loans_2014
union
select * from Loans_2015
union
select * from Loans_2016
union
select * from Loans_2017
)
select * into Loans_Join_table from Loans_Join

create view CS_Join as (
select * from  CS_2013
union
select * from  CS_2014
union
select * from  CS_2015
union
select * from  CS_2016
union
select * from  CS_2017
)
select * into CS_Join_table from CS_Join

create view FlatFile as (

select * from Loans_Join
left join CS_Join on Loans_Join.Cust = CS_Join.Cust

)

Now, Suppose I would like to create a Analysis Table only for 2014-2015. In order to that I will need to comment all the parts of code of the other years... including those parts in the views where I am union-ing all the views from all the years - Loans_Join and CS_Join.
In my real code there are something like 20 groups beside Loans and CS.
There is a reason why in order to create my Analysis Table I'm dividing it to parts of years and not using parameters. It's a little long for me here to get into those reasons.
I'm asking for an easy way I can set code sections and comment them when I execute the query.
Something like this:
set code sections = (2013,2014,2015,2016,2017)
comment Code_Sections = (2014,2015)
and the press the F5 key.. Is someone know an option like that?


text:
Q: java.sql.Connection compatibility issue between java 1.5 and java 1.6 java.sql.Connection is implemented into a verbose connection to get more information for unit tests.
Using java 1.6 compiler results in following compilation errors:
The type VerboseConnection must implement the inherited abstract method Connection.createArrayOf(String, Object[])
    The type VerboseConnection must implement the inherited abstract method Connection.createBlob()
    The type VerboseConnection must implement the inherited abstract method Connection.createClob()
    The type VerboseConnection must implement the inherited abstract method Connection.createNClob()
    The type VerboseConnection must implement the inherited abstract method Connection.createSQLXML()
    The type VerboseConnection must implement the inherited abstract method Connection.createStruct(String, Object[])
    The type VerboseConnection must implement the inherited abstract method Connection.getClientInfo()
    The type VerboseConnection must implement the inherited abstract method Connection.getClientInfo(String)
    The type VerboseConnection must implement the inherited abstract method Connection.isValid(int)
    The type VerboseConnection must implement the inherited abstract method Connection.setClientInfo(Properties)
    The type VerboseConnection must implement the inherited abstract method Connection.setClientInfo(String, String)
    The type VerboseConnection must implement the inherited abstract method Wrapper.isWrapperFor(Class)
    The type VerboseConnection must implement the inherited abstract method Wrapper.unwrap(Class)

Implementing the above methods works fine in 1.6 But again if we use
 Java 1.5 compiler, results in the following compilation errors
NClob cannot be resolved to a type
    SQLClientInfoException cannot be resolved to a type
    SQLClientInfoException cannot be resolved to a type
    SQLXML cannot be resolved to a type
    The import java.sql.NClob cannot be resolved
    The import java.sql.SQLClientInfoException cannot be resolved
    The import java.sql.SQLXML cannot be resolved

Please suggest on how to make it work in both the versions with out
maintaining 2 different files for different versions?

A: If you need to supply both a Java 1.5 and a Java 1.6 implementation, you could use an abstract base class in your project and add a Java version dependent implementation in a separate project.
Depending on the Java version compile one or the other and include the resulting class files in your main jar file.
This is the approach we use in the implementation of Jaybird (Firebird JDBC driver).


text:
Q: od prints extra value I have a binary file containing 4-byte floats. I want to print these floats using od. However, od prints one additional value at the very first position. What is going on here?
The file looks like this:
xxd test | head -1

0000000: 932a 6541 7cdf 6b41 6c7e 7141 d779 7641  .*eA|.kAl~qA.yvA

od prints this:
cat test | od -f -An -v -w4 | head -2

   14,322894
   14,742062

The first printed value (14.32) is not the first value in the file. The second printed value (14.74) is the actual first value from the file. I verified with several hex editors that

932a 6541

is 14.74206 (or a value very close to that). So where is od getting the extra value (14.32) from? This also happens when all other options are omitted:
cat test | od -f | head -2

0000000       14,322894       14,742062       15,093365       15,404746
0000020       15,652825       15,938543        16,25734      16,616056

A: od is correct. I based my expected output on two hex editors which showed a floating-point value other than the one I selected. Thank you, @schily, for pointing out that the first four bytes actually represent 14.32 and that od is therefore correct.


text:
Q: System.IO.File.Copy() produces System.IO.IOException: The specified network name is no longer available I have a windows service (C# .Net 3.5) that grabs data from a network share and does a copy to the host of the service.
The size of the data copied ranges from 50KB to 750MB, and the number of files copied varies.  In perhaps 20% of the copies I am getting System.IO.IOException: The specified network name is no longer available.
My google-fu is failing to turn up an answer as to what might cause this during a File.Copy.  Has anyone seen/solved this before?
Here is the recursive method that does the copy.  The exception occurs on line File.Copy(fromFile, toFile, overwrite);
private static int RecursiveCopyDirectory(string from, string to, bool merge, bool overwrite, int depth)
    {
        depth++;

        if (!from.EndsWith(Path.DirectorySeparatorChar.ToString()))
        {
            to += Path.DirectorySeparatorChar;
        }
        if (!to.EndsWith(Path.DirectorySeparatorChar.ToString()))
        {
            to += Path.DirectorySeparatorChar;
        }

        System.Diagnostics.Debug.WriteLine(string.Format("RecursiveDirectoryCopy( {0}, {1}, {2} )", from, to, merge));
        if (Directory.Exists(to))
        {
            if (!merge)
            {
                return (int)EventEnum.FileSystemError_DirectoryAlreadyExists;
            }
        }
        else
        {
            Directory.CreateDirectory(to);
        }

        string[] directories = Directory.GetDirectories(from);

        foreach (string fromDirectory in directories)
        {
            string [] fromDirectoryComponents = fromDirectory.Split(Path.DirectorySeparatorChar);
            string toDirectory = to + fromDirectoryComponents[fromDirectoryComponents.Length - 1];
            RecursiveCopyDirectory(fromDirectory, toDirectory, merge, overwrite, depth);
        }

        string[] files = Directory.GetFiles(from);

        foreach (string fromFile in files)
        {
            string fileName = Path.GetFileName(fromFile);
            //System.Diagnostics.Debug.WriteLine(string.Format("Name: {0}", to + fileName));
            string toFile = to + fileName;

            File.Copy(fromFile, toFile, overwrite);
        }

        return (int)EventEnum.GeneralSuccess;
    }

A: File.Copy() opens up underline streams. You might have lost connection while File.Copy() is in progress. So, it can't flush and close the stream.
One possibility to recover from this, is to use the FileStream class and
call Win32 API CloseHandle when such exception occurs, doing so will release
the OS file handle so you can re-open the file.
[ DllImport("Kernel32") ]
public static extern bool CloseHandle(IntPtr handle);

FileStream fs;
try {
...
}

catch(IOException)
{
// If resource no longer available, or unable to write to.....
if(...)
CloseHandle(fs.Handle);
}

Also, MSDN recommends not to rely on overwrite. Try deleting existing file and creating new one when copying them.
File.Copy(..., ..., TRUE) does not work properly.

Be very careful with this method, as the Overwrite = True does NOT work properly.

I had an existing destination file that had some information inside it that was somehow preserved and carried over to the source file that was supposed to copy over it.  This should be impossible, but I confirmed it for myself.

A: The error seems to indicate that the network connection is lost partway through and probably isn't to do with the code at all. If the same folder copy succeeds sometimes and fails other times then this would back up that it's not the code to blame and must be a resource access issue.

A: It turns out that the customer that was using this software was running two instances of it simultaneously, against the same data set.  Once the redundant instance was stopped it resolved the error.  Thanks everyone who answered.


text:
Q: Multer fileFilter callback doesn't throw error I have this fileFilter code for multer. My problem is, when I call back an error, my Express app gets stuck, and eventually the page gives ERR_CONNECTION_RESET. This happens if I try to upload anything other than a jpeg.
const upload = multer({
  storage: storage,
  fileFilter: function (req, file, cb) {
    return cb(new ExpressError("Only images are allowed", 400));
  },
});

the storage is a cloudinary storage which looks like so
const { CloudinaryStorage } = require("multer-storage-cloudinary");
const storage = new CloudinaryStorage({
  cloudinary,
  params: {
    folder: "BilbaoBarrios",
    allowedFormats: ["jpeg", "png", "jpg"],
  },
});

Also, strangely, if I put the storage variable after FileFilter, it will also work with pngs, but still not with any other file format, which means order is in play here.
Thank you for your time.

A: Just to confirm, is Cloudinary being accessed within an in-office platform and behind a firewall (or VPN)? In case you are accessing it behind a firewall, delivering images & other Cloudinary assets sometimes requires whitelisting the Cloudinary domain (res.cloudinary.com) on your firewall.
Also, you can check out the sample I have on this link and see if it is blocked as well: https://codesandbox.io/s/upload-feature-demo-ckvgi?file=/src/CldUploaderForm.js


text:
Q: Tomcat 6.0 doesn't set Cookies in webkit based browsers on localhost I'm working on a website that runs on Tomcat 6.0 at localhost:8080. Interestingly enough, Tomcat seems to only be able to set cookies on Firefox. Opera and WebKit based browsers (Chrome, WinSafari) seem to fail. Is this a known issue and is there a solution?

A: So the problem was we were using a blank string as our cookie domain value. This works in Firefox. I had tried changing the base to locahost and 127.0.0.1 but that hadn't worked previously. There are two reasons for this: the cookies spec requires domains to have 2 or 3 dots in them (hence localhost shouldn't technically work, even though it's aliased). Also, the app host base was localhost:8080, and it's been changed to 127.0.0.1:8080. This satisfies the same domain condition.


text:
Q: Minecraft servers - 1 external IP, 2 servers, 2 ports - avoid specifying port in game - SRV record I have two minecraft servers, on sub-domains. www.server1.example.com and www.server2.example.com. server1 is port 25565, server2 is port 25566.
When users want to connect to a non-default port in minecraft, they have to specify www.server2.example.com:25566 to connect to the server. On the default port, this is not needed, they can simply connect via www.server1.example.com.
How can I pass along which port they're connecting to on the backside of things, so that users connecting to a non-standard port only have to type in the sub domain?
I think I may need something like SRV ( http://en.wikipedia.org/wiki/SRV_record ) anyone have experience with this?
Threads with people that have this working via SRV: http://www.minecraftforum.net/topic/1434125-srv-dns-records-server/ - the guy surviveminecraft is in my same situation, and has this working.
-UPDATE/RESOLUTION -
This is how I got this working, hopefully it will help someone else in my position.
I created a subdomain sub.example.com for the secondary server running on the non-standard port. ( 25566 )
In my provided DNS manager, under my SRV settings, I applied this in the provided boxes:
_minecraft._tcp.sub priority:0 weight:5 port:25566 target:<ip address here>

'_minecraft' is just a symbolic name, 'sub' is the name of your subdomain, for example it could be '_tcp.dev' if your subdomain was dev.example.com. Once the subdomain and the SRV are linked, it should work, providing you have the correct port entered and forwarded.
More info in my blog here.

A: Looks like the Minecraft client issues fetches a SRV record upon connect and uses the info there?  Interesting.
Basically you'll need an A record in DNS pointing to your server.  You probably already have two of these.
And then two CNAME records naming your first and second instance.  The CNAME's need to point to the name in the above A record.  Your CNAMEs need to end in the same domain as the respective server, I believe.
And then two SRV records, according to this format:
_minecraft._tcp.cname.domain.tdl. outside_port IN SRV 10 5 internal_port a_record.domain.tdl.
You'd replace cname above with the CNAME's you chose, and substitute the ports in the text above accordingly.
All this needs to be done on your provider's DNS server, or through their configuration utility they may provide.  Never configured a SRV record before on a publicly accessible DNS but that's what I take after reading the forum posts you provided.

A: The port is independent from DNS. This is not possible with DNS, you will need to get a second IP address in order to circumvent the need for specifying a port in Minecraft

A: If you are looking for a way to do it without SRV Records you can use the third party software "Minecraft Redirect Proxy" https://github.com/RenegadeEagle/minecraft-redirect-proxy
The first packet that is send to a Minecraft Server includes the requested hostname. This application will inspect that packet and redirect all trafic to the user configured Minecraft Server by the requested hostname.
(See this answer for reference and an example: https://superuser.com/a/1695521/1652996)