text:
Q: Using couchdb authentication by xmpp users I'd like use couchdb for a web application with external user authentication by a XMPP-Server (Openfire). How can I achieve that? Let's say we have thre users:

*

*basicuser@mydomain.tld

*advanceduser@mydomain.tld

*moreadvanceduser@mydomain.tld

Now basicuser@mydomain.tld should be able to read all documents that are suited for basic users.
advanceduser@mydomain.tld should be able to read AND write all documents that are suited for basic users.
moreadvanceduser@mydomain.tld should be able to read all documents that are suited for basic and advanced users.
Is that possible?

A: following OpenFire's Database installation Guide, only relational Databases work directly with Open Fire:

*

*MySQL

*Oracle

*Microsoft SQLServer

*PostgreSQL

*IBM DB2

*HSQLDB

My first thought was to try and move the complete database to couchdb.
Anyways, you will need different groups for mapping the different types of users. As far as I know, read/write access in CouchDB cannot be granted or revoked for single documents, but for databases. So you will end up with 3 databases, each for one type of access level.
I am not sure if it is a good advice to hanlde document based authentication in CouchDB by "tagging" documents with authlevels.
So, I can think of different szenarios:

*

*If your XMPP server ot the database
was able to verify credentials via
webservices, you could make use of
that in the login procedure in your
couchapp.

*If there are Webservices to your Openfire backing database, you could use these to synchronize users with couchdb and map them to auth lvl groups. I think this is not a very good approach, as you will have to handle updated or deleted users as well and have another point to think about security as well. This could of course also be done by scripting on python or what ever language you prefer.

*Use LDAP to provide auth. Does not work with CouchDB for now.

*Maybe a good idea would be to make
use of Z-XMPP, strophe or
basically any js framework that
handles XMPP in some way?  There you
could learn about XMPP
authentication and maybe use this to
verify auth credentials with XMPP. I also just learned that there is a book about "Professional XMPP Programming with JavaScript and jQuery".

Now, these are no complete solutions provided, but something to think about, and discuss it.
Oh, and there's another Thread here at StackOverflow.
Regards, Chris


text:
Q: Query a TreeNodeCollection I have a treeview control on a windows form UI and it has a few nodes (with multiple child nodes).
I want to query the nodes collection so as to, say,
1. select those whose name start with 'x'
2. select those which do not have any data in Node.Tag field.
Can someone please suggest me a way to do this. Linq would make it easy and neat, but I found nothing much on Linq to query TreeNodeCollection.
Thanks,

A: Because TreeNodeCollection pre-dates .NET 2.0, it isn't a generic collection, so it doesn't implement IEnumerable<T>, which is the 'master' type for LINQ goodness.
However, you can just call .Cast<TreeNode>() on a TreeNodeCollection, and you get an IEnumerable<TreeNode>, which you can then do all the LINQy goodness to.
(this approach works for any such collection that implements IEnumerable but not IEnumerable<T>)

A: You may try something like this with a Fixpoint operator allowing recursive lambdas
// Fix point operator
public static Func<T, T> Fix<T>(Func<Func<T, T>, Func<T, T>> f)
{
    return t => f(Fix<T>(f))(t);
}

then
// your treeView
var tv = new TreeView();

// Your filter Func
Func<TreeNode, bool> filterStartWithXorNoData =
    node => node.Text.StartsWith("x") || string.IsNullOrEmpty(node.Text);

// Your recursive lambda
var filteredNodes = Fix<IEnumerable<TreeNode>>(
    f =>
    nodeList =>
    nodeList.SelectMany(node => f(node.ChildNodes.Cast<TreeNode>()))
      .Union(nodeList.Where(filterStartWithXorNoData)))
      (tv.Nodes.Cast<TreeNode>());

A: I've tried something similar recently and struggled with the LINQ approach due to the nested nodes collection under each parent.
I solved my problem with a recursive function that searched all nodes. Reasonably elegant.
VB:
Private Function FindNode(name As String, root As TreeNode) As TreeNode
    For Each n As TreeNode In root.Nodes
        If n.Name = name Then
            'Found, get out
            Return n

        Else
            'Recursively call FindNode to search this node's children
            Dim soughtNode = FindNode(name, n)
            If soughtNode IsNot Nothing Then
                Return soughtNode
            End If
        End If
    Next

    Return Nothing

End Function

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting objects like button from view. iOS I created a button in my cover.h file for my first view
#import <UIKit/UIKit.h>

@interface cover : UIViewController
{

     IBOutlet UIButton *Enter;

}

@property (nonatomic, retain) UIButton *Enter;
-(IBAction)buttonpressed:(id)sender;

@end

and connected it with the actual button in the inteface builder by choosing File's Owner in the tiny box that gives you the choice of File's Owner, First Responder, and View
Then I went to cover.m file and added the following code
-(IBAction)buttonpressed:(id)sender
{

      [[NSBundle mainBundle] loadNibNamed:@"nextView" owner:self options:nil];
      NSLog(@"pressed");

}

