text:
Q: SQL-> multibuscador Access (VBA) Tengo un formulario en Access que me sirve para buscar herramientas (brocas en el ejemplo) en una BBDD.
He construido el buscador para que se pueda operar con entre 0 y 4 variables a tener en cuenta (0 variables seleccionadas = el formulario muestra todas las brocas)
El buscador cuenta con 4 selectores de las diversas propiedades de la broca.
La consulta SQL se basa en los 4 campos OCULTOS que definen la selección, ya que si se dejara un selector vacío, la consulta SQL no funcionaría. Por esta razón, los campos ocultos siempre están auto rellenados con un * o con un 0 en el caso de la altura de trabajo que es un valor numérico mayor o igual a (>=) en vez de un campo igual a (=).
Mi idea, es que si el usuario selecciona 1 o 2 variables, lo campos ocultos completen la sentencia SQL añadiendo un * (toda la selección) en el campo correspondiente.

En el caso de la foto, solo se habría seleccionado el diámetro de la broca a buscar dándonos igual el sentido de giro, la altura de trabajo y el tipo de broca.
Como podréis observar, los campos ocultos contienen * para que la consulta SQL no falle al encontrarse un valor null.
La sintaxis SQL:
SELECT HERRAMIENTA.Ubicacion, HERR_BROCA.diametro, HERR_BROCA.Sentidogiro, HERR_BROCA.altura_trabajo, HERR_BROCA.altura_total, HERR_BROCA.modelo

FROM HERRAMIENTA, HERR_BROCA

WHERE herramienta.id_herramienta = HERR_BROCA.id_broca

AND HERR_BROCA.diametro = (forms![BuscaBroca].[sql_diametro].value)

AND HERR_BROCA.Sentidogiro = (forms![BuscaBroca].[sql_sentidogiro].value)

AND HERR_BROCA.altura_trabajo >= (forms![BuscaBroca].[sql_alturatrabajo].value)

AND HERR_BROCA.modelo = (forms![BuscaBroca].[sql_modelo].value)
;

El problema que tengo es que el access no me reconoce por ejemplo el caracter * cuando estamos hablando de diámetro de brocas al ser un campo numérico. Dice que es demasiado compleja la expresión.
¿Hay alguna forma de que el access permita hacer una multiselección de esta manera? ¿Alguna idea de como podría solucionarlo?
Escribir aquí es como hacer chuletas para el examen, aprendes haciéndolas... y se me ocurre cambiar el diámetro de broca de campo numérico a texto pero... ¿Hay alguna otra forma?
Esto podría seguir dando problemas si reconociera el * como texto en si mismo en vez de como (* = "cualquier cosa que existe en la tabla")
EDITO CON LA MEJORA PROPUESTA POR EL COMPAÑERO #Esei

SELECT
    HERRAMIENTA.Ubicacion,
    HERR_BROCA.diametro,
    HERR_BROCA.Sentidogiro,
    HERR_BROCA.altura_trabajo,
    HERR_BROCA.altura_total,
    HERR_BROCA.modelo
FROM
    HERRAMIENTA,
    HERR_BROCA
WHERE
    (HERRAMIENTA.id_herramienta)=(HERR_BROCA.id_herramienta)
And
    ((HERR_BROCA.diametro) Like IIf(((forms!BuscaBrocas.sql_diametro.value)=1),(forms!BuscaBrocas.buscar_diametro.value),'*'))
And
    ((HERR_BROCA.Sentidogiro) like IIf(((forms!BuscaBrocas.sql_sentidogiro.value)=1),(forms!buscabrocas.buscar_sentidogiro),'*'))
And
    ((HERR_BROCA.altura_trabajo)>=(forms!BuscaBrocas.sql_alturatrabajo.value))
And
    ((HERR_BROCA.modelo) like IIf(((forms!BuscaBrocas.sql_modelo.value)=1),(forms!buscabrocas.buscar_modelo),'*'))
;

De esta manera, si seleccionamos un valor para utilizalo en el buscador, las variables ocultas pasaran de 0 a 1 para indicar al bucle IIF que se encuentra dentro de la consulta SQL que entre en la opcion: "coger el valor del formulario", en vez de la opcion "usar * porque la variable en cuestion no se esta utilizando en el buscador"
Como observareis, para poder utilizar un asterisco (*) en el buscador he tenido que sustituir el operador = por el operador like.
La consulta funciona, mostrando los datos en un buscador en tiempo real que se actualiza conforme modificamos las variables a buscar.
El problema que surge en este momento es que:
Si el buscador arroja cero registros, el formulario desaparece y se queda en blanco totalmente
Esto debe de ocurrir porque el origen de datos es una consulta sql en la configuracion del propio sub-formulario que muestra los resultados.
Cuando los datos devueltos son cero, el cuerpo del formulario se vuelve blanco y solo muestra el encabezado del mismo.
Un saludo, y muchas gracias de nuevo #Esei

A: Esta hecho.
Es posible con un campo numerico comparar con: numeros (obvio) y * (no numero) en una consulta SQL que se lanza desde el ACCESS.
Hay que utilizar el poerador LIKE en vez del operador =.
Hay que tener mucho cuidado con los simbolos " y ' puesto que son esenciales para que el compilador haga su "magia" sin errores.
Mi consulta sql:
SELECT *

FROM herr_broca

WHERE
diametro_trabajo Like IIf(forms!BuscaBrocas.sql_diametro.value=1,forms!BuscaBrocas.buscar_diametro.value,"*")
And
altura_trabajo>=forms!BuscaBrocas.sql_altura_trabajo.value And sentido_giro Like IIf(forms!BuscaBrocas.sql_sentido_giro.value=1,forms!BuscaBrocas.buscar_sentido_giro.value,"*")
And
modelo Like IIf(forms!BuscaBrocas.sql_modelo.value=1,forms!BuscaBrocas.buscar_modelo.value,"*")
And ubicacion Like IIf(forms!BuscaBrocas.sql_ubicacion.value=1,forms!BuscaBrocas.buscar_ubicacion.value,"*");

De esta manera consigo que en un formulario sin clickar botones, el sub-formulario de busqueda me filtre las herramientas en tiempo real en cuanto el operador cambia el campo diametro, el campo tipo de broca... o una combinacion de los campos que componen el buscador (multibusqueda por ejemplo de una broca del diametro 4 con giro 'horario' que este en el almacen 3).
Esencial si quieres en el propio buscador permita actualizar (alta, baja o modificacion) sin mucho codigo adicional, seleccionar los datos de una tabla o consulta directa sobre tabla en vez de una vista o consulta sobre varias tablas (este sesgundo caso no permite actualizar en los formularios puesto que el access se 'lia' a la hora de hacerlo automaticamente).
Un saludo,
gracias por la ayuda compañeros.
Espero que mi duda pueda servirle a alguien mas.


text:
Q: Excel VBA HTML errors on second call I've Googled my fingers off and can't seem to find relief. Here's my code that sometimes works but mostly doesn't.  Errors are in the comments.
Sub Junk2()
ThisWorkbook.Worksheets("Sheet1").Activate
Dim oIE As Object
Dim ht As HTMLDocument
Set oIE = CreateObject("InternetExplorer.Application")
oIE.Visible = True
oIE.navigate ("https://www.google.com/search?q=Google.Com")
'This works fine. oIE is good
Do Until oIE.Busy And oIE.readyState = 4
'ERROR Method failed  occurs here oIE is empty
DoEvents
Loop
Set ht = oIE.document 'ERROR 462 OCCURS HERE
End Sub

redpajama_set_name: RedPajamaStackExchange


text:
Q: Installing custom SSL certificate in Node (UNABLE_TO_VERIFY_LEAF_SIGNATURE) I'm trying to access an API, but I'm getting the following error:
{ FetchError: request to https://www.cryptopia.co.nz/api/GetMarkets failed, reason: unable to verify the first certificate
    at ClientRequest.<anonymous> (.../node_modules/node-fetch/index.js:133:11)
    at ClientRequest.emit (events.js:159:13)
    at TLSSocket.socketErrorListener (_http_client.js:389:9)
    at TLSSocket.emit (events.js:159:13)
    at emitErrorNT (internal/streams/destroy.js:64:8)
    at process._tickCallback (internal/process/next_tick.js:152:19)
  name: 'FetchError',
  message: 'request to https://www.cryptopia.co.nz/api/GetMarkets failed, reason: unable to verify the first certificate',
  type: 'system',
  errno: 'UNABLE_TO_VERIFY_LEAF_SIGNATURE',
  code: 'UNABLE_TO_VERIFY_LEAF_SIGNATURE' }

I tried using ssl-root-cas and I tried manually adding a certificate using NODE_EXTRA_CA_CERTS. Neither of these worked.
The API is for a cryptocurrency exchange. I can connect to it using Chrome. I used a few SSL scanners and I got "This server's certificate chain is incomplete." Here's the results for one of the scanners: https://www.ssllabs.com/ssltest/analyze.html?d=www.cryptopia.co.nz
After a bit of Googling, it looks like the error is caused by Node not downloading the intermediate certificate. Chrome downloaded it, so Chrome worked fine. I used Chrome to download the certificate as a .cer file, converted it to a .pem file using OpenSSL, then used Node's NODE_EXTRA_CA_CERTS to load it, but it didn't do anything.
How can I fix this issue?
I cannot make changes to the server. I contacted Cryptopia, but it'll probably take them weeks to respond. And obviously, I'm not going to disable strict SSL since I'm dealing with money.

A: You need to provide the whole CA chain to your application, i.e. both the missing intermediate CA certificate(s) and the root certificate:
options=require('url').parse('https://www.cryptopia.co.nz/api/GetMarkets');
options.ca = require('fs').readFileSync('myca.pem');
require('https').get(options, (r) => {
   console.log(r.headers)
});

myca.pem is here the concatenation of the PEM representation for the certificates of the intermediate "COMODO RSA Extended Validation Secure Server CA" and the root "COMODO RSA Certification Authority". I've provided it as pastebin here.


text:
Q: Java : Alpha Beta Pruning I'm trying to implement a Mini Max & Alpha Beta Pruning algorithm in java, for some reason the Pruning algorithm does not perform a single prune although the algorithm visits 24,911 Nodes.
The GameNode values are initiated to -99 for MaxNodes and 99 for MinNodes aswell as Alpha=-99 \ Beta=99.
The game is called "Nim" and the value is either 1 or -1, win or lose, no score.
Any idea why pruning does not happen ?
Here's the Code for the Pruning :
public static int Prune(GameNode n){

    if(n.getSuccessors()==null)
        return n.GetUtilityValue();

    else if(n.getPlayer().equals(GameNode.Player.MAX)) // A's move
    {
        int value;

        if(n.getFather()!=null){

            if(n.getFather().getAlpha()>n.getAlpha())
                n.setAlpha(n.getFather().getAlpha());//Pass down alpha value

            if(n.getFather().getBeta()<n.getBeta())
                n.setBeta(n.getFather().getBeta());//Pass down beta value

        }

        for(GameNode s : n.getSuccessors())
        {
            if(n.getValue() > n.getBeta()) // if Current value > Beta => then prune this node
            {
                GameNode.prune++;
                break;
            }

                if(s!=null){
                GameNode.counter++;
                value = MiniMax(s);

                if(value>n.getValue()){// Is leaf bigger then current value ? then set value and Alpha value

                    n.setValue(value);
                    if(value > n.getAlpha())
                        n.setAlpha(value);

                    }
                }

        }

    return n.getValue();

    }
    else // B's move
    {
        int value;

        if(n.getFather().getAlpha()>n.getAlpha())
            n.setAlpha(n.getFather().getAlpha());//Pass down alpha value

        if(n.getFather().getBeta()<n.getBeta())
            n.setBeta(n.getFather().getBeta());//Pass down beta value

        for(GameNode s : n.getSuccessors())
        {
            if(n.getValue() < n.getAlpha())// if Current value < Alpha => then prune this node
            {
                GameNode.prune++;
                break;
            }

                if(s!=null) {
                GameNode.counter++;
                value = MiniMax(s);

                if(value<n.getValue()){// Is leaf smaller then current value ? then set value and Beta value

                    n.setValue(value);
                    if(value < n.getBeta())
                        n.setBeta(value);

                    }
                }

        }

    return n.getValue();

    }
}


