text:
Q: jQuery menu with XML To be honest I didn't still used XML with jQuery.
I have a little XML (below):
<folder title="Home">
  <item title="Welcome" />
  <folder title="My Photos">
    <folder title="Holidy">
      <item title="Photo 1" />
      <item title="Photo 2" />
      <item title="Photo 3" />
      <item title="Photo 4" />
      <item title="Photo 5" />
    </folder>
    <folder title="Christmas">
      <item title="Photo 1" />
      <item title="Photo 2" />
      <item title="Photo 3" />
      <item title="Photo 4" />
      <item title="Photo 5" />
      <item title="Photo 6" />
      <item title="Photo 7" />
      <item title="Photo 8" />
    </folder>
    <folder title="Zoo">
      <item title="Photo 1" />
      <item title="Photo 2" />
      <item title="Photo 3" />
      <item title="Photo 4" />
    </folder>
  </folder>
  <folder title="My Videos">
    <item title="Movie 1" />
    <item title="Movie 2" />
    <item title="Movie 3" />
    <item title="Movie 4" />
    <item title="Movie 5" />
    <item title="Movie 6" />
    <item title="Movie 7" />
    <item title="Movie 8" />
  </folder>
  <folder title="My Audio">
    <folder title="Artist 1">
      <folder title="Album 1">
        <item title="Track 1" />
        <item title="Track 2" />
        <item title="Track 3" />
        <item title="Track 4" />
        <item title="Track 5" />
        <item title="Track 6" />
        <item title="Track 7" />
      </folder>
      <folder title="Album 2">
        <item title="Track 1" />
        <item title="Track 2" />
        <item title="Track 3" />
        <item title="Track 4" />
        <item title="Track 5" />
        <item title="Track 6" />
        <item title="Track 7" />
        <item title="Track 8" />
      </folder>
    </folder>
    <folder title="Artist 2">
      <folder title="Album 1">
        <item title="Track 1" />
        <item title="Track 2" />
        <item title="Track 3" />
        <item title="Track 4" />
        <item title="Track 5" />
        <item title="Track 6" />
        <item title="Track 7" />
      </folder>
    </folder>
    <folder title="Podcasts">
      <item title="Track 1" />
      <item title="Track 2" />
      <item title="Track 3" />
      <item title="Track 4" />
      <item title="Track 5" />
      <item title="Track 6" />
      <item title="Track 7" />
      <item title="Track 8" />
    </folder>
  </folder>
</folder>

and I want to populate the html in this order (below):

Sub-directory

File One

File Two

File Three

<spanclass="files">FileFour

<spanclass="files">FileFive

File Six

and I want to navigate inside...
I have understand how to load the XML but I didn't understand how to put inside the span TAG the title text.
And when naveigate into "My Photos"... how to see the child contents...
Thanks in advance for the help.
EDIT:
Here the jQuery (below):
$.ajax({
        type: "GET",
        url: "content.xml",
        dataType: "xml",
        success: function (xml) {
            $(xml).find('Home').children().each(function () {

                var title_text = $(this).attr('title');
                var spanFiles = $('span.files');

                spanFiles
                    .html(title_text)
                    .appendTo('div.entry');

            });
        }
    });

but doesn't work...

A: Just use xml as datatype with the load function, as I think was the road you walked. Then you must loop your top folder. But first, your xml should be like this:
<folders>
    <folder>
        <subfolder>
            <item></item>
        </subfolder>
    </folder>
</folders>

And why are you using title? You should use: Text
Then use each to loop your folders:
$(xml).find('folder').each(function() {
});