SO when  I go to the nextView.xib and modify nextView.m and nextView.h and access its buttons and do the same thing I did for  cover.xib cover.m and cover.h , it doesn't work properly.
What happens is that when I click the enter button in the cover view it shuts down the app. This does not happen until I connected the button to function and outlet (Meaning when it was just switching views and the second view wasn't doing anything it would work)
Thank you for any help you can give. Sorry if I haven't given enough information, kinda new at this, but as find out more info I should have had, I will add it.
Thank you
Edit 1 :
I did not notice anywhere where it said there was an error or anything like that. It built correctly

A: *

*It's convention to capitalize class names.  I'd Suggest CoverViewController.  This makes it more obvious, when reading your code, what we're looking at.

What is your intent here?  To show nib after nib of content?
Is the "files owner" of every nib a CoverViewController?
What you have actually done is (catastrophically) reloaded the views for the existing controller.  This will not end well.
What you want to do is create another instance of the same class:
-(IBAction)buttonpressed:(id)sender {
CoverViewController nextController = [[CoverViewController alloc] initWithNibName:@"nextView"];
[navigationController pushViewController:nextController animated:NO];
}

If you're not using a nav controller, you probably want to be.
Read up on the View Controller Programming Guide.


text:
Q: App on device is different than app on simulator I've done my app and it works great on the Corona Simulator, but, once I run it on my device, it doesn't run a bunch of instruction.
These are:
function onCollision( event )
    if ( event.phase == "began" ) then
        if event.object1.myName == "ground" and event.object2.myName == "spaceShip" then

                local a = score.get()
                print(a)
                local b = score.load()
                print(b)

                if (a < b) then
                    best.alpha = 1

                    scoreToBeat.text = score.load()
                    scoreToBeat.alpha = 1

                else
                    score.save()
                    newRecord.alpha = 1
                end

                timer.cancel(tmrScore)
                gameOver.alpha = 1
                tapToReplay.alpha = 1
                replay.alpha = 0.01
                fade.alpha = 0
                timer.cancel(tmrIS)
                spaceShip.alpha = 1
                if(playEffects) then
                    media.playEventSound( "sounds/gameover.mp3" )
                    playEffects = false
                end
                speed = 0

     end
    end
  end

 Runtime:addEventListener( "collision", onCollision )

Particularly, it performs only "speed = 0" and only the first time I run the app, which means that if I start a new game, it won't even work "speed = 0".
I'm 100% sure that the app is running on the device is the same that runs on the simulator (I tried to change some text).
What can I do?

A: There could be multiple reasons: the physics not started when get back to scene; the objects aren't dynamic; one of them no longer exists or is no longer a physics object; the handler was removed when game ended and not restarted.
To figure out, add some print statements to see what parts execute:
function onCollision( event )
    print 'entered collision'
    if ( event.phase == "began" ) then
        print 'collision began'
        if event.object1.myName == "gd" and event.object2.myName == "hero" then
            print 'collision objects are gd and hero'

            speed = 0

            if (score.get() < score.load()) then
                print 'score smaller'
                ...

            else
                print 'score not smaller'
                ...

            end
        else
             print( 'collision objects are', event.object1.myName, event.object2.myName )
        end
    end
end

Update:
I had a typo score = 0, should have been speed = 0.


text:
Q: qmake: how to build dependencies without TEMPLATE=subdirs TL;DR: Is there a way to build a target from a .pro file in a different project without using TEMPLATE = subdirs?
Long version:
I have a complex project (mycomplexproject) with lots of subirs and *.pro files. One module (moduleA) depends on a DLL built in a different project outside of this project (anotherproject). Because reasons I cannot create a *.pro file with a subdirs template in somerootdir.
Is there a way to add a dependency in moduleA.pro so anotherproject is built whenever moduleA is built and anotherproject.dll does not exist without having to create a *.pro file in somerootdir?

somerootdir/
    anotherproject/                // must be independent of mycomplexproject
        anotherproject.pro
        lib/
            anotherproject.dll     // the result of building anotherproject
    [...]
    mycomplexproject/
        core/
            core.pro
        modules/
            moduleA/
                moduleA.pro        // depends on anotherproject.dll built from anotherproject.pro
            moduleB/
                moduleB.pro
            modules.pro            // uses subdir template
        mycomplexproject.pro       // uses subdir template

P.S.: moduleA is only built under certain circumstances, and building anotherproject is only necessary if moduleAis built.


text:
Q: How do I send a message to a flask-socketio client outside of request and application context? I'm running a python web server, using eventlet for WSGI, with flask and flask-socketio.  A web page is served to the client over HTTPS, and that page uses socketio to start a websocket connection back to the server.
When the socketio connection is established, the client sends a message to the server asking for some state.  The server receives this message, and uses send(sign_config) to send a message back to the server.
All of this works.
However, the reason I'm using socketio is that on occasion, state changes on the server side and this needs to be pushed to the client.  I've tried this a number of different ways and all of them fail, but here is what I'm currently trying:
with self.app.app_context():
    self.socketio.send(sign_config, room = sid)

I'm not sure if the app_context() is needed or not.  I don't get an exception if it's there or not.  Either way, the send function does not generate any exception.  However, the message is not received by the client.  Furthermore, the next socketio ping request to the server fails.  After a short time, the client reestablishes the connection to the server, with a new sid.  In short, sending this message seems to kill the websocket connection, or at least move something out of sync.  I'm certain the sid I'm using is correct.
This is basically the code that actually sets up the environment:
app = Flask(__name__)
app.config['SECRET_KEY'] = 'asdf'
socketio = flask_socketio.SocketIO(app)
socketio.run(app, host = '0.0.0.0', port = 443, certfile = cert_path, keyfile = key_path_result, ssl_version = ssl.PROTOCOL_TLS)

The app and socketio objects are being passed to a different class which handles some of this stuff, which is why the code above is self.app and self.socketio.  But they are the same objects.
Does anybody know what might be going on here?
Edit, some other things I've tried:
# This produces no exception, but fails to send and breaks websocket connection
with self.app.app_context():
    self.socketio.send(sign_config, namespace = '/', room = sid)

# This produces no exception, but fails to send and breaks websocket connection
with self.app.app_context():
    send(sign_config, namespace = '/', room = sid)

# This produces no exception, but fails to send and breaks websocket connection
self.socketio.send(sign_config, namespace = '/', room = sid)

Here are the messages that are sent and received by the server:
# The connection is open, and communicating
203786b0b9f54526bd71827a7ba0c4e0: Received packet PING data None
203786b0b9f54526bd71827a7ba0c4e0: Sending packet PONG data None
203786b0b9f54526bd71827a7ba0c4e0: Received packet PING data None
203786b0b9f54526bd71827a7ba0c4e0: Sending packet PONG data None
203786b0b9f54526bd71827a7ba0c4e0: Received packet PING data None
203786b0b9f54526bd71827a7ba0c4e0: Sending packet PONG data None

# Server sends a message to the client with flask_socketio.send(sign_config, namespace = '/', room = sid)
# This message is not received by the client
emitting event "message" to 203786b0b9f54526bd71827a7ba0c4e0 [/]
203786b0b9f54526bd71827a7ba0c4e0: Sending packet MESSAGE data 2["message",{<my message data here>}]

# Client sends a ping
203786b0b9f54526bd71827a7ba0c4e0: Received packet PING data None

# Server sends a pong that is not received by the client
203786b0b9f54526bd71827a7ba0c4e0: Sending packet PONG data None

# Server seems to recognize the client is gone and closes the connection
203786b0b9f54526bd71827a7ba0c4e0: Client is gone, closing socket
203786b0b9f54526bd71827a7ba0c4e0: Client is gone, closing socket

# Client realizes the connection is down and reconnects
(1335) accepted ('192.168.5.1', 52399)
250467e2dd1f439b8724a2338cbc3fb4: Sending packet OPEN data {'pingInterval': 25000, 'pingTimeout': 60000, 'upgrades': [], 'sid': '250467e2dd1f439b8724a2338cbc3fb4'}
250467e2dd1f439b8724a2338cbc3fb4: Sending packet MESSAGE data 0
250467e2dd1f439b8724a2338cbc3fb4: Received request to upgrade to websocket
250467e2dd1f439b8724a2338cbc3fb4: Upgrade to websocket successful

# Client sends a message on successful connection
250467e2dd1f439b8724a2338cbc3fb4: Received packet MESSAGE data 2["message",{<}]
received event "message" from 250467e2dd1f439b8724a2338cbc3fb4 [/]

# Servers sends a message (in request context) in response using flask_socketio.emit('message', data)
# The client receives this message
emitting event "message" to 250467e2dd1f439b8724a2338cbc3fb4 [/]
250467e2dd1f439b8724a2338cbc3fb4: Sending packet MESSAGE data 2["message",{<my message data here>}]

# Connection stays back up until the server sends an out of request context message, where the whole process repeats
250467e2dd1f439b8724a2338cbc3fb4: Received packet PING data None
250467e2dd1f439b8724a2338cbc3fb4: Sending packet PONG data None
250467e2dd1f439b8724a2338cbc3fb4: Received packet PING data None
250467e2dd1f439b8724a2338cbc3fb4: Sending packet PONG data None
250467e2dd1f439b8724a2338cbc3fb4: Received packet PING data None
250467e2dd1f439b8724a2338cbc3fb4: Sending packet PONG data None

A: To send an event without a request context you have to specify both the room and the namespace. If one or both of these are missing, an attempt to get the from the request context will be made, and this is when you get the error.


text:
Q: CSS class selector wildcard So I was wondering if there was a way to throw a wildcard into my CSS?
I have several classes that are .button-0, .button-1, .button-2, .button-3, etc. within a button element. I want to get all the .button-* classes to define.
Is it possible to do something like:

button .button-[=*] {
  margin-right: 2rem;
}

A: Use an attribute selector:
button [class*="button-"] {
  margin-right: 2rem;
}

Example Here

From MDN:

[attr*=value] - Represents an element with an attribute name of attr and whose value contains at least one occurrence of string "value" as substring.

button [class*="button-"] {
  color: red;
}
<button>
    text
    text
    text
</button>

As Chad points out, it is entirely possible that an element can contain a class such as this-is-my-button-class. In which case, that undesired element would be selected. In order to prevent this, you could use a combination of two selectors:
Example Here
button [class^="button-"],
button [class*=" button-"] {
  margin-right: 2rem;
}

The selector button [class^="button-"] ensures that the element will be selected if it starts with button-. Since it's possible the element's first class doesn't start with button-, the selector [class*=" button-"] (note the whitespace), ensures that it will be selected.

A: You can do like this
button[id|=button]{
    color:red;
}

All buttons whose id contain the word button will get affected. For example http://jsfiddle.net/czp28jpb/


text:
Q: $GF(n,20)$ is prime iff : $GF(n,20) \mid S_{4^{n-1}}$?
Let us define recurrence equation as :
$S_n=S_{n-1}^{10}-10\cdot S^8_{n-1}+35\cdot S^6_{n-1}-50\cdot S^4_{n-1}+25\cdot S^2_{n-1}-2$ , with $S_0=12$
and let us define following notation :
$GF(n,20)=20^{2^n}+1$

Now , note that :
$GF(1,20) \mid S_1$ , $GF(2,20) \mid S_4$
$GF(1,20) \nmid S_2$ , $GF(1,20) \nmid S_3$ , $GF(1,20) \nmid S_4$
$GF(2,20) \nmid S_1$ , $GF(2,20) \nmid S_2$ , $GF(2,20) \nmid S_3$
$GF(3,20) \nmid S_1$ , $GF(3,20) \nmid S_2$ , $GF(3,20) \nmid S_3$
So ,one can formulate following assumption :

$GF(n,20)$  is prime iff : $GF(n,20) \mid S_{4^{n-1}}$ , where $n>0$

My question : What would be the easiest way to prove or disprove this statement ?
P.S.
Here you can find proof of correctness of Lucas-Lehmer primality test .
Mathematica code based on the assumption above (output is set of $GF(n,20)$ primes) :
Select[Table[GF = 20^(2^n) + 1;
For[i = 1; s = 12, i <= 4^(n - 1), i++,
s = Mod[s^10 - 10*s^8 + 35*s^6 - 50*s^4 + 25*s^2 - 2, GF]];
If[s == 0, "GF" <> ToString@n, n], {n, Range[15]}], StringQ]


text:
Q: Definition of locally closed subscheme I'm wondering how to define a locally closed subscheme formally. My attempt is to define it as a morphism $f:X\rightarrow Y$ which can factor as $f = g\circ i$ where $g$ is an open immersion and $i$ closed immersion.
My question:

*

*Is the factorization $f = g\circ i$ unique in some sense? Could it be described by ideal sheaf?

*For any given locally closed subset, is there a unique reduced scheme structure making it as a locally closed subscheme?

*Is quasiprojective scheme locally closed subscheme? If it is, when we say $X$ is a quasiprojective scheme, is the immersion $f$ part of data of $X$ or we only need $X$ can be immerse into some $\mathbb P^n$?
In Hartshorne, quasiprojective morphism is defined as a morphism $f:X\rightarrow Y$ is quasiprojective if it factors into an open immersion $j:X'\rightarrow X$ followed by a projective morphism $g:X'\rightarrow Y$. The order of composition is different from that in immersion.
In some other place, quasiprojective variety might be even defined as: a quasiprojective variety is a open subset of a projective variety. For which I don't know if projective variety is part of data.

A: *

*No. Let $x\in\Bbb A^1_k$ be a closed point, and consider $\{x\}\to U\to \Bbb A^1_k$ as $U$ varies among the open subsets of $\Bbb A^1_k$ containing $x$.

*Yes. Suppose $W\subset X$ is a locally closed subset. Write $W=U\cap V$ with $U$ open and $V$ closed. Equip $U$ with the restriction of the structure sheaf on $X$ and $V$ with the reduced induced subscheme structure. Then $W=U\times_X V$ is a reduced subscheme structure on $W$.

*Hartshorne's definition of a locally closed immersion is famously not quite correct in general. To be more specific, Hartshorne's locally closed immersion is the opposite order from what you've written - an open immersion in to a closed subscheme. One can interchange the order of these when either the source is reduced or the composite morphism is quasi-compact. The latter condition is satisfied when the source is (locally) noetherian, and given Hartshorne's general perspective on noetherian hypotheses, I think the best way to proceed is to assume he's working in the locally noetherian situation. This gives that a scheme $X$ quasi-projective over $S$ via $f:X\to S$ can be written as a locally closed subscheme of $\Bbb P^n_S$ for some $n$. Generally one interprets this as the second condition you've written - there exists a map, but it's not generally packaged as part of the data of $f$.


text:
Q: Android client and java server in the same git project I am developing a simple Android application and it should communicate with server using REST api. Both client and server use kotlin and serialize classes to json with Jackson and API looks like:
class xRequest { .. }
class xResponse { .. }

Client and server have their own git repositories and I use Android Studio and Idea to work with them separately. This leads to class declaration duplication as they both need to know API.
What's the best way  to get rid of duplication? I could move API to some third project and then build - publish - add dependency on it but that's a lot of work during development.
Is it a good idea to move them to the single project so it will look the way:
my project
  api
  android-client
  server

Thanks

A: It's a classic duplication problem. What we usually do in this case?
Extract duplicated code to the separate entity and reuse it.
So, I would introduce a new pure java project called core and add it as a dependency to android-client and server.


text:
Q: Find the salary difference between two months Suppose we have 3 columns in a table emp_no, salary, month
emp_no    salary    month
123       1000       jan
123       2000       feb
123       3000       march

So, output should look like:
emp_no    salary    month      diff
123       1000       jan       1000
123       2000       feb       1000
123       3000       march

A: select emp_no,
       salary,
       month,
       lag(salary) over (partition by emp_no order by month) - salary as diff_to_prev
       lead(salary) over (partition by emp_no order by month) - salary as diff_to_next
from emp_table;

This assumes that month is in fact a DATE (or timestamp) column that can be sorted properly.

A: Since there is not much info, this script aims to show the principle.
select t1.emp_no, t1.month as current month, t2.salary as current salary,
t2.month as prev_month, t2.salary as prev_salary,
coalesce(t2.salary - t1.prev_salary, 0) as difference

from SalaryTable t1
outter join (
select emp_no, month as prev_month, salary as prev_salary
from SalaryTable where month=
    (select add_months(max(month),-1) from SalaryTable)
) t2
on t1.emp_no = t2.emp_no

COALESCE may be changed to a CASE to handle mismatch between previuos and current months according to your needs.


text:
Q: Is there a way to uncheck "Landed Cost Per Line" on Item Receipt Form I'm new to NetSuite. I need the checkbox "Landed Cost Per Line" on Item Receipt form to remain unchecked. I did try 2 ClientScript but it is not working.
When you click on "Receive" button on the Purchase order, it goes to the Item Receipt form and as the page loads, the checkbox is auto-checked. The checkbox is found under the "Item&Expenses" subtab.
I tried doing it via workflows but the field is not available/does not show there. So I tried via scripts.
[1.] The first try it unchecks it but then throws an error message "*TypeError Cannot read properties of undefined (reading 'setValue') suitescript*" and restrict you from navigating through subtabs.

/**
*@NApiVersion 2.x
*@NScriptType ClientScript
*/

define(['N/error', 'N/record'], function(error, record){
  function pageInit(context){
    if (context.mode == 'create' || context.mode == 'edit')
      var currentRec = context.currentRecord;
      currentRec.setValue({
        fieldId: 'landedcostperline',
        value: 'F'
      });
    }

  return{
    pageInit : pageInit
  };
});

[2.] With the second trial, nothing happened i.e the checkbox gets auto-check as the page loads.

/**
*@NApiVersion 2.x
*@NScriptType ClientScript
*/
define(['N/error', 'N/record'],
    function(error, record){
        function pageInit(context){
            if (context.mode == 'create' || context.mode == 'edit'){
                var currentRec = context.currentRecord;
                currentRec.submitFields({
                    type: record.Type.ITEM_RECEIPT,
                    values: {
                        landedcostperline: 'F'
                    },
                    options: {
                        enableSourcing: false,
                        ignoreMandatoryFields : true
                    }
                });
            }
        }

        return{
          pageInit : pageInit
        };
    }
);

Where did I go wrong?

A: Forget about the scripts. Actually, it's a setting in Setup > Accounting > Accounting Preferences > Order Management. Just uncheck it there.


text:
Q: Rails 4 with X-Editable doesn't work I think I'm missing something... probably minor but I couldn't find a solution for the past few hours. I'm beginning with websites so forgive the noob question
I'm using this library (I've tried many...)
https://github.com/bootstrap-ruby/bootstrap-editable-rails
I do everything as instructed (see steps below)
I refresh my webpage and I have no error (meaning everything has loaded), but when I click on "superuser", nothing happens. No pop-up, no error message, just nothing. I'm thinking something is missing. Maybe some javascript isn't enabled or something... Can't tell