text:
Q: Explain a pun please I think it's the right place to ask. English is not my native, so while I'm able to understand a majority of puns I come acrossб this one puzzles me:
Here's a link to the image.

A: Omg, I'm such a slowpoke. It turned out to be simple. Got it right after pressing post button.
It's

"pun skill", obviously.

A: I think Pun is a literary term which means playing with words by using Homonyms (It means each of two or more words having the same spelling or pronunciation but different meanings and origins) for example Fare & Fair.


text:
Q: Hartl Rails Tutorial - Having issue with undefined method 'sign_in' during tests So I'm running through the Michael Hartl Rails tutorial and just after creating the edit page (end of Listing 9.3), I get the following errors when I run my tests.  As far as I know, I defined the sign_in method and make it available in my application controller.  Not exactly sure where I went wrong as his tutorial says my tests should pass by this point.  Any help is appreciated.  (Also, please let me know if I need to include anything else)

Failures:
1) User pages edit page
       Failure/Error: sign_in user
       NoMethodError:
         undefined method sign_in' for #<RSpec::Core::ExampleGroup::Nested_2::Nested_4::Nested_1:0x00000108a92118>
       # ./spec/requests/user_pages_spec.rb:60:inblock (3 levels) in '
2) User pages edit page
       Failure/Error: sign_in user
       NoMethodError:
         undefined method sign_in' for #<RSpec::Core::ExampleGroup::Nested_2::Nested_4::Nested_1:0x00000108820560>
       # ./spec/requests/user_pages_spec.rb:60:inblock (3 levels) in '
3) User pages edit page
       Failure/Error: sign_in user
       NoMethodError:
         undefined method sign_in' for #<RSpec::Core::ExampleGroup::Nested_2::Nested_4::Nested_1:0x00000108846be8>
       # ./spec/requests/user_pages_spec.rb:60:inblock (3 levels) in '
4) User pages edit with invalid information
       Failure/Error: sign_in user
       NoMethodError:
         undefined method sign_in' for #<RSpec::Core::ExampleGroup::Nested_2::Nested_4::Nested_2:0x00000103e6cd60>
       # ./spec/requests/user_pages_spec.rb:60:inblock (3 levels) in '
Finished in 0.98841 seconds
  23 examples, 4 failures

Test Document: user_pages_spec.rb
require 'spec_helper'

    describe "User pages" do

    subject { page }
    .
    .
    .

    describe "edit" do
        let(:user) { FactoryGirl.create(:user) }
        before do
            sign_in user
            visit edit_user_path(user)
        end

        describe "page" do
            it { should have_content("Update your profile") }
            it { should have_title("Edit user") }
            it { should have_link('change', href: 'http://gravatar.com/emails') }
        end

        describe "with invalid information" do
            before { click_button "Save changes" }

            it { should have_content('error') }
        end
    end
end

Session Helper: sessions_helper.rb
module SessionsHelper

    def sign_in(user)
        remember_token = User.new_remember_token
        cookies.permanent[:remember_token] = remember_token
        user.update_attribute(:remember_token, User.encrypt(remember_token))
        self.current_user = user
    end

    def signed_in?
        !current_user.nil?
    end

    def current_user=(user)
        @current_user = user
    end

    def current_user
        remember_token = User.encrypt(cookies[:remember_token])
        @current_user ||= User.find_by(remember_token: remember_token)
    end

    def sign_out
        current_user.update_attribute(:remember_token,
                                      User.encrypt(User.new_remember_token))
        cookies.delete(:remember_token)
        self.current_user = nil
    end
end

Application Controller: application_controller.rb
class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  include SessionsHelper
end

A: This is telling you that sign_in isn't a method in the scope of the test so you can't use it in the before block like that. It's a controller method not a test method.
Simplest approach is to create a spec helper method which does the signing in, which you can call in the context of a before block which sets up state for any test requiring a signed in user.
One way to do this would be I have a "user_signs_in" helper which uses capybara to visit signin path, fill in signin in form with correct details, and then follow redirects.
Related stackoverflow q:
How do I simulate a login with RSpec?


text:
Q: Permissionset issue in Apex When I try to look for a permission set associated with a particular user in a controller class,  I am seeing a permissionset with name X00ed0000000TTlfAAG and ID 0PSd0000000XJ15 related to the user. (I searched for this permission set I am unable to find how this is related to the user).

I tried from DEV console and I get nothing back too:
Execute Anonymous: list users_info = [SELECT PermissionSet.id,AssigneeId FROM PermissionSetAssignment WHERE Id =:'0PSd0000000XJ15'];
11:20:49.019 (19656000)|SOQL_EXECUTE_BEGIN|[1]|Aggregations:0|select PermissionSet.id, AssigneeId from PermissionSetAssignment where Id = :tmpVar1
11:20:49.032 (32737000)|SOQL_EXECUTE_END|[1]|Rows:0

I am a sys admin in my org , When I try to copy paste this URL I get insufficient priviledges. I checked the Recyle bin too , nothing there to delete.
Is this a bug , the ID seems to be a valid permset ID.?

A: There are two categories of PermissionSets that are stored in the PermissionSet object:

*

*standalone Permission Sets (have IsOwnedByProfile = false)

*Permission Sets owned by Profiles (have IsOwnedByProfile = true)

Standalone Permission Sets are the ones you are used to; they appear in the list of PermissionSets when you click on 'Permission Sets' from the Setup menu, and you can assign them to users using the PermissionSetAssignment object. You can Create, Edit, and Delete Standalone Permission Sets. They are NOT associated with any particular Profile.
Permission Sets owned by Profiles are the strange ones you are seeing above that start with X00. Under the hood, each Salesforce Profile record has an associated PermissionSet record, which links together all of the Object, Field, App, User, and Setup Entity Access permissions that define the Profile. These do NOT appear in the Setup menu's "Permission Sets" area, because they are represented by their corresponding Profiles. Moreover, they are NOT assigned to users, at least not directly --- the ProfileId field on the user record is the only link that connects you to the associated Profile's corresponding PermissionSet.
In your class above, you should filter out the PermissionSets owned by Profiles by adding IsOwnedByProfile = true to your SOQL WHERE clause:
List<PermissionSet> standalonePermSets = [
   select Id,Name from PermissionSet where IsOwnedByProfile = false
];

A: the PermissionSet IsOwnedByProfile as you can tell from the name (00e is the Profile keyprefix)
set permission set details here:
http://www.salesforce.com/us/developer/docs/api/index_Left.htm#StartTopic=Content/sforce_api_objects_permissionset.htm
your query will never return a value because the PermissionSetAssignment record ids start with 0Pa
[SELECT PermissionSet.id,AssigneeId FROM PermissionSetAssignment WHERE PermissionSet.id =:'0PSd0000000XJ15'
UPDATE
here's the query that solved the question
[select Id, Name[,......] from PermissionSet where Id IN (select Id from PermissionSetAssignment where AssigneeId =: USER_ID_PROVIDED_BY_THE_USER)]


text:
Q: w10 live usb from iso I downloaded an ISO of W10 to upgrade my parents laptop as they have limited download limits.
I also downloaded the media creation tool from the microsoft site but it seems to be a glorified download tool.
I have seen this thread for updating. I'm fine with doing an upgrade and a wipe but how do I create a live boot image onto a usb on a w7 machine?
I would prefer not to use a third party tool to do this. I have access to both an Ubuntu and W7 machine.

A: Once you have the ISO, you can use this tool to create your bootable USB drive.


text:
Q: JTable inside JScrollPane: best height to disable scrollbars I am using the following code to create JTable inside JScrollPane to show column headers
JTable won't show column headers
String[] columnNames = {"header1", "header2", "header2", "header3"};
Object[][] data = new Object[num][4];
//feed values into data using for

JTable chart = new JTable(data, columnNames);
chart.setShowVerticalLines(false);
chart.setEnabled(false);
chart.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

JScrollPane sp = new JScrollPane(chart);
sp.setPreferredSize(new Dimension(width, chart.getHeight() + 5));
panel.add(sp);

The problem is that I need to compute a height for JScrollPane so the whole JTable can be visible and JScrollBars won't appear. How can I do that?
num changes from 2 to 4 and if it is 4 then scroll bars appear.  width is fixed.

A: The basic approach is

*

*JTable is-a Scrollable which unfortunately doesn't do too well in calculating a prefScrollable, so you have to do it yourself

*either use a LayoutManager which lays out all at their pref (f.i. FlowLayout), or implement max in JTable (if you use a resizing but max-respecting manager like BoxLayout)

*JScrollPane is-a validationRoot, so the revalidate must happen on the parent of the scrollPane

Something like:
final JTable table = new JTable(10, 5) {

    @Override
    public Dimension getPreferredScrollableViewportSize() {
        Dimension dim = super.getPreferredScrollableViewportSize();
        // here we return the pref height
        dim.height = getPreferredSize().height;
        return dim;
    }

};
final JComponent content = new JPanel();
content.add(new JScrollPane(table));
Action add = new AbstractAction("add row") {

    @Override
    public void actionPerformed(ActionEvent e) {
        ((DefaultTableModel) table.getModel()).addRow(new Object[]{});
        content.revalidate();
    }
};

A: converting my comments here to the answer, crazy, crazy, really crazy, everything could be complicating the simple things, by assuming that every rows have got the same size, long methods for columnmodel, expanding methods, have to add column renderer/editor, etc..

import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.TableColumn;

public class TablePreferredSize {

    private String[] head = {"One", "Two", "Three", "Four", "Five", "Six"};
    private String[][] data = new String[25][6];
    private JTable table = new JTable(data, head);
    private DefaultTableColumnModel columnModel = new DefaultTableColumnModel();
    private TableColumn column = new TableColumn();
    private int rowHeight = 23;
    private int rowWidth = 0;

    public TablePreferredSize() {
        table.setRowHeight(23);
        table.setIntercellSpacing(new Dimension(1, 1));
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        column = new TableColumn();
        column.setModelIndex(0);
        column.setHeaderValue("One");
        column.setPreferredWidth(250);
        columnModel.addColumn(column);
        rowWidth += column.getPreferredWidth();
        column = new TableColumn();
        column.setModelIndex(1);
        column.setHeaderValue("Two");
        column.setPreferredWidth(120);
        columnModel.addColumn(column);
        rowWidth += column.getPreferredWidth();
        column = new TableColumn();
        column.setModelIndex(2);
        column.setHeaderValue("Three");
        column.setPreferredWidth(80);
        columnModel.addColumn(column);
        rowWidth += column.getPreferredWidth();
        column = new TableColumn();
        column.setModelIndex(3);
        column.setHeaderValue("Four");
        column.setPreferredWidth(120);
        columnModel.addColumn(column);
        column = new TableColumn();
        column.setModelIndex(4);
        column.setHeaderValue("Five");
        column.setPreferredWidth(70);
        columnModel.addColumn(column);
        column = new TableColumn();
        column.setModelIndex(5);
        column.setHeaderValue("Six");
        column.setPreferredWidth(30);
        columnModel.addColumn(column);
        table.setColumnModel(columnModel);
        table.setPreferredScrollableViewportSize(new Dimension(rowWidth, 12 * rowHeight));
        JScrollPane scrollPane = new JScrollPane(table);
        JFrame frame = new JFrame("Table PreferredSize");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(scrollPane);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                TablePreferredSize t = new TablePreferredSize();
            }
        });
    }
}