And in there you can check if there's a subfolder:
if($(this).find('subfolder').length > 0) { //loop the items from the subfolder }

And to get the text from an item simply:
$(this).find('item').text();

Start with this and you'll be fine and get back here if you're failing. And remember to say what's not working rather than not working...
EDIT: And in your code you're replacing the contents of that span over and over again.
EDIT2: This is how you should append your items:
var text = $(this).find('item').text(),
    $span = $(document.createElement('span')).addClass('files');

$span.html(text).appendTo('div.entry');


text:
Q: Can Cross-Origin Resource Sharing headers authorize X-Domain IFRAME access? Adjusting the height of an IFRAME to match its content page's height can be a real drag when the containing and content pages are not from the same domain.
Do the Cross-Origin Resource Sharing (CORS) headers make it possible for the content page to authorize cross-domain access to its resources and thus allow its containing page to read its height? (or, alternatively, the containing page authorize the content page to announce its height?)
Or is CORS strictly an AJAX thing?

A: CORS doesn't let you do that, but you can use cross-document messaging to send strings between iframes and their parent windows even on different domains, and use that to communicate.
Most browsers support this although Internet Explorer's way differs from the others'.
Assuming what you want is to have the iframe announce to the parent page its desired height, you could put this in your iframe code (not tested):
var message = {
    width: desiredWidth,
    height: desiredHeight
};
window.parent.postMessage(JSON.stringify(message),'*');

And this in your containing page:
function onMessage (event) {
    if (event.source != theIFrameElement.contentWindow) return;
    var message = JSON.parse(event.data);
    var desiredHeight = message.height;
    var desiredWidth = message.width;
}

if (window.attachEvent)
    window.attachEvent('onmessage', onMessage);
else if (window.addEventListener)
    window.addEventListener('message', onMessage, false);

The attachEvent is for IE and addEventListener is for everyone else. You might want to check the target origin for security purposes, but that's the general idea.
EDIT: Browser support for Cross-document messaging (—fsb)

redpajama_set_name: RedPajamaStackExchange


text:
Q: SQLSTATE[HY000]: General error: 1364 Field 'cliente_id' doesn't have a default value Tengo las siguientes relaciones:
 cliente-> factura,
factura->detalle,
materiaPrima->detalle

Como seria la manera mas practica de realizar el ingreso de la factura, ya que no creo que 1 solo boton pueda realizar varias acciones, de tal forma necesito separar en 2 partes la vista, la primera que me tome el dato de la factura y luego del cliente,
El orden que asumo para crear el registro de dicha factura es primero crear la factura tomando el id del cliente, pero me lanza este error, no se si tengo mal la relacion, o no se como enviar ese dato realmente. estos son los modelos y el controlador que se encarga de hacer el guardar, me gustaria si con 1 solo formulario podria realizar el ingreso de todo en esta relacion, pero soy nuevo manejando laravel realmente.
LOS MODELOS
    class Cliente extends Model
{
    protected $table = "Cliente";
    protected $fillable = ['nombre', 'documento','direccion','ciudad','telefono', 'email'];

    public function facturas()
    {
        return $this->hasMany(factura::class);
    }
}

class Factura extends Model
{
    protected $table = "Factura";
    protected $fillable = ['num_factura','fecha'];

    public function materiasPrimas()
    {
        return $this->belongsToMany(MateriaPrima::class, 'detalle','factura_id','materiaPrima_id')->withPivot('precio','cantidad');
    }

    public function cliente()
    {
        return $this->belongsTo(Cliente::class);
    }
}

class MateriaPrima extends Model
{
    protected $table = "MateriaPrima";
    protected $fillable = ['codigo', 'nombre', 'unit','precio_in','cantidad', 'foto'];

public function facturas()
    {
        return $this->belongsToMany(Factura::class, 'detalle','materiaPrima_id','factura_id')->withPivot('precio','cantidad');
    }

AHORA EN ESTE CONTROLLADOR ENVIO LOS DATOS DE TODOS LOS CLIENTES
public function crear()
    {
        can('crear-Factura');
        $cliente = Cliente::orderBy('id')->pluck('nombre', 'id')->toArray();
        return view('Factura.crear',compact('cliente'));
    }

public function guardar(Request $request)
    {
        $factura=Factura::create($request->all());
        $factura->cliente()->sync($request->cliente_id);
        return redirect()->route('Factura')->with('mensaje', 'El registro se creo correctamente');
    }

este es el formulario que esta tomando los datos:

    Numero de Factura

    <input type="text" name="num_factura" id="num_factura" class="form-control" value="{{old('num_factura', $data->num_factura ?? '')}}" required/>

    Fecha

    <input type="date" name="fecha" id="fecha" class="form-control" value="{{old('fecha', $data->fecha ?? '')}}" required/>

     Seleccione Proveedor

    <select name="cliente_id[]" id="cliente_id" class="form-control" multiple required>
@foreach($cliente as $id => $nombre)
  <option
  value="{{$id}}"
  {{is_array(old('cliente_id')) ? (in_array($id, old('cliente_id')) ? 'selected' : '')  : (isset($data) ? ($data->cliente->firstWhere('id', $id) ? 'selected' : '') : '')}}
  >
  {{$nombre}}
  </option>
@endforeach
</select>


text:
Q: React Native : A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade I am getting this error while I am building APK in my rn project.
OS :Windows
RN Version 0.62
I'm using gradle version 6.3, with the build tool version 3.63
> A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
   > AAPT2 aapt2-3.6.3-6040484-windows Daemon #0: Unexpected error during link, attempting to stop daemon.
     This should not happen under normal circumstances, please file an issue if it does.

A: Since the main work of AAPT2 is to change the resources into binary format. I was getting the same error with image as one of the image size is upto 3Mb so AAPT2 was not able to convert that, so after reducing the size, the applicatikn build gets successful.
In your case there must be some linking issue.


text:
Q: How can a program tell if another process is running as a service? I have a Win32 program which I can direct to monitor another Win32 process.
I want to find a way for the monitoring program to determine if the monitored process is running as a Win32 service.
Not all services run as SYSTEM and not all services have services.exe as a direct parent, so I don't regard these obvious techniques as being robust enough.
To be clear, what I'm looking for is a way to write the function:
bool isService(HANDLE aProcessHandle) { ... }

A: You can do this easily using WMI. I realize that you did not specify C#, but the WMI api is available on all platforms in quite similar fashion.
First we need an object shaped like a Win32_Service
public class Win32_Service
{
    public Win32_Service(ManagementBaseObject obj)
    {

        AcceptPause = (bool)(obj["AcceptPause"] ?? false);
        AcceptStop = (bool)(obj["AcceptStop"] ?? false);
        Caption = (string)(obj["Caption"] ?? "");
        CheckPoint = (UInt32)(obj["CheckPoint"] ?? 0);
        CreationClassName = (string)(obj["CreationClassName"] ?? "");
        Description = (string)(obj["Description"] ?? "");
        DesktopInteract = (bool)(obj["DesktopInteract"] ?? false);
        DisplayName = (string)(obj["DisplayName"] ?? "");
        ErrorControl = (string)(obj["ErrorControl"] ?? "");
        ExitCode = (UInt32)(obj["ExitCode"] ?? 0);
        InstallDate = (DateTime)(obj["InstallDate"] ?? DateTime.MinValue);
        Name = (string)(obj["Name"] ?? "");
        PathName = (string)(obj["PathName"] ?? "");
        ProcessId = (UInt32)(obj["ProcessId"] ?? 0);
        ServiceSpecificExitCode = (UInt32)(obj["ServiceSpecificExitCode"] ?? 0);
        ServiceType = (string)(obj["ServiceType"] ?? "");
        Started = (bool)(obj["Started"] ?? false);
        StartMode = (string)(obj["StartMode"] ?? "");
        StartName = (string)(obj["StartName"] ?? "");
        State = (string)(obj["State"] ?? "");
        Status = (string)(obj["Status"] ?? "");
        SystemCreationClassName = (string)(obj["SystemCreationClassName"] ?? "");
        SystemName = (string)(obj["SystemName"] ?? "");
        TagId = (UInt32)(obj["TagId"] ?? 0);
        WaitHint = (UInt32)(obj["WaitHint"] ?? 0);
    }
    bool AcceptPause;
    bool AcceptStop;
    string Caption;
    UInt32 CheckPoint;
    string CreationClassName;
    string Description;
    bool DesktopInteract;
    string DisplayName;
    string ErrorControl;
    UInt32 ExitCode;
    DateTime InstallDate;
    string Name;
    string PathName;
    UInt32 ProcessId;
    UInt32 ServiceSpecificExitCode;
    string ServiceType;
    bool Started;
    string StartMode;
    string StartName;
    string State;
    string Status;
    string SystemCreationClassName;
    string SystemName;
    UInt32 TagId;
    UInt32 WaitHint;
};

Now we query WMI for services. Here I just pull all services. If you have more specific criteria, simply modify the query "Select * from Win32_Service"
var services = new System.Collections.Generic.List<Win32_Service>();
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * from Win32_Service"))
{
    using (ManagementObjectCollection results = searcher.Get())
    {
        foreach (ManagementObject obj in results)
        {
            services.Add(new Win32_Service(obj));
        }
    }
}

Now you can use Linq to query services.
Reference: http://msdn.microsoft.com/en-us/library/ms974579.aspx


text:
Q: Spotfire IF Statement in Custom Expression If(Len([case_SPEC]> 0),[case_SPEC],[case_type])
When I tried above formula I receive an error

'>' as invalid operator

Could someone help in fixing this.

A: Try this
If(Len([THROUGHPUT_SPEC]) > 0,[THROUGHPUT_SPEC],[SUB_TYPE])

You omitted the closing bracket in Len([THROUGHPUT_SPEC])


text:
Q: How to run the SuiteTest many times in testNG file How to run the same set of tests many times use testNG.
I want to run one class with a few test (@Test) many times via Jenkins.
I want to create parametres in Jenkins with number tests to run.
XML file name: SmokeTests
 <?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

 <suite name="testNG_SmokeTesty" >
     <test name="Products Module">
         <classes>
             <class name="Products" />
         </classes>
     </test>
 </suite>

A: Please use invocationCount in @Test, so that while you run the test case through testng XML, that testcase will be executed that many time.
Example:
@Test (invocationCount =3)
public void testMethod(){
}
this "testMethod" will be executed three times.


text:
Q: How to open a cashdrawer in android, using USB connected printer? We have a Point of Sale Application in that, iam using bluetooth, USB printer for receipt printing, through bluetooth option when i eject cashdrawer its working fine and iam using printer.printFormattedTextAndOpenCashBox(text, 40),
When coming to USB printing, got the printing, but unable to open the cashdrawer, i didnt found any methods like above for USB.


text:
Q: UPDATE con PDO en función PHP no funciona Actualización 2: He metido un formulario para acceder directamente a PHP y ver si lo que falla es ese archivo o el JS y efectivamente desde el formulario se hace el UPDATE correctamente. El fallo debería estar en el JS y el Ajax supongo. Por la consola sé que el parámetro que entra en JS es el correcto.
Actualización: He rediseñado el código para que la función llame a JavaScript y esta mande los datos a PHP con Ajax como me ha indicado un usuario, pero sigue sin realizar el UPDATE.
Php donde se genera el Html que llama a la función:
foreach($libros as $libro){
                     echo  "
";
                      echo "
";
                        echo "
";
                          echo "
";
                            echo "";
                          echo "
";
                        echo "
";
                        echo "
";
                          echo "
". $libro['titulo'] ."
";
                            echo "
". $libro['autor']."
";
                        echo "
";
                        echo "
";
                                  echo "
";
                                  echo "";
                                   echo " Leído
";
                                  echo "
";
                                  echo "";
                                    echo "  Enviar
";
                               echo  "

";
                    }

Mi archivo .js:
function marcarLeido(isbn) {

var url = 'marcarLeido.php';
$.ajax({
  url: url,
  method: "POST",
  data: {
    isbn

  },
  success: function (response) {
    console.log("JS ok");

  }
});

}
Php que recibe el POST y realiza el update:
<?php session_start(); ?> <!DOCTYPE html>  <meta charset="utf-8">  <?php
    if (isset($_POST['isbn']) ) {
        include("funcionesPDO.php");

        $isbn = $_POST['isbn'];

        $conex = conectar();

        $stmt = $conex->prepare("UPDATE books SET leido = 1 WHERE isbn = :id AND id_usuario = :par");
        $stmt->bindValue(':par', $_SESSION['usuario_id']);
        $stmt->bindValue(':id', $isbn);
        $stmt->execute();

        desconectar($conex);

    } ?>

Tengo una lista de libros que muestro en el HTML como tarjetas con sus datos más un botón. Quiero que al darle a ese botón cambie el valor de un campo en la base de datos, por lo que le paso a la función el id del libro en concreto. Sin embargo, aunque la conexión es correcta ya que el SELECT funciona y me aparecen los datos que quiero, no se llega a hacer el UPDATE. Lo único que he conseguido sacar en la consola es que cuando hago click al botón se le mete el id del primer libro aunque le de al cuarto, y si le doy de nuevo al cuarto se le mete el id del segundo y así sucesivamente. Pero aún así, no cambia el campo "leido" de esos libros.
Aquí mi php (conecto con PDO):
<?php
                    include("funcionesPDO.php");
                    $conex = conectar();

                    $stmt = $conex->prepare("SELECT * FROM books WHERE leido = 0 AND id_usuario = :is");
                    $stmt->bindValue(':is', $_SESSION['usuario_id']);
                    $stmt->execute();
                    $libros = $stmt->fetchAll(PDO::FETCH_ASSOC);

                    function marcarLeido($idParam){

                      $stmt = $conex->prepare("UPDATE books SET leido = 1 WHERE id = :id AND id_usuario = :par");
                      $stmt->bindValue(':par', $_SESSION['usuario_id']);
                      $stmt->bindValue(':id', $idParam);
                      $stmt->execute();
                      }

                    foreach($libros as $libro){
                     echo  "
";
                      echo "
";
                        echo "
";
                          echo "
";
                            echo "";
                          echo "
";
                        echo "
";
                        echo "
";
                          echo "
". $libro['titulo'] ."
";
                            echo "
". $libro['autor']."
";
                        echo "
";
                        echo "
";
                                  echo "
";
                                  echo "";
                                   echo " Leído
";
                                  echo "
";
                                  echo "";
                                    echo "  Enviar
";
                               echo  "

";
                    }
                    desconectar($conex);
                    ?>

A: Desde el código HTML que generas con los echos, no puedes llamar directamente a una función en PHP, debes llamar a una función Javascript que ejecute un GET o POST con una petición AJAX. Ya desde está función podrás ejecutar el código PHP con el UPDATE.
Lo primero que deberías mirar es sí, la llamada se está haciendo de forma correcta, puedes comprobarlo desde la pestaña Network del navegador. Puedes tener un problema en si la URL es correcta o no. Posteriormente mirar que recibe bien el parámetro GET.


text:
Q: Using Python, select files in a directory that have been modified in the last 60 days I've used glob.glob to list files in a directory.
files = glob.glob("C:/Folder/*.csv")
I want to narrow that list to only list files modified in the last 60 days. I'm not sure how to do that. Stumbled across os.path.getmtime() on google but I can't work out how to apply that to files = glob.glob("C:/Folder/*.csv")
Any ideas?

A: Building on what you already provided and what you already know with os.path.getmtime(), you can use the time.time() function to get the current time. You can substract the modified time from the current time to get the time difference in seconds. I use (60*60*24) to get this to days.
The following code does each of those steps:
import glob
import os
import time

files = glob.glob("C:/Folder/*.csv")
modified_files = list()
current_time = time.time()

for csv_file in files:
    time_delta = current_time - os.path.getmtime(csv_file)
    time_delta_days = time_delta / (60 * 60 * 24)
    if time_delta_days < 60:
        modified_files.append(csv_file)

print(modified_files)

Edit:
A more pythonic way to write this might be:
import glob
import os
import time

def test_modified(filename):
    delta = time.time() - os.path.getmtime(filename)
    delta = delta / (60*60*24)
    if delta < 60:
        return True
    return False

mfiles = [mfile for mfile in glob.glob("C:/Folder/*.csv") if test_modified(mfile)]
print(mfiles)

A: Example with pathlib module:
from pathlib import Path
import time

folder = Path(r"d:\temp")
files = list(folder.glob("*.csv"))
sixty_days_ago = time.time() - (60*60*24) * 60

fresh_files = [f for f in files if f.stat().st_mtime > sixty_days_ago]

for f in fresh_files: print(f)

A: You could use sort to filter the elements in the folder by last modification time:
files = glob.glob(folder_path)

files.sort(key=os.path.getmtime, reverse=True)

In this way you'll get the list of items in the folder ordered by last modification time.


text:
Q: Lion-like scrollbar with jQuery? Does anyone know a jQuery plugin that makes Mac OS X Lion style scrollbars for every browser?

Edit: Here's an image for Windows users

A: Interesting stuff, I wrote a plugin that does just that. It's called LionBars.

A: Antiscroll is probably one of the best plugins available that recreates Mac OS X Lion scrollbars in every browser.
Some of the great features of Antiscroll:

*

*Fades in and out

*Size of container can be dynamically adjusted and scrollbars will adapt

*Supports mousewheels, trackpads, other input devices natively

*Shows scrollbars upon hovering

*Supports IE7+, Firefox 3+, Chrome, Safari, Opera

Demo: http://automattic.github.io/antiscroll/

A: The scrollpane Jquery Plugin is the closest you'll get.
see the lozenge demo.
To make it more like Lion, you could customize it to only show the bar when the track div is hovered over and ensure you use the animateEase function.
Oh and for extra Apple goodness change the direction of the scroll so down is up and up is down :-)

A: The day Lion was released I was very fond of the scrollbar in the OS. The browsers already have a slick default scrollbar but I thought how about them Windows users ;).
It is still under construction but it might help you out: OSX Scroll
Based on tinyscrollbar but I made some adjustments. You can enable autohide (like in the OS). Just have a look at the source files.
Hope it helps.

A: This is an old question.. but maybe someone is still interested in my version:
Source: https://github.com/pixelass/customScrollBar
Example: http://pixelass.github.io/customScrollBar/
This plugin actually replicates the scrollbar more precisely than antiscroll or nicescroll.. etc.
The plugin allows full control over the scrollbars (currently only vertical) and does not require mousewheel.js (as most plugins do)
Removing this dependency was the main goal of my version.
It also listens to the scroll event (as antiscroll does).
The fade-in and hover resize on the scrollbars were missing on all other plugins I found. My version includes an example to show how to achieve this effect.
There are optional (pseudo-)event-listeners "scrollEnded" "clicked" which are fired when the user's scroll has ended or when the scroll-bar-thumb is clicked.
This plugin also allows almost any imaginable style and setting of the scrollbar, as click-arrows (up-down-arrows).
Alpha
This is still alpha (time of posting) but development will continue as time passes.

A: nanoScroller.js is a jQuery plugin that coded with Coffeescript and it makes its job: http://jamesflorentino.github.com/nanoScrollerJS/

A: Use my plugin: scrollYou
It uses a simple approach to make the scroll inside the own element. So you dont have to add more elements to make it roll.

A: jScrollPane plus a little bit of modification would do.
This is a tutorial about it.

A: nanoscroller or nicescroller would be a better option for smooth scrolling.

A: This one has scroll bars like the ones on Mac and is very simple to install. You can basically apply any skin you like with css.


text:
Q: Nodejs ReadFileStream in batches I am trying to read the file in chunks. but it gives me random behavior. Sometimes code run file properly but some times it not reading file data prpperly. my code is as follow:
import * as split2 from 'split2';
import * as through2 from 'through2';
import { createReadStream, createWriteStream, existsSync, mkdirSync, promises,
writeFileSync } from 'fs';