My application.js is like this:
//= require jquery
//= require jquery_ujs
//= require bootstrap
//= require bootstrap-editable
//= require bootstrap-editable-rails
//= require jquery.turbolinks
//= require turbolinks
//= require_tree .

Turbolinks.enableProgressBar();

I have added the file bootstrap-editable.css to my app/assets/stylesheets folder
and changed my application.css.scss to
//= require ./bootstrap
//= require rails_bootstrap_forms
//= require font-awesome
//= require_tree .
//= require_self
//= require bootstrap-editable

I then go in my class partial and add the following "dummy" snippet of code
  superuser

I refresh my webpage and I have no error (meaning everything has loaded), but when I click on "superuser", nothing happens. No pop-up, no error message, just nothing. I'm thinking something is missing
Thanks for your help!

A: I don't know if you still need an answer but try the following.

*

*Download this https://vitalets.github.io/x-editable/assets/zip/bootstrap3-editable-1.5.1.zip ( include corresponding files to your app directories).

*Add something like that in your view:

MyUserName

*Add some javascript into your application.js:
$(document).ready(function() {
    $('#username').editable({
        type: 'text',
        url: '/edit',
        title: 'Enter username'
    });});

*Read more details here:
https://vitalets.github.io/x-editable/docs.html


text:
Q: Check if YouTube video is live or uploaded I have a YouTube Live Event. I am able to play the video using the YouTube IFrame Player API. I want to know if there is any way that I can find if the video is a Live event video or a regular uploaded video. I need this information for designing my controls.

A: The only way you can do this (currently) is with youtube backend api.
Get data about the video based on its id and in the response you have a property snippet.liveBroadcastContent which is either live, none, or upcoming.

A: The IFrame API provides a Playback quality function which returns a string representation of the current video quality.
From my tests, this function will return an undocumented string auto for live events.
Related discussion can be found in this issue on YouTube's iOS Player Helper Library's GitHub page.


text:
Q: Inheriting Abstract Class Attributes that are final I have a superclass that is Abstract and has the following attributes and constructor in it.
public abstract class Equipment {

  public final String serialNumber;

  public final String brand;

  public final String model;

  public final float equipmentPrice;

  public final Integer equipmentStatus;

  public float transactionPrice;

  public Equipment(String serialNumber, String brand, String model, float equipmentPrice, Integer equipmentStatus, float transactionPrice) {
  }

}

Child class:

public class Treadmill extends Equipment {

  public double maxSpeed;

  public Treadmill(Integer equipmentStatus, float transactionPrice, double maxSpeed) {
  }

}

Question: in the child class, do I need to include the final attributes that are from the parent class as follows, or should it be the same as the above construct in the child class? Or, should the child constructor hold both the parent and child attributes as follows though most of the parent attributes are final?
public Treadmill(String serialNumber, String brand, String model, float equipmentPrice, Integer equipmentStatus, float transactionPrice, double maxSpeed) {
  }

Final means they can not be changed. If that is the case, how can I have it applied for each child class since the attributes are common for all the different child classes?
Thank you!

A: While all your child classes have the same parent class, this does not mean that an instance of a child class is sharing any of its member fields with any other object.
If we have:
class P {
  final int x;
  P(int x) {
    this.x = x;
  }
}

class A extends P {
  A(int x) {
    super(x);
  }
}

class B extends P {
  B(int x) {
    super(x);
  }
}

Then each instance of A and B have their own field x and each instance can set it to a different value.
You can say:
  ...
  A a = new A(1);
  A aa = new A(2);
  B b = new B(3);
  // and also
  P p = new P(4);
  ...

and each of your objects has a different value for its instance of x.

A: About the part in my comment that you "don't need these parameters in the child constructor": it is possible that a subclass will always use the same value for that variable, in that case it doesn't need it be passed. For example
abstract class GroundVehicle {
  public final int wheelCount;
  protected GroundVehicle(int wheels) {
     wheelCount = wheels;
  }
}
class Car {
  public Car() { // no need for a parameter,
    super(4);    // we always have 4 wheels
  }
}
class Motorbike() {
   public Motorbike() {
     super(2);  // we do need to pass something though
   }
}


text: Q: Opening Selenium Browser in a JavaFX WebView I want to know if there is anyway I can open up the Selenium WebDriver in a WebView rather than the default behavior of opening in a new window. If not is there anyway I can get the same functionality (Being able to press buttons, and fill text fields) through the JavaFX WebView.


text:
Q: How does Django handle template name clashes? ...when several apps define similarly named templates outside of a proper hierarchy. Thank you.

A: Not exactly clear on what you mean.  When you are specifying a template you should name it appropriately and specify it exactly.  If you mean something like the admin that chooses the "best" template from a list of templates, it's uses a simple algorithm to find the best match.  It does this simply by passing a list of templates to loader.select_template and the first one that is valid is used.

A: The template loaders are applied in the order you've defined in settings.TEMPLATE_LOADERS.
For example, if you have the app_directories loader running AFTER the filesystem loader and your template is located in the filesystem loader, the app_directories loader will never be used.
If you're talking about the app_directories loader specifically, it searches your app template folders in the order they are defined in INSTALLED_APPS.
If you have conflicting template names that are not on purpose (not some kind of override hierarchy), chances are you are better off prefixing each template folder with the app name.
# this is standard
myapp/templates/myapp/index.html
myapp2/templates/myapp2/index.html


text:
Q: Is it possible to only use high side driver of fet driver ic? Is it possible to only use high side part of IR2103 mosfet driver ic, being fully functional, without adding low side driver external components?

A:
Is it possible to only use high side part of IR2103 mosfet driver ic

You can: -

*

*Use the bottom only

*The top only

*Both as half a H bridge

*Not use both simultaneously (and independently) because of the shoot through protection prevents this (thanks to @StainlessSteelRat for pointing this out): -

The lower side MOSFET connection is a high impedance with a few nF of capacitance and leaving it open circuit won't cause problems.


text:
Q: Elasticsearch stops after import data from model
*

*I deployed my app to vps.

*Started Elasticsearch, and checked it with ps aux | grep elasticsearch

*cd app/currect && RAILS_ENV=production bin/rails c

*User.import
Output:
Scoped order and limit are ignored, it's forced to be batch order and batch size
  User Load (0.4ms)  SELECT "users".* FROM "users"  ORDER BY "users"."id" ASC LIMIT 10
Faraday::ConnectionFailed: connection refused: localhost:9200

*Elasticsearch stopped and import doesn't work, why ?
I am using Ubuntu 14, Puma server, SQLite database. Does it matter?
Additional notes:
https://github.com/rusikf/pmi_parser/blob/master/Gemfile.lock - gemfile.lock from project
http://pastebin.com/J6Wi8qBF - elasticsearch config
http://pastebin.com/3BKmZG4G - elasticsearch log
Before User.import
ps aux | grep elasticsearch
shows elasticsearch process
After User.import
ps aux | grep elasticsearch
doesn't show process
How to check if elasticsearch uses 9200 port ?

A: The problem was resolved by changing ip to vps ip address:9200 + running Model_name.__elasticsearch__.create_index! force: true in rails console


text:
Q: Integral of an exponent of an exponent For a homework problem, I have to integrate this:
$$\int{4^{(4+x)^x}}dx$$
How would I go around to starting this question? I don't know how to evaluate this, and I've tried to use u-subs and integration by parts, but to no avail. Could anyone lead me in the right direction?

A: There is almost certainly no closed form solution.  Even the much simpler integral $\int x^x$ cannot be expressed in terms of elementary functions.
You could do various numerical approximations to find bounds, or maybe write down a power series expansion.  But that's as far as you can really go here.


text:
Q: Draw L.circle in a custom pane I want to draw L.circle in a custom pane but I am using mapbox.js and hence the leaflet version 0.7.7.How can I draw L.circle in a custom pane? Do we have to copy some js files from the 1.0 version of leaflet? Please help me and explain how to do this.

A: In leaflet source file search for function _initPanes(). Inside the function create a new custom pane and attach it to mapPane.
pane.myCustomPane = this._createPane('leaflet-mycustom-pane-css');

Update L.Circle code to attach the circle to your custom mapPane.


text:
Q: How to filter chunked array in Vue's computed property? I have a bunch of data fetched from a computed property and I want to make it filterable in name via the search input.
The data looks like this (from vue devtools):
chunkedAirlines: Array[6]
    0: Array[6]
      0: Object
        id: 1
        name: "Lorem ipsum 1"
      1: Object
        id: 2
        name: "Lorem ipsum 2"
      ...

    1: Array[6]
      0: Object
        id: 3
        name: "Lorem ipsum 3"
      1: Object
        id: 4
        name: "Lorem ipsum 4"
      ...

I already tried solution from this question but I still cannot get it work as I wanted. The value inside chunkedAirlines does not updated on key up.
Here is my code:
<template>

                    <input
                        type="text"
                        id="search-input"
                        class="form-control border-left-0"
                        placeholder="Find airline..."
                        aria-label="Airline"
                        aria-describedby="search-airline-button"
                        v-model="search"
                        @keyup="findAirline">

                    New Airline

{{ airline.name }}

</template>

A: You're doing it wrong.
Here's a working example:
<template>

                    <input
                        type="text"
                        id="search-input"
                        class="form-control border-left-0"
                        placeholder="Find airline..."
                        aria-label="Airline"
                        aria-describedby="search-airline-button"
                        v-model="search">

                    New Airline

{{ airline.name }}

</template>

This way You simply have your search input bind to the search variable in your data object, then computed property gets updated if user searches something and shows filtered data, or if theres no search returns the items normally.
Hope this helps.


text:
Q: updating image source using jquery not working properly I'm trying to update my image source using jquery. To do it, I am calling .load
function that will return a string which in turn will be used to replace the image source.
srcResult value is new/icon.png:

HTML Side

What happens is that when the javascript is loaded, the image is loaded like this:
 new/icon.png

Am I missing something hence the issue is persisting?