A: What if you call ?
sp.getColumnHeader().getHeight()


text:
Q: Javascript Rendering Animations on HTML5 DOM from Array. First Run SLOW! Second Run Smooth. How come? I have a question regarding animations via javascript in HTML using DOM. In this case I am using a  with absolute possition and css + jQuery and animate the div.
So when I run through my big array of positions x,y the animation runs very slow. I am running at 100ms (80ms) Interval, but it seems that the rendering is not fast enough and my animations takes longer than 10 seconds...
When re-running the animation it seems that the instructions have been somehow cached ( Rendering ) and my animations runs just perfect.
Then again if I wait for lets say 5 mins, it will be slow again. ( Seems to be low level machine code memory  which has been deleted, because it was not used again? )
I just cant figure out how to let my animation run smooth, if its executed the first time.
I tried fabric.js to render animations... Same problem. At the first run its slow. Second run and following are smooth.
function render_mouse()
 {
     if(play_pos < mousefile_length)
         {
            $('.mouse').remove();
            $("body").append(
            $('

')
            .css('position', 'absolute')
            .css('top', play_mousefile[play_pos+1] + 'px')
            .css('left', play_mousefile[play_pos] + 'px')
            .css('width', mousesize)
            .css('height', mousesize)
            .css('background-image', 'url(images/cursor.png')
                    );
            play_pos = play_pos +2;
            }
    else {
        clearInterval(play_mousetimer);
         }
   }

UPDATED:
 $('#mouse').animate({
                 left: rec_mousefile[play_pos]+"px",
                 top : rec_mousefile[play_pos+1]+"px"
                 },80);

A: The animation would be faster if you didn't do so many operations on the mouse div every time.
Basically, append the mouse to the dom once, with all the CSS needed for the initial render, cache the reference to the appended element, and then manipulate ONLY the css properties necessary for the animation.
By keeping the element in the dom, rather than removing and re-appending each time, you should see a bit of a performance increase. Further, saving a reference to the appended element will prevent you from having to re-query the dom before giving another update.
The animation should always be a bit faster on a second run due to caching, but these optimizations should help the initial run at least a bit.
** edit in response to comment **
You could cache the reference to the mouse div outside the function, or hang it off the render function itself, a la:
var mouseDiv = $('#mouse');
function render_mouse()
{
    if(mousefile_length > play_pos)
                {
                 mouseDiv.animate({
                 left: rec_mousefile[play_pos]+"px",
                 top : rec_mousefile[play_pos+1]+"px"
                 },80);

                 play_pos=play_pos+2;
        }
   else {playtimer.stop();}
}

or
function render_mouse()
{
    // query the first time, and then use the cached version thereafter
    render_mouse.mouse = render_mouse.mouse || $('#mouse');
    if(mousefile_length > play_pos)
                {
                 render_mouse.mouse.animate({
                 left: rec_mousefile[play_pos]+"px",
                 top : rec_mousefile[play_pos+1]+"px"
                 },80);

                 play_pos=play_pos+2;
        }
   else {playtimer.stop();}
}


text:
Q: How to collapse a tree to a fixed size in a balanced way I'm building a web app that shows employee hierarchy in a company. A user can select any employee and a network size , and I need to display the reporting hierarchy for that employee/manager capped to the size. For ex: If an employee has 1000 members under him (direct reports and indirect reports) and if user wants to see a network of size 100 for this user, then I need to collapse the sub trees or not expand under him, so that overall nodes seen in the UI <=100.
This is what I got so far.
public void CollapseTree(Employee employee, int maxSize)
    {
        int size = 0;
        Queue<Employee> queue = new Queue<Employee>();
        queue.Enqueue(employee);
        employee.isVisited = true;
        size++;

        while (queue.Count > 0)
        {
            // Dequeue the employee
            Employee emp = queue.Dequeue();

            foreach (Employee report in emp.Directs)
            {
                // Check if we already visited this node
                if (!report.isVisited)
                {
                    queue.Enqueue(report);
                    report.isVisited = true;
                    size++;

                    // If we reached maximum size, then exit
                    if (size == maxSize)
                    {
                        return;
                    }
                }
            }
        }
    }

    public class Employee
    {
        public HashSet<Employee> Directs { get; set; }

        public string Name { get; set; }

        public int TotalDirects { get; set; }

        public int TotalReports { get; set; }

        public bool isVisited { get; set; }

        public Employee(string name)
        {
            this.Name = name;
            this.Directs = new HashSet<Employee>();
        }
    }
}

What I have done is add a bool isVisited property to the nodes and then traverse the tree in BFS marking them as visited till I reach the max size. This doesn't create balance trees bcoz if for ex: we want a max network size of 10, and an employee E1 has 3 directs D1, D2 and D3. D1, D2 and D3 in turn have 20 reports each, then we expand D1, D2, D3 in first level and then go on to expand D1 and stop after we see 6 of D1's reports. This doesn't work.
I want to expand an employee only if we can expand all his directs w/o reaching the max network limit, else leave his/her subtree as collapsed.
How can I do this?


text:
Q: 35km difference between Google Earth and Map coordinates when manual input I have GPS coordinates. If i enter them manually in the Google Maps Engine, there is a 35 km distance between the points and the same coordinate in Google Earth.
However, if i import the Earth's KMZ into MAPS, they are located correctly but cannot see the coordinate.
Is there some behind the scenes conversion made by Maps?


text:
Q: How to correctly shrink the bullets of itemize How can I shrink the bullets of itemize without change its positioning and the centering versus the items? My code below show that behaviour in fact the two item underneath have a bullet shifted down respect the other two above...
\documentclass{book}

\begin{document}

\begin{itemize}
\item One
\item Two
\end{itemize}

\renewcommand\labelitemi{\tiny$\bullet$}

\begin{itemize}
\item One
\item Two
\end{itemize}

\end{document}

A: You can raise the bullet to your liking. The following does that (to the extreme):

\documentclass{article}
\newlength{\mylen}
\setbox1=\hbox{$\bullet$}\setbox2=\hbox{\tiny$\bullet$}
\setlength{\mylen}{\dimexpr0.5\ht1-0.5\ht2}

\setlength{\parindent}{0pt}% Just for this example
\begin{document}

\begin{minipage}{0.3\linewidth}
\begin{itemize}
\item One
\item Two
\end{itemize}
\end{minipage}\begin{minipage}{0.3\linewidth}
\renewcommand\labelitemi{\tiny$\bullet$}
\begin{itemize}
\item One
\item Two
\end{itemize}
\end{minipage}\begin{minipage}{0.3\linewidth}
\renewcommand\labelitemi{\raisebox{\mylen}{\tiny$\bullet$}}
\begin{itemize}
\item One
\item Two
\end{itemize}
\end{minipage}
\end{document}

On the left is the default $\bullet$. The middle shows \tiny$bullet$ while the last shows a raised \tiny$\bullet$ to exactly the same vertical height as it should be for $\bullet$. However, as mentioned, this is a bit extreme. You could avoid all the length calculations and just use \raisebox{0.25ex}{\tiny$\bullet$} which yields a comparable positioning.
I would also suggest using enumitem which allows you to obtain a similar output using
\begin{itemize}[label=\raisebox{0.25ex}{\tiny$\bullet$}]
  %...
\end{itemize}

A: using \tiny shifts the math axis so the vertical alignment of the bullet, so what you want is not a smaller font but a smaller symbol in the same font set (or to raise the symbol by hand)

\documentclass{book}

\begin{document}

\begin{itemize}
\item One
\item Two
\end{itemize}

\renewcommand\labelitemi{$\cdot$}

\begin{itemize}
\item One
\item Two
\end{itemize}

\renewcommand\labelitemi{{\boldmath$\cdot$}}

\begin{itemize}
\item One
\item Two
\end{itemize}

\end{document}

A: The smaller symbol can be centered around the original math axis via \vcenter:
\documentclass{book}
\begin{document}

\begin{itemize}
\item One
\item Two
\end{itemize}

\renewcommand\labelitemi{$\vcenter{\hbox{\tiny$\bullet$}}$}

\begin{itemize}
\item One
\item Two
\end{itemize}

\end{document}


text:
Q: Dependency Injection for access to current User I'm trying to level up as a developer, and am currently building an app using RxSwift with MVVM. Most of my view models need access to the current user object. In just about every view controller, before I do anything, I have to fetch info for current user from database, and only then, can all other code be executed ( because so much of the logic depends on the state of the User). This also means most code is at least nested one level since fetching user is async. I actually input User into initializer of view model. There must be a better way to persist the current user throughout app. Ive recall reading a bit about dependency injection and how it allows data to be passed along as dependencies to other objects. Is this a scenario where injection could be a viable solution? Im open to other suggestions as well!
Potential solutions I've thought of since time of post

*

*just pass along User through segues and assign to currentUser property in each view controller

*after login, create a shared observable of type Observable<User> in RootViewController, and subscribe to it wherever need be. But i'd still have to put code into subscription block wherever i subscribe.


text:
Q: php FTP login check I have a few ftp servers that I manage for an engineering company. Some of these ftp servers are set-up as data back-up severs through a php interface.
I do maintenance twice a day whereby I stop the ftp daemon (proftpd) on the ftp
server I am doing maintenance on.
However, one of the requirements for the php app to work is to log into each ftp server, download a statistics file (which is mailed to the CEO). Currently if proftpd is stopped on any of the ftp servers, and the php app is running, php hangs (via the browser) while trying to log into the (stopped) ftp server.
I have set the timeout to 90 (default) seconds down to 5 seconds, but the same
thing happens.
How can I prevent php from hanging the browser while php is doing login on the stopped ftp server?
Any pointers?
Thank You
Danny

A: You could do a pre check with fsockopen() and store its connection state in session (so as to not do the check on every reload).
<?php
session_start();

if(!isset($_SESSION['ftp_connectable'])){
    $sock = @fsockopen('ftp.yourserver', 21, $errno, $errstr, 1);//< 1sec timeout
    if ($sock) {
        $_SESSION['ftp_connectable'] = true;
    }else{
        $_SESSION['ftp_connectable'] = false;
    }
    @fclose($sock);
}

if($_SESSION['ftp_connectable'] === true){
    echo 'FTP Server is connectable!';
}else{
    echo 'FTP Server is not connectable!';
}

Then show a notice the server is down based on $_SESSION['ftp_connectable'] you can add a Try Again button that clears the $_SESSION['ftp_connectable'] variable and try's the connection state again.


text:
Q: JodaTime de/serialization across time zones breaks code After deploying to production environemnt my code broke, and after quite a bit of bug chasing, I discovered that JodaTime was handling de/serialization differently in production than in dev environement. Apparently significantly, the production server is on another time zone.
Deserialization and serialization on development:
scala> val input = "2013-09-07T17:11:03.117+03:00"
input: String = 2013-09-07T17:11:03.117+03:00

scala> val thisIsDev = new DateTime(input).toString()
thisIsDev: String = 2013-09-07T17:11:03.117+03:00

scala> input == thisIsDev
res3: Boolean = true