async streamFile(streamType: string, promiseThunk: PromiseThunk, bufferSize = 100) {
return new Promise<unknown>(async (resolve, reject) => {
  const readStream = createReadStream(join(this.basePath, streamType), { encoding: 'utf8' });

  let buffer = [];

  readStream

    .pipe(split2())

    .pipe(
      through2((chunk, enc, callback) => {

        buffer.push(JSON.parse(chunk));
        if (buffer.length < bufferSize) {
          callback();
        } else {

          promiseThunk(buffer)
            .then(() => {
              buffer = [];
              callback();
            })
            .catch((reason: any) => {

              reject(reason);
            });
        }
      }),
    )
    .on('error', async (error) => {

      reject(error);
    })
    .on('finish', async () => {

      if (buffer.length > 0) {
        promiseThunk(buffer)
          .then(() => {

            resolve(true);
          })
          .catch((reason: any) => {

            reject(reason);
          });
      } else {
        resolve(true);
      }
    });
});
}

private async readFileAndProcess(path) {
await this.streamFile(
  path,
  (items: any[]) => {
    if (items.length > 0) {
      return this.processItems(items);
    } else {

      return Promise.resolve();
    }
  },
  2,
);
}

here I am calling streamFile function from  readFileAndProcess function.  and after all, file read sending resolve(). What is wrong here?


text:
Q: Merge vertical lists in Vim Is there a way which allows me to merge lists vertically?
For example, if I have have these two lists:
A E
B F
C G
D H

I would like to end up with the following:
A
E
B
F
C
G
D
H

A: :%s/\v^(\w) /\1\r/g

: ........... command
% ........... whole file
\v .......... very magic (avoid backslashes)
(\w) ........ word character
\1 .......... all patter in parenthesis
\r .......... Carriage Return "Enter"
g ........... globally

A: This is simple, just place the cursor on the column between the lists.
Insert visualblock-mode <C-v>, mark the whole column, hit r to replace it, and then <CR> and you have what you want.

A: You could also do it with an external filter. Mark the relevant lines in visual mode and press !. The following filter does what you want on a POSIX system:
paste -sd' ' | tr ' ' '\n'


text:
Q: enable php on apache2 (using Ubuntu 16.04) I've installed Apache2 on my Ubuntu 16.04.1 System.
I want to install and activate PHP7.0 on my Webserver too.
I installed php and tried to activate the module in Apache2.
When restarting the server, I get:
Job for apache2.service failed because the control process exited with error code. See "systemctl status apache2.service" and "journalctl -xe" for details.

When I execute "systemctl status apache2.service, I get:
-- Unit apache2.service has begun starting up.
Jan 30 12:19:58 tom-450-a141ng apache2[29920]:  * Starting Apache httpd web server apache2
Jan 30 12:19:58 tom-450-a141ng apache2[29920]:  *
Jan 30 12:19:58 tom-450-a141ng apache2[29920]:  * The apache2 configtest failed.
Jan 30 12:19:58 tom-450-a141ng apache2[29920]: Output of config test was:
Jan 30 12:19:58 tom-450-a141ng apache2[29920]: [Mon Jan 30 12:19:58.942761 2017] [:crit] [pid 29935:tid 140264661432192] Apache is running a threaded MPM, but your PHP Module is not compiled to be threadsafe.
Jan 30 12:19:58 tom-450-a141ng apache2[29920]: AH00013: Pre-configuration failed
Jan 30 12:19:58 tom-450-a141ng apache2[29920]: Action 'configtest' failed.
Jan 30 12:19:58 tom-450-a141ng apache2[29920]: The Apache error log may have more information.
Jan 30 12:19:58 tom-450-a141ng systemd[1]: apache2.service: Control process exited, code=exited status=1
Jan 30 12:19:58 tom-450-a141ng systemd[1]: Failed to start LSB: Apache2 web server.
-- Subject: Unit apache2.service has failed
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit apache2.service has failed.
--
-- The result is failed.
Jan 30 12:19:58 tom-450-a141ng systemd[1]: apache2.service: Unit entered failed state.
Jan 30 12:19:58 tom-450-a141ng systemd[1]: apache2.service: Failed with result 'exit-code'.
Jan 30 12:19:58 tom-450-a141ng sudo[29892]: pam_unix(sudo:session): session closed for user root

So I can't start Apache anymore.
I've searched everywhere for a solution.
Plz help

A: As you need to install php7, just remove the currently installed one using-
sudo apt-get purge php*
and then run
sudo apt-get -y install php7.0 libapache2-mod-php7.0
Then you can install other modules as per your need using-
apt-get -y install php7.0-mysql php7.0-curl php7.0-gd php7.0-intl php-pear php-imagick php7.0-imap php7.0-mcrypt php-memcache
systemctl restart apache2

A: The error "[Mon Jan 30 12:19:58.942761 2017] [:crit] [pid 29935:tid 140264661432192] Apache is running a threaded MPM, but your PHP Module is not compiled to be threadsafe." describes that you are using a threaded MPM, that is, event or worker, but your mod_php module depends on a php installation that is not thread-safe, thus you can only use it with prefork.
If you want to use a threaded MPM (which is fine, a good idea too and I recommend it too), you should not use mod_php, you should use php-fpm instead.
You will find how to configure it in the Official Apache Wiki

A: You can do this directly with below command
sudo apt-get install php5 libapache2-mod-php5 php5-mcrypt


text:
Q: Download link to android SDK WITH Eclipse Please help me with the download link to android SDK WITH Eclipse (any version just before android studio release is fine) because i'm having a serious problem with my existing projects in android studio

A: Ahh, just found the link I was looking for.
Links to bundles:

linux 64 bit vm:
http://dl.google.com/android/adt/adt-bundle-linux-x86_64-20140702.zip
linux 32 bit vm:
  http://dl.google.com/android/adt/adt-bundle-linux-x86-20140702.zip
mac:
  http://dl.google.com/android/adt/adt-bundle-mac-x86_64-20140702.zip
win32:
  http://dl.google.com/android/adt/adt-bundle-windows-x86-20140702.zip
win64:
  http://dl.google.com/android/adt/adt-bundle-windows-x86_64-20140702.zip

Source:
https://code.google.com/p/android/issues/detail?id=72584


text:
Q: How to create a parametric equation for a curve using data points After performing a loess regression I have a set of points that predict a curve and I would like to create a parametric function that would fit this curve with a good degree of accuracy, but i'm not sure how. How would I create the equation? The output data below is for an input of 0 to 9.9 intervals are set at 0.1
To be clear, I'm not looking to perform another regression, I want an equation that I can write in the form f(x)=....
1.003883 1.005017 1.006127 1.007213 1.008276 1.009313 1.010323 1.011307 1.012268 1.013208 1.014128 1.015031 1.015917 1.016774 1.017589 1.018366 1.019108 1.019821 1.020507 1.021173 1.021821 1.022456 1.023082 1.023704 1.024326 1.024951 1.025585 1.026216 1.026836 1.027445 1.028046 1.028640 1.029231 1.029819 1.030407 1.030996 1.031590 1.032189 1.032795 1.033411 1.034039 1.034677 1.035314 1.035950 1.036584 1.037219 1.037854 1.038489 1.039126 1.039764 1.040404 1.041046 1.041691 1.042340 1.042992 1.043649 1.044310 1.044975 1.045643 1.046313 1.046986 1.047660 1.048335 1.049011 1.049687 1.050363 1.051040 1.051715 1.052390 1.053063 1.053735 1.054404 1.055071 1.055736 1.056397 1.057054 1.057709 1.058364 1.059017 1.059670 1.060322 1.060972 1.061622 1.062272 1.062920 1.063568 1.064214 1.064860 1.065505 1.066150 1.066793 1.067436 1.068078 1.068719 1.069360 1.069999 1.070638 1.071277 1.071914 1.072551
Plotted Curve

A: This is a problem for a computer.  In Mathematica:
data = {1.003883, 1.005017, 1.006127, 1.007213, 1.008276, 1.009313,
  1.010323, 1.011307, 1.012268, 1.013208, 1.014128, 1.015031,
  1.015917, 1.016774, 1.017589, 1.018366, 1.019108, 1.019821,
  1.020507, 1.021173, 1.021821, 1.022456, 1.023082, 1.023704,
  1.024326, 1.024951, 1.025585, 1.026216, 1.026836, 1.027445,
  1.028046, 1.028640, 1.029231, 1.029819, 1.030407, 1.030996,
  1.031590, 1.032189, 1.032795, 1.033411, 1.034039, 1.034677,
  1.035314, 1.035950, 1.036584, 1.037219, 1.037854, 1.038489,
  1.039126, 1.039764, 1.040404, 1.041046, 1.041691, 1.042340,
  1.042992, 1.043649, 1.044310, 1.044975, 1.045643, 1.046313,
  1.046986, 1.047660, 1.048335, 1.049011, 1.049687, 1.050363,
  1.051040, 1.051715, 1.052390, 1.053063, 1.053735, 1.054404,
  1.055071, 1.055736, 1.056397, 1.057054, 1.057709, 1.058364,
  1.059017, 1.059670, 1.060322, 1.060972, 1.061622, 1.062272,
  1.062920, 1.063568, 1.064214, 1.064860, 1.065505, 1.066150,
  1.066793, 1.067436, 1.068078, 1.068719, 1.069360, 1.069999,
  1.070638, 1.071277, 1.071914, 1.072551};

fitfun = Fit[data, {1, x, x^2, x^3}, x]

$1.0453 + 0.0008714 x - 4.4225 \times 10^{-6} x^2 + 2.59026 \times 10^{-8} x^3$
Show[
 ListPlot[data, PlotStyle -> Red],
 Plot[fitfun, {x, 0, 100}]
 ]

Obviously if you want a better fit, use more terms:
If you use fitfun = Fit[data, {1, x, x^2, x^3, x^4, x^5, x^6}, x]
you get:

A: As David G. Stork answered, fitting data with polynomials is a quite easy task (you can do it using Excel).
You also could use fitting techniques with rational approximations, the model being
$$y=\frac{\sum_{i=0}^n a_ix^i}{1+\sum_{i=1}^m b_ix^i}$$ selecting the degrees $m,n$ of numerator and denominator.
Looking at your data, which look to be quite linear for the large values of $x$, it seems that $m=n-1$ could be a good idea.
So, using $n=3$ (as David G. Stork did in his first example) and $m=2$, the adjusted model is
$$y=\frac{1.00314-0.0503071 x+0.00380452
   x^2+2.59032\times 10^{-6}x^3}{1-0.0510772 x+0.00382303 x^2}$$ for which all parameters are highly significant from a statistical point of view.
Remark : as tehy have been used, your data are supposed to start at $x=1$ and not at $x=0$ with an increment of $1$. So, for the first fit, the first $y$ is predicted to be $1.00540$ and $1.00409$ for the second model (to be compared to the experimental value $1.003883$.


text:
Q: How to point multiple domains to the same website that is not the main website in Odoo 14 I use a multi website setup in Odoo 14 and I want to have multiple domains pointing at one domain that isn't the main domain.
example
I have 2 websites
website A is the main website, everything that isn't part of a known domain should end up here
website B is a secondary website. I want multiple domains to point to this domain. currently in Odoo there is only one field where I can put a domain..
is there any syntax with which I can put multiple domains into the domain field or Is it possible to seperate them f.e. using semicolons or commas?
example image - this is where I need to put multiple domains


text:
Q: Disable / Enable a button in Xcode Hi i'm new with Swift programming.
What im trying to do is Disable my button (signIn) in viewDidLoad and only enable when the textfields have text in them. Here's what i've achieved so far. (not much though!)
class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    signIn.isEnabled = false

    // Do any additional setup after loading the view, typically from a nib.
}

@IBOutlet weak var emailtxt: UITextField!
@IBOutlet weak var passwordtxt: UITextField!
@IBOutlet weak var signIn: UIButton!