A: load() returns an object. If you're not interested in pre-loading, just replace your code as follows:
$("#iconImage").children('img').prop('src', 'Users/NewIcon');

However, if you wish to preload the image, use the following:
var src = 'Users/NewIcon',
    img = new Image();

img.src = src;
img.onload = function() {
    $('#iconImage').children('img').prop('src', this.src);
};

It's worth noting that you will also need to wrap your code in the DOMReady event if you're not doing that already.


text:
Q: Programming a Discord bot with Python- How do I make it join a voice channel? I want to make the bot join the voice channel that I'm in when prompted. Here's what I have:
@client.event
async def on_message(message):
  if message.content.startswith('.join'):
    channel = 775902254951301125
    await channel.connect()

It doesn't seem to work, any tips?

A: I think this is what you're looking for!
@client.command(pass_context=True)
async def join(ctx):
    channel = ctx.message.author.voice.voice_channel
    await client.join_voice_channel(channel)

That was pulled straight from this video which was just a google search away.

A: try run in command prompt/powershell
py -m pip install -U discord.py[voice]

and then try again
Similar case:
Making a bot join a vc and play music

A: import discord
from discord.ext import commands
client = commands.Bot(command_prefix = '>')

@client.event
async def on_ready():
  print ("Log : "+str(client.user))
  ch = await client.fetch_channel("enter id voice channel")
  await ch.connect()

client.run('token')


text:
Q: Munging PyTorch's tensor shape from (C, B, H) to (B, C*H) Given an input tensor of shape (C, B, H) torch.Size([2, 5, 32]) of some neural net layers, where

*

*channels = 2

*batch_size = 5

*hidden_size = 32

The goal is to flatten the channels and manipulate the input tensor to the shape (B, C*H) torch.Size([5, 2 * 32]), where:

*

*batch_size = 5

*hidden_size = 32 * 2

I've tried to do the following:
import torch

t = torch.rand([2, 5, 32])

# Changed from (channels, batch_size, hidden_size)
# -> (batch_size, channels, hidden_size)
t = t.permute(1, 0, 2)

# Reshape using view(), where batch_size is t.size(0)
# and -1 is to flatten the left over values to the other dimension.
z = t.contiguous().view(t.size(0), -1)

print(z.shape)
print(z)

[out]:
torch.Size([5, 64])
tensor([[0.3911, 0.9586, 0.2104, 0.3937, 0.9976, 0.3378, 0.0630, 0.6676, 0.0806,
         0.9311, 0.5219, 0.1697, 0.7442, 0.5162, 0.2555, 0.0826, 0.5502, 0.9700,
         0.3375, 0.5012, 0.9025, 0.8176, 0.1465, 0.1848, 0.3460, 0.9999, 0.7892,
         0.7577, 0.6615, 0.2620, 0.6868, 0.2003, 0.4840, 0.8354, 0.9253, 0.3172,
         0.9516, 0.8962, 0.1272, 0.2268, 0.6510, 0.5166, 0.6772, 0.9616, 0.9826,
         0.5254, 0.9191, 0.4378, 0.7048, 0.8808, 0.0299, 0.1102, 0.9710, 0.8714,
         0.7256, 0.9684, 0.6117, 0.1957, 0.8663, 0.4742, 0.2843, 0.6548, 0.9592,
         0.1559],
        [0.2333, 0.0858, 0.5284, 0.2965, 0.3863, 0.3370, 0.6940, 0.3387, 0.3513,
         0.1022, 0.3731, 0.3575, 0.7095, 0.0053, 0.7024, 0.4091, 0.3289, 0.5808,
         0.5640, 0.8847, 0.7584, 0.8878, 0.9873, 0.0525, 0.7731, 0.2501, 0.9926,
         0.5226, 0.0925, 0.0300, 0.4176, 0.0456, 0.4643, 0.4497, 0.5920, 0.9519,
         0.6647, 0.2379, 0.4927, 0.9666, 0.1675, 0.9887, 0.7741, 0.5668, 0.7376,
         0.4452, 0.7449, 0.1298, 0.9065, 0.3561, 0.5813, 0.1439, 0.2115, 0.5874,
         0.2038, 0.1066, 0.3843, 0.6179, 0.8321, 0.9428, 0.1067, 0.5045, 0.9324,
         0.3326],
        [0.6556, 0.1479, 0.9288, 0.9238, 0.1324, 0.0718, 0.6620, 0.2659, 0.7162,
         0.7559, 0.7564, 0.2120, 0.3943, 0.9497, 0.7520, 0.8455, 0.4444, 0.4708,
         0.8371, 0.6365, 0.3616, 0.0326, 0.1581, 0.4973, 0.6701, 0.9245, 0.8274,
         0.3464, 0.7044, 0.5376, 0.0441, 0.5210, 0.8603, 0.7396, 0.2544, 0.3514,
         0.5686, 0.3283, 0.7248, 0.4303, 0.9531, 0.5587, 0.8703, 0.1585, 0.9161,
         0.9043, 0.9778, 0.4489, 0.9463, 0.8655, 0.5576, 0.1135, 0.1268, 0.3424,
         0.1504, 0.2265, 0.1734, 0.1872, 0.3995, 0.1191, 0.0532, 0.6109, 0.1662,
         0.6937],
        [0.6342, 0.1922, 0.1758, 0.4625, 0.7654, 0.6509, 0.2908, 0.1546, 0.4768,
         0.3779, 0.2490, 0.0086, 0.6170, 0.5425, 0.6953, 0.4730, 0.5834, 0.8326,
         0.0165, 0.8236, 0.0023, 0.7479, 0.5621, 0.9894, 0.5957, 0.0857, 0.6087,
         0.5667, 0.5478, 0.8197, 0.9228, 0.7329, 0.4434, 0.5894, 0.9860, 0.6133,
         0.2395, 0.4718, 0.8830, 0.6361, 0.6104, 0.6630, 0.5084, 0.7604, 0.7591,
         0.3601, 0.6888, 0.6767, 0.9178, 0.5291, 0.0591, 0.4320, 0.7875, 0.5038,
         0.4419, 0.0319, 0.3719, 0.5843, 0.0334, 0.3525, 0.0023, 0.1205, 0.4040,
         0.7908],
        [0.0989, 0.8436, 0.0425, 0.6247, 0.6091, 0.4778, 0.2692, 0.4785, 0.9217,
         0.9604, 0.6355, 0.4686, 0.9414, 0.7722, 0.8013, 0.1660, 0.6578, 0.6414,
         0.6814, 0.6212, 0.4124, 0.7102, 0.7416, 0.7404, 0.9842, 0.6542, 0.0106,
         0.3826, 0.5529, 0.8079, 0.9855, 0.3012, 0.2341, 0.9353, 0.6597, 0.7177,
         0.8214, 0.1438, 0.4729, 0.6747, 0.9310, 0.4167, 0.3689, 0.8464, 0.9395,
         0.9407, 0.8419, 0.5486, 0.1786, 0.1423, 0.9900, 0.9365, 0.3996, 0.1862,
         0.6232, 0.7547, 0.7779, 0.4767, 0.6218, 0.9079, 0.6153, 0.1488, 0.5960,
         0.4015]])

Although the permute() + view() achieve the desired output, are there other ways to perform the same operation? Is there a better way that can directly rehape without first permutating the order of the shape?

A: Let's look "behind the curtain" and see why one must have both permute/transpose and view in order to go from a C-B-H to B-C*H:
Elements of tensors are stored as a long contiguous vector in memory. For instance, if you look at a 2-3-4 tensor it has 24 elements stored at 24 consecutive places in memory. This tensor also has a "header" that tells pytorch to treat these 24 values as a 2-by-3-by-4 tensor. This is done by storing not only the size of the tensor, but also "strides": what is the "stride" one need to jump in order to get to the next element along each dimension. In our example, size=(2,3,4) and strides=(12, 4, 1) (you can check this out yourself, and you can see more about it here).
Now, if you only want to change the size to 2-(3*4) you do not need to move any item of the tensor in memory, only to update the "header" of the tensor. By setting size=(2, 12) and strides=(12, 1) you are done!
Alternatively, if you want to "transpose" the tensor to 3-2-4 that's a bit more tricky, but you can still do that by manipulating the strides. Setting size=(3, 2, 4) and strides=(4, 12, 1) gives you exactly what you want without moving any of the real tensor elements in memory.
However, once you manipulated the strides, you cannot trivially change the size of the tensor - because now you will need to have two different "stride" values for one (or more) dimensions. This is why you must call contiguous() at this point.
Summary
If you want to move from shape (C, B, H) to (B, C*H) you must have permute, contiguous and view operations, otherwise you just scramble the entries of your tensor.
A small example with 2-3-4 tensor:
a =
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],

       [[12, 13, 14, 15],
        [16, 17, 18, 19],
        [20, 21, 22, 23]]])

If you just change the view of the tensor you get
a.view(3,8)
array([[ 0,  1,  2,  3,  4,  5,  6,  7],
       [ 8,  9, 10, 11, 12, 13, 14, 15],
       [16, 17, 18, 19, 20, 21, 22, 23]])

Which is not what you want!
You need to have
a.permute(1,0,2).contiguous().view(3, 8)
array([[ 0,  1,  2,  3, 12, 13, 14, 15],
       [ 4,  5,  6,  7, 16, 17, 18, 19],
       [ 8,  9, 10, 11, 20, 21, 22, 23]])

A: Einops allows doing such element rearrangements in one (readable) line
from einops import rearrange
import torch

t = torch.rand([2, 5, 32])
y = rearrange(t, 'c b h -> b (c h)')
y.shape  # prints torch.Size([5, 64])


text:
Q: Printing the lowest and second lowest values in an array using methods (Java) I am new to Java and have been given an assignment that asks:
Description
A group of friends decide to run the Boston Marathon. Their names and times (in minutes) are below:
Name       Time(minutes)

Elena       341
Thomas      273
Hamilton    278
Suzie       329
Phil        445
Matt        402
Alex        388
Emma        275
John        243
James       334
Jane        412
Emily       393
Daniel      299
Neda        343
Aaron       317
Kate        265

Find the fastest runner. Print the name and his/her time (in minutes).
Find the second fastest runner. Print the name and his/her time (in minutes).
Instructions
Write a method that takes as input an array of integers and returns the index corresponding to the
person with the lowest time. Run this method on the array of times. Print out the name and time
corresponding to the returned index.
Write a second method to find the second‐best runner. The second method should use the first method
to determine the best runner, and then loop through all values to find the second‐best (second lowest)
time.
Here is a program skeleton to get started:
class Marathon {
 public static void main (String[] arguments){
 String[] names ={
 "Elena", "Thomas", "Hamilton", "Suzie", "Phil", "Matt", "Alex",
 "Emma", "John", "James", "Jane", "Emily", "Daniel", "Neda",
 "Aaron", "Kate"
};
 int[] times ={
 341, 273, 278, 329, 445, 402, 388, 275, 243, 334, 412, 393, 299,
 343, 317, 265
 };
 int i1 = fastestIndex(times);
 int i2 = secondFastestIndex(times);
 //
 // your output based on the index i1 and i2
 //
 }
 // your two Java methods:
 // fastestIndex() and secondFastestIndex()
}