Notice the +03:00 at the end of the ISO8601 string, both initially and after reserialization. Now this is what happens in production, which is on +0 time zone:
scala> val sameInput = "2013-09-07T17:11:03.117+03:00"
sameInput: String = 2013-09-07T17:11:03.117+03:00

scala> val thisIsProd = new DateTime(sameInput).toString()
thisIsProd: String = 2013-09-07T14:11:03.117Z

scala> sameInput == thisIsProduction
res1: Boolean = false

As you can see, +03:00 was absolved and the date string's format changed time zones.
Is this a solved problem? Suggestions?
Edit:
To clarify, the problem with this is that if I serialize, change time zones (go to a different server for example), then deserialize and reserialize, I end up with a different string than what I started with. This is why my production broke, but my tests didn't. Took me a while to figure this out.
Note: These ISO8601 strings are used on a CouchDb server that sorts them alphanumerically, that's why I can't use JodaTime methods for comparison.
Edit 2:
Ideally the answer would suggest how to deserialize an ISO8601 string into DateTime object without loosing the time zone information (on different time zones).
Edit 2.1: I opened a relevant question and got the solution I needed here.

A: Given your edited question, the simplest answer is to force every datetime to be in the same timezone, so for example
scala> new DateTime("2013-09-07T17:11:03.117+03:00").withZone(DateTimeZone.UTC)
res1: org.joda.time.DateTime = 2013-09-07T14:11:03.117Z

scala> new DateTime("2013-09-07T14:11:03.117Z").withZone(DateTimeZone.UTC)
res2: org.joda.time.DateTime = 2013-09-07T14:11:03.117Z

However be aware that in this situation you are losing information i.e. the timezone in which the date resides.  If you are using your date for internal purposes (e.g. finding new items) then this doesn't matter so much, bit if you are sending your data back to users then you need to find another solution.


text:
Q: Figure out name of project in SSIS Is it possible to figure out the name of the project while in SSIS either through a script task, or a variable?
I know how to get the PackageName, and the TaskName, but in this case, I need the ProjectName.

A: This is, admittedly, holy-set-the-house-on-fire-hacktastic, but it works when run via SSDT...  You need a couple of things for this Script Task to work:
1. A variable to access so you can climb to its parent.
2. A reference to Microsoft.SqlServer.DTSRuntimeWrap
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using RuntimeWrapper = Microsoft.SqlServer.Dts.Runtime.Wrapper;

[Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{

    public void Main()
    {
        RuntimeWrapper.IDTSProject100 p = ((RuntimeWrapper.IDTSProject100)((Package)Dts.Variables["User::myVar"].Parent).Project);
        string projectName = GetProjectName(p);

        Dts.TaskResult = (int)ScriptResults.Success;
    }

    private string GetProjectName(RuntimeWrapper.IDTSProject100 proj)
    {
        System.Reflection.PropertyInfo pInfo = proj.GetType().GetProperty("Project",
        System.Reflection.BindingFlags.Public |
        System.Reflection.BindingFlags.NonPublic |
        System.Reflection.BindingFlags.Instance);
        Project p = (Project)pInfo.GetValue(proj, null);

        return p.Name;
    }

    enum ScriptResults
    {
        Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
        Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
    };
}

A: This is a possible solution I tried a while ago.
Just Map  System::VersionGUID to @Version and System::PackageID to @Package as the below query.
DECLARE @Package uniqueidentifier = ?
DECLARE @Version uniqueidentifier = ?
DECLARE @ProjectName nvarchar(100) = (
SELECT proj.name
FROM [catalog].[packages] pkg
INNER JOIN catalog.projects proj ON pkg.project_id = proj.project_id
WHERE package_guid= @Package
AND version_guid = @Version
)

SELECT ISNULL(@ProjectName, 'running from ssdt') as ProjectName;

If the project is deployed in SSIS Catalogs and it is not running from SSDT you will get the project name, otherwise it will return null using the ISNULL function you can put whatever. I hope this can help you someway.
EDIT: version_guid clarification
The version_guid will be different if the project has been deployed in several folders.
Looking for documentation msdn site is very short about version_guid property.

Gets the version GUID generated when the package is first created.
  This field is read-only.

Asumming the creation of the package in the SSISDB will be at deployment the version_guid should be different for every project deployment.
I didn't test in deep but I recreated that scenario: deploy the same project in two different folders.

Note package_guid and version_guid columns.


text:
Q: matlab find() indices of cells for particle, 4-D double I have the following problem.
Considering I have 4 Particles in one area.
The particles travel through this area with a certain velocity. At any given point in time, however, I want to know in which cell such a particle is located.
My sample code looks like this:
x = -10:1:10; % area
y = -10:1:10;

particle = zeros(1,2,1,4); % 4 Particle
particle(1,1,1,1) = 9.5;  % x-position of the first particle
particle(1,2,1,1) = 9.5; %  y-position of the first particle
particle(1,1,1,2) = 7.25;
particle(1,2,1,2) = 8.5;
particle(1,1,1,3) = 6.25;
particle(1,2,1,3) = 7.5;
particle(1,1,1,4) = 5.25;
particle(1,2,1,4) = 6.5;

for xp=1:size(particle,3)
    for yp=1:size(particle,4)
        if particle(1,1,xp,yp) < x(1)
            cell_x = 1;
        elseif particle(1,1,xp,yp) > x(end)
            cell_x = size(x,2);
        else
            cell_x = find(x <= particle(1,1,xp,yp),1,'last');
        end
        if particle(1,2,xp,yp) < y(1)
            cell_y = 1;
        elseif particle(1,2,xp,yp) > y(end)
            cell_y = size(y,2);
        else
            cell_y = find(y <= particle(1,2,xp,yp),1,'last');
        end
    end
end

My code takes too long for a number of 52 x 10 particles. I wanted to omit a for loop by entering yp as an array in particle(1,2,xp,yp), but unfortunately the find() function can't handle arrays. Or am I wrong? Do you have an idea how to make it work much faster so that I have
cell_x = [20,18,17,16]
cell_y = [20,19,18,17]

A: An example code to my comment
x = -10:1:10; % area x

%input data
Numberofdata=4;
saved_x=[9.5 7.25 6.25 5.25];

%conversion from value to index
idx_x1=floor(saved_x)+abs(min(x))+1;
%search for index
for k=1:Numberofdata
idx_x2(k,1)=find(x <=saved_x(k),1,'last');
end

%    Output
[idx_x1' idx_x2]

20    20
18    18
17    17
16    16

I know it is applied to a vector and not a matrix however, you can apply this transformation to any dimension of your Matrix.
In the case you are not changing x in steps of 1 but something like that:
x=min_x:dx:max_x

then the you need to do the following:
idx_x1=floor(saved_x/dx)+abs(min_x/dx)+1;


text:
Q: Installing plugins for Eclipse offline I want to install e(fx)clipse for Eclipse Neon, however eclipse is running on a machine that does not have internet access. Is there a way I can manually download a plugin and install it to eclipse?
To clarify: I have access to the internet on another machine that I can use to transfer files onto the machine with Eclipse.

A: you can download the update-site as a zip by modifying the update site adress last part by site_assembly.zip
example : Install URL becomes,
http://download.eclipse.org/efxclipse/updates-released/2.4.0/pluginName
http://download.eclipse.org/efxclipse/updates-released/2.4.0/pluginName_assembly.zip

change version number if you need an other one
and then use this zip to install your plug-in (Help > Install New Software > Add) as you do but instead of adding an update site url select zip and give the zip you download see this answer part 2 for screenshot :


text:
Q: how to display calculated timedelta as time in python I'm calculating time stored in timewarrior via timew-report python library.
I'm adding up the time, which I'm able to do.  And I'm trying get the total to display in just a number of hours:minutes:seconds, without days.
My script....
#!/usr/bin/python
import sys
import datetime
from datetime import timedelta
from timewreport.parser import TimeWarriorParser #https://github.com/lauft/timew-report

parser = TimeWarriorParser(sys.stdin)

total = datetime.datetime(1, 1, 1, 0, 0)
for interval in parser.get_intervals():
    duration = interval.get_duration()
    print(duration)
    total = total + duration
print(total)

...works properly, returning:
0:01:09
0:06:03
7:00:00
0:12:52
20:00:00
0001-01-02 03:20:04

...but instead of showing 0001-01-02 03:20:04 I'd like it to say 27:20:04.
How do I get it to be formatted like that?
Am I taking the wrong approach by initializing total like datetime.datetime(1, 1, 1, 0, 0)?

A: On the assumption that interval.get_duration is returning a datetime.timedelta object each time, you can just add these to an existing datetime.timedelta object, and then do the arithmetic to convert to HH:MM:SS format at the end.  (You will need to do your own arithmetic because the default string representation for timedelta will use days and HH:MM:SS if the value exceeds 24 hours, which you don't want.)
For example:
import datetime

total = datetime.timedelta(0)
for interval in parser.get_intervals():
    duration = interval.get_duration()
    total += duration

total_secs = int(total.total_seconds())
secs = total_secs % 60
mins = (total_secs // 60) % 60
hours = (total_secs // 3600)

print("{hours}:{mins:02}:{secs:02}".format(hours=hours, mins=mins, secs=secs))

A: For anyone interested in this timewarrior report, here's my final working code.  Put this in scriptname located in timewarrior extensions directory then invoke like timew scriptname tagname to see a timereport showing annotations and total uninvoiced time for a given tag (it can also be used without a tag to display all time entries).
#!/usr/bin/python
import sys
import datetime
from datetime import timedelta
from timewreport.parser import TimeWarriorParser #https://github.com/lauft/timew-report

parser = TimeWarriorParser(sys.stdin)

total = datetime.timedelta()
tags = ''
for interval in parser.get_intervals():
    tags = interval.get_tags()
    # this report shows only un-invoiced time, so we ignore "invoiced" time entries
    if 'invoiced' not in tags:
        # hide 'client' and 'work' tags since they clutter this report
        if 'clients' in tags:
            tags.remove('clients')
        if 'work' in tags:
            tags.remove('work')
        date = interval.get_start()
        duration = interval.get_duration()
        ant = interval.get_annotation()
        sep = ', '
        taglist = sep.join(tags)
        output = str(date.date()) + ' - ' + str(duration) + ' - ' + taglist
        if ant:
            output += ' ||| ' + str(ant)
        print(output)
        total = total + duration

print('----------------')

# We calculate the time out like this manually because we don't want numbers of hours greater than 24 to be presented as days
total_secs = int(total.total_seconds())
secs = total_secs % 60
mins = (total_secs // 60) % 60
hours = (total_secs // 3600)

# for new versions of python 3.6 and up the following could work
# print(f"{hours}:{mins:02}:{secs:02}")
# but for older python this works...
print("total = {hours}:{mins:02}:{secs:02}".format(hours=hours, mins=mins, secs=secs))

A: Pass total seconds to timedelta function from datetime like below:
total = your_total.timestamp()
total_time = datetime.timedelta(seconds=total)
str(total_time)


text:
Q: Ubuntu 16.04 Laptop GTX 1070 Cannot Install from USB I am a beginner with Ubuntu, and I wanted to try to install it alongside Windows 10 on a new laptop with NVidia GTX 1070 (UEFI). I am running into some strange problems, and I was wondering if someone could help.
I created a bootable USB drive with the latest Ubuntu 16.04 image from Canonical, and I am now trying to boot into it with the "Try Ubuntu without installing" option.
As many others, I have a problem booting into the USB. If I use the USB to boot into the "Try Ubuntu without Installing" option without editing anything, I get the following error:

nouveau 0000:01:00.0: fifo: read fault at .... engine 1f ....
nouveau 0000:01:00.0: HUBO ...
nouveau 0000:01:00.0: DRM: failed to create kernel channel, -22

where the dots represent a bunch of numbers and/or stuff that may not be relevant. The screen then turns black, until I force the laptop to shutdown.
After searching the web, I came across several solutions. One of them was to go into the "Try Ubuntu without Installing" option by pressing "e" and adding "nouveau.modeset=0" in the middle of the second line as follows:

quiet splash nouveau.modeset=0 ---

and pressing f10 to boot. I have also tried adding "nouveau.modeset=0" after the "---" signs, or getting rid of "quiet splash", or using "nomodeset=0", to no avail.
Instead of a completely blank screen, I now get the Ubuntu logo with 5 dots getting filled. However, after about 5 seconds, the screen starts flickering between Completely Black and the Ubuntu logo (with all 5 dots completely filled) every second. After about 20 minutes, it still shows the same behavior, and I just decided to shut it down.
I have tried everything that I could find, such as checking if the USB had any problems, going inside the BIOS and disabling secure boot, and using "nomodeset" instead of "nouveau.modeset=0". It seems that it is a problem with the graphics drivers for Nvidia 1070, but I can't even boot into a USB to download them in the first place.
Anyone has any idea on how I could fix this? It seems that most people got it working with the fixes above, but they are just not working for me.
Laptop Specs:

NVIDIA GTX 1070
Intel(R) Core(TM) i7-7700HQ CPU
SMBIOS Version 3.0
BIOS Mode UEFI
Secure Boot State OFF
BIOS Version American Megatrends Inc.

Thank you for your time! Please let me know!
EDIT1: I was able to get the USB to work by adding also:
"acpi=off" in the options.
However, now I can only boot my computer with that option in GRUB, and when I do, I need to force shutdown the computer.
I tried reinstalling all the nvidia drivers and trying different ACPI options. Still cannot fix the problem, or at least find an ACPI option that allows me to shutdown the system...

A: I found out that the problem was that my laptop had the MSHYBRID option enabled by default in the BIOS. It seems that this is enables NVIDIA Optimus, which allows for the use of both GPUs (the Intel integrated and the GTX 1070), but causes a whole lot of problems with the current version of Ubuntu 16.04.
Luckily, my BIOS had the option to change MSHYBRID to DISCREET within the advanced chipset options, which means that now it will only be using the NVIDIA card.
After that everything worked perfectly. I reinstalled Ubuntu (if the USB didn't boot I would just add the "nomodeset" option to the GRUB Ubuntu option, but do not remember if it was necessary). When booting, I no longer have to change any GRUB options (so maybe the "nomodeset" was only necessary to allow for USB booting)
Still not the best option tho, as it doesn't allow me to change back to the integrated GPU when I am not working on intensive applications. There's a few solutions online, but I am happy with what I have. Fighting with a few wifi problems now...
Cheers!

A: Had the same issue after installing ubuntu 19.10. I added the parameter nomodeset to the kernel options and the system boots just fine. Accessing kernel options via key "e" in the GRUB menu on "Advanced Ubuntu Options".


text:
Q: Increment the name attribute of each input but keep radio buttons grouped together after using jQuery clone I have several different types of input that I am cloning using jQuery clone.  Can the number at the beginning of the name attribute be incremented for each input when they are cloned?  I have been trying to figure this out while keeping the Radio button's name's the same after each increment so that they remain grouped together.
Here is a Fiddle to see the  that I am cloning.
http://jsfiddle.net/aHA2d/
Here is my HTML

  <input type="radio" name="1_radio" class="some_vechicle" value="cars" /> Cars
  <input type="radio" name="1_radio" class="some_vechicle" value="bikes" /> Bikes

  <input type="text" name="2_text" class="some_name" value="" /> Model Name

  <input type="text" name="3_text" class="some_year" value="" /> Year

  <textarea name="4_area" rows="3" cols="10"  class="myArea" value=""></textarea>

  <input type="radio" name="5_radio" class="some_color" value="cars" /> Blue
  <input type="radio" name="5_radio" class="some_color" value="bikes" /> Red

  <input type="text" name="6_text" class="some_manufacturer" value="" /> Manufacturer

  <input type="button" class="btnAdd" value="Add" />

Here is the JavaScript that I am using to create the clone
$(document).ready(function() {
    $('.btnAdd').click(function() {
        var c = $('.container:first').clone(true);
        $('.container:last').after(c);
    });
});

Here is an example of the HTML I am trying to create after cloning the div tag once.

  <input type="radio" name="1_radio" class="some_vechicle" value="cars" /> Cars
  <input type="radio" name="1_radio" class="some_vechicle" value="bikes" /> Bikes

  <input type="text" name="2_text" class="some_name" value="" /> Model Name

  <input type="text" name="3_text" class="some_year" value="" /> Year

  <textarea name="4_area" rows="3" cols="10"  class="myArea" value=""></textarea>

  <input type="radio" name="5_radio" class="some_color" value="cars" /> Blue
  <input type="radio" name="5_radio" class="some_color" value="bikes" /> Red

  <input type="text" name="6_text" class="some_manufacturer" value="" /> Manufacturer

  <input type="button" class="btnAdd" value="Add" />

  <input type="radio" name="7_radio" class="some_vechicle" value="cars" /> Cars
  <input type="radio" name="7_radio" class="some_vechicle" value="bikes" /> Bikes

  <input type="text" name="8_text" class="some_name" value="" /> Model Name

  <input type="text" name="9_text" class="some_year" value="" /> Year

  <textarea name="10_area" rows="3" cols="10"  class="myArea" value=""></textarea>

  <input type="radio" name="11_radio" class="some_color" value="cars" /> Blue
  <input type="radio" name="11_radio" class="some_color" value="bikes" /> Red

  <input type="text" name="12_text" class="some_manufacturer" value="" /> Manufacturer

  <input type="button" class="btnAdd" value="Add" />

A: Try this:
$(document).ready(function() {
    $('.btnAdd').click(function() {
        var b = $('.container [name]').length;
        var c = $('.container:first').clone().find('[name]').attr('name', function(i, cur) {
            var n = cur.match(/\d+/g).join('');
            var s = cur.match(/\D+/g).join('');
            return (b + ++n) + s;
        }).end()
        $('.container:last').after(c);
    });
});

http://jsfiddle.net/8E3sC/
As the cloned button is generated dynamically you should delegate the event:
$(document).on('click', '.btnAdd', function() { // ...  })


text:
Q: Wrong user when pushing to heroku? When I'm pushing using git push heroku master the app gets uploaded on a wrong user that I'm not using anymore.
How can I switch to the correct one I'm currently using?

A: I think you could just copy your heroku files to a new folder, then from there heroku create and have control


text:
Q: Mysql Select data and time Well i writing betting script got all data in mysql
Table Games row BetillDate row BetillTime
BetillDate| BetillTime
--------------------
2015-01-21|15:00:00|
2015-01-29|15:00:00|
2015-01-27|15:00:00|

How to Mysql Select Date its today and time its now in one select...
This select not working right ..
SELECT DISTINCT
class.`name`
FROM
class
INNER JOIN market ON class.game_id = market.class_id
WHERE
market.betTillDate > NOW() AND
market.betTillTime > NOW()

or if its not possible how can i do it?
Thanks!

A: I suggest fixing the database by adding a field of DATETIME type and concatenating those two fields into it.
Alter table TABLEX add BetillDateTime DATETIME;
Update TABLEX set BetillDateTime = TIMESTAMP(CONCAT(BetillDate,' ',BetillTime));

Now you have a single field for both date and time, and should fix your code to use only that one, then later drop the other two.
And now all you need in the where clause is:
WHERE market.BetillDateTime > NOW()

A: SELECT DISTINCT
class.`name`
FROM
class
INNER JOIN market ON class.game_id = market.class_id
WHERE
TIMESTAMP(market.betTillDate,market.betTillTime) > NOW()


text:
Q: create nested xml document in c# i am a newbie in XmlDocument.i want to create nested xml document in c#.through some reaserach i fount that XmlDocument are recommended way to create xml if size is small.
i am having some trouble while creating nested tags
code:
XmlDocument doc = new XmlDocument();
XmlDeclaration xDeclare = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
XmlElement root = doc.DocumentElement;
doc.InsertBefore(xDeclare, root);
XmlElement el = (XmlElement)doc.AppendChild(doc.CreateElement("FIXML"));
el.AppendChild(doc.CreateElement("Header")).InnerText = "";
el.AppendChild(doc.CreateElement("RequestHeader")).InnerText = "";
el.AppendChild(doc.CreateElement("MessageKey")).InnerText = "";
el.AppendChild(doc.CreateElement("RequestUUID")).InnerText = "938692349";
Console.WriteLine(doc.OuterXml);

its giving output as
<?xml version="1.0" encoding="UTF-8"?>
<FIXML>
    <Header></Header>
    <RequestHeader></RequestHeader>
    <MessageKey></MessageKey>
    <RequestUUID>938692349</RequestUUID>
</FIXML>

but it should be like
<?xml version="1.0" encoding="UTF-8"?>
<FIXML>
    <Header>
        <RequestHeader>
            <MessageKey>
                <RequestUUID>938692349</RequestUUID>
            </MessageKey>
        </RequestHeader>
    </Header>
</FIXML>

A: Much easier with the newer XML API (XDocument)
var doc =
    new XElement("FIXML",        // you can optionally add an XDocument as outer element
      new XElement ("Header",
          .... // more child elements, values and/or attributes
          new XElement("RequestUUID", 938692349)
      ));

doc.Save(fileName);

A: You are appending all your children to the root element. You probably need something along the lines of:
XmlDocument doc = new XmlDocument();
XmlDeclaration xDeclare = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
XmlElement documentRoot = doc.DocumentElement;
doc.InsertBefore(xDeclare, documentRoot);
XmlElement rootEl = (XmlElement)doc.AppendChild(doc.CreateElement("FIXML"));
XmlElement child1 = (XmlElement)rootEl.AppendChild(doc.CreateElement("Header"));
XmlElement child2 = (XmlElement)child1.AppendChild(doc.CreateElement("RequestHeader"));
...

A: The problem is in your following statement....
el.AppendChild(doc.CreateElement("Header")).InnerText = "";
el.AppendChild(doc.CreateElement("RequestHeader")).InnerText = "";
el.AppendChild(doc.CreateElement("MessageKey")).InnerText = "";
el.AppendChild(doc.CreateElement("RequestUUID")).InnerText = "938692349";

you are appending everything to el. This is why you are getting the wrong out put instead as per your output you should do like below...
XmlElement header = doc.CreateElement("Header")).InnerText = "";
XmlElement RequestHeader = doc.CreateElement("RequestHeader")).InnerText = "";
header.AppendChild(RequestHeader);

This code will help to achieve expected output.

A: If you want to do this dynamically using XElement. Assuming your input is present in some kind of collection or Array. You can try the below method.
List<string> xmlList = new List<string>();
        xmlList.Add("FIXML");
        xmlList.Add("Header");
        xmlList.Add("RequestHeader");
        xmlList.Add("RequestUUID");

        XElement parentNode = null;
        string lastParent = null;

        foreach (var item in xmlList)
        {
            if (parentNode == null)
            {
                parentNode = new XElement(item);
                lastParent = XmlConvert.EncodeName(item);
            }
            else
            {
                var ln = parentNode.DescendantsAndSelf().FirstOrDefault(x => x.Name.LocalName == lastParent);
                ln.Add(new XElement(XmlConvert.EncodeName(item)));
                lastParent = XmlConvert.EncodeName(item);

            }
        }

        Console.WriteLine(parentNode);
        Console.ReadLine();


text:
Q: Java couchdb4j DB connection I'm using couchdb4j to establish a connection with couchDB. It's working fine when im connecting to my local db, this is the code for that:
Session LocalSession= new Session("localhost", 5984);

But i'm trying to get a connection with this site: stockquotetest.cloudant.com but it's not working, can anybody spot the problem?
Session NewSession = new Session("stockquotetest.cloudant.com/", 5984, "user", "pass");

i'm getting this error: INFO: basic authentication scheme selected
I also get this
java.net.UnknownHostException: https
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.security.ssl.SSLSocketImpl.connect(Unknown Source)
at sun.security.ssl.SSLSocketImpl.<init>(Unknown Source)
at sun.security.ssl.SSLSocketFactoryImpl.createSocket(Unknown Source)
at org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory.createSocket(SSLProtocolSocketFactory.java:82)
at org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory.createSocket(SSLProtocolSocketFactory.java:127)
at org.apache.commons.httpclient.HttpConnection.open(HttpConnection.java:707)
at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:387)
at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:323)
at com.fourspaces.couchdb.Session.http(Session.java:364)
at com.fourspaces.couchdb.Session.get(Session.java:325)
at com.fourspaces.couchdb.Session.getDatabaseNames(Session.java:167)
at CouchDBTest.ConnectDB(CouchDBTest.java:41)
at Home$4.actionPerformed(Home.java:166)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

when I run this line of code:
        Session NewSession = new Session("https://user:pass@stockquotetest.cloudant.com/", 80, true);

A: I reproduced this and ran into another issue before I got it working. First, the 6-parameter constructor for Session is what you're after:
public Session(String host, int port, String user, String pass, boolean usesAuth, boolean secure) {

In the example you gave above, this would work:
new Session("stockquotetest.cloudant.com", 443, "user", "pass", true, true);

This is because if you don't set secure to true, the URL will not be constructed with https.

After that was working, the next error was the Database class assuming that update_seq is an int. Cloudant will return a String update_seq, not an integer. I altered the field, response parsing, and getter in the Database class from int to String to make the code work for me.

A: try this one ... make sure you are suing coucjdb4j lib for couchdb connection.
Session studentDbSession = new Session("localhost", 5984);
Database studentCouchDb = studentDbSession.getDatabase("database_name");
Hope this will help you.


text:
Q: Save and retrieve data "by date" using Core Data I'm trying to figure out how to save data "by date" in Core Data using Swift 2.0. In SQL I would want something like
select sum(amount) from X where date = 'date'
To accomplish this, I would need to
1. Record the time/date an item was added
2. Define some line of code that will function like the SQL statement above

I'm not sure how to do either of these. I've looked around online at Apple's documentation but didn't see anything. Can someone point me in the right direction?

A: Use NSExpressionDescription:
NSExpressionDescription *sumAmountDescription = [[NSExpressionDescription alloc] init];
sumAmountDescription.name = @"sumAmount";
sumAmountDescription.expression = [NSExpression expressionForKeyPath:@"@sum.amount"];
sumAmountDescription.expressionResultType = NSInteger32AttributeType;

NSDate *date = <your date>;

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"<entity name here>"];
request.resultType = NSDictionaryResultType;
request.predicate = [NSPredicate predicateWithFormat:@"date == %@", date];
request.propertiesToFetch = @[sumAmountDescription];

NSError *error;
NSArray *result = [context executeFetchRequest:request error:&error];

NSDictionary *values = result.firstObject;
NSNumber *sumAmount = values[@"sumAmount"];


text:
Q: Does back-face culling really improve performance? I was testing face culling via simple cubes drawn on the screen (in theory 3 faces would not be drawn at any time during the rotation). I corrected my vertices so that everything faces the right way and then did glEnable(GL_CULL_FACE). The problem is that I don't see any change in the frame rate I'm getting (that is, cull_face has not appeared to improve performance at all).
Are my conditions simply not ones where culling helps, and if so, what types of situations does culling have a distinct advantage?
About my test case: I simply draw a bunch of cubes dispersed in a large cube. In increased the number of cubes until my frame rate dropped significantly so I could measure performance improvements. I definitely saw improvements when changing how vertices are handled. But I see no change with face culling.

A: Rasterizing polygons, especially with simple shaders / lighting, is so fast on modern GPUs that for small polygons you may not be able to notice the difference.
If you want to see the difference more clearly, try using larger polygons or more complicated shader programs to increase the percent of your time being spent on shading.


text:
Q: is a kendoui typescript definition file available? I'm looking for a typescript definition file for kendo ui? I checked nuget and here https://github.com/borisyankov/DefinitelyTyped with no luck.

A: KendoUI ships with kendo.all.d.ts. A file officially maintained by the kendo team. Read more here : http://docs.kendoui.com/howto/typescript/overview
UPDATE
You might need to locate it in your program files C:\Program Files (x86)\Telerik\Kendo UI for ASP.NET MVC Q1 2013\typescript


text:
Q: Android dalvikvm pausing app making it laggy For some reason, This class is doing too much work and lags which is a major issue in the context of my app. When a user clicks on a location on the map, it should get the address of that location quickly but unfortunately I get logCat dalvikvm paused, memory freed messages and thread doing too much work on application. Not sure why. I close db connections after they are opened.
private class GeocoderTask extends AsyncTask<String, Void, List<Address>> {

    @Override
    protected List<Address> doInBackground(String... locationName) {
        Geocoder geocoder = new Geocoder(getBaseContext());
        List<Address> addresses = null;

        try {
            // get maximum of 3 addresses that match input text
            addresses = geocoder.getFromLocationName(locationName[0], 3);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return addresses;
    }

    @Override
    protected void onPostExecute(List<Address> addresses) {

        if (addresses == null || addresses.size() == 0) {
            Toast.makeText(getApplicationContext(), "No location found",
                    Toast.LENGTH_SHORT).show();
        }

        // clear existing markers on map
        map.clear();

        // add markers on map for each matching address
        for (int i = 0; i < addresses.size(); i++) {
            Address address = (Address) addresses.get(i);

            // creating an instance of geoPoint to display in googleMap
            latLng = new LatLng(address.getLatitude(),
                    address.getLongitude());

            String addressText = String.format(
                    "%s, %s",
                    address.getMaxAddressLineIndex() > 0 ? address
                            .getAddressLine(0) : "", address
                            .getCountryName());

            markerOp = new MarkerOptions();
            markerOp.position(latLng);
            markerOp.title(addressText);

            map.addMarker(markerOp);
            // Locate the first location
            if (i == 0)
                map.animateCamera(CameraUpdateFactory.newLatLng(latLng));

        }

    }

}

/**
 * Locates address using LatLng coordinates
 * @author Aaron
 *
 */
private class ReverseGeocodingTask extends AsyncTask<LatLng, Void, String> {
    Context mContext;

    public ReverseGeocodingTask(Context context) {
        super();
        mContext = context;

    }

    // Finding address using reverse geocoding
    @Override
    protected String doInBackground(LatLng... params) {
        Geocoder geocoder = new Geocoder(mContext);
        double latitude = params[0].latitude;
        double longitude = params[0].longitude;

        List<Address> addresses = null;
        String addressText = "";

        try {
            addresses = geocoder.getFromLocation(latitude, longitude, 3);
            Thread.sleep(500);
        } catch (IOException e) {
            e.printStackTrace();

        } catch (InterruptedException e) {
            e.printStackTrace();
            e.printStackTrace();
        }

        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);

            addressText = String.format(
                    "%s, %s, %s",
                    address.getMaxAddressLineIndex() > 0 ? address
                            .getAddressLine(0) : "", address.getLocality(),
                    address.getCountryName());

        }

        return addressText;
    }

    @Override
    protected void onPostExecute(String addressText) {
        // Setting the title for the marker.
        // This will be displayed on taping the marker
        markerOp.title(addressText);

        // Placing a marker on the touched position
        map.addMarker(markerOp);

    }

}

And Logcat produces
03-04 16:47:38.037: I/Choreographer(16424): Skipped 39 frames!  The application may be doing too much work on its main thread.
03-04 16:47:38.287: W/ActivityThread(16424): ClassLoader.loadClass: The class loader returned by Thread.getContextClassLoader() may fail for processes that host multiple applications. You should explicitly specify a context class loader. For example: Thread.setContextClassLoader(getClass().getClassLoader());
03-04 16:47:38.407: D/dalvikvm(16424): GC_FOR_ALLOC freed 1017K, 14% free 11702K/13476K, paused 48ms, total 49ms
03-04 16:47:38.637: D/dalvikvm(16424): GC_FOR_ALLOC freed 1052K, 12% free 11965K/13476K, paused 25ms, total 25ms
03-04 16:47:38.907: D/dalvikvm(16424): GC_FOR_ALLOC freed 1101K, 9% free 12300K/13476K, paused 25ms, total 25ms
03-04 16:47:39.277: D/dalvikvm(16424): GC_FOR_ALLOC freed 1330K, 10% free 12526K/13892K, paused 28ms, total 28ms
03-04 16:47:39.537: D/dalvikvm(16424): GC_FOR_ALLOC freed 1486K, 11% free 12667K/14192K, paused 36ms, total 36ms
03-04 16:47:39.757: D/dalvikvm(16424): GC_FOR_ALLOC freed 1324K, 10% free 13025K/14384K, paused 32ms, total 32ms
03-04 16:47:40.037: D/dalvikvm(16424): GC_FOR_ALLOC freed 1774K, 13% free 13039K/14852K, paused 52ms, total 55ms
03-04 16:47:40.107: D/dalvikvm(16424): GC_FOR_ALLOC freed 29K, 12% free 13178K/14852K, paused 27ms, total 27ms
03-04 16:47:40.337: D/dalvikvm(16424): GC_FOR_ALLOC freed 906K, 11% free 13477K/15040K, paused 32ms, total 33ms
03-04 16:47:40.417: I/dalvikvm(16424): Jit: resizing JitTable from 4096 to 8192
03-04 16:47:40.607: D/dalvikvm(16424): GC_FOR_ALLOC freed 1098K, 14% free 13388K/15448K, paused 28ms, total 28ms
03-04 16:47:42.687: D/dalvikvm(16424): GC_FOR_ALLOC freed 1307K, 14% free 13429K/15448K, paused 30ms, total 30ms
03-04 16:47:42.687: I/dalvikvm-heap(16424): Grow heap (frag case) to 14.147MB for 1048592-byte allocation
03-04 16:47:42.717: D/dalvikvm(16424): GC_FOR_ALLOC freed 5K, 13% free 14448K/16476K, paused 28ms, total 28ms
03-04 16:47:42.787: D/dalvikvm(16424): GC_FOR_ALLOC freed 1073K, 19% free 13418K/16476K, paused 29ms, total 29ms
03-04 16:47:43.217: D/dalvikvm(16424): GC_FOR_ALLOC freed 1550K, 19% free 13425K/16476K, paused 29ms, total 29ms
03-04 16:47:43.527: D/dalvikvm(16424): GC_FOR_ALLOC freed 1657K, 17% free 13685K/16476K, paused 30ms, total 30ms
03-04 16:47:44.337: D/dalvikvm(16424): GC_FOR_ALLOC freed 1620K, 15% free 14084K/16476K, paused 34ms, total 34ms
03-04 16:47:46.547: D/dalvikvm(16424): GC_FOR_ALLOC freed 2071K, 15% free 14140K/16476K, paused 37ms, total 37ms
03-04 16:47:52.147: D/dalvikvm(16424): GC_FOR_ALLOC freed 2585K, 18% free 13636K/16476K, paused 38ms, total 39ms
03-04 16:47:54.737: D/dalvikvm(16424): GC_FOR_ALLOC freed 1834K, 17% free 13804K/16476K, paused 48ms, total 48ms
03-04 16:48:05.387: D/dalvikvm(16424): GC_FOR_ALLOC freed 2096K, 17% free 13766K/16476K, paused 50ms, total 50ms
03-04 16:48:51.197: D/dalvikvm(16424): GC_FOR_ALLOC freed 2062K, 17% free 13750K/16476K, paused 43ms, total 46ms
03-04 16:48:55.627: D/dalvikvm(16424): GC_FOR_ALLOC freed 2033K, 17% free 13757K/16476K, paused 40ms, total 40ms
03-04 16:49:45.877: D/dalvikvm(16424): GC_FOR_ALLOC freed 2055K, 17% free 13745K/16476K, paused 41ms, total 42ms
03-04 16:50:31.287: D/dalvikvm(16424): GC_FOR_ALLOC freed 2041K, 17% free 13744K/16476K, paused 38ms, total 38ms
03-04 16:51:21.397: D/dalvikvm(16424): GC_FOR_ALLOC freed 2038K, 17% free 13744K/16476K, paused 37ms, total 37ms
03-04 16:52:06.817: D/dalvikvm(16424): GC_FOR_ALLOC freed 2040K, 17% free 13744K/16476K, paused 38ms, total 38ms
03-04 16:52:56.817: D/dalvikvm(16424): GC_FOR_ALLOC freed 2038K, 17% free 13744K/16476K, paused 39ms, total 39ms
03-04 16:53:42.307: D/dalvikvm(16424): GC_FOR_ALLOC freed 2039K, 17% free 13744K/16476K, paused 39ms, total 39ms
03-04 16:54:32.277: D/dalvikvm(16424): GC_FOR_ALLOC freed 2038K, 17% free 13744K/16476K, paused 90ms, total 90ms

A: Keep in mind that onPostExecute gets run on the UI thread and yours seems quite hefty, running through a loop that creates multiple objects. With this in mind I think you should try make your onPostExecute method in your GeocoderTask more lightweight. Consider doing all of the processing in your doInBackground method and then only call map.animateCamera(CameraUpdateFactory.newLatLng(latLng)) in onPostExecute()


text:
Q: Decrypt SSL traffic with the openssl command line tool 8 For my final steps in my script I followed this to obtain the client encryption key to perform the decryption with.
client.random xxd -p crnd.bin
5b689404b500456eef2f1a79ec782eb3eeaac3a8d7c02ae03c8426f363b1
8a33

server.random xxd - srnd.bin
5b6894043bb1289e158b0278ef66dc53c9fa71e75e900739af2657cd4476
ec1e

(echo -n key expansion ; cat srnd.bin crnd.bin) > master_seed.key
xxd -p master_seed.key
6b657920657870616e73696f6e 5b6894043bb1289e158b0278ef66dc53c9
fa71e75e900739af2657cd4476ec1e 5b689404b500456eef2f1a79ec782e
b3eeaac3a8d7c02ae03c8426f363b18a33
note: as before the spaces are not there I added them for clarity

key=$(cat master_secret.hex)
openssl dgst -sha256 -mac hmac -macopt hexkey:$key <master_seed.key -binary >a1
openssl dgst -sha256 -mac hmac -macopt hexkey:$key <a1 -binary >a2
openssl dgst -sha256 -mac hmac -macopt hexkey:$key <a2 -binary >a3
openssl dgst -sha256 -mac hmac -macopt hexkey:$key <a3 -binary >a4
##
cat a1 master_seed.key | openssl dgst -sha256 -mac hmac -macopt hexkey:$key -binary >k1
cat a2 master_seed.key | openssl dgst -sha256 -mac hmac -macopt hexkey:$key -binary >k2
cat a3 master_seed.key | openssl dgst -sha256 -mac hmac -macopt hexkey:$key -binary >k3
cat a4 master_seed.key | openssl dgst -sha256 -mac hmac -macopt hexkey:$key -binary >k4
cat k1 k2 k3 k4 | head -c104 | xxd -p -c104 > k1_k4.hex
truncate -s-1 k1_k4.hex

$cat k1_k4.hex
64666eafe1cbd51f2e2b50799b40f6007c3dc56fe0aac1312d35b5e8b6bf9af6ecf07e1dff27c784
4bf20108190203c4210ff9df6c4eb6e907ddd1f49646ab4b243c80a6ae9b4808ca94445e3d771d3e
06b71ee0deb4c1879986c4c6a4b78bf1c3c1083a6ddce9ff
dd bs=40 count=1 if=k1_k4.hex of=cmackey.hex 2>/dev/null
dd bs=40 count=1 skip=1 if=k1_k4.hex of=smackey.hex 2>/dev/null
dd bs=80 skip=1 if=k1_k4.hex 2>/dev/null | dd bs=64 count=1 of=cenckey.hex 2>/dev/null
dd bs=80 skip=1 if=k1_k4.hex 2>/dev/null | dd bs=64 skip=1 count=1 of=senckey.hex 2>/dev/null

$cat cmackey.hex
64666eafe1cbd51f2e2b50799b40f6007c3dc56f

$cat smackey.hex
e0aac1312d35b5e8b6bf9af6ecf07e1dff27c784

$cat cenckey.hex
4bf20108190203c4210ff9df6c4eb6e907ddd1f49646ab4b243c80a6ae9b4808

$cat senckey.hex
ca94445e3d771d3e06b71ee0deb4c1879986c4c6a4b78bf1c3c1083a6ddce9ff

Encrypted handshake wireshark log
TLSv1.2 Record Layer: Handshake Protocol: Encrypted Handshake Message
    Content Type: Handshake (22)
    Version: TLS 1.2 (0x0303)
    Length: 64
    Handshake Protocol: Encrypted Handshake Message

Handshake Protocol: Encrypted Handshake Message
16030300409a1bf36b786c3b5985617c76afd985d68ffdaf
6d9f1a25ef40159702b5adef402bdb5196ce76a93fd73049
3accf929447fa9c6f1172d6b4035f5578ebfe95c6d

Saved just the encrypted data (last 64 bytes to cenc.dat)
$xxd -p cenc.dat
9a1bf36b786c3b5985617c76afd985d6 8ffdaf6d9f1a25ef40159702b5ad
ef402bdb5196ce76a93fd730493accf929447fa9c6f1172d6b4035f5578e
bfe95c6d
Note: space added again for clarity

$xxd -p iv.bin
9a1bf36b786c3b5985617c76afd985d6

$xxd -p encmsg.bin
8ffdaf6d9f1a25ef40159702b5adef402bdb5196ce76a93fd730493accf9
29447fa9c6f1172d6b4035f5578ebfe95c6d

Last
$cat encmsg.bin | openssl aes-256-cbc -d -K $key -iv $iv -nopad |xxd
gives the same result of bad decrypted data not a finished (14) record

Dave, In comparing my output byte for byte I do not see any problems with my steps. I've gone over this a dozen or more times manually and calling my script and I get the same output which is wrong as you pointed out it does not decrypt to a finish message. Are you spotting anything here?
Thanks


text:
Q: importing opencv moduls I have a simple code as mentioned below:
import cv
from opencv.cv import *
from opencv.highgui import *

img = cv.LoadImage("test.jpg")
cap = cv.CreateCameraCapture(0)
while cv.WaitKey(1) != 10:
    img = cv.QueryFrame(cap)
    cv.ShowImage("cam view", img)
cascade = cv.LoadHaarClassifierCascade('haarcascade_frontalface_alt.xml', cv.Size(1,1))

But I faced to this error:
# AttributeError: 'module' object has no attribute 'LoadImage'

when I change the code to below:
import cv
#from opencv.cv import *
#from opencv.highgui import *

img = cv.LoadImage("test.jpg")
cap = cv.CreateCameraCapture(0)
while cv.WaitKey(1) != 10:
    img = cv.QueryFrame(cap)
    cv.ShowImage("cam view", img)
cascade = cv.LoadHaarClassifierCascade('haarcascade_frontalface_alt.xml', cv.Size(1,1))

now the first error got solve and another error raise.
AttributeError: 'module' object has no attribute 'LoadHaarClassifierCascade'

I need both of the modules but it seems that they have conflict to gether.
Now what I have to do?

A: In OpenCV to load a haar classifier (in the python interface anyway) you just use cv.Load.
import cv
cascade = cv.Load('haarcascade_frontalface_alt.xml')

See the examples here.
Also, the samples that come with the OpenCV source are really good (in OpenCV-2.xx/samples/python).

A: How do you access the stuff you've imported?
# imports the cv module, all stuff contained in it and
# the module itself is now accessible via: cv.classname, cv.functionname
# where classname, functionname is the name of the class/function which
# the cv module provides..
import cv

# imports everything contained in the opencv.cv module
# after this import it is available via it's classname, functionname, etc.
# Attention: without prefix!!
from opencv.cv import *

# @see opencv.cv import
from opencv.highgui import *

@see python modules for more details about modules and imports in python.
If you can provide which classes are contained in which module I could add a specific solution for your problem.


text:
Q: How to handle age restriction in Banner ads on android app I want to implement banner ads in my android app in such a way if the user clicks on it app activity will confirm the user's age and then redirect to the ad URL. I guess that I can use the onAdClicked method, but not sure what to write under it, as I don't know how AdMob generates URLs. Can someone help me with this?
Another thing, do I really need to ask for age confirmation after clicking ads in an app designed for under 18 years or younger?
Thanks in advance.


text:
Q: Зачем нужен std::endl? Здравствуйте. Что значит endl в:
std::cout << "Таблица информации" << std::endl;

A: Важно заметить, что std::endl не только вставляет знак перевода строки. Вы можете вставлять '\n', или '\r\n', но вывод строки произойдет лишь в конце блока (программы) или при сбрасывании буфера.
std::endl принудительно очищает буфер вывода, и строка выводится сразу же вслед за этой командой.

A: Окончание строки. Также может использоваться спец.символ "\n". Например, cout<<"ПРИМЕР!\nТаблица информации"; выведет "ПРИМЕР" на одной строке, а "Таблица информации" на новой строке.
A: ostream& endl ( ostream& os );

Вставляет символ перевода строки в данном случае после текста.
A: СonsoleOUT << [т.е. На нее] "TEXT" << ENDLine


text:
Q: remove saved image while editing the form magento 2 Before explaining what is my issue let me explain what I want to achieve?
I am creating a custom form which takes some information and saves into a custom table.It includes a file upload which is mostly an image.
So what I did?
I successfully uploaded the file to a location on server and saved the information as well as file name on my custom table.Below is what i did to save the file.
<?php

namespace Custom\Addprofile\Controller\Index;

//use Magento\Framework\App\RequestInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Filesystem;
use Magento\MediaStorage\Model\File\UploaderFactory;

class Addprofile extends \Magento\Framework\App\Action\Action {

    protected $resultPageFactory;

     /**
     * @var RequestInterface
     */
    protected $request;
    protected $_objectManager;
    protected $messageManager;

    protected $uploaderFactory;

    protected $fileSystem;

    protected $fileId = 'concession_card';
    protected $allowedExtensions = ['jpg', 'png', 'jpeg'];

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory,
        \Magento\Framework\App\RequestInterface $request,
        \Magento\Framework\ObjectManagerInterface $objectManager,
        \Magento\Framework\Message\ManagerInterface $messageManager,
        UploaderFactory $uploaderFactory,
        Filesystem $fileSystem
    ){
        $this->resultPageFactory = $resultPageFactory;
        parent::__construct($context);
        $this->request = $request;
        $this->_objectManager = $objectManager;
        $this->messageManager = $messageManager;
        $this->uploaderFactory = $uploaderFactory;
        $this->fileSystem = $fileSystem;
    }
    public function execute(){
        $post = $this->request->getPostValue();
        if (isset($_FILES['concession_card']['name']) && $_FILES['concession_card']['name'] != "") {
                    $destinationPath = $this->getDestinationPath();

                    $uploader = $this->uploaderFactory->create(['fileId' => $this->fileId])
                    ->setAllowCreateFolders(true)
                    ->setAllowRenameFiles(true)
                    ->setAllowedExtensions($this->allowedExtensions);

                if (!$fileData = $uploader->save($destinationPath)) {
                    throw new LocalizedException(
                        __('File cannot be saved to path: $1', $destinationPath)
                    );
                }
                $fileName = $fileData['file'];
                $post['concession_card'] = $fileName;
                }
        //var_dump($post);die();
        $model = $this->_objectManager->create('Custom\Addprofile\Model\Profile');
        $model->setData($post);
        $model->save();
        $this->messageManager->addSuccess('Profile has been successfully added.');
    }

    public function getDestinationPath()
    {
        return $this->fileSystem
            ->getDirectoryWrite(DirectoryList::MEDIA)
            ->getAbsolutePath('/customer/profile/');
    }
}

Till here there is no issue.But let us assume if I need to edit the same form.I need to again take the image and replace it with the image. I can do all these using above code but I couldn't remove the previously uploaded image.
The reason I want to delete previously uploaded image is, there is no use of it so removing it would be a good idea.
In short
I want to remove the previously uploaded image and replace it with new one.
So can anyone help me out here. How can I remove the previously uploaded image in magento 2?
Thanks

A: As you are saving this data in your custom table, so let's assume you have primary id in your custom table like(cid)
In your form html you have to set cid in hidden variable like
<input type="hidden" name="cid" value='<?php echo $cid?>' >

Where $cid is primary id , I think you can easily get like other data.
Now in your controller action
$post = $this->request->getPostValue();

So in your controller you will get cid if your form is edit one , so lets first check if its saved one or edit one
$cid=$post['cid'];
if(!empty($cid)){
        $model = $this->_objectManager->create('Custom\Addprofile\Model\Profile')->load($cid);
        $previousImage=$model->getConcessionCard();
        if(file_exists($previousImage)){ // here we are checking Image is exist or not. If its exist then we can remove it
        unlink($previousImage);
        }
}


text:
Q: Decoding hexacode with multiple encodings We have multiple hexadecimals strings which represent a user message. These strings went trough several legacy systems, here is my code to decode those values:
import pandas as pd
import codecs

df = pd.read_csv("testBDD.csv")

for index in df.index:

   hexCode = str(df['hex'][index])
   hexCode = hexCode[2:]
   bytes_array = bytes.fromhex(hexCode)
   Msg = bytes_array.decode(encoding='utf-8',errors='ignore')
   print(Msg)

and I get:

"message": "La maison n'\u00e9tant plus habit\u00e9e depuis le mois d'octobre 2019 (vide de meubles) je souhaite r\u00e9silier l'abonnement ainsi qu'\u00eatre d\u00e9grev\u00e9 de la taxe de collecte et de traitement des eaux us\u00e9es \u00e0 compter du 1er janvier 2020 si possible. J'ai une attestation de la mairie de

We note that we still have some encoded parts, my question would be: how to handle those parts? Is there a way we can decode further this message?
The message is originally in French, my opinion is that special characters such as "é", "à" etc... have been encoded multiple times by the legacy system hence their presence.


text:
Q: Approximating a line integral over a rectifiable path by a line integral over a polygonal path in an infinite dimensional space Let $E$ be a complex Banach algebra and $U\subseteq E$ an open subset. Suppose we are given a continuous map $f:U\to E$ and a rectifiable path $\gamma:[a,b]\to U$.

For each tagged partition $\{a=t_0<t_1<\dots<t_n=b\}$ with tags $\tau_k\in [t_{k-1},t_k]$, we consider the Riemann sum
$$
\sum_{k=1}^n f(\gamma(\tau_k))\mkern2mu[\gamma(t_k)-\gamma(t_{k-1})].
$$
Analagously to the case $E=\mathbb{C}$, we may define the line integral of $f$ along $\gamma$ by the limit of the net of Riemann sums as the mesh of the partitions tends to $0$. (This limit exists, since $f$ is continuous and $\gamma$ is rectifiable.)

I want to prove the following lemma from Conway's book on Complex Analysis (cf. page 65) in this more general setting.

1.19 Lemma. For every $\epsilon>0$ there exists a polygonal path $\Gamma$ in $U$ such that $\Gamma(a)=\gamma(a)$, $\Gamma(b)=\gamma(b)$ and $$\Bigl\lvert\int_{\gamma} f-\int_{\Gamma}f\mkern2mu\Bigr\rvert<\epsilon.$$

By this old paper on Cauchy's theorem in Banach spaces, the above lemma is easily seen to be true (cf. page 77). On the other hand, an essential part of Conway's proof uses the fact that $\mathbb{C}$ is locally compact and hence $f$ uniformly continuous in a neighbourhood of $\gamma([a,b])$, which is not the case anymore if $E$ is infinite dimensional. Do I miss something?

A: The paper you cite does not show exactly this statement: it uses a stronger hypothesis than continuity on $f$ to gaurantee the argument works. One should expect non-uniform continuity to represent a real problem if only continuity is assumed. In the paper you linked, the function $f$ is required to have the analog of continuous differentiability that $$\delta(z,h) = \lim_{\lambda \to 0} \frac{f(z+\lambda h) - f(z)}{\lambda}$$ be continuous in a neighborhood of a point $z_0$ where it is "F-differenntiable." This implies that $f$ is locally Lipschitz, which is enough to give uniform continuity in a neighborhood of $\gamma$ and make the argument work as it does in $\mathbb{C}$.


text:
Q: Division in javascript function subtraction(num1, num2){
    var num3;
    num3 = num1 - num2;
    document.writeln("Difference "+ num3);
    return (num3);
}

function division(num1, num2){
    difference = parseFloat(subtraction());
    var x;
    while(difference > 0){
        difference = num1-num2;
        x = x + 1;
    }
    document.writeln("Quotient" + x);
}

Hi! I wanted to do a division function but the catch is I will not use "/". This is what I got and so far this prints out "undefined" and if I stated x = 0 it will print out "0".

A: I fixed some problems with your code:
function division(num1, num2){
        var difference = num1-num2; // difference is now a local variable

        var x = 0;  // x should be initialized
        while(difference > 0){
            difference = difference-num2; // difference should change, not always be num1-num2
            x = x + 1;
        }
        console.log("Quotient" + x);
        console.log("Remainder" + (difference+num2));
   }

http://jsbin.com/UQIqejo/1/edit
You still have some problems with the algorithm itself, as num2 being less than or equal to 0 will result in an infinite loop, but i expect finding those problems is part of the fun.
EDIT: Smaller version of the same code:
 function divisionSmall(a,b) {
      var x = 0;
      while ((a-=b) > 0) x++;
      console.log('Quotient', x);
      console.log('Remainder', a+b);
    }

EDIT2: Correct division:
function divisionSmall(a,b) {
  var x = 0;
  while ((a-=b) > 0) x++;
  return [x, a+b];
}

function divisionCorrect(a,b) {
  var ans;
  if (b === 0) return ['INF', 0];

  if ((a > 0) && (b > 0)) {
    return divisionSmall(a,b);
  }

  if ((a > 0) && (b < 0)) {
    ans = divisionSmall(a,-b);
    return [-ans[0], ans[1]];
  }

  if ((a < 0) && (b > 0)) {
    ans = divisionSmall(-a,b);
    return [-ans[0] - 1, b-ans[1]];
  }

  if ((a < 0) && (b < 0)) {
    ans = divisionSmall(-a,-b);
    return [ans[0] + 1, -b-ans[1]];
  }
}

console.log(divisionCorrect(11,3));   //  3, 2
console.log(divisionCorrect(11,-3));  // -3, 2
console.log(divisionCorrect(-11,3));  // -4, 1
console.log(divisionCorrect(-11,-3)); //  4, 1

There is still the challenge of doing the logic without ifs :). Good luck.

A: If your doing numbers their is a  simpler way to do this using recursion:
function divide(num,denom) {
  if (num < denom) return 0;
  return (1 + divide(num - denom, denom));
}

For negative numbers you would have to extend this to track if numbers were less than 0. Also, while concise and neat, this breaks down for large numerators and small denominators as the max call stack size will be exceeded.

A: I believe your issue is with your while loop. If the subtraction method returns a negative number it will not compute.
User Math.abs to get absolute value.
   <script>
   function division(num1, num2){
        var difference = Math.abs(parseFloat(subtraction(num1, num2)));
        var x = 0;
        while(difference > 0){
            difference = difference-num2;
            x = x + 1;
        }
        document.writeln("Quotient" + x);
   }
   function subtraction(num1, num2){
      var num3;
      num3 = num1 - num2;
      document.writeln("Difference "+ num3); return (num3);
   }
   </script>


text:
Q: Closed because unicorns not working I bought the "Closed because unicorns" power, but it won't let me close any questions with it. The feature doesn't seem to be working as advertised.
I still have all of the standard "closed" options, and I don't appear to have any new options.

A: The description says

"Closed because unicorns" is the only valid close reason.

(emphasis mine). There are other reasons to choose from, but they're not valid, so the question will be closed because unicorns no matter what you choose.*
*technically, that excludes "belongs on" and "duplicate" closure.

A: It only changes the reasons on question that are already closed to read they were closed because of unicorns.


text:
Q: Windows 7, HP Printer, Windows Update Drivers and A4 page sizes I have a HP Photosmart Printer and I am running Windows 7 Ultimate.
I am in the UK and have Windows Regional Settings configured correctly as UK.
As I really don't want to install HP's bloaty printer drivers I am using the drivers from Windows Update.
With the exception of General Everyday Printing, I am not able to save the Printing Shortcuts to be anything except Letter page size.
General Everyday Printing was set up as A4 by default on installation but I tend to use Fast/Economical Printing a lot more to save ink and time but it always defaults to Letter.
I can change it every time I print but that is getting rather tiresome.
I have tried updating the setting on the printer properties dialog, outside of any application, but it reverts back to Letter.
Is there any way to force the driver to use a different paper size for the Fast/Economical Printing?
It must be possible as General Everyday Printing is set to A4.

A: It might not be what you have asked, but your question just sounds like a hard workaround...
I would suggest to just go through these steps:

*

*Install the drivers, try to do this as bare as possible.

*Remove all software as long as it doesn't break printing.

*Go through Sysinternals Autoruns and disable anything from HP as long as it doesn't break printing.

The latest stable always tend to work better than those that come with Windows Update,
it might contain some bloat but in the end it's just a bit more disk space that shouldn't hurt if you removed the extras.
If you refuse to do this then you could figure out where the setting is saved and prevent reverts.

*

*Use Sysinternals Process Monitor to figure out the files and registry keys being accessed.

*Save the settings of the printer and check in Process Monitor where it saved them.

*Try to understand why it would revert, try to limit the write permissions on the key/file.

Good luck!