I need help to create a function in signIn that keeps button disabled until text fields (emailtxt & passwordtxt) have text in them and then proceed.
Glad if anyone can sort me.
Thanks in advance!

A: First add these for all of your textFields in viewDidLoad():
    emailtxt.addTarget(self, action: #selector(textFieldDidChange(_:)),
                        for: UIControlEvents.editingChanged)
   passwordtxt.addTarget(self, action: #selector(textFieldDidChange(_:)),
                        for: UIControlEvents.editingChanged)

Then use this:
@objc func textFieldDidChange(_ textField: UITextField) {
    self.buttonIsEnabled()
}

func buttonIsEnabled() {
    var buttonIsEnabled = true

    defer {
        self.signIn.isEnabled = buttonIsEnabled
    }

    guard let emailtxt = self.emailtxt.text, !emailtxt.isEmpty  else {
        addButtonIsEnabled = false
        return
    }

    guard let passwordtxt = self. passwordtxt.text, ! passwordtxt.isEmpty  else {
        addButtonIsEnabled = false
        return
    }

}

I use this way in my codes and it works well.
Even you can add more methods for additional checking to buttonIsEnabled, like:
self.checkEmailIsValid(for: emailtxt)

Of course you should handle this method before:
 func checkEmailIsValid(for: String) {
   //...
}

A: Set ViewController as delegate for emailtxt and passwordtxt like this,
override func viewDidLoad() {
    super.viewDidLoad()
    signIn.isEnabled = false

    emailtxt.delegate = self
    passwordtxt.delegate = self

    // Do any additional setup after loading the view, typically from a nib.
}

Conform your ViewController to UITextFieldDelegate and enable/disable as the text input is finished,
extension ViewController: UITextFieldDelegate {

    func textFieldDidEndEditing(_ textField: UITextField) {
        if emailtxt.text?.isEmpty == false && passwordtxt.text?.isEmpty == false {
            signIn.isEnabled = true
        } else {
            signIn.isEnabled = false
        }
    }
}

Here is the fix for your code you shared.
import UIKit
extension UIViewController {

    func hideKeyboardWhenTappedAround() {
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
        tap.cancelsTouchesInView = false
        view.addGestureRecognizer(tap)
    }

    @objc func dismissKeyboard() {
        view.endEditing(true)
    }
}

extension SignInVC: UITextFieldDelegate {

    func textFieldDidEndEditing(_ textField: UITextField) {
        if emailtxt.text?.isEmpty == false && passwordtxt.text?.isEmpty == false {
            signIn.isEnabled = true
        } else {
            signIn.isEnabled = false
        }
    }
}
class SignInVC: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        signIn.isEnabled = false
        emailtxt.delegate = self
        passwordtxt.delegate = self
        self.hideKeyboardWhenTappedAround()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    @IBOutlet weak var emailtxt: UITextField!
    @IBOutlet weak var passwordtxt: UITextField!
    @IBOutlet weak var signIn: UIButton!
}

A: What I would do is create an IBAction from one of your text fields, and set the event to Editing Changed:

The code should look like this:
@IBAction func textFieldEditingDidChange(_ sender: UITextField) {

}

You can then connect that same outlet to both of your text fields by dragging from the outlet to your remaining field. If you've connected both correctly, clicking on the circle to the left of your IBAction should show two text fields:

The action will now be fired every time text changes in either of your fields.
Then, at the top of the file, I'd create a computed property that returns false unless there is something in both fields:
var shouldEnableButton: Bool {
    guard let text1 = textField1.text, let text2 = textField2.text else {
        return false
    }
    return text1.isEmpty && text2.isEmpty ? false : true
}

Finally, we add shouldEnableButton to our IBAction:
@IBAction func textFieldEditingDidChange(_ sender: UITextField) {
    button.isEnabled = shouldEnableButton
}

Important
When you connect your second text field to the outlet, it will incorrectly assign Editing Did End as its event:

Delete this event and click and drag from Editing Changed to your IBAction:

A: Use SwiftValidator
https://github.com/SwiftValidatorCommunity/SwiftValidator
by this, you will set validation of email & password like below
import SwiftValidator

let validator = Validator()

validator.registerField(emailTextField, errorLabel: emailErrorLabel, rules: [RequiredRule(), EmailRule(message: "Invalid email")])

// MARK: - ValidationDelegate
extension ViewController: ValidationDelegate {
    func validationSuccessful() {
        self.loginUser()
    }

    func validationFailed(_ errors:[(Validatable ,ValidationError)]) {
        for (field, error) in errors {

//Handle as per need - show extra label - shake view etc
/*
            if let field = field as? UITextField {
                Utilities.shakeTheView(shakeView: field)
            }
            error.errorLabel?.text = error.errorMessage
            error.errorLabel?.isHidden = false
*/
        }
    }
}


text:
Q: using mobile keyboard search button I have a search textbox in my windows phone 8 app. I dont want to add a search button for this, but rather use the search button on the mobile soft keyboard.
Any code snippets or links providing inputs for the same?.
Also I might deploy this app on android and iOS, so will the logic work for that too, as used for windows phone using c#?.

A: That's not possible, and if you customize the buttons in a way that could be considered not too consistent for user experience, it may not be accepted for certification.
Take a look at this already existing SO post :
Windows Phone 7 Physical Button Overloading

A: You could instead use the "enter key" in your keyboard and that way eliminate the extra icon.
I can supply code sample.
Edit
    If (e.Key == Key.Enter)
    {
       // do search stuff here
    }

This should be put inside the event for textchanged.
Then It would work.
Hope it helped

A: In the keydown eventhandler use
If (e.Key == Key.Enter)
{
   // do search stuff here
}


text:
Q: How to import Math.X in Haskell? I would like to use Math.NumberTheory.Moduli.Class in my Haskell program. It doesn't seem to be included in Prelude since when I try to use it in GHCI
> (3 :: Mod 5) + (4 :: Mod 5)

we have Not in scope: type constructor or class 'Mod'. I also can't seem to import it into GHCI since none of the following work
> import Math.NumberTheory.Moduli.Class
> import Math.NumberTheory.Moduli
> import Math.NumberTheory

because "Could not find module". Finally,
cabal install Math.NumberTheory

seems to have no knowledge of any such package names "Math". Moreover, I can't figure out how to use any of the packages in Math.NumberTheory. How does one import these into a Haskell program?

A:
It doesn't seem to be included in Prelude

Prelude is a module, not a package, and thus can not include other modules.  You probably mean "base".

cabal install Math.NumberTheory seems to have no knowledge of any such package names "Math"

Because that is a module name, not a package which is a collection of modules (roughly).  You need to tell cabal to install the package not the module.
Try instead:
cabal install arithmoi
ghci
import Math.NumberTheory.Moduli.Class

Or as a project-in-a-file:
$ cat so.hs
#!/usr/bin/env cabal
{- cabal:
        build-depends: base, arithmoi
-}

module Main where

import Math.NumberTheory.Moduli.Class

main :: IO ()
main = return ()
$ chmod +x so.hs ; ./so.hs 2>/dev/null 1>&2 ; echo $?
0


text:
Q: fbgraph error code Does anyone know where can I find all the error code and error type for FBGraph? While handling error, I want to check what error FBGraph throws (like: duplicate post error, access token expire error) and take action accordingly. (I a working on Ruby On Rails 3)
I referred the documentation, but it doesn't list out the code and type of all the errors. Where can I find these error codes?
Thanks... :)

A: This has long been a problem with using the Graph API.  There's no documentation anywhere as to all the possible errors that you can receive.  Additionally there are errors that you receive randomly that don't occur when you make the same request again (ie bugs).
A lot of the Graph API seems to have an underlying structure that makes FQL queries.  So, when those FQL based queries throw an error you can find the code here:  http://fbdevwiki.com/wiki/Error_codes#FQL_Errors


text:
Q: Prioritize Intent flag FLAG_ACTIVITY_SINGLE_TOP I have an intent which I would like to start an activity if the activity is not currently on the top of the back stack (i.e. what FLAG_ACTIVITY_SINGLE_TOP achieves). However, if the activity is not on top of the stack I would like to clear the stack and create a new history with the given activity on top.
i.e.
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);

Now, the problem is that this always clears the back stack and places the activity on top, generating a new activity. Effectively FLAG_ACTIVITY_SINGLE_TOP isn't doing anything. Is there a clean way to prioritize the FLAG_ACTIVITY_SINGLE_TOP, so that no new activity is created when the current activity is on top?
Thanks.

A: For anyone wondering, the equivalent of FLAG_ACTIVITY_SINGLE_TOP can simply be defined in the manifest, within the activity tag:
android:launchMode="singleTop"


text:
Q: Can MVC handle regular URL path requests, too? ASP.NET MVC newbie question:
I've set up a MVC site, with a few controllers.  Now my site also has a lot of content files, which are stored in a network of subfolders within my web site, and I need to be able to access them directly, e.g.
http://mydomain.com/Content/Images/Geography/Asia/Japan/TokyoAtNight.jpg

Is there a way to make this a direct pass-through to the content folder, as specified by the path, or do I have to make a Content controller that interprets the rest of the URL and returns the file as some kind of ActionResult?  Bear in mind, of course, that there will be lots of different content types, not just JPEGs.
Thanks for your help!

A: This should work without you doing anything - static files are not processed by the routing engine.

A: You want to look into Routing, and IgnoreRoute specifically. Here are a couple of places to start.
Asp.Net Routing: How do I ignore multiple wildcard routes?
http://www.asp.net/mvc/tutorials/asp-net-mvc-routing-overview-cs

A: Take a look at the @Url.Content() helper method.
Url.Content("~Content/Images/Geography/Asia/Japan/TokyoAtNight.jpg")

A: Yes.
The IRouteHandler and the route registration in your global.asax is your extensibility point for configuring how MVC handles url paths.
However, by default ASP.NET MVC will allow you to access image files directly, without any additional configuration.


text:
Q: Session creation in Google appengine (Python) - simple auth failing We have an application running on Google Appengine (Python 2.7), that uses Simple Auth for login and webapps2 framework.
We are currently only supporting Facebook login.
Problem: At times the facebook login - session creation does not work properly.
This doesn't happen always and it affects only 10 % of the overall traffic on the site.
The callback from Facebook auth to our site comes properly, we are also able to get the Facebook auth token. But the session creation alone fails.
Control flow:
1) User clicks on "Login with Facebook" button on our page
2) User is redirected to Facebook for permissions (if its the first time login)
3) User is redirected back to our site on giving proper authorization in Facebook
4) User auth token is obtained on our site and we fetch user details from Facebook graph API using this token
5) A session is created and the cookie header is set on the response object (Place where issue occurs currently)
6) User is redirected to our dashboard (Dashboard is a screen that is displayed only for logged in users. So if the session/cookie is not created properly, the user will be redirected back to login page).
Remedy already tried:
My first guess was that the session creation is taking more time than the next line of code to execute. This can happen in case the session creation is an async process. So I have included a small delay between the session creation line and the next line. The idea was to given enough time for the uncommitted changes to be committed. Additionally, if the session was not really created at the end of the sleep time, I attempt to recreate the session object.
ok, user = self.auth.store.user_model.create_user(auth_id, **_attrs)
logging.info("creating user : "+str(ok)+" | user" +str(user))
if ok:
    self.auth.set_session(self.auth.store.user_to_dict(user))
    logging.info("User: "+str(self.auth.get_user_by_session()))
    if( self.auth.get_user_by_session() is None ):
        logging.info("Existing user logging in.. But the set session didn't work So wait for sometime")
        time.sleep(0.5)
        if( self.auth.get_user_by_session() is None ):
            logging.info("Existing user logging in.. But the set session didn't work So try again")
            self.auth.set_session(self.auth.store.user_to_dict(user))