I wrote a program that prints the first and second place times and names but now I am starting to think I didn't follow the instructions correctly. Could anyone help me figure out what I should do differently?
Here is my amateur code:
public class Lab
{
    public static void main(String[] args)
    {
        String[] names = {
            "Elena", "Thomas", "Hamilton", "Suzie", "Phil", "Matt",
            "Alex", "Emma", "John", "James", "Jane", "Emily", "Daniel", "Neda", "Aaron", "Kate"
        };

        int[] times = {
            341, 273, 278, 329, 445, 402, 388, 275, 243, 334, 412, 393, 299, 343, 317, 265
        };

        int firstplace = times[0];
        String firstname = names[0];

        int secondplace = times[0];
        String secondname = names[0];

        for (int counter = 0; counter < times.length; counter++)
        {
            if (times[counter] < firstplace) {
                firstplace = times[counter];
                firstname = names[counter]; }
        }

        for (int counter = 0; counter < times.length; counter++)
        {
            if (times[counter] > firstplace)
                if (times[counter] < secondplace) {
                    secondplace = times[counter];
                    secondname = names[counter]; }
        }
            System.out.printf("The fastest runner is: %s (%d Minutes)%n", firstname, firstplace);
            System.out.printf("The second fastest runner is: %s (%d Minutes)%n", secondname, secondplace);
        } // end main
    } // end class Lab

This is what it prints:
The fastest runner is: John (243 Minutes)
The second fastest runner is: Kate (265 Minutes)

A: Since this is an assignment I cannot tell you the exact code, but here is what you can do.
It is a better idea to break your code into functions that perform specific tasks and this is what your starter code says. You need to write two functions fastestIndex and secondFastestIndex. The fastestIndex is the function that should return the fastestIndex and secondFastestIndex should return the second fastest index, so just structure you code so that the code that performs the task for fastestIndex is in the corresponding method (you can do this by just moving the current fragment of the code to new method) and same for secondFastestIndex and then call both of them from the main method.
This is the best I could explain. Basic skeleton should be like this:
void main() {
   // do some task;
   // call fastestIndex;
   // call secondFastestIndex;
}

int fastestIndex() {
   // code
     int firstplace = times[0];
     String firstname = names[0];
     for (int counter = 0; counter < times.length; counter++)
        {
            if (times[counter] < firstplace) {
                firstplace = times[counter];
                firstname = names[counter]; }
        }
     // return stuff
}

//Same for secondFastestIndex

Just work around to restructure a code like the skeleton and you will be fine. Also make sure to call fastestIndex from secondFastestIndex to avoid redundancy and completely follow the instructions.

A: Alright so the complete answer you want is this:
Your teacher gives you specific pseudo-code on how to solve this problem and you should follow it.

Write a method that takes as input an array of integers and returns the index corresponding to the person with the lowest time.

this is it: public static int fastestIndex(int[] times){...}
it is static because it is not an instance method (meaning you don't have to create an instance of an object to call it)
and the second one also has the same signature
public static int secondFastestIndex(int[] times)

and inside it calls the first method to help find the second fastest index
then you print both.
Here is the full code
public class Lab
{
    public static void main(String[] args)
    {
            String[] names = {
                "Elena", "Thomas", "Hamilton", "Suzie", "Phil", "Matt",
                "Alex", "Emma", "John", "James", "Jane", "Emily", "Daniel", "Neda", "Aaron", "Kate"
            };

            int[] times = {
                341, 273, 278, 329, 445, 402, 388, 275, 243, 334, 412, 393, 299, 343, 317, 265
            };

            int win = fastestIndex(times);
            int second = secondFastestIndex(times);
            System.out.printf("The fastest runner is: %s (%d Minutes)%n", names[win], times[win]);
            System.out.printf("The second fastest runner is: %s (%d Minutes)%n", names[second], times[second]);
    } // end main

    public static int fastestIndex(int[] times)
    {

        int fastestIndex = 0;

        for (int counter = 0; counter < times.length; counter++)
        {

            if (times[counter] < times[fastestIndex])
            {
                fastestIndex = counter;
            }
        }

        return fastestIndex;

    }

    public static int secondFastestIndex(int[] times)
    {
        int fastestIdx = fastestIndex(times);
        int secondFastestIdx = 0;

        for (int counter = 0; counter < times.length; counter++)
        {
            //you search for the fastest, but you ignore it if it is
            // equal to the fastest index (so you are really finding the 2nd)
            if (times[counter] < times[secondFastestIdx] && counter != fastestIdx)
            {
                secondFastestIdx = counter;
            }
        }

        return secondFastestIdx;
    }

} // end class Lab

hope this helps

A: Yes, you have largely missed the instruction in the problem.

The second method should use the first method to determine the best runner, and then loop through all values to find the second‐best (second lowest) time.

That clearly means that secondFastestIndex() should first invoke fastestIndex(),  and then use the returned value to evaluate the second fastest runner, which I don't see in your code. Here is the kind of implementation that should satisfy it:
int secondFastestIndex(){
   //...
   fastestRunnerIndex = fastestIndex()
   //Run loop again on the array and ignore the fastestRunnerIndex while finding the smallest number in it.
   return secondFastestRunnerIndex;
}

A: You should consider also the case when the fastest is in place one. Then, you cannot equal secondfastestIndex to 0 in the first place.
(For example, in the case of 70, 250, 300, 450). Pay attention to the method to find the second fastest. Previous comments are wrong in terms of secondFastest
package mitJava2010;

public class As3_Marathon {
    public static void main(String[] arguments) {
        String[] names = { "Elena", "Thomas", "Hamilton", "Suzie", "Phil", "Matt", "Alex", "Emma", "John", "James",
                "Jane", "Emily", "Daniel", "Neda", "Aaron", "Kate" };
        int[] times = { 70, 273, 278, 329, 445, 402, 388, 275, 243, 334, 412, 393, 299, 343, 317, 265 };

        for (int i = 0; i < names.length; i++) {
            System.out.println(names[i] + ": " + times[i]);
        }

        int f = findTheFastest(times);
        int sf = find2fastest(times);
        System.out.println("The fastest is " + names[f] + " with " + times[f] + " minutes");

        System.out.println("The second fastest is " + names[sf] + " with " + times[sf] + " minutes");
    }

    private static int find2fastest(int[] times) {
        int f = findTheFastest(times);
        int sf = (f != 0) ? 0 : 1;
        for (int i = sf + 1; i < times.length; i++) {
            if (times[i] < times[sf] && i != f)
                sf = i;

        }
        return sf;
    }

    private static int findTheFastest(int[] times) {
        int minIn = 0;
        for (int i = 1; i < times.length; i++) {
            if (times[i] < times[minIn])
                minIn = i;
        }
        return minIn;

    }
}

A: The search is fine. Just put them as a methods and call those methods from the main program. The instructions specified to call methods.
Put the firstplace searching loop in a method "firstplace(int [] times)" and carry out the first place searching in this method. And the do the same for the second place as well.
I am new to programming and this was what I felt would make the code follow the instructions.


text:
Q: I cannot understand this grep pattern
file="value"

here is the content of value:
first col1 col2 col3
second col1 col2 col3
three col1 col2 col3
wanted output:
first col1 col2 col3
three col1 col2 col3
condition: we work with variables not with files directly. the search pattern should be stored in a variable as well.
In order to have this result, I do:

var=second
grep -v $var $file > $tmp;mv $tmp $file

tmp must be initialized with any value in order to work
But I came accross this and I just do not understand my bash anymore:

grep −v  "^${var},"  $file > $tmp;mv $temp $file

Apart from the fact that it does not work for me, I would like to understand the meaning or at least what it is intended to do; maybe I can arrange it after.
what does mean "^${var},"    !!??
what I know so far:
^ -> start of line
$ -> end of line
^$ -> ?
{} -> match exactly
, -> ?
all these symbols together -> ?
Any idea folks ? thank you so much.

A: Your command is using double quotes, which means that bash gets to play with the argument first.
In the following:
grep −v "^${var}," $file > $tmp;mv $temp $file

...with:
var=foo

...bash will expand ${var} to foo, resulting in:
grep −v "^foo," $file > $tmp;mv $temp $file

(it'll also expand $file, $tmp and $temp (?), but that's not interesting)

A: To add to Roger's answer,
defining your variable between {} within a string indicate to bash which part is the string and which part is the variable.
For instance if you write it like this:
"^$var,"

bash will expand it this way: "^'value of variable named var,'" which would result in a blank value since the variable is var and not var, giving this end result : "^"
if you use the curly brace instead like this:
"^${var},"

bash will look for a variable var and append ^ at the start and a , at the end giving you this value after expansion "^'var value',"
so with
var=foo

you would get "^foo," as your grep pattern


text:
Q: What is FireFox's Device Manager used for? In FireFox, there is a Device Manager (Options->Advanced->Certificates->Security Devices) that allows you to import middle-ware for cryptographic tokens (as far as  can tell).
Can someone tell me what does FireFox do with these?
From what I have seen online, my guess is that it allows the automatic authentication of the user, when he navigates to a web page. Is that right?
But can it be used for anything else?
For example, is there a way to sign some data with JavaScript, using an imported middle-ware and a cryptographic token?

A: One use for these is using a smart card to authenticate to a website. This technology employs mutual SSL authentication where a user is authenticated by using a certificate. Usually you only have one-sided SSL authentication, where the server tries to authenticate that it really is who it says it is (normal SSL, EV, etc.), but this can also be done from the client side, resulting in much stronger authentication.
The smart card is used to store the private key of the certificate on the smart card, thereby making it much more difficult for the private key to be duplicated. Also some smartcards offer support for PIN numbers when trying to use the stored private key, resulting in two-factor authentication (something you have, the smart card, and something you know, the PIN number).


text:
Q: Shell script help on finding and replacing strings I have a config file as hive-site.xml
One configuration element is;
  <property>
    <name>hadoop.embedded.local.mode</name>
    <value>true</value>
  </property>

I want to change the "true" to "false" by a shell script.
But in the file there are lots of configuration elements such as;
   <value>true</value>

tags.
So the "sed" command I used to find and replace strings is difficult to be used here with my knowledge. Appreciate if anyone can help me with this.

A: This is probably a job for XPath and a reasonable XML library. Doing this from a shell script directly is going to create a complicated and likely fragile solution. I'm going to use python and the popular lxml library as an example:
from lxml import etree

tree = etree.fromstring('''
  <property>
    <name>hadoop.embedded.local.mode</name>
    <value>true</value>
  </property>
''')

e = tree.xpath('//property[name="hadoop.embedded.local.mode"]/value')[0]
e.text = 'false'
print etree.tostring(tree)

Basically that selects any property node (anywhere in the doc) if it contains a <name> element with that value, then it selects the value element. You can then modify the element's content to your liking and print as a string again. XPath is standard, so roughly the same code ought to work in other implementations as well.

A: Obviously quite a few ways to do this, but why not try awk (gawk)?
#!/bin/bash

gawk \
'
    BEGIN {
        FLAG = 0;
    }

    /hadoop.embedded.local.mode/ {
        FLAG = 1;
    }

    />[     ]*true[     ]*</ {
        if (FLAG == 1) {
            FLAG = 0
            gsub("true", "false")
        }
    }

    {
        print
    }
' "$@"

Invoke the above script as:
<script> hive-site.xml

A: You can give the whole block and change.
sed -i '/s/<property><name>hadoop.embedded.local.mode<\/name><value>true<\/value<\/property>
/<property><name>hadoop.embedded.local.mode<\/name><value>false<\/value><\/property>/'
hive-site.xml

A: If the value you want to change is always on the next line you can first get the line number of the desired element with
NUMBER=$(grep -n "<desired element>" filename | awk -F: '{print $1}')

Then increment to the next line
let NUMBER="NUMBER + 1"

Then use sed or ex to modify the value, I prefer ex in these cases, as it eliminates the need for an interim text file.
{
print "${NUMBER}s/true/false/"
print "wq"
} | ex filename

A: sed javax.jdo.option.ConnectionURL
new_val="Chandu_jdbc"
sudo sed -i "/javax.jdo.option.ConnectionURL/!b;n;c${new_val}" /tmp/hive-site.xml
sudo sed -i '/javax.jdo.option.ConnectionURL/!b;n;c'${new_val}' /tmp/hive-site.xml
sudo sed -i "/javax.jdo.option.ConnectionURL/!b;n;c${new_val}" /tmp/hive-site.xml
sudo sed -i '/javax.jdo.option.ConnectionURL/!b;n;c'"${new_val}"'' /tmp/hive-site.xml


text:
Q: Prolog find non related graph nodes I have the following graph:

My goal is to get all the direct connections of a certain node and all of the nodes that are not connected with a certain node for example:
connections(1,X).
X=3;
X=4;
X=5;
X=6.
noConnections(1,X).
X=2.
This is my code:
% knowledge base

path(1, 6).
path(1, 5).
path(1, 4).
path(1, 3).
path(6, 5).
path(5, 4).
path(4, 2).
path(2, 3).

% rules

connections(X,Y) :- path(X,Y) ; path(Y,X).
noConnections(X,Y) :- \+path(X,Y).

As you can see I succesfully did connections but cant find out how to do it for noConnections

A: One way :
connected(X, Y) :-
    path(X,Y);path(Y,X).

% fetching all nodes of the database
collectAllNodesButX(X, L) :-
    setof(A, B^(path(A,B);path(B,A)), L1),
    select(X, L1, L).

% main predicate
notConnected(X, L) :-
   collectAllNodesButX(X,Nodes),
   % we exclude all nodes that succeed the predicate connected/2
   findall(Y, (member(Y, Nodes), \+connected(X, Y)), L).

Now, we get :
?- notConnected(1, L).
L = [2] .

?- notConnected(X, [2]).
X = 1 .

A: You can use the not(Goal) predicate. You can say not(path(X,Y)); not(path(Y,X)). which is just the inversion of your goals. If the node directly connects to whichever node you are checking for, the result is false. No connections returns true then.


text:
Q: fatal error Call to a member function getReadConnection() pn boolean on my localhost I AM GETTING THIS on going to my backend or front end on magento 1.9.2.2

Fatal error: Call to a member function getReadConnection() on boolean
  in C:\xampp\htdocs\shokart\includes\src__default.php on line 32629

I dont know what to do as i am new to magento

A: Open include/config.php. and add php comment # all lines there.

A: By the way - windows does not work with Magento well. I was struggling with it whole week and Virtual Box with LAMP worked for me much better.


text:
Q: Classic ASP, Sending E-mail on windows server 2008 - error '8004020f' I am trying to send e-mail with classic ASP (I am stuck with an old app so I have to use classic ASP here) on Windows Server 2008 R2, IIS 7.5.
I guess lots of thing change from win server 2003 to 2008. I am using the following code but I am getting this error (BTW, error message is so "informative");

error '8004020f'
/poo.asp, line 32

Here is the code;

<%

    'Declare variables
    Dim sch, cdoConfig, cdoMessage
    sch = "http://schemas.microsoft.com/cdo/configuration/"

    Set cdoConfig = CreateObject("CDO.Configuration")

    With cdoConfig.Fields
        .Item(cdoSendUsingMethod) = cdoSendUsingPort
        .Item(cdoSMTPServer) = "mail.example.com"
        'Set SMTP port which is 25 by default
        .Item(sch & "smtpserverport") = 587
        .Update
    End With

    Set cdoMessage = CreateObject("CDO.Message")

    With cdoMessage
        Set .Configuration = cdoConfig
        .From = "info@example.com"
        .To = "me@example2.com"
        .Subject = "Sample CDO Message"
        .TextBody = "This is a test for CDO.message"
        .Send
    End With

    Set cdoMessage = Nothing
    Set cdoConfig = Nothing

Response.write "<title>A message has been sent.</title>A message has been sent."

%>

Also, I just installed Microsoft Exchange Server MAPI Client and Collaboration Data Objects 1.2.1 from http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=1004 into my server but it didn't change anything.
NOTE: I could send e-mail over localhost if it works. doesn't matter.

A: You might come across the following error:

error '8004020f'  The event class for this subscription is in an
invalid partition

This error message comes from cdosys.h, and has nothing to do with any sort of "partition" - it is actually lumped in with other errors in an overloaded message. The error code is actually attributed to the following:
CONST LONG CDO_E_RECIPIENTS_REJECTED = 0x8004020FL

Which means that the e-mail was rejected by the server for some reason. Here are some things you can try to alleviate the problem:

*

*Make sure the SMTP server allows anonymous (non-authenticated) relaying. If your SMTP requires outgoing authentication, see Article #2026.

*Check if the problem is specific to the domain name(s) used in the e-mail addresses of the recipients. For example, some users have complained that they can send to users on their own domain only; others have said that they can send to any domain except their own (see Article #2511 for some potential causes and solutions).

*It may be simply that the e-mail address is being rejected, but other configuration settings on the SMTP server are preventing the true error message from being relayed propely back to the ASP script ... so verify that the address is valid.

*If you have a proxy or firewall, make sure the web server is set up to correctly pass through it, that the SMTP server knows about it, and that the proxy allows access to port 25.

*Try using a SendUsing value of 1 (pickup) instead of 2 (port). E.g. the following line:
.Item(cdoSendUsingMethod) = cdoSendUsingPort

Becomes
.Item(cdoSendUsingMethod) = cdoSendUsingPickup

http://classicasp.aspfaq.com/email/why-does-cdo-message-give-me-8004020f-errors.html


text:
Q: INSERT INTO with SubQuery MySQL I have this Statement:
INSERT INTO qa_costpriceslog (item_code, invoice_code, item_costprice)
    VALUES (1, 2, (SELECT item_costprice FROM qa_items WHERE item_code = 1));

I'm trying to insert a value copy the same data of item_costprice, but show me the error:
Error Code: 1136. Column count doesn't match value count at row 1

How i can solve this?

A: I was disappointed at the "all or nothing" answers. I needed (again) to INSERT some data and SELECT an id from an existing table.
INSERT INTO table1 (id_table2, name) VALUES ((SELECT id FROM table2 LIMIT 1), 'Example');

The sub-select on an INSERT query should use parenthesis in addition to the comma as deliminators.
For those having trouble with using a SELECT within an INSERT I recommend testing your SELECT independently first and ensuring that the correct number of columns match for both queries.

A: Your insert statement contains too many columns on the left-hand side or not enough columns on the right hand side.  The part before the VALUES has 7 columns listed, but the second part after VALUES only has 3 columns returned: 1, 2, then the sub-query only returns 1 column.
EDIT: Well, it did before someone modified the query....

A: You can just simply e.g.
INSERT INTO modulesToSections (fk_moduleId, fk_sectionId, `order`) VALUES
    ((SELECT id FROM modules WHERE title="Top bar"),0,-100);

A: Use numeric literals with aliases inside a SELECT statement.  No () are necessary around the SELECT component.
INSERT INTO qa_costpriceslog (item_code, invoice_code, item_costprice)
  SELECT
    /* Literal number values with column aliases */
    1 AS item_code,
    2 AS invoice_code,
    item_costprice
  FROM qa_items
  WHERE item_code = 1;

Note that in context of an INSERT INTO...SELECT, the aliases are not actually necessary and you can just SELECT 1, 2, item_costprice, but in a normal SELECT you'll need the aliases to access the columns returned.

A: As a sidenote to the good answer of Michael Berkowski:
You can also dynamically add fields (or have them prepared if you're working with php skripts) like so:
   INSERT INTO table_a(col1, col2, col3)
     SELECT
       col1,
       col2,
       CURRENT_TIMESTAMP()
     FROM table_B
     WHERE b.col1 = a.col1;

If you need to transfer without adding new data, you can use NULL as a placeholder.

A: If you have multiple string values you want to add, you can put them into a temporary table and then cross join it with the value you want.
-- Create temp table
CREATE TEMPORARY TABLE NewStrings (
        NewString VARCHAR(50)
    );
-- Populate temp table
INSERT INTO NewStrings (NewString) VALUES ('Hello'), ('World'), ('Hi');

-- Insert desired rows into permanent table
INSERT INTO PermanentTable (OtherID, NewString)
    WITH OtherSelect AS (
        SELECT OtherID AS OtherID FROM OtherTable WHERE OtherName = 'Other Name'
    )
    SELECT os.OtherID, ns.NewString
    FROM OtherSelect os, NewStrings ns;

This way, you only have to define the strings in one place, and you only have to do the query in one place. If you used subqueries like I initially did and like Elendurwen and John suggest, you have to type the subquery into every row. But using temporary tables and a CTE in this way, you can write the query only once.


text:
Q: Angular TypeError: name.replace is not a function for ng-style I'm new to angular and keep getting the following error in the console TypeError: name.replace is not a function. I'm not sure what's exactly causing it, but it seems to be caused by the ng-style statement and maybe something to do with the camelCase?
The part I don't understand is why ng-style="isFrontView() || !matches && {'display': 'none'}" throws the error, but ng-style="!isFrontView() || !matches && {'display': 'none'}" doesn't throw the error.
In an attempt to remedy the situation I tried removing the camelCase from the function name and went all lowercase. I also attempted to use !!isFrontView(), but neither seemed to remove the error message.
Do anyone know what is the cause of this error message and a potential fix?

HTML Template:

        <canvas id="canvasLayer-shell" data-layername="front" width="617" height="427"></canvas>

        <canvas id="canvasLayer-shell" data-layername="back" width="617" height="427"></canvas>

Backend Code:
$scope.frontView = true;
$scope.matches = true;

$scope.isFrontView = function() {
   return $scope.frontView;
};

$scope.changeView = function() {
    $scope.frontView = !$scope.frontView;
};

P.S. Even with the console error everything still functions normally.

A: Your potential issue is due to the incorrect usage of ng-style. ng-style sets a watcher on the expression and sets the element's style with the help of jquery/jqlite element.css. And Inside element.css css attribute (name) is converted to the standard camel casing (which uses regex string replace). In your specific case the expression evaluated to boolean (true) instead of an object (ng-style does this for each property) and boolean does not have replace property (which is available on a string object) and hence it fails. You can test this by converting your expression to evaluate to a string by using string concatenation.
i.e ng-style="'' + (isFrontView() || !matches && {'display': 'none'})"
Looking at the expression all you need it to hide and show the element, you could well make use of ng-show/ng-hide directives to achieve that.

A: This can happen if the expression evaluated returns the wrong type.
Expression evaluated:
ng-style="$vm.getStyles()"

must return an object literal:
return { order: -1 };

A: This is a late answer but I might help others that have the same issue  like me.In my case the error is a.replace is not a function and finally I found the reason. It was happening due to ng-style and the expression was data-ng-style="isCompare==true ? {'max-height':'423'} : ***' '***  .... that space between single qoutes  caused the error.After removing space the error went away.


text:
Q: IOS - No "touchend" event for not fullscreen webview "onTouchEnd" is not firing when touch ends outside of webview.
Compile with XCode 6, iOs 8, iPhone 6
I have next layout:
|Navigation TAB|
|Left view|Web view|Right view|
|page view|

I can receive all touch events, when touch starts and ends, in web view.
But if I start touch in webview and then move touch outside of it, I would stop receiving touchmove events as soon as I leave webview border, and no touchend event is received.
Code fot test html file:

This is a test

 Lore ip sum

Code of "viewDidLoad" function
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

self.webView = [[UIWebView alloc] initWithFrame:self.mainView.bounds];

[self.webView setScalesPageToFit:YES];
[self.webView setAlpha:1];

/* Disable scrolling of web view */
for (id subview in [self.webView subviews]) {
    if ([subview isKindOfClass:[UIScrollView class]]) {
        ((UIScrollView*)subview).bounces = NO;
    }
}

self.webView.scrollView.bounces = NO;
self.webView.scrollView.canCancelContentTouches = NO;
self.webView.scrollView.scrollEnabled = NO;

self.webView.backgroundColor = [UIColor magentaColor]; //[UIColor colorWithRed:(45.0/255.0) green:(50.0/255.0) blue:(53.0/255.0) alpha:1];
self.webView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin| UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
[self.mainView addSubview:self.webView];

NSString * localHtmlFilePath = [[NSBundle mainBundle] pathForResource:@"main" ofType:@"html" inDirectory:@"www"];
NSString *html = [NSString stringWithContentsOfFile:localHtmlFilePath encoding:NSUTF8StringEncoding error:nil];

[self.webView loadHTMLString:html baseURL:nil];

How this can be fixed? Is there are some configuration that I missed?
Complete source code can be found here: https://github.com/Daraku/WebViewBug

A: I have been strugling with the same for past 30minutes, in the end i've decided to implement a timeout which is getting restored with every touchmove and starts on touchstart, and gets cleared on touchend. Timeout is for lets say 1500ms, and if i don't get touchend fired from within the webview as it should, i fire it when the timeout ends.
Hope i made a point. Its not perfect but serves as partial fix. In my case hackaround for iScroll( _execEvent('scrollCancel') )

A: I had a similar issue where I've embedded a webview in a native app. The native app has a header of say 60 px and below it sits the webview.
When swiping up from the webview and releasing your finger on the header the 'touchend' event doesn't propagate to the webview.
I found that the Y coordinate on the 'touchmove' event is negative when leaving the webview at the top so I leverage that fact by listening to it and programmatically triggering a touchend event. Works like a boss!
document.addEventListener("touchmove", function(e) {
if (e.changedTouches[0].pageY < 0) {
    e.preventDefault();
    document.dispatchEvent(new Event('touchend'));
}

}, false);
Here's a gist of the same code: https://gist.github.com/EddyVerbruggen/70b96fce47fa7bf7a34f03e3a2ecb85f


text:
Q: Is there any open source software for Linux that will create a full file index and allow for querying of that index? I essentially am looking for a piece of software for my own server similar to how Google works.  I would like to be able to index my videos, pictures, music, and documents and have them searchable from a web page (similar to Google).  I am not opposed to working this, I just haven't been able to find any full featured software that would do this, just pieces.
I have seen the following that don't really fit my needs :

*

*Recoll (http://www.lesbonscomptes.com/recoll/) seems like a great product, however it only indexes documents.

*Tracker (https://projects.gnome.org/tracker/)  This also seems like a good product, it doesn't have a web frontent, but it seems like I could come up with that if I really wanted to add it.  The parts that concern me here are separation of code, I would ideally just like a service that the frontend could make a request to that wouldn't have any UI dependencies.

These are the two main pieces that I have found, there are definitely technologies out there that would help (such as Apache Lucene). But my main question, is this something that I should write myself?  I do have the knowledge to go about this, and I fully plan on doing it if that is what needs to happen, I just want to know if maybe there are some existing technologies that I am missing.


text:
Q: Find all natural number solutions in Prolog program For example if I want to get all possible natural number pairs that sum to 10, how would I get prolog to do that?
If my code is something like this:
sumsTo10(X,Y):-
   Z is X+Y,
   Z == 10.

Then yes, if I ask if 5 and 5 sum to 10 I get a true as an answer, but I'd like something like this:
?-sumsTo10(A,B).
[1,9]
[2,8]
....

A: You can use the Constraint Logic Programming library over Finite Domains (clpfd) for that:
:- use_module(library(clpfd)).

sumsTo10(X,Y):-
    [X,Y] ins 1..10,
    X + Y #= 10,
    label([X,Y]).

This then generates:
?- sumsTo10(X,Y).
X = 1,
Y = 9 ;
X = 2,
Y = 8 ;
X = 3,
Y = 7 ;
X = 4,
Y = 6 ;
X = Y, Y = 5 ;
X = 6,
Y = 4 ;
X = 7,
Y = 3 ;
X = 8,
Y = 2 ;
X = 9,
Y = 1.

The first line specifies that both X and Y are in the 1..10 domain (that is 10 inclusive, but that does not matter). The second line is a constraint: it restricts the fact that X + Y should be equal (#=) to 10. This only adds the constraint: it will not ground X and Y to values where this actually holds, but from the moment X and Y are (partially) grounded, and the constraint is not met, it will fail. If you for instance set X to 10, it will derive that Y can only be 0, but since Y is in the interval 1..10, that is not possible hence the system will fail.
Finally by using label([X,Y]) we will assign values in the domain to X and Y such that the constraint holds.

A: Your Prolog could provide between/3. Then
?- between(1,10,X), between(1,10,Y), X+Y =:= 10.
X = 1,
Y = 9 ;
X = 2,
Y = 8 ;
X = 3,
Y = 7
...


text:
Q: How to query using expressive syntax in NEST (Elasticsearch)? I am looking to write a small tool to query elasticsearch using NEST APIs and would like to support queries such as status:[400 TO 499] AND (extension:php OR extension:html)
I thought that SearchQueryString or SimpleQueryString API would have helped, but it is not able to get the right results.
var r = await this.client.SearchAsync<LogEvent>(s => s
    .Query(q =>
        q.SimpleQueryString(c => c.Query(searchQuery))) // searchQuery -> query string
    .From(from)
    .Size(size)
    .Index("oxyb*")
    .Sort(ss =>
        ss.Descending(f => f.TimeStamp)));

Also notice that a similar syntax is supported by elasticsearch API Query String Query

A: You can use the query_string query to support those kinds of queries. These map to NEST's QueryString query
var from = 0;
var size = 20;
var searchQuery = "status:[400 TO 499] AND (extension:php OR extension:html)";
var response = await this.client.SearchAsync<LogEvent>(s => s
    .Query(q => q
        .QueryString(c => c
            .Query(searchQuery)
        )
     )
    .From(from)
    .Size(size)
    .Index("oxyb*")
    .Sort(ss => ss
        .Descending(f => f.TimeStamp)
    )
);

which yields
POST http://localhost:9200/oxyb*/logevent/_search?pretty=true
{
  "from": 0,
  "size": 20,
  "sort": [
    {
      "timeStamp": {
        "order": "desc"
      }
    }
  ],
  "query": {
    "query_string": {
      "query": "status:[400 TO 499] AND (extension:php OR extension:html)"
    }
  }
}

A: You cound use the QueryString Query in nest:
var r = client.Search<LogEvent>(s => s
    .Query(q => q.QueryString(qs => qs
       .Query("Some String")
       .AnalyzeWildcard(true)
       .DefaultOperator(Operator.And)));


text:
Q: Como abrir una instancia de navegador con Excel 2016 - Este codigo funcionaba en excel 2010 y IE Estoy tratando de abrir una instancia del navegador con Excel 2016 y Windows 10 y no funciona, este mismo codigo funcionaba con Excel 2010 y W7, no estoy pudiendo encontrar el error.
Sub Macro_Inicio_Navegador()

the_start:
Set objIE = CreateObject("InternetExplorer.Application")
    objIE.Top = 0
    objIE.Left = 0
    objIE.Width = 800
    objIE.Height = 600
    objIE.Visible = True

    On Error Resume Next

    objIE.Navigate ("http://google.com")

Do
    DoEvents
        If Err.Number <> 0 Then
        objIE.Quit
        Set objIE = Nothing
        GoTo the_start:
        End If
Loop Until objIE.ReadyState = 4

Set AllLinks = objIE.Document.GetElementsByTagName("a")

For Each Hyperlink In AllLinks
If InStr(Hyperlink.Innertext, " ") > 0 Then
MsgBox "Encontrada"
Hyperlink.Click
Exit For
End If
Next
End Sub


text:
Q: Automatically play and loop an array of videos, and change CSS with each Firstly, I am a code novice, and I appreciate that my ignorance may not be overly welcome. Nonetheless, if you are willing to indulge and help me, I would appreciate it a lot.
So, it appears that in previous years and in response to other people, people have expressed http://stackoverflow.com/questions/17521012/html5-video-loop-src-change-on-end-play-function-not-working as an answer to the first part of my question. Code from aforementioned answer:
<video id="homevideo" width="100%" autoplay onended="run()">
    <source src="app/video1.mp4" type='video/mp4'/>
</video>

&
video_count =1;
videoPlayer = document.getElementById("homevideo");

function run(){
        video_count++;
        if (video_count == 4) video_count = 1;
        var nextVideo = "app/video"+video_count+".mp4";
        videoPlayer.src = nextVideo;
        videoPlayer.play();
   };

To expand on this, however, how would one construct this if the videos aren't following a video[number].mp4 naming convention? I should say, I found and tried the solution offered here initially, but it would only loop the first video and not play the others for some reason.
Lastly, and additionally, I'd like each video to have a pre-defined CSS change attached to it. For instance, when a specific video plays, the background-color of the parent element would change to an assigned colour. The same would happen for each of the videos in the array, each having a colour pre-defined that the background colour would change to.
If people are able to offer a solution, and also briefly explain it so that I may hopefully learn, that would be terrific!
Many thanks in advance, people.

A: Just make an array with classes matching your videos:
var example = ['foo', 'bar', 'faz', 'video4'];

And then you set it in your loop, after var nextVideo (you already have that counter, just reuse it);
var videoPlayer.classList = example[video_count-1]; // -1 as you count from 1->4, but the array 0->3


text:
Q: .attr() as a variable in attribute selector not work I have code like this

    Title
    <input id="post-titie" type="text">

About Title

Visitors can see your title even if they're not logged in.

The title is public.

$('.form textarea, :input').focus(function(){

    var forwhom = $(this).attr('id'); /* not working */
    /* var forwhom = 'post-title';  works */

    var _msg = $(this).parents().eq(2).find('div[for-field="'+forwhom+'"]');
    $(_msg).transition('fade down').transition('show');

    console.log(forwhom);
    console.log(_msg);
}

What I want to do is when <input> or <textarea> focused, show messages div with .message class.
I make $(this).attr('id') as a variable (eg. post-title), and find it with .find('div[for-field="'+forwhom+'"]'). This is not working.
But If I replace var forwhom from $(this).attr('id') (jQ selector) to a absolute value like post-title, It does work.
It's strange! According to jQuery documentation, the .attr() method returns a string not an object.
What is the problem?

A: Div attribute for-field="post-title" and input has post-titie there is spelling mistake.
post-title and post-titie are not same that's why your code is not finding the div with for attribute.

A: I am getting id attribute. Check for console error:
$(function(){
    $('.form textarea, :input').focus(function(){

    var forwhom = $(this).attr('id'); /*  working */
    /* var forwhom = 'post-title';  works */

    console.log(forwhom);
});

});

Here is the working fiddle
https://jsfiddle.net/sesn/x1ju006b/1/

A: some tips:
1) use chrome dev tools to test out your selectors in the console
2) use .prop() instead of .attr()
3) .closest() instead of $(this).parents().eq(2)


text:
Q: fatal: could not create work tree dir 'ncorr_2D_matlab' I was trying cloning "https://github.com/justinblaber/ncorr_2D_matlab" in my Matlab folder as per instructions but got this error:
fatal: could not create work tree dir 'ncorr_2D_matlab': No such file or directory

I even tried creating the directory but still got error:
Cloning into 'ncorr_2D_matlab'...
C:/Users/DHRUV DARDA/Documents/MATLAB/ncorr_2D_matlab/.git: No such file or directory

When I tried this in the User/'DHRUV DARDA'/Documents folder, I faced these errors above, but when I did the same in User/'DHRUV DARDA', it worked. Can someone explain why?

A: Make sure you are not cloning in a folder (Documents/) which could be synchronized automatically with a Microsoft OneDrive cloud storage service.
That would immediately mess up the repository which is trying to be created.
To confirm this, try and clone it in a simpler path (for testing)
mkdir C:\test
cd C:\test
git clone https://github.com/justinblaber/ncorr_2D_matlab


text:
Q: Custom ListVIew and onclick Here is my code - everything. I did as you told but I still can`t click on nothing. I mean I can click but nothing happens

package fixus.core;

import java.util.ArrayList;
import java.util.Iterator;

import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import fixus.lib.News;
import fixus.testing.DataInput;

public class NewserActivity extends ListActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        DataInput di = new DataInput();
        ArrayList news = di.getNews();

        NewsArrayAdapter naa = new NewsArrayAdapter(NewserActivity.this, R.layout.row, news);
        setListAdapter(naa);
        ListView lv = getListView();

        lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView parent, View view,
          int position, long id) {
        Log.i("testy", "I Clicked on Row " + position + " and it worked!");
      }
    });

   }

    @Override
    /**
     * When the user selects an item in the list, do an action
     * @param ListView l
     * @param View v
     * @param int position
     * @param long id
     */
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);

        final int index = position;

        //You can add whatever you want to happen when you click here

        Log.i("testy", "I Clicked on Row " + index + " and it worked!");

    }

    private class NewsArrayAdapter extends ArrayAdapter {
        protected ArrayList items;

        public NewsArrayAdapter(Context context, int textViewResourceId, ArrayList items) {
            super(context, textViewResourceId, items);
            this.items = items;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = convertView;

            if(v == null) {
                LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                v = vi.inflate(R.layout.row, null);
            }

            News news = this.items.get(position);
            if(news != null) {
                TextView tt = (TextView) v.findViewById(R.id.toptext);
                TextView bt = (TextView) v.findViewById(R.id.bottomtext);

                if (tt != null) {
                      tt.setText("Name: "+ news.getName());
                }
                if(bt != null){
                      bt.setText("Status: "+ news.getUrl().toString());
                }
            }

            return v;
        }
    }

}
If you know a good tutorial/example that would show me the good way I would love to see it :)

A: In your list activity what you should do is something like the following:
public class YourClass extends ListActivity {
    //Your Variables
    ArrayList<Type> yourlist;
    YourAdapterClass adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        yourlist = new ArrayList<Type>();
        this.adapter = new YourAdapterClass(this, R.layout.row, yourlist);
        setListAdapter(this.adapter);
        //you might be able to see if the below works instead of overriding
        ListView lv = getListView();

        lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
          int position, long id) {
        Log.i("testy", "I Clicked on Row " + position + " and it worked!");
      }
    });
    }

    @Override
    /**
     * When the user selects an item in the list, do an action
     * @param ListView l
     * @param View v
     * @param int position
     * @param long id
     */
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);

        final int index = position;

        //You can add whatever you want to happen when you click here

        Log.i("testy", "I Clicked on Row " + index + " and it worked!");

    }

//other methods can go here for you list

}

You don't want to have your onClickListener inside your getView(...) method in the List Adapter, that is just where you are suppose modify the way your row looks like (adding buttons, textfields, etc. for each row) instead you want to have the onClickListener in a class that extends ListActivity that connects to your Adapter
Good luck, hope this helped
//Edit (adding more info)
You need to 'add it to your adapter' in the onCreate method (see edited code above) Hopefully that should fix the problem. Let me know if it still doesn't work though. If that doesn't work you can try using the setOnItemClickListener code I put in the onCreate method instead, if that still doesn't work I would try checking out some tutorials (I'll see if i can find you a good one)

A: I added this code to my method getView inside my class CustomAdapter.
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View row = convertView;

        /* ...Code for holder and so on... */

        row.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.v(LOG_TAG, "ROW PRESSED");
            }
        });

        row.setTag(holder);

        setupItem(holder);

        return row;

 }


text:
Q: Implode Issue On PHP Form In spite of the fact that I'll probably look like a complete idiot, I'm going to post my entire files to see what I'm doing wrong.
I have form built into the page like so:
<form method="post" class="form-horizontal" id="final_form" action="send_mail.php">

Search for your dream home

       and save now!

                <legend>Which Areas are you interested in?</legend>

                            <input type="checkbox" name="arrayValue[]" id="area[0]" value="Sparks" style='margin-top:-5px !important;'> Sparks

                            <input type="checkbox" name="arrayValue[]" id="area[1]" value="Stead" style='margin-top:-5px !important;'> Stead

                            <input type="checkbox" name="arrayValue[]" id="area[2]" value="North Reno" style='margin-top:-5px !important;'> North Reno

                            <input type="checkbox" name="arrayValue[]" id="area[3]" value="South Reno" style='margin-top:-5px !important;'> South Reno

                            <input type="checkbox" name="arrayValue[]" id="area[4]" value="Double Diamond" style='margin-top:-5px !important;'> Double Diamond

                <input type="button" onclick="jQuery('#myModal').modal('show')" value="CONTINUE" />

Some Content

Some Content!

            This Website Is Brought To You By: Ken Holden

            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>

What type of home are you looking for?

        <input type="hidden" name="template" id="template" value="Buyers" />

                            <select class="span3 required" name="minPrice" id="minPrice">
                                <option value="">Price</option>
 <option value='$50,000 - $150000'>$50,000 - $150000</option><option value='$150,000 -
$300,000'>$150,000 - $300,000</option><option value='$300,000 - $400,000'>

$300,000 - $400,000</option><option value='$400,000 +'>$400,000 +</option>
</select>

                            <select class="span3 required" name="minBedrooms" id="minBedrooms">
                                <option value="">Bedrooms</option>
<option value='1-2'>1-2</option><option value='2-4'>2-4</option><option value='4+'>4+
</option>                                </select>

                            <select class="span3 required" name="minBathrooms" id="minBathrooms">
                                <option value="">Bathrooms</option>
<option value='1-2'>1-2</option><option value='2-4'>2-4</option><option value='4+'>4+
</option>                                </select>

                            <select class="span3 required" name="realtor" id="realtor">
                                <option value="">Currently Working With a Realtor</option>
                                <option value="Yes">Yes</option>
                                <option value="No">No</option>
                            </select>

                            <select class="span3 required" name="move" id="move">
                                <option value="">When Do You Plan On Moving?</option>
                                <option value="30-90 days">30-90 days</option>
                                <option value="90-120 days">90-120 days</option>
                                <option value="I'm just looking">I'm just looking</option>
                            </select>

                    <textarea class="" id="wantedArea" name="wantedArea" style="display:none;"></textarea>

                        First Name

                            <input class="required" type="text" id="fname" name="fname" placeholder="First Name" />

                        Email

                            <input class="required" type="text" id="email" name="email" placeholder="Valid Email Required" />

                        Cell Phone

                            <input class="required" type="text" id="phone" name="phone" placeholder="Cell Phone" />

Here is the php
<?php

$webmaster_email = "email@email.com";

$webmaster_email2 = "email@email.com";

$fname = $_REQUEST['fname'];
$email = $_REQUEST['email'];
$phone = $_REQUEST['phone'];
$minBedrooms = $_REQUEST['minBedrooms'];
$minBathrooms = $_REQUEST['minBathrooms'];
$minPrice = $_REQUEST['minPrice'];
$move = $_REQUEST['move'];
$realtor = $_REQUEST['realtor'];

if( !empty($_REQUEST) && is_array($arrayValue) ) {

$arrayValue = array();
$areas = implode("," , $_REQUEST['arrayValue']);

}

$emailfrom = $_REQUEST['email'];

$headers = 'From: '.$emailfrom."\r\n".

$email_to = "test@gmail.com, ";

/* This bit sets the URLs of the supporting pages.
If you change the names of any of the pages, you will need to change the values here.
*/
$feedback_page = "index.html";
$thankyou_page = "thankyou.html";

/*
The following function checks for email injection.
Specifically, it checks for carriage returns - typically used by spammers to inject a CC
list.
*/
function isInjected($str) {
$injections = array('(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if(preg_match($inject,$str)) {
    return true;
}
else {
    return false;
}

}

// If the user tries to access this script directly, redirect them to the feedback
form,
if (!isset($_REQUEST['email'])) {
header( "Location: $feedback_page" );
}

// If email injection is detected, redirect to the error page.
elseif ( isInjected($email) ) {
header( "Location: $error_page" );
}

// If we passed all previous tests, send the email then redirect to the thank you page.
else {
mail( $email_to, "You Have a New Lead",
"Name: $fname\nEmail: $email\nPhone: $phone\nMinBedrooms: $minBedrooms\nMinPrice:
$minPrice\nMove Date: $move\nRealtor: $realtor\nAreas: $areas", $headers );
}

echo "";
?>

My checkboxes are not returning any values. Does anyone know why? I've worked to make things correct and I think I've got the array set up right thanks to the help of another question, but I think I'm asking the wrong question in my other post.

A: Your $arrayValue is not defined before the first if statement which is why the is_array($arrayValue) does not succeed.  Please try:
if( !empty($_REQUEST['arrayValue'])) {
  $arrayValue = array();
  $areas = implode("," , $_REQUEST['arrayValue']);
}

A: In your HTML this should be the name:

 <input type="checkbox" name="arrayValue" id="area[4]" value="Double Diamond" style='margin-top:-5px !important;'> Double Diamond

In your PHP
 if( !empty($_REQUEST) && is_array($arrayValue) )
       {

      $arrayValue = array();
      $arrayValue[] = $_REQUEST['arrayValue'];
       }
      $areas = implode(",",$arrayValue);

 put it in the array first then implode it as a string.

A: just check by printing php global variable $_REQUEST on your php. You can do it by writing print_r($_REQUEST); if it does not shows anything or black array, make use of $_POST instead of $_REQUEST at each place in php file. Hope it will solve your problem.