But the above-mentioned technique is not working. And so, there is a flaw in my diagnosis.
Requesting help in solving this problem. Please let me know if you need more information on the same.

A: In general, waiting is a poor excuse for synchronization.
In either case you'll want to dig into your auth library to investigate.
You don't want auth.set_session to be async.  Make it synchronous.  That should make life easier.
Find out how get_user_by_session() works.  The problem you describe sounds a lot like eventual consistency behavior.  This may happen if get_user_by_session() issues a datastore query operation, which may return eventually consistent results.  For your get_user_by_session() operation, you want strongly consistent results, so the library should be using a datastore get operation.  In fact, since you just created the user and session, the library should have cached that information and shouldn't need to hit the datastore at all.
The library being python, you should be able to step through the library code and figure out what's going on.


text:
Q: Prove that if $f,g\in F[x]$ are non-constant polynomials, then $f(g)$ is a non-constant polynomial For any polynomials $f$, $g$ $\in F[x]$ (where $F$ is a field), let $f(g)$ denote the polynomial obtained by substituting $g$ for the variable $x$ in $f$.
t,
Suppose $f,g \in F[x]$ are non-constant polynomials (by non-constant, I mean they are of degree $> 0$. So, for example, $f(x) = 5$ is constant, while $g(x) = x^4 + 2x$ is not).  I need to prove that $f(g)$ is also a non-constant polynomial.
It seems like an extremely intuitive thing, and my thoughts are that it should be shown using a degree argument.
I.e., if $f,g$ are non-constant polynomials, then $deg(f)\geq 1$ and $deg(g) \geq 1$. So, I was thinking that I could show that then $deg(f(g))\geq 1$ as well, but I am not sure what the actual mechanics of showing this should be.
Could anybody please let me know how to go about proving this?  Thank you ahead of time for your time and patience!

A: Show that if $f$ is of degree $n$ and if $g$ is of degree $m$, then $f(g)$ is of degree $mn$. To this end, note that if $f = \lambda X^n + \cdots$ and if $g = \mu X^m+\cdots$ then the unique term of degree $mn$ in $f(g)$ is $\lambda \mu^m X^{mn}$, and this is nonzero since $\lambda\mu^m\neq 0$.


text:
Q: CTE generating "multi-part identifier could not be bound" I have a stored procedure that uses a CTE and it has worked fine. I recently moved to a new server however and now it kicks up an error

The multi-part identifier "DOWNLOADS_downloadCategoryLink.categoryID" could not be bound

I can fix this by changing the compatibility level of the database to 80 (SQL Server 2000) but I'd prefer to fix the problem properly - anyone have any ideas where I'm going wrong?
The stored procedure is:
;WITH CTE( CategoryID, ParentCategoryID )
AS
(
    SELECT CategoryID, ParentCategoryID
    FROM DOWNLOADS_fileCategories
    WHERE CategoryID = @startCategoryID

    UNION ALL

    SELECT a.CategoryID, a.ParentCategoryID
    FROM DOWNLOADS_fileCategories a
    INNER JOIN CTE b ON b.CategoryID = a.ParentCategoryID
)
SELECT CategoryID INTO #tempLinkTable FROM CTE

set @query = 'SELECT TOP ' + cast(@noRecordsToReturn as varchar(5)) + ' DOWNLOADS_files.downloadID, DOWNLOADS_files.fileTypeID, DOWNLOADS_files.downloadName, DOWNLOADS_files.downloadFileName, DOWNLOADS_files.sizeInKb, DOWNLOADS_files.dateAdded, DOWNLOADS_files.visible, SYS_fileTypes.fileTypeName, SYS_fileTypes.fileTypeExtension
FROM DOWNLOADS_files LEFT OUTER JOIN SYS_fileTypes ON DOWNLOADS_files.fileTypeID = SYS_fileTypes.fileTypeID INNER JOIN
                  #tempLinkTable ON DOWNLOADS_downloadCategoryLink.categoryID = #tempLinkTable.categoryID
ORDER BY DOWNLOADS_files.dateAdded DESC'

exec(@query)

The tables I have are:
DOWNLOADS_files
downloadID
downloadFileName

DOWNLOADS_fileCategories
categoryID
parentCategoryID
categoryName

DOWNLOADS_fileCategoryLink
categoryID
downloadID

Many thanks!
Bob

A: Your dynamic SQL generates a query like
SELECT TOP 10 DOWNLOADS_files.downloadID,
              DOWNLOADS_files.fileTypeID,
              DOWNLOADS_files.downloadName,
              DOWNLOADS_files.downloadFileName,
              DOWNLOADS_files.sizeInKb,
              DOWNLOADS_files.dateAdded,
              DOWNLOADS_files.visible,
              SYS_fileTypes.fileTypeName,
              SYS_fileTypes.fileTypeExtension
FROM   DOWNLOADS_files
       LEFT OUTER JOIN SYS_fileTypes
         ON DOWNLOADS_files.fileTypeID = SYS_fileTypes.fileTypeID
       INNER JOIN #tempLinkTable
         ON DOWNLOADS_downloadCategoryLink.categoryID = #tempLinkTable.categoryID
ORDER  BY DOWNLOADS_files.dateAdded DESC

The inner join condition
   INNER JOIN #tempLinkTable
     ON DOWNLOADS_downloadCategoryLink.categoryID = #tempLinkTable.categoryID

references a table DOWNLOADS_downloadCategoryLink that doesn't exist in the query. I'm surprised the query ever worked but maybe there was some parser bug that has since been fixed.
To fix this properly we would need to know what table categoryID actually belongs to.
Edit: Maybe
SELECT TOP (@noRecordsToReturn) DOWNLOADS_files.downloadID,
                                DOWNLOADS_files.fileTypeID,
                                DOWNLOADS_files.downloadName,
                                DOWNLOADS_files.downloadFileName,
                                DOWNLOADS_files.sizeInKb,
                                DOWNLOADS_files.dateAdded,
                                DOWNLOADS_files.visible,
                                SYS_fileTypes.fileTypeName,
                                SYS_fileTypes.fileTypeExtension
FROM   DOWNLOADS_files
       INNER JOIN DOWNLOADS_downloadCategoryLink
         ON DOWNLOADS_downloadCategoryLink.downloadID = DOWNLOADS_files.downloadID
       INNER JOIN #tempLinkTable
         ON DOWNLOADS_downloadCategoryLink.categoryID = #tempLinkTable.categoryID
       LEFT OUTER JOIN SYS_fileTypes
         ON DOWNLOADS_files.fileTypeID = SYS_fileTypes.fileTypeID
ORDER  BY DOWNLOADS_files.dateAdded DESC


text:
Q: Magento - CatalogSearch Module overriding not working I want to override the "prepareProductCollection" function of layer in core CatalogSearch module. This is what I have written:
File Path:Company/Module/Model/CatalogSearch/Layer.php
class Company_Module_Model_CatalogSearch_Layer extends Mage_CatalogSearch_Model_Layer
{
public function prepareProductCollection($collection)
{
    parent::prepareProductCollection($collection);

    Mage::getModel('cataloginventory/stock_item')->addCatalogInventoryToProductCollection($collection);

    $collection->getSelect()->order('is_in_stock desc');
    return $this;
}
}

And in the config file:
<config>
    <modules>
        <Company_Module>
            <version>0.0.0.1</version>
        <Company_Module>
    </modules>
    <global>
        <models>
            <module>
               <class>Company_Module_Model</class>
            </module>
            <catalogsearch>
                <rewrite>
                   <layer>Company_Module_Model_CatalogSearch_Layer</layer>
                </rewrite>
            </catalogsearch>
        </models>
    </global>
</config>

I think I might be missing something? Can anyone help me with this?

A: You missed ending the catalogsearch tag in config.xml

A: add require_once(app/Mage/CatalogSearch/Model/Layer) at the top

A: I've tried to do the exact same thing.
I followed multiple tutorials and tried several things. In the end I ended up having 503 errors all the time (without any maintanance.flag file - other shop sites worked well).
But I managed to fix that. I will show you what I have now and also what the reason for the 503 was, in case someone stumbles across that problem:
I've named the Module Company/CatalogSearch and it is made up of three files:
app/code/local/Company/CatalogSearch/Model/Layer.php :
<?php
class Company_CatalogSearch_Model_Layer extends Mage_CatalogSearch_Model_Layer {

    public function prepareProductCollection($collection) {

        parent::prepareProductCollection($collection);

        // YOUR CODE HERE

        return $this;
    }
}

app/code/local/Company/CatalogSearch/etc/config.xml :
<?xml version="1.0"?>
<config>
    <modules>
        <Company_CatalogSearch>
            <version>0.1</version>
        </Company_CatalogSearch>
    </modules>
    <global>
        <models>
            <catalogsearch>
                <rewrite>
                    <layer>Company_CatalogSearch_Model_Layer</layer>
                </rewrite>
            </catalogsearch>
        </models>
    </global>
</config>

app/etc/modules/Company_CatalogSearch.xml :
<?xml version="1.0"?>
<config>
    <modules>
        <Company_CatalogSearch>
            <active>true</active>
            <codePool>local</codePool>
        </Company_CatalogSearch>
    </modules>
</config>

And that's all.
To the 503 problem:
In the file app/code/local/Company/CatalogSearch/etc/config.xml I had
<rewrite>
    <layer>
        Company_CatalogSearch_Model_Layer
    </layer>
</rewrite>

instead of
<rewrite>
    <layer>Company_CatalogSearch_Model_Layer</layer>
</rewrite>

Hope that helps!


text:
Q: convert date to epoch using a format string I need my bash script to convert a string to seconds (since the epoch) using a FORMAT string, where both the date and format strings are given by the user. It seems it can be done in the BSD version of date like this,
date -j -f "$format" "$date" +%s //format can be anything, e.g. "%Y %m %d %H:%M"

but I use Ubuntu. Is there any way to accomplish this using bash/awk/perl etc?

A: date -d "$date" +%s

For example,
$ date='2016 05 03 16:00' date -d "$date" +%s
1462248000

There's no way to specify the format of the date passed to -d, but there's no reason to do so. date uses heuristics which handle your date format just fine.
If the format is not handled by the heuristics, you won't be able to use GNU's date.

A: I suggest you use Perl, with its core Time::Piece module
$ perl -MTime::Piece -E 'say Time::Piece->strptime(@ARGV)->epoch' 'Dec 25 2015 06:05:04' '%b %d %Y %H:%M:%S'
1451023504

A: You can use perl to convert time to EPOCH
but you need to change some variables if your format changes
perl -MTime::Local -e '%mon=(Jan=>0,Feb=>1,Mar=>2,Apr=>3,May=>4,Jun=>5,Jul=>6,Aug=>7,Sep=>8,Oct=>9,Nov=>10,Dec=>11);$date=join("\ ",@ARGV);print timelocal($5,$4,$3,$2,$mon{$1},$6),"\n" if($date=~/\w{3}\s+(\S{3})\s+(\d+)\s(\d+):(\d+):(\d+)\s(\d+)/)' Sun Sep 25 10:29:10 2022

A: For date supporting %s:
date +%s

For Perl:
perl -e 'print time(),"\n"'


text:
Q: Is there a way to shorten jQuery code, especially when using show and hide functions? I'm trying to find jQuery functions that might make this jQuery code shorter. I tried looking at toggle, but i couldn't see how it could work. I'm just trying to learn jQuery's best practices at the moment. Thank you.
$(".play").click(function (e) {
  e.preventDefault();
  video.ref.playVideo();
  $(".play").hide();
  $(".pause").show();
});
$(".pause").click(function (e) {
  e.preventDefault();
  video.ref.pauseVideo();
  $.(".pause").hide();
  $(".play").show();
});

A: I can't think of how to make it shorter, but it can perform better by caching the two main jQuery objects and referring to the current object $(this) when possible.
var $_play = $('#play'),
    $_pause = $('#pause');
$_play.click(function(e){
    video.ref.playVideo();
    $(this).hide();
    $_pause.show();
    e.preventDefault();
});
$_pause.click(function(e){
    video.ref.pauseVideo();
    $(this).hide();
    $_play.show();
    e.preventDefault();
});

A: The code is short already, but you could combine the 2 events if you really wanted to.
var $playPause = $(".play,.pause").click(function(e){
    var func = $(this).hasClass('play') ? 'play' : 'pause';
    e.preventDefault();
    video.ref[func+'Video']();
    $playPause.toggle();
});


text:
Q: Octahedron to tetrahedron ratio in generalized polyominoes in the tetrahedral-octahedral honeycomb Drake Thomas and I have proposed a sequence A343909 to the On-Line Encyclopedia of Integer Sequences (OEIS), which counts "generalized polyforms": generalizations of free polyominoes (Tetris pieces), but with cells in the tetrahedral-octahedral honeycomb.
That is, take a subset of tetrahedral or octahedral cells in the honeycomb such that each cell is connected to every other cell by a chain of face-to-face connections. Consider two subsets to be the same if there is a rigid transformation that takes one to the other.
The ($0$-indexed) sequence begins:
 1, 2, 1, 4, 9, 44, 195, 1186, 7385, 49444, 337504, ...
Which is to say that there is

*

*1 polyform with 0 cells (the empty polyform),

*2 polyforms with 1 cell (the tetrahedron and the octahedron),

*1 polyform with 2 cells (the tetrahedron attached to the octahedron by a face),

*4 polyforms with 3 cells, and

*9 with 4 cells, as shown below:

Tetrahedra/octahedra breakdown
It's hard to compute large values of this sequence, but here is the breakdown of the number of octahedra and tetrahedra in $8$- and $9$-cell polyforms.:
$n = 8 \\ A343909(8) = 7385$

*

*1 octahedron, 7 tetrahedra: $1$

*2 octahedra,  6 tetrahedra: $285$

*3 octahedra,  5 tetrahedra: $3223$

*4 octahedra,  4 tetrahedra: $3440$

*5 octahedra,  3 tetrahedra: $432$

*6 octahedra,  2 tetrahedra: $4$
$n = 9 \\ A343909(9) = 49444$

*

*1 octahedron, 8 tetrahedra: $1$

*2 octahedra,  7 tetrahedra: $356$

*3 octahedra,  6 tetrahedra: $10853$

*4 octahedra,  5 tetrahedra: $27632$

*5 octahedra,  4 tetrahedra: $10141$

*6 octahedra,  3 tetrahedra: $459$

*7 octahedra,  2 tetrahedra: $2$
Questions
In these (and smaller) cases, the greatest number of polyforms occurs when the number of octahedra is $\lfloor (n-1)/2 \rfloor$. Based on the fact that the honeycomb is composed of alternating regular octahedra and tetrahedra in a ratio of 1:2, I would have expected the mode to be closer to one-third.

*

*In the limit, is the mode asymptotic to $n/2$, $n/3$, or something else?

*For a fixed number of cells, does the number of polyforms with $m$ octahedra have a known distribution in $m$?

*What is the minimum number of octahedra than an $n$-cell polyform can have? The maximum number?

A: I will take a stab at the maximum number of octahedra: A sequence of octahedron-maximal polyoctets is obtained by starting with the unique 4-oct-1-tet pentoctet, and adding further 3-oct-1-tet tetroctet modules by their sole tetrahedral face in a zig-zag fashion along an axis which can extend indefinitely without any modules overlapping. Each member of this sequence is maximal because all tetrahedron faces are used and if there were any fewer tetrahedra, there would not be enough tetrahedron faces to attach all of the octahedra. Counting, the $k$th polyoctet in this sequence has $3k+1$ octahedra and $k$ tetrahedra, for $4k+1$ cells. For numbers of cells between 5,9,13, etc., the maximum is achieved simply by removing the proper number of "leaf" octahedra, since again if there were any fewer tetrahedra, it would be impossible to connect all octahedra.
Putting this all together, if there are $c$ cells, then at most $$c-\left\lfloor\frac{c-1}4\right\rfloor$$ of them are octahedra (the rest necessarily being tetrahedra).
I suspect the minimum number of octahedra should be accessible as well, although it's a bit trickier because of the fact that connecting an octahedron to one of the tetrahedra on a fully-surrounded octahedron actually connects to two of them simultaneously. If I get the details worked out I will update this answer.


text:
Q: Delete parallel lines to calculate total network length I have problem with parallel lines in QGIS. I want to delete lines, which have common courses with others (expample of lines is in the picture below) .
Context: The lines are network-lines and to calculate the total lenght of the network's roads/ways I need to be able to ignore the duplicate lines.


text:
Q: How to diff a single directory in mercurial I have two local mercurial repos, let's call them product and skunkworks.  Skunkworks is a clone of product and has a lot of recent commit activity against it.  I need to be able to package up the diffs from one small part of the directory tree and pull those out as a patch file.
I've got the following layout on disk:
c:/dev/product
c:/dev/skunkworks

The area of diffs I want to package up is from c:/dev/skunkworks/buildstuff.  This directory exists in the product repo.  I don't want to expose everyone else to the changes in the rest of skunkworks just yet, but need to be able to share my new build goodness.
I've tried a number of different parameter settings and combinations of the 'hg diff' command but am obviously doing something wrong.  Any pointers or suggestions would be greatly appreciated.
Thanks!

A: This can be done pretty easily, but first lemme suggest that the next time you're doing to independent bits of work (the build work and the rest of skunkworks) you do them in separate heads -- then you can push the buildwork directly to product using hg push w/o moving skunkworks over there too.  That pattern would look like:
hg clone product skunkworks
cd skunkworks
... build hacking ...
hg commit
... build hacking ...
hg commit
hg update REVNUMBER # where revnumber is the last revision that exists in product
... skunkworks hacking ...
hg commit  # at this point you'll see (+1 heads)
... more skunkworks hacking ...
hg commit

at that point your skunkworks clone will have two heads, one with build work and one with skunkworks.  You can switch back and forth while working, alternating between build and sunkworks while keeping them separate within the same clone.  If while working on skunkworks you want the build niceties too you can do:
hg update SKUNKWORKSHEAD
hg merge BUILDHEAD

that merges the buildwork into skunkworks, but the buildwork stuff still doesn't have any skunkworks as its parent, so at anytime you could do:
cd ../product
hg pull -r BUILDHEAD ../skunkworks

and you'd move only the build stuff into product without any of the other skunkworks changes.
This is the optimal way to do such a thing (technically called anonymous branches) because when you are ready to move skunkworks into product it'll know exactly where the build changes came from and how to correctly integrate them into skunkworks.
Whew, all that said what you want to do now is probably:
cd skunkworks
hg diff -I buildstuff/** -r LAST_REV_IN_PRODUCT -r tip > ../applyme.patch
cd ../product
hg import --no-commit ../applyme.patch
hg commit

The drawback there is that when you do merge skunkworks back into product all the build changes will already be there, which will make the merge less automatic that it might otherwise be.

A: I think all you want is to run in skunkworks hg diff buildstuff -r <rev> where <rev> is the last revision matching the product repo.
Below creates a number of files and directories representing the original repository:
C:\>hg init test
C:\>cd test
C:\test>echo >file1
C:\test>echo >file2
C:\test>md dir1
C:\test>md dir2
C:\test>echo >dir1\file3
C:\test>echo >dir1\file4
C:\test>echo >dir2\file5
C:\test>echo >dir2\file6
C:\test>hg ci -Am 1
adding dir1/file3
adding dir1/file4
adding dir2/file5
adding dir2/file6
adding file1
adding file2

We'll clone and change a file in each of the subdirectories:
C:\test>cd ..
C:\>hg clone test skunk
updating to branch default
6 files updated, 0 files merged, 0 files removed, 0 files unresolved

C:\>cd skunk
C:\skunk>echo >>dir1\file4
C:\skunk>echo >>dir2\file5
C:\skunk>hg st
M dir1\file4
M dir2\file5

C:\skunk>hg ci -m skunk

Now just display the diff for dir2 compared to the previous checkin:
C:\skunk>hg diff dir2 -r 0
diff --git a/dir2/file5 b/dir2/file5
--- a/dir2/file5
+++ b/dir2/file5
@@ -1,1 +1,2 @@
 ECHO is on.
+ECHO is on.


text:
Q: Перенос значение php, которое выводится в базу Не могу понять, как перенести значение (в данном случае название товара - $item и итоговая цена - $total_price).
Эти значение выводятся из корзины в оформление заказа. Нужно, чтобы по нажатию кнопки "Подтвердить заказ" они вместе с другими значениями (фио, адрес и тд) улетали в базу.
Сразу извиняюсь возможно за дурацкий вопрос и за кривой код.
Код php:

Код страницы:

База:

A: У тебя total_price из формы не отправляется.
Вставляй результат в форму, типа так:
<input type="hidden" name="total_price" value={$total_price}

И oformzak.php полно ошибок


text:
Q: how to convert vcard 3.0 to 2.1 using cardme We have application which has mobile client and server application. Mobile clients gets installed in Symbian OS s60 which only supports vCard 2.1 to sending and receiving.
 In the server side application I am using cardme 0.2.5. which is receiving vCard version 2.1 from the mobile phone and it is getting saved properly in the database as version 2.1.
The problem comes when I edit any contact in the server application the new vCard gets saved in version 3.0 and when server syncs with the mobile device, mobile device is not able to parse vCard 3.0 properly because it supports only 2.1
While doing research I found that the the VCardWriter cannot write in vCard version 2.1 back
       public void setOutputVersion(VCardVersion outputVersion) throws VCardException {
               if(outputVersion == null) {
                 this.outputVersion = VCardVersion.V3_0;
               }
             else {
                if(outputVersion == VCardVersion.V2_1 || outputVersion ==          VCardVersion.V4_0) {
                  throw new VCardException("Version "+outputVersion+" not supported.");

         this.outputVersion = outputVersion;
      }
     }

Is there anyway we can write the object back to vCard version 2.1
I have tried using other jar versions but found that from cardme 2.0 onwards it only writes in vcard 3.0. Older versions doesn't support photo to be added in the vCard.
Any help or suggestion would be welcomed
Thanks

A: if the mobile device only has problems parsing the photo tag you could set the compatibility mode of cardme to MS_OUTLOOK. This will cause cardme to write PHOTO,LOGO,SOUND and KEY in v2.1 format.
If the above doesn't work for you, you could download version 0.1.4 of cardme which supports VCard v2.1 (including PHOTO) you can download it here cardme 0.1.4
Since the old version of cardme uses a different package name, you can re-build the vcard using the 0.1.4 version of library is another part of your program.


text:
Q: MergeBehavior when overriding collection elements in custom B2C Policies I am trying to structure my base & ext policies so that base remains pretty static. To do this I am overriding claims, etc in the ext policy - which works well. However, when trying to override a Validation Technical profile, it appears that the new items are being added at the beginning of the collection and not the end as I would have expected.
So if I have this:
base.xml
<TechnicalProfile Id="LocalAccountSignUpWithLogonEmail-NoVerify">
  <DisplayName>Email signup</DisplayName>
     … <!-- stuff removed for brevity -->
  <ValidationTechnicalProfiles>
    <ValidationTechnicalProfile ReferenceId="AAD-UserWriteUsingLogonEmail" />
  </ValidationTechnicalProfiles>
  <UseTechnicalProfileForSessionManagement ReferenceId="SM-AAD" />
</TechnicalProfile>

and this
ext.xml
 <TechnicalProfile Id="LocalAccountSignUpWithLogonEmail-NoVerify">
   <ValidationTechnicalProfiles>
     <ValidationTechnicalProfile ReferenceId="API-UpdateUser" />
     <ValidationTechnicalProfile ReferenceId="API-GetUser" />
   </ValidationTechnicalProfiles>
 </TechnicalProfile>

They execute in the order of

*

*API-UpdateUser

*API-GetUser

*AAD-UserWriteUsingLogonEmail

Is there anyway to control this order as I need the user to be created before the API stuff executes? i.e. Execute in order 3, 1, 2

A: From what I have learned, if the override adds an element with the same elementname and ID, it replaces that element from the base policy.
So, if the extension policy contains:
````
 <TechnicalProfile Id="LocalAccountSignUpWithLogonEmail-NoVerify">
   <ValidationTechnicalProfiles>
     <ValidationTechnicalProfile ReferenceId="API-UpdateUser" />
     <ValidationTechnicalProfile ReferenceId="API-GetUser" />
     <ValidationTechnicalProfile ReferenceId="AAD-UserWriteUsingLogonEmail" />
   </ValidationTechnicalProfiles>
 </TechnicalProfile>

````
then "AAD-UserWriteUsingLogonEmail" won't be invoked 2 times, it will be invoked once, as third validation profile, because the referenceId="AAD-UserWriteUsingLogonEmail" overrides the declaration of that element in the base policy file.
The documentation is not very clear about this, and the closest doc I have found is in https://github.com/Azure-Samples/active-directory-b2c-advanced-policies/blob/master/Documentation/Features%20part%206.md, where it says:

Same element in the child policy and parent policy implies, child
  policy is overriding that element of the parent policy

That documentation doesn't make clear what "same element" means, it seems to me to be the same XPath and same ID (with the ID being whatever attribute is the unique id of the element).

A: You need to overwrite all of them in the correct order in the extension policy. For example, if your base policy has following validation technical profile AAD-UserWriteUsingLogonEmail
In the extension policy, you add AAD-UserWriteUsingLogonEmail again, in the correct order:

*

*API-UpdateUser

*API-GetUser

*AAD-UserWriteUsingLogonEmail


text:
Q: Ruby on Rails error - NoMethodError in Statuses#new I get this error NoMethodError in Statuses#new when I try to view a page in my app after I add the form field... I'm new to ruby on rails so am keen to be able to fully understand this...
<%= f.input :user_id %>

Here is the full error message:
NoMethodError in Statuses#new

Showing /Users/danlee/Projects/treebook/app/views/statuses/_form.html.erb where line #14 raised:

undefined method `user_id' for #<Status:0x007feb53cdd138>
Extracted source (around line #14):

11:     </div>
12:   <% end %>
13:
14:   <%= f.input :user_id %>
15:   <%= f.input :content %>
16:   <div class="form-actions">
17:     <%= f.button :submit %>
Trace of template inclusion: app/views/statuses/new.html.erb

Rails.root: /Users/danlee/Projects/treebook

Application Trace | Framework Trace | Full Trace
app/views/statuses/_form.html.erb:14:in `block in _app_views_statuses__form_html_erb__4012047659275744874_70324335923840'
app/views/statuses/_form.html.erb:1:in `_app_views_statuses__form_html_erb__4012047659275744874_70324335923840'
app/views/statuses/new.html.erb:3:in `_app_views_statuses_new_html_erb___64465850179705865_70324349236340'
app/controllers/statuses_controller.rb:29:in `new'
Request

Parameters:

None
Show session dump

Show env dump

Response

Headers:

None

Github repository for the app is here too: https://github.com/pixeljugglerdan/treebook

A: It looks like you haven't added the :user_id column to your statuses. This file isn't running any code in the #change method: https://github.com/pixeljugglerdan/treebook/blob/master/db/migrate/20120911210237_add_user_id_to_statuses.rb
You'll probably want to re-run the migration with something like:
class AddUserIdToStatuses < ActiveRecord::Migration
  def change
    add_column :statuses, :user_id, :integer
  end
end


text:
Q: Data Table Table Tools Button not displaying in IE I am using data table table  tool option (http://datatables.net/extensions/tabletools/). It works fine on Firefox and Crome but not working in IE. Even the button of exporting type is not showing. The  other things of data table works fine in IE. I have included the following line
 var table = $('#dtable').DataTable({

        "paging": false,

        dom: 'T<"clear">lfrtip'
    });

the following figure showing firefox result

IE result:
i can not figure out the issue.

A: It is because table tools uses Adobe Flash Player. I was having same problem. After installing Adobe Flash Player in Internet Explorer I get all the buttons.(Have to admit IE is a headache).


text:
Q: How to fill the pixels of an image in android studio? I would like to fill in the "pixels" of an example image: a 480x800 image I would like to match up to 800x800 but without changing the width or height, I would like to do so by adding more pixels but a black color without the image being distorted

A: I believe you are looking for some thing like 9 patch feature
This will give you the ability to specify how image will grow,so you can start from there.


text:
Q: What is the difference between a Maven and a free-style software project in Jenkins / Hudson? What is the difference between a Maven and a free-style software project in Jenkins / Hudson?
I noticed that there is a difference when a failing JUnit tests resulted in a successful build of the Maven project, while the free-style build failed.

A: A maven project is a project that will analyze the pom.xml file in greater detail and produce a project that's geared towards the targets that are invoked. The maven project is smart enough to incorporate build targets like the javadoc or test targets and automatically setup the reports for those targets. There is little configuration required for it. See: https://wiki.jenkins.io/display/JENKINS/Building+a+maven2+project for more information on Maven project.
A Free-Style project is a project that can incorporate almost any type of build. While a maven project you can only build maven projects, the Free-Style project is the more "generic" form of a project. You can execute shell/dos scripts, invoke ant, and a lot more. Majority of the plugins are written to use the free-style project. The maven module is limited in that it can't invoke a shell script, or anything else just the maven targets. See: https://wiki.jenkins.io/display/JENKINS/Building+a+software+project for more information on a Free-Style project.


text:
Q: Three.js plane doesn't cast shadow I'm stacking a plane and a sphere on top of a bigger plane, as seen in the following image

From WebGL inspector, it seems all three object are drawn in the shadowmap, but only the sphere is effectively appearing in the shadowmap, causing the smaller plane to never cast a shadow on the bigger one
Here's the scene construction
renderer.shadowMap.enabled = true

camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 5000);
camera.position.z = 600;
window.controls = new THREE.OrbitControls(camera, renderer.domElement);

light = new THREE.SpotLight(0xffffff, 1, 0, Math.PI / 2);
light.position.set(1, 1000, 1);
light.castShadow = true;
light.shadow = new THREE.LightShadow(new THREE.PerspectiveCamera(50, 1, 1, 5000));

scene.add(light);

var planeGeometry = new THREE.PlaneGeometry( innerWidth * 0.5, innerHeight * 0.5, 10, 10);
var plane = new THREE.Mesh( planeGeometry, new THREE.MeshPhongMaterial({ color: 0xffcccc }));
plane.rotation.x = -Math.PI / 2;
plane.castShadow = true;
plane.receiveShadow = true;
scene.add(plane);

var sphere = new THREE.SphereGeometry(100, 16, 8);
var spheremesh = new THREE.Mesh(sphere, new THREE.MeshPhongMaterial( ));
spheremesh.position.y = 200;
spheremesh.castShadow = true;
spheremesh.receiveShadow = true;
scene.add(spheremesh);

var planeGeometry1 = new THREE.PlaneGeometry( innerWidth, innerHeight, 10, 10);
var plane1 = new THREE.Mesh( planeGeometry1, new THREE.MeshPhongMaterial( ));
plane1.position.y = -250;
plane1.rotation.x = -Math.PI / 2;
plane1.castShadow = true;
plane1.receiveShadow = true;
scene.add(plane1);

A: By default, three.js culls front faces when generating shadow maps.
renderer.shadowMap.renderReverseSided = true; // default is true

That means only back faces (from the point of view of the light) cast shadows. Culling front faces of your plane leaves nothing left to cast a shadow.
So one option is to replace your PlaneGeometry with a thin BoxGeometry, which has depth.
A second option is to set
renderer.shadowMap.renderSingleSided = false; // default is true

In this case, your plane will cast a shadow, but there may be self-shadowing artifacts since you have both plane.castShadow = true and plane.receiveShadow = true.
Typically, the first option is the best option.
three.js r.86


text:
Q: HTML rendering using NSTextView I have an HTML with base 64 encoded inline image. I have to display this in an application. I am using NSTextView to display this. Now this works fine in 10.6 but in 10.5 instead of the image I kind of see a placeholder. So I went ahead and tried opening that HTML with Text Edit. The same thing happened. TextEdit on 10.6 is able to render it perfectly but 10.5 TextEdit is just not able to render the image.
Can some one please tell me what could be wrong. The HTML is like -

..

PS: Please dont ask why I am not using WebView. I have to use NSTextView.


text:
Q: Accessing attrs in custom view in Kotlin I am creating a custom view in Kotlin.
For the constructors, I have followed the suggestions listed here: https://blog.q42.nl/the-danger-of-assumptions-kotlin-with-android-custom-views-adb79bf2da45
My problem is that now the init block doesn't recognise the attrs parameter since they are not in the primary constructor.
Am I missing something?

A: Just make the constructors with bodies and call a function initialising attributes from within.
For example:
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
    attrs?.let { initAttrs(it) }
}

private fun initAttrs(attrs: AttributeSet) {
    ...
}


text:
Q: Access Form Events - What control to use to execute code dynamically I have created a form to enter training events.
I have an unbound calculated control at the top of my form which reflects the status of the training. Calculated control source:
=IIf(IsNull([Txt_TrainComm]),"NEW",IIf(IsNull([Txt_TrainComp]),"COMMENCED",IIf(IsNull([txtAssNom]),"ASSESSMENT REQUIRED",IIf(IsNull([txtAssComp]),"ASSESSMENT - NOMINATED","ASSESSED"))))
My form has a few key dates (Text Box Names: txt_TrainComm, txt_TrainComp, txtAssNom & txtAssComp) to be entered in that order. What I want to happen is as the dates are entered other form controls are enabled, the footer is made visible etc. I have written a code that when placed in the Form Current Event works fine when switching from one record to the next. Please see my code so far below:
Private Sub Form_Current()
If Me.StatusName = "NEW" Then
Me.StatusName.Width = 1418
Me.Txt_TrainComp.Enabled = False
Me.Txt_TrainComm.Enabled = True
Me.Page_Assessment.Enabled = False
    If Me.FormFooter.Visible = True Then
    Me.FormFooter.Visible = False
    Me.cmdShowdetails__.Caption = "Show Assessment <<"
    Dim WindowHeightNEW As Long
    WindowHeightNEW = Me.WindowHeight - Me.FormFooter.Height
    Me.Move Left:=Me.WindowLeft, Top:=Me.WindowTop, Height:=WindowHeightNEW
    End If
End If

If Me.StatusName = "COMMENCED" Then
Me.StatusName.Width = 2552
Me.Txt_TrainComp.Enabled = True
Me.Txt_TrainComm.Enabled = True
Me.Page_Assessment.Enabled = False
    If Me.FormFooter.Visible = True Then
    Me.FormFooter.Visible = False
    Me.cmdShowdetails__.Caption = "Show Assessment <<"
    Dim WindowHeightCOMM As Long
    WindowHeightCOMM = Me.WindowHeight - Me.FormFooter.Height
    Me.Move Left:=Me.WindowLeft, Top:=Me.WindowTop, Height:=WindowHeightCOMM
    End If
End If

If Me.StatusName = "ASSESSMENT REQUIRED" Then
Me.StatusName.Width = 4253
Me.Txt_TrainComp.Enabled = True
Me.Txt_TrainComm.Enabled = True
Me.Page_Assessment.Enabled = True
    If Me.FormFooter.Visible = False Then
    Me.FormFooter.Visible = True
    Me.cmdShowdetails__.Caption = "Hide Assessment <<"
    Dim WindowHeightASSREQ As Long
    WindowHeightASSREQ = Me.WindowHeight + Me.FormFooter.Height
    Me.Move Left:=Me.WindowLeft, Top:=Me.WindowTop, Height:=WindowHeightASSREQ
    End If
End If'

If Me.StatusName = "ASSESSMENT - NOMINATED" Then
Me.StatusName.Width = 4925
Me.Txt_TrainComp.Enabled = False
Me.Txt_TrainComm.Enabled = False
Me.Page_Assessment.Enabled = True
    If Me.FormFooter.Visible = False Then
    Me.FormFooter.Visible = True
    Me.cmdShowdetails__.Caption = "Hide Assessment <<"
    Dim WindowHeightASSNOM As Long
    WindowHeightASSNOM = Me.WindowHeight + Me.FormFooter.Height
    Me.Move Left:=Me.WindowLeft, Top:=Me.WindowTop, Height:=WindowHeightASSNOM
    End If
End If

If Me.StatusName = "ASSESSED" Then
Me.StatusName.Width = 1985
Me.Txt_TrainComp.Enabled = False
Me.Txt_TrainComm.Enabled = False
Me.Page_Assessment.Enabled = True
    If Me.FormFooter.Visible = False Then
    Me.FormFooter.Visible = True
    Me.cmdShowdetails__.Caption = "Hide Assessment <<"
    Dim WindowHeightASSD As Long
    WindowHeightASSD = Me.WindowHeight + Me.FormFooter.Height
    Me.Move Left:=Me.WindowLeft, Top:=Me.WindowTop, Height:=WindowHeightASSD
    End If
End If

End Sub

What I cant get to work, is placing the code in the correct control event so that for example, when a date is entered into txt_TrainComp, the code is run dynamically. I have to switch to a different record and then back for the changes to take effect which isn't the desired result. I have tried BeforeUpdate, AfterUpdate, OnDirty, OnChange and they dont seem to work.
Is someone able to please have a look and make a suggestion to what event or code changes I need to make? Hopefully I have provided enough information.
Thank you in advance.

A: Thanks to RetiredGeek, FormObject_LostFocus() was the correct event to run the code after focus is changed.
Private Sub Txt_TrainComm_LostFocus()
Call FormUpdate
Me.TrainingStatus.Value = Me.StatusName
End Sub

Private Sub Txt_TrainComp_LostFocus()
Call FormUpdate
Me.TrainingStatus.Value = Me.StatusName
End Sub

Private Sub txtAssComp_LostFocus()
Call FormUpdate
Me.TrainingStatus.Value = Me.StatusName
End Sub

Private Sub txtAssNom_LostFocus()
Call FormUpdate
Me.TrainingStatus.Value = Me.StatusName
End Sub


text:
Q: Stuck at an average of ~40 sec Intermediate, ~120 sec Expert -- how best to improve from here? Is there a particular mindset or technique that allows you to push beyond the ~1 mine / sec barrier?
e.g.:

*

*less flagging?

*more clever "leaps" into uncharted territory?
  (which I see on some of the world-record youtube vids)

*training on custom mode, with a higher/lower mine density than usual?

*better ways to start/open the field?

*targeting some specific goal, such as better mouse control?

Because after learning the initial few basic patterns like 1-2-1 and 1-2-2-1, and 2-3-2 and so forth, and some of the typical arrangements you see around 3s, 4s, and 5s, I'm finding myself completely blocked at my current average rate of ~1 mine/sec on Intermediate mode (i.e. 40 sec avg, 28 at best) and much worse on Expert mode, probably 140 sec on avg, 119 best.
[Ultra geeks:  my 3BV/sec seems to peak at ~2.0, although I am not convinced that 3BV is a very accurate measure of board difficulty...]
Any rapid-improvement epiphanies you could share?  Thanks, all.

A: Although I'm sure you know this, you didn't mention it in your question.
If you have the number of flags placed around a number equal to that number, then clicking with both left+right mouse will clear all other squares around that number as well.
This is especially useful when there is a sparse area with a lot of 1s, because you can clear a ton of space per click.

A: As far as I know, no "serious" minesweepers use the question marks;  it's generally an option that is disabled with extreme prejudice.  And even the marker flags (right-click) are used sparingly so as to not waste too much time.  You only use enough to be able to leverage them for the dual-button click & propagate opening a large area.
Here is a page that lists some of these more advanced tips at the bottom, more along the lines of what I'm looking for, but I'm wondering which of these really makes a difference in going from 'meh' pretty fast, to 'holy crap how is that even possible' fast:

http://www.minesweeper.info/wiki/Strategy

e.g. should I work on "efficiency" for a while, instead of raw speed, to see a significant improvement?
I'm hoping someone has personal experience like, 'oh, I remember when this one thing dawned on me and I beat all my top scores by a huge margin'.  Because that actually happened to me when I saw this vid:

(which needs to be watched in slo-mo to appreciate)

after which I minimized my flagging and actively tried to take "leaps" into squares behind the front lines instead, where I'd normally just pick at the "surface" squares so to speak, around the edges of the open areas.  I dunno how else to describe it

A: I had those kind of records about 4-5 years ago, and have since improved to 20s intermediate, 74s expert. I'd say there were probably periods when I managed to knock 5-10 seconds off expert in a few days, and I can recommend a few things to try.

*

*Firstly, learning to chord efficiently would likely reduce your time significantly with a bit of practice. However, my records were done without flagging, so this is certainly an option (world record for non-flagging is 39s).

*The main thing to aim for, is only place flags if you're going to use them for chording.

*Particularly on intermediate, if not using flags, try to place your clicks in places that are more likely to create an opening. That is, it's possible to know a cell is safe even if it isn't next to a mine you've already found - target these!

*Try to work from one side of the board to the other, leaving nothing behind. Don't leave a 50/50 chance til the end.

*If you think you're stuck on a bit of it, don't guess unless you have to, instead try to be certain you're stuck. By spending some time thinking about it you will gradually get familiar with situations like these, and learn to leave them behind, in hope for a connection to a part you're not stuck on.

*Other than that, practice, make sure you've uncovered all the logic, and get familiar with the patterns, for example try to see a '3' which has two mines next to it as a '1' automatically in your mind.

A: If you don't have your next move within that second, guess. Players in Minesweeper generally come in two categories, those who strive for a decent win/loss ratio, and those who strive for speed. You can sacrifice your win/loss ratio for a massive gain in speed by keeping your click-speed up at the expense of your accuracy. The other techniques mentioned can still be used to give you the probabilities for a bomb in a certain location, and these can be memorized, but it only takes one victory to achieve what you want.


text:
Q: Prove that $\,f(z) \equiv 0,\,$ if $\,f(z)\,$ is entire Let $f(z)$ be an entire analytic function, such that
$$
\int_{0}^{2\pi}\lvert\, f(re^{i\theta}) \rvert\,d\theta\le r^{16/5}, \quad
\text{for all}\,\,\, r>0
$$
Show that
$$f(z)\equiv 0.$$
Thank you for you help.
Maybe we need to use Cauchy Theorem.

A: Using Cauchy Integral Formula, for $r\to 0$, we obtain that $f(0)=f'(0)=f''(0)=0$. Thus $f(z)=z^3g(z)$, where $g$ is also entire, and we get for $g$ that
$$
\int_0^{2\pi} \lvert g(r\mathrm{e}^{i\vartheta})\rvert\,d\vartheta\le r^{1/5}, \quad r>0.
$$
Now, for every $z\in\mathbb C$, let $r>2\lvert z\rvert$, and according to Cauchy Integral Formula
$$
g(z)=\frac{1}{2\pi i}\int_{|w|=r}\frac{g(w)\,dw}{w-z},
$$
and hence
$$
\lvert g(z)\rvert \le \frac{1}{2\pi}\max_{|w|=r}\lvert  w-z\rvert^{-1}\int_0^{2\pi}\lvert g(r\mathrm{e}^{i\vartheta})\rvert \,d\vartheta\le \frac{1}{2\pi}\cdot \frac{2}{r}\cdot r^{1/5}
=\frac{1}{\pi r^{4/5}}\to 0,
$$
as $r\to \infty$.
Thus $g\equiv 0$, and so is $f$.


text:
Q: Get Value from source code by HttpWebResponse C# I'm use HttpWebResponse in c# for Response my Request
And saves Response data(string) in StreamReader
It's work !
But i need to Messages box for some text in StreamReader
 Look this aera :

Country	 United States (US)

this is HTML code !
and i want get This from it

United States (US)

--note :
every request the : 'images/flags/us.png' And 'United States flag' It's Change to Others !

A:
Also , Html Agility Pack is the best work ! , I'm uses Regex really is
  work!


text:
Q: Tokenizing Strings in a File I have a file which I am tokenizing all the strings in it.
So each token gets stored in char *token = (char *) malloc(len + 1); The token gets released before the new one is allocated so I need a way to store the tokens for further use.
What's a good strategy to store the tokens? I have a function which prints out one single token string at a time.
My question here is not about how to tokenize or parse so please disregard the implementation of that. My question is, I have a bunch of strings that get allocated and released several times within a loop. So how would I store each allocation somewhere else for further use?

A: Generally tokens are not stored to file.  They are requested by the parser when the parser is ready to read more input.
As such, tokens are stored in memory on the program's heap, and after they have been processed (which might be long before the file is fully parsed) they are freed.
--- Update to follow the edit ---
If you are worried about excessive allocation and deallocation, then you have a number of solutions, depending on the detail of the issue you are attempting to solve.
For strings, you can create them through a "string builder" interface, which checks to see if a string is already present with that text, and if so, returns a reference to the already present string.  Note that for this to work properly, all returned strings must be immutable (as changing a string in one reference will change the string in all references).  Similar solutions are possible for numbers, boolean values, etc.
For token reuse, you can make the token into a structure that mostly references by pointer the data likely to "used" by the parser.  That way the parser grabs the "fields" of the token, and the "skeleton" token can be added back to a "reuse queue".  The reuse queue should reset the "data" references of the token before returning it to the tokenizer, which would be rewritten to ask the queue for it's data structures.  In the event that there are no tokens "in the queue" the queue should silently allocate them.
Other solutions exist too, depending on how crafty you want to get.


text:
Q: Why I get a lot of unwanted output when I convert ByteBuffer to String? I write a UDP server to receive messages from clients using NIO:
DatagramChannel channel = DatagramChannel.open();
channel.socket().bind(new InetSocketAddress(9999));
ByteBuffer buf = ByteBuffer.allocate(1024);
buf.clear();
while (channel.receive(buf) != null) {
      System.out.println("---has received data:" + new String(buf.array(), ASCII));
      buf.clear();
}

then I use nc command to send some data to the UDP server
nc -u 127.0.0.1 9999 < ./test.txt

there is only one line in test.txt
#cat ./test.txt
12345678

and the output of the server is like this

so how could I get the 12345678 string and remove the following '口' things?

A: This is not unwanted output, this is because you print the entirety of your Buffer.
buf.clear(); does not clear the buffer with zeros, it just resets the position to 0.

A: DatagramChannel channel = DatagramChannel.open();
channel.socket().bind(new InetSocketAddress(9999));

ByteBuffer chunkData = ByteBuffer.allocate(1024);
chunkData.clear();

channel.receive(chunkData);

// remove unwanted data
byte[] validData = new byte[chunkData.position()];
System.arraycopy(chunkData.array(), 0, validData, 0, validData.length);

System.out.println("---has received data:" + new String(validData));

A: System.out.println("---has received data:" + new String(buf.array(), ASCII));

You're ignoring the datagram length. This should be:
System.out.println("---has received data:" + new String(buf.array(), 0, buf.position()-1, ASCII));