text:
Q: I want to select all the data specified from multiple tables, but it only select one data I have written a SQL query through which I want to select all the related data specified from multiple tables but when I run the query it only retrieve single data but I want to select all the data. Here is my query:
    $mysqli->query("SELECT projectDescription, location,budget,date,
    SUM(ebudget) as expense_budget, SUM(totalAmount) as overtime_budget,
    SUM(totalPrice) as material_budget FROM projecttable, expensestable,
    overtimetable,dailyworkusage WHERE
    expensestable.projectID=projecttable.projectID AND
    overtimetable.projectID=projecttable.projectID AND
    dailyworkusage.projectID=projecttable.projectID") or die($mysqli-
    >error());

A: That's because you are missing a GROUP BY clause (in non-ancient versions of MySQL, you would have met a syntax error). Add this at the end of your query:
GROUP BY projectDescription, location, budget, date

Also, you do want to use explicit joins instead of old-school, implicit joins. Using aliases for table names is also a good practice. Here is an updated version of your query:
SELECT
    projectDescription,
    location,
    budget,
    date,
    SUM(ebudget) as expense_budget,
    SUM(totalAmount) as overtime_budget,
    SUM(totalPrice) as material_budget
FROM projecttable p
INNER JOIN expensestable e ON e.projectID = p.projectID
INNER JOIN overtimetable o ON o.projectID = p.projectID
INNER JOIN dailyworkusage d ON d.projectID = p.projectID
GROUP BY
    projectDescription,
    location,
    budget,
    date

Please add the relevant table prefixes to all these columns (it cannot be told without seeing your actual table structures, that you did not show).


text:
Q: job queue implementation for python Do you know/use any distributed job queue for python? Can you share links or tools

A: In addition to multiprocessing there's also the Celery project, if you're using Django.

A: There's also "bucker" by Sylvain Hellegouarch which you can find here:

*

*http://trac.defuze.org/wiki/bucker
It describes itself like this:

*

*bucker is a queue system that supports multiple storage for the queue (memcached, Amazon SQS for now) and is driven by XML messages sent over a TCP connections between a client and the queue server.

A: Look at beanstalkd

A: redqueue?
It's implemented in python+tornado framework, speaks memcached protocol and is optionally persistent into log files.
Currently it is also able to behave like beanstalkd, the reserve/delete way in memcache protocol as well.
REDQUEUE

A: If you think that Celery is too heavy for your needs then you might want to look at the simple distributed task queue:

*

*https://github.com/rojkov/taskqueue

*http://simpletaskqueue.readthedocs.org/

A: Pyres is a resque clone built in python. Resque is used by Github as their message queue. Both use Redis as the queue backend and provide a web-based monitoring application.
http://binarydud.github.com/pyres/intro.html

A: It's a year late or whatever, but this is something I've hacked together to make a queue of Processes executing them only X number at a time. http://github.com/goosemo/job_queue

A: Also there is Unix 'at'
For more info:
man at

A: You probably want to look at multiprocessing's Queue. Included in Python 2.6, get it on PyPI for earlier versions of Python.
Standard library documentation: http://docs.python.org/library/multiprocessing.html
On PyPI: http://pypi.python.org/pypi/multiprocessing

redpajama_set_name: RedPajamaStackExchange


text:
Q: Text editor to handle extremely large files I generated 300mb text file, trying to edit it using sublime 3 on xubuntu 13.10 64 bit, it's so slow and crashing, I'm not a vim/vi user, what is the best editor to work with these kind of files.
I only need to search for and remove duplicated text.

A: There is a graphical vim - gvim - that may be more acceptable to you than the less graphical versions. I haven't tried it on large files though.
But it really comes down to personal preference. vi could do the job, but you're not comfortable using it. That's fine, but you might not like anything suggested either. So just try a few until you find one that works both for your large files and yourself.
The problem you will find is that no editor will work well if it doesn't have the system resources available to do its job. There are limitations that may stop you no matter what editor you try - for example a 32bit system will cause problems for all editors past a couple of hundred meg. A lot of the better known editors will have tricks like disabling features, increasing swap space, etc, to allow large files to be edited.


text:
Q: how to save file location to database sqlite3 - django i want to save file location to database sqlite3, but the file just save it to local storage. i tried to make it but there's error :

here's my models :
from django.db import models
from django.core.files.storage import FileSystemStorage

fs = FileSystemStorage(location='/media/mp3')

class Audio_store(models.Model):
    record=models.FileField(storage=fs)

forms.py :
from django import forms
from .models import Audio_store

class AudioForm(forms.ModelForm):
    class Meta:
        model = Audio_store
        fields= ['record']

views.py :
def homepage(request):
    form = AudioForm()
    audio = Audio_store.objects.all()
    if request.method == "POST":
        form = AudioForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
        return redirect("homepage")

    context={'form':form, 'audio':audio}
    return render(request, "homepage.html", context=context)

please help me to fix it


text:
Q: Mongodb - which data type for events I am a Mongo DB beginner.
I have to create a collection that can store events. All the documents in the Event will  have a FROM_TIME and TO_TIME keys whose values can vary as follows :

*

*{FROM_TIME : "September 1,1939", TO_TIME : "August 1945"}

*{FROM_TIME : "August 15,1947", TO_TIME : "August 15,1947"}

*{FROM_TIME : "1857", TO_TIME : "1858"}

*{FROM_TIME : "December 7,1944 11:00", TO_TIME : "December 7,1944 14:40"}

*{FROM_TIME : "January 1971", TO_TIME : "November 1972"}

Given the random occurrence of the FROM_TIME and TO_TIME, will it be possible to query for events like :

*

*List of events in the second half of the 19th century

*List of events on August 15
and so on.

I request people here to provide leads in case I need to rethink the structure of my collection as I'm quite naive at Mongo(or any other non-relational)DB.
***1st Edit begins here
I wrote the following code:
DBObject dbObject = new BasicDBObject();

        dbObject.put("EVNTATMC_ID", new ObjectId());
        dbObject.put("EVNTATMC_DESC", "Pearl Harbour");
        dbObject.put("EVNTATMC_FROM_TIME", Date.valueOf("1944-12-07"));
        dbObject.put("EVNTATMC_TO_TIME", Date.valueOf("1944-12-07"));
        dbObject.put("EVNTATMC_EVNTCMPD_ID", new ObjectId());
        dbObject.put("EVNTATMC_MTRL_ID", null);
        // dbObject.put("EVNTATMC_AUDIT", 1);
        dbObject.put("EVNTATMC_REMARKS", "First insert");

        eventAtomic.insert(dbObject);
dbObject = new BasicDBObject();

        dbObject.put("EVNTATMC_ID", new ObjectId());
        dbObject.put("EVNTATMC_DESC", "1857 Revolt");
        dbObject.put("EVNTATMC_FROM_TIME", "1857");
        dbObject.put("EVNTATMC_TO_TIME", "1858");
        dbObject.put("EVNTATMC_EVNTCMPD_ID", new ObjectId());
        dbObject.put("EVNTATMC_MTRL_ID", null);
        // dbObject.put("EVNTATMC_AUDIT", 1);
        dbObject.put("EVNTATMC_REMARKS", "Only years");

        eventAtomic.insert(dbObject);

Here, I dumbly used String to store incomplete dates but how should I store just an year like 1992, 2001, 2012 or just a month like January, September or something like August 2010 ? I'm not sure as to whether I'm expecting the correct thing ! Please guide me as to how I must handle such 'incomplete' timings.
***1st Edit ends here

A: Store the FROM_TIME and TO_TIME as DateTime. See Here:
http://www.mongodb.org/display/DOCS/Dates
Then, you can query (rang query for example)
see the answer here:
https://stackoverflow.com/a/8136834/131809
So, for all events on August 15th 2012:
var start = new Date(2012, 08, 15);
var end = new Date(2012, 08, 16);

db.myEventCollection.find({created_on: {$gte: start, $lt: end}});


text:
Q: How can I read from an RS485 COM port in C++ with Windows? I try to control a voltage source via RS485 (via a USB to RS485 converter). I use Standard C++ in Visual Studio.
I wrote the following code. Writing works fine, the voltage source responds to all input, but reading back bytes is difficult for me.
For example, the answer might be the following string: "12.000" (31 32 2E 30 30 30 0A)
#include <iostream>
#include <string.h>
#include <windows.h>
#include <msports.h>
#include <stdlib.h>

const unsigned char oe = static_cast<unsigned char>(148);

int main()
{

    //create new handle
    HANDLE hComm;
    hComm = CreateFile(L"\\\\.\\COM5",
        GENERIC_READ | GENERIC_WRITE,
        0,
        0,
        OPEN_EXISTING,
        FILE_FLAG_OVERLAPPED,
        0);
    if (hComm == INVALID_HANDLE_VALUE)
        printf("CreateFile handle failed ERROR: %d.\n", GetLastError());

    /*
    //Timwouts
    COMMTIMEOUTS CTO;
    CTO.ReadIntervalTimeout = 500;
    CTO.ReadTotalTimeoutConstant = 500;
    CTO.ReadTotalTimeoutMultiplier = 500;
    CTO.WriteTotalTimeoutConstant = 500;
    CTO.WriteTotalTimeoutMultiplier = 500;

    //build DCB strukture
    DCB dcb;

    if (!BuildCommDCB(L"COM5 baud=115200 parity=N data=8 stop=1", &dcb))
    {
        MessageBox(0, L"Error BuildCommDCB", L"Test", MB_OK);
    }

    if (!SetCommTimeouts(hComm, &CTO))
    {
        MessageBox(0, L"Error CommTimeouts", L"Test", MB_OK);
    }
    */

    //Variables for read RS485
    char sBuffer[1024];

    //Variables for user input values
    char parameter1;
    float floatV;
    char parameter2;

    while (true) {
        std::cout << "Hallo, was m" << oe << "chten Sie tun?\n";
        std::cin >> parameter1 >> floatV >> parameter2;
        //std::cout << "parameter1: " << parameter1 << "\n";
        //std::cout << "floatV: " << floatV << "\n";
        //std::cout << "parameter2: " << parameter2 << "\n";
        //system("cls");

        if (parameter1 == 'Q' && parameter2 == 'V') {
            uint32_t Voltage = (uint32_t)(floatV * 1000);
            char myString[30];
            sprintf_s(myString, "%f", floatV);

            //Set new voltage
            //VSET:
            TransmitCommChar(hComm, 'V');
            TransmitCommChar(hComm, 'S');
            TransmitCommChar(hComm, 'E');
            TransmitCommChar(hComm, 'T');
            TransmitCommChar(hComm, ':');
            //Wert
            TransmitCommChar(hComm, myString[0]);
            TransmitCommChar(hComm, myString[1]);
            TransmitCommChar(hComm, myString[2]);
            TransmitCommChar(hComm, myString[3]);
            TransmitCommChar(hComm, myString[4]);
            TransmitCommChar(hComm, myString[5]);
            //ENTER
            TransmitCommChar(hComm, 0x0A);

            //Get the voltage of the source
            //Control V
            //56 53 45 54 3F 0A
            TransmitCommChar(hComm, 'V');
            TransmitCommChar(hComm, 'S');
            TransmitCommChar(hComm, 'E');
            TransmitCommChar(hComm, 'T');
            TransmitCommChar(hComm, '?');
            TransmitCommChar(hComm, 0x0A);

            //Sleep(100);
            /*
            LPVOID buffRead = 0;
            DWORD dwBytesRead = 0;
            if (!ReadFile(hComm, &buffRead, 6, &dwBytesRead, NULL))
            {
                printf("error reading from input buffer \n");
            }
            printf("Data read from read buffer is \n %s \n", (char*)buffRead);
            */

            DWORD dwBytesRead = 0;
            char bytes_to_receive[7];

            if (!ReadFile(hComm, bytes_to_receive, 7, &dwBytesRead, NULL)) {
                printf("SetCommState failed. Error: %d.\n", GetLastError());
                //CloseHandle(hComm);
                //return (4);
            }
            else {
                printf("Bytes read %d -> %s\n", dwBytesRead, bytes_to_receive);
            }

            /*if (ReadFile(hComm, sBuffer, 7, NULL, NULL)) {
                printf("%s \n", sBuffer);
            }
            else {
                printf("Reading file fails! \n");
            }*/

            /*UINT numberBytesRead = _lread(
                HFILE  hFile,
                LPVOID lpBuffer,
                UINT   uBytes
            );*/
        }
    }
}

The output I get is:
Hallo, was möchten Sie tun?
Q12V
SetCommState failed. Error: 87.
Hallo, was möchten Sie tun?

The voltage source jumps to 12V, so she got the command.
EDIT:
I changed FILE_FLAG_OVERLAPPED to FILE_ATTRIBUTE_NORMAL, now I get:
Hallo, was möchten Sie tun?
Q12V
Bytes read 7 -> 12.000
╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠G┤°V
Hallo, was möchten Sie tun?

So it basically seems to work, but I get a lot of strange signs.
EDIT 2:
Another problem that I still face is that after restarting the computer nothing works anymore and I need to start HTerm, press connect and disconnect, what apparently makes a few initializations that I miss in my program. After that it works till the next restart of the computer. Do you have any ideas what I might not have in my program?

A: You get strange signs because bytes_to_receive is not a null-terminated string. printf keeps reading bytes until it sees a null (0) byte. You don't put a null byte in bytes_to_receive, so it keeps printing until it goes off the end and finds one somewhere else.
ReadFile tells you how many bytes were read, in dwBytesRead, so you can add a null byte for printf: bytes_to_receive[dwBytesRead] = '\0';.
Make sure to increase the size of bytes_to_receive to 8 because now you are writing one extra byte. Still pass 7 to ReadFile because you don't want to read 8 bytes - you are adding the null byte yourself after reading the data.

A: Ok, in the meantime I solved the problem. Some extra code is needed, I hope I can help the next one who has the same problem, otherwise I am open to suggestions for improvement. Thank you for your support, I have distributed upvotes to all who have helped me.
DCB Dcb;
COMMTIMEOUTS Cto;
HANDLE hComm;

//Create file Handle
hComm = CreateFile(L"\\\\.\\COM5",
    GENERIC_READ | GENERIC_WRITE,
    0,
    0,
    OPEN_EXISTING,
    FILE_ATTRIBUTE_NORMAL,
    0);
if (hComm == INVALID_HANDLE_VALUE) {
    printf("CreateFile handle failed ERROR: %d.\n", GetLastError());
}

//Data Center Bridging
Dcb.DCBlength = sizeof(Dcb);
GetCommState(hComm, &Dcb);
Dcb.BaudRate = CBR_115200;
Dcb.fParity = false;
Dcb.fNull = false;
Dcb.StopBits = ONESTOPBIT;
Dcb.Parity = NOPARITY;
Dcb.ByteSize = 8;
SetCommState(hComm, &Dcb);

//Timeouts
Cto.ReadIntervalTimeout = 0;
Cto.ReadTotalTimeoutMultiplier = 0;
Cto.ReadTotalTimeoutConstant = 0;
Cto.WriteTotalTimeoutMultiplier = 0;
Cto.WriteTotalTimeoutConstant = 0;
SetCommTimeouts(hComm, &Cto);


text:
Q: Fastest way of converting a quad to a triangle strip? What is the fastest way of converting a quadrilateral (made up of four x,y points) to a triangle strip? I'm well aware of the general triangulation algorithms that exist, but I need a short, well optimized algorithm that deals with quadrilaterals only.
My current algorithm does this, which works for most quads but still gets the points mixed up for some:
#define fp(f) bounds.p##f

/* Sort four points in ascending order by their Y values */
point_sort4_y(&fp(1), &fp(2), &fp(3), &fp(4));

/* Bottom two */
if (fminf(-fp(1).x, -fp(2).x) == -fp(2).x)
{
    out_quad.p1 = fp(2);
    out_quad.p2 = fp(1);
}
else
{
    out_quad.p1 = fp(1);
    out_quad.p2 = fp(2);
}

/* Top two */
if (fminf(-fp(3).x, -fp(4).x) == -fp(3).x)
{
    out_quad.p3 = fp(3);
    out_quad.p4 = fp(4);
}
else
{
    out_quad.p3 = fp(4);
    out_quad.p4 = fp(3);
}

Edit: I'm asking about converting a single quad to a single triangle strip that should consist of four points.

A: *

*Locate an extremum point of the quad w.r.t a coordinate. Let it be p, where p is an iterator on a cyclic container

*Check if p + 2 lies inside of the ear formed by {p - 1, p, p + 1}. If yes, seek extremum w.r.t. other coordinate (or switch from min to max or vice versa) and repeat step 1.

*Split the quad into two triangles by cutting off the "ear" around the extremum point:
t0 = { p - 1, p, p + 1} and
t1 = { p + 1, p + 2, p - 1 }
No need to sort, just locate the extremum. If your quads are guaranteed to be convex (real quadrilaterals) then skip the extremum search and choose arbitrary p.
Edit: Modified according to suggestion from the comment. Also the formulation suggested by the commenter is simpler to implement:

*

*Given a quad A, B, C, D form the diagonals  AC and BD

*If points B and D lie on different sides of AC then AC can be used to split the quad

*Apply the same reasoning to BD and points A and C

A: Given a quad A B C D we can split it into A B C, A C D or A B D, D B C.
Compare the length of A-C and B-D and use the shorter for the splitting edge. In other words use A B C, A C D if A-C is shorter and  A B D, D B C otherwise.


text:
Q: Run python threads on multiple cores I know that Python 2.7 does not allow one to run multiple threads on different cores, and you need to use the multiprocessing module in order to achieve some degree of concurrency. I was looking at the concurrent.futures module in Python 3.4. Does using a ThreadPoolExecutor allow you to run different threads on different processes, or is it still bound by GIL constraints? If not, is there a way of running threads on different processors using Python 3.4?
For my use case, using multiple processes is absolutely not feasible.

A: No. ThreadPoolExector is just a class to help with scheduling work on multiple threads. All of the normal thread constraints still apply.
To clear up some confusion, threads will run on different processors / cores as the operating system chooses, they just won't run concurrently. The exception is that some C based functions release the GIL temporarily while performing actions not needing the lock.


text:
Q: How to connect programmatically to an embedded HornetQ server I'm running an embedded HornetQ server on an OSGI container following an example for embedded HornetQ Core.
I have three OSGI containers: one for the server, one for a producer and a last one for a consumer. Everything works on local.
The code I'm using in both the producer and consumer for connecting to the server is the following:
// Step 4. As we are not using a JNDI environment we instantiate the objects directly
ServerLocator serverLocator = HornetQClient.createServerLocatorWithoutHA(new TransportConfiguration(NettyConnectorFactory.class.getName()));
ClientSessionFactory sf = serverLocator.createSessionFactory();

I've tried looking at the TransportConfiguration methods, but no setter was found.

A: You need to pass parameters to the Transport configuration:
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("port", org.hornetq.core.remoting.impl.netty.TransportConstants
                      .DEFAULT_PORT);
parameters.put(TransportConstants.HOST_PROP_NAME, "127.0.0.1");

TransportConfiguration configuration = new TransportConfiguration(
        NettyConnectorFactory.class.getName(), parameters);

Notice you have / could do the same to the NettyAcceptor. I'm not sure how you are configuring the acceptors at your test.. but I hope you get the idea.


text:
Q: How to import js file from other js file I'm trying to import TodoItem.jsx to TodoList_spec.jsx.
Here's my project directory structure.
- TodoMVCTuts
  - app
  - bootstrap
  - config
  - database
  - node_modules
  - public
  - resources
    - assets
      - js
        - components
          - TodoItem.jsx
  - storage
  - tests
    - js
      - components
        - TodoList_spec.jsx
  - vendor

Here's my code:
// /tests/js/components/TodoList_spec.jsx
import React from 'react';
import TestUtils from 'react-addons-test-utils';
// ** Import TodoItem.jsx **
//import TodoItem from  '../resources/assets/js/components/TodoItem';
import { expect } from 'chai';
import { List, Map } from 'immutable';
**

How can I achieve that? Thanks in advance.

A: This should work
import TodoItem from  '../../../resources/assets/js/components/TodoItem';


text:
Q: How to put batch command output in desired column of csv file i'm new in batch programmation and it's been 8 hours i'm trying to figure how to resolve my problem. That's why i'm here, i'm sure I passed out of something ...
I have a command
@ECHO OFF
echo Demarre le %date:~0,8% a %time:~0,5% >> C:\TEMP\pointage.csv

which put in pointage.csv the date on PC start up (we will call it A)
I have another command
@Echo Off&SetLocal
For /F "UseBackQ Tokens=1-4" %%A In (
    `Powershell "$OS=GWmi Win32_OperatingSystem;$UP=(Get-Date)-"^
    "($OS.ConvertToDateTime($OS.LastBootUpTime));$DO='d='+$UP.Days+"^
    "' h='+$UP.Hours+' n='+$UP.Minutes;Echo $DO"`) Do (
    Set "%%A"&Set "%%B"&Set "%%C")
Echo Temps de fonctionnement: %d% jour, %h% heures, %n% minutes >> C:\TEMP\pointage.csv
Echo Eteint le %date:~0,8% a %time:~0,5% >> C:\TEMP\pointage.csv

which put in pointage.csv the date when PC is shutdown (call B) + the time that pass between launch and shutdown (call C)
The problem is :
A, B & C are located in A1 for A, A2 for B, A3 for C in my pointage.csv
I want to put :

*

*Every A results on column A,

*Every B results on column B,

*Every C results on column C.
in my pointage.csv
How to do that ? I tried many things, for example creating 3 files.txt and put them A,B & C then trying to use for /F function. But I don't find anything which works a little bit.
Thank you for helping !

A: Ok I found the problem, it's really simple ...
echo "hello";"stack";"overflow" >> pointage.csv

Worked
Here is my all code :
@echo off
setlocal
for /f %%a in ('wmic os get lastbootuptime ^| find "."') do (
  set _datetime=%%a
  )
set _boottime=%_datetime:~6,2%-%_datetime:~4,2%-%_datetime:~0,4%%_datetime:~8,2%:%_datetime:~10,2%

For /F "UseBackQ Tokens=1-4" %%A In (
    `Powershell "$OS=GWmi Win32_OperatingSystem;$UP=(Get-Date)-"^
    "($OS.ConvertToDateTime($OS.LastBootUpTime));$DO='d='+$UP.Days+"^
    "' h='+$UP.Hours+' n='+$UP.Minutes;Echo $DO"`) Do (
        Set "%%A"&Set "%%B"&Set "%%C"
)

Echo "%_boottime%";"%date:~0,8% %time:~0,5%";"%d% days, %h% hours, %n% minutes" >> C:\TEMP\pointage.csv

endlocal


text:
Q: Error while running react using npm start I am learning react and have gotten the following error.
npm ERR! errno 1
npm ERR! learningreact@0.1.0 start: `react-scripts start`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the learningreact@0.1.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!```

A: Delete your package-lock.json file and node_modules folder. Then do npm cache clean.
npm cache clean --force
npm install

And run again.

A: You should try to delete your file package-lock.json and folder node_modules and then clear the npm cache by doing :
npm cache clean --force

Then :
npm install
npm start


text:
Q: nVidia X Settings does not launch- Ubuntu 17.10 (specs Lenovo U-31
 Processor
Intel Core i7-5500U (Intel Core i7)
Graphics adapter
NVIDIA GeForce 920M - 2048 MB, Core: 954 MHz, Memory: 900 MHz, DDR3
also includes the typical Intel Graphics 5500)
My problem is simple. I have installed the proprietery drivers and I have installed the nVidia settings software through sudo apt install nvidia-settings.
It installed fine and it appears on my app drawer however whenever I click on it, it never launches. Basically nothing happens. I have tried uninstalling and reinstalling but it did not help. Any ideas?


text:
Q: Passing varargs The below is a simple logger class I implemented my project.
/* g++ test.cpp -o test */

#include <fstream>
#include <string>

#include "fmt/fmt.h"

typedef enum Severity
{
    LOG_INFO = 0,
    LOG_WARNING,
    LOG_ERROR
} Severity;

class Logger
{
public:
    Logger(const std::string &log_file);
    ~Logger();

    template <typename... Args> void DoLog(Severity severity, const std::string& context, fmt::format_string<Args...> fmt, Args&&...args);
private:
    std::ofstream fout;
};

static const std::string severity_str[3] = {
    "INFO",
    "WARNING",
    "ERROR"
};

Logger::Logger(const std::string &log_file)
{
    fout.open(log_file, std::ofstream::out | std::ofstream::trunc);
}

Logger::~Logger()
{
    fout.close();
}

template <typename... Args>
void Logger::DoLog(Severity severity, const std::string& context, fmt::format_string<Args...> fmt, Args&&...args)
{
    fout << fmt::format("[{:<7}] [{}] {}", severity_str[severity], context, fmt::format(fmt, std::forward<Args>(args)...)) << std::endl;
}

int main()
{
    Logger log("log.txt");
    log.DoLog(LOG_INFO, "0", "Yo");
    log.DoLog(LOG_INFO, "1", "Hello {}", 42);
    log.DoLog(LOG_ERROR, "2", "Word {0:02X}", 0xFF);
    log.DoLog(LOG_WARNING, "3", "! {} {}", 4, 5);
    uint8_t opcode = 0xDD;
    log.DoLog(LOG_ERROR, "CPU::HandlePrefixCB", "Unknown opcode: {0:02X}", opcode);
    uint8_t &ref = opcode;
    log.DoLog(LOG_ERROR, "CPU::HandlePrefixCB", "Unknown opcode: {0:02X}", ref);
    return 0;
}

Even though this file compiles and runs without problems, when I add them to my project codebase and compile, g++ outputs a bunch of undefined references like ones below
C:/TDM-GCC-64/bin/../lib/gcc/x86_64-w64-mingw32/9.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: obj/CPUOpcodes.o:CPUOpcodes.cpp:(.text+0xf47): undefined reference to `void Logger::DoLog<unsigned char&>(Severity, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, fmt::v8::basic_format_string<char, fmt::v8::type_identity<unsigned char&>::type>, unsigned char&)'
C:/TDM-GCC-64/bin/../lib/gcc/x86_64-w64-mingw32/9.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: obj/CPUOpcodes.o:CPUOpcodes.cpp:(.text+0x3011): undefined reference to `void Logger::DoLog<unsigned char&>(Severity, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, fmt::v8::basic_format_string<char, fmt::v8::type_identity<unsigned char&>::type>, unsigned char&)'
...

I suspect the problem lies on how I handle varags fmt::format_string<Args...> fmt, Args&&...args in DoLog. I can't find anything wrong with it. Is there anything I should fix?

A: The third parameter to DoLog should just be a string (I changed output to std::cout for testing)
#include <map>
#include <iostream>
#include <string>

#include <fmt/format.h>

typedef enum Severity
{
    LOG_INFO = 0,
    LOG_WARNING,
    LOG_ERROR
} Severity;

static const std::string severity_str[3] =
{
    "INFO",
    "WARNING",
    "ERROR"
};

class Logger
{
public:
    Logger() = default;
    ~Logger() = default;

    template<typename... args_t>
    void DoLog(Severity severity, const std::string& context, const std::string& fmt, args_t&&... args)
    {
        std::cout << fmt::format("[{:<7}] [{}] {}", severity_str[severity], context, fmt::format(fmt, std::forward<args_t>(args)...)) << std::endl;
    }

};

int main()
{
    Logger log;
    log.DoLog(LOG_INFO, "0", "Yo");
    log.DoLog(LOG_INFO, "1", "Hello {}", 42);
    log.DoLog(LOG_ERROR, "2", "Word {0:02X}", 0xFF);
    log.DoLog(LOG_WARNING, "3", "! {} {}", 4, 5);
    uint8_t opcode = 0xDD;
    log.DoLog(LOG_ERROR, "CPU::HandlePrefixCB", "Unknown opcode: {0:02X}", opcode);
    uint8_t& ref = opcode;
    log.DoLog(LOG_ERROR, "CPU::HandlePrefixCB", "Unknown opcode: {0:02X}", ref);
    return 0;
}


text:
Q: Using JQuery AJAX to submit a form to PHP, return data is empty When I run this code below, the "data" returned is an empty string "[]".  (At least viewed through the Chrome Console Viewer)
If I comment out the "event.preventDefault();" line in the JS I get a page reload, as expected, and a JSON string with results that passes JSONLint. I know the PHP is working as I am getting new inserts into the mySQL database and the return values make sense.
Everything seems to run correctly even with "data" is returned empty... (i.e. I am getting the console.log of FIRST first and SECOND second followed by the empty string.)  I just can't get the returned "data" values in the JS context.
I'm kinda new to web development, not to programming... but does anyone spot a rookie mistake?  I have read over about 12 similar questions and tried many things, but nothing is helping...
Thanks in advance.

$(document).ready(function() {
    $('form').submit(function(event) {
        var formData = {
            'firstName': $('input[name=firstName]').val(),
            'lastName': $('input[name=lastName]').val(),
            'email': $('input[name=email]').val(),
            'password': $('input[name=password]').val()
        };

        $.ajax({
            type: 'POST',
            url: 'createaccount.php',
            data: formData,
            dataType: 'json'
        })
            .done(function(data) {
                console.log("SECOND");
                console.log(data);
            });

        console.log("FIRST");
        event.preventDefault();
    });
});
    input {
        border-radius: 5px;
        border-width: 1px;
        margin: 2px;
    }

Join website

                    <form action="createaccount.php" method="post">
                        First Name:<input type="text" name="firstName" />

                        Last Name:<input type="text" name="lastName" />

                        Email:<input type="email" name="email" />

                        Password:<input type="password" name="password" />

                        <input type="submit" value="Sign Up" name="submit" />
                    </form>

<?php

    $firstName = $_POST["firstName"];
    $lastName = $_POST["lastName"];
    $email = $_POST["email"];
    $password = $_POST["password"];
    $submit = $_POST["submit"];

    $errors = array();
    $data = array();

    if ($submit) {
        if (!$email) {
            $errors['email'] = "Email is required.";
        }
        else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errors['validemail'] = "Valid email is required.";
        }

        if (!$password) {
            $errors['password'] = "Password is required.";
        }
        else {
            if (strlen($password) < 8) {
                $errors['passwordlength'] = "Password must be at least 8 characters long";
            }
            if (!preg_match("#[A-Z]+#", $password)) {
                $errors['passwordcaps'] = "Password must contain at least one Capital Letter";
            }
        }

        if (empty($errors)) {

            require 'dbconnect.php';

            $query="SELECT * FROM Users WHERE email='".mysqli_real_escape_string($link, $email)."'";

            $result = mysqli_query($link, $query);

            $results = mysqli_num_rows($result);

            if ($results) {
                $errors['exists'] = "That email address is already registered.";
            }
            else {
                $firstName = mysqli_real_escape_string($link, $firstName);
                $lastName = mysqli_real_escape_string($link, $lastName);
                $email = mysqli_real_escape_string($link, $email);
                $password = md5(md5($email).$password);

                $query="INSERT INTO `Users` (`FirstName`, `LastName`, `Email`, `Password`, `IsRater`, `IsRatee`) VALUES('$firstName', '$lastName', '$email', '$password', '1', '1');";

                if(!mysqli_query($link, $query)) {
                    $errors['SQLQuery'] = "Failed SQL Insert" . mysqli_error($link);
                }
                else
                {
                    $data['success'] = true;
                    $data['message'] = 'Your account has been created!';
                }
            }
        }

        if(!empty($errors)) {
            $data['success'] = false;
            $data['errors'] = $errors;
        }
    }

    echo json_encode($data);
?>

A: The PHP code checks whether $_POST['submit'] is set before doing anything with the form data, but you never set that in formData. Try:
    var formData = {
        'firstName': $('input[name=firstName]').val(),
        'lastName': $('input[name=lastName]').val(),
        'email': $('input[name=email]').val(),
        'password': $('input[name=password]').val(),
        'submit': 'on'
    };


text:
Q: Are there any configuration settings for file upload with Sitecore Web Forms For Marketers? Is it possible to configure

*

*where a file is uploaded to (it's currently being upload direct to the media library)

*how a file is displayed in the Form Report (currently a long link string that can't be easily read nor clicked on)

*which file types are allowed (e.g. images only)

*how the file will be forwarded by email

We have a multi-site solution, so ideally we'd like to be able to set these on a form by form basis, but be able to configure defaults as Solution Default > Site default > Form specific.
I've already seen that there are code examples for limiting file size, which is something else we'd like to do.
So are any of these directly configurable, or will we need to code them?
Edit:
Web Forms For Marketers  2.3.0 rev.131126
Running on Sitecore 7.0 rev. 140120 (7.0 Update-4).

A: Yes you can define path where file will upload in case of file field.
Please see attached screenshot.

A: All file upload settings are located under:
/sitecore/System/Modules/Web Forms for Marketers/Settings/Field
Types/Simple Types/File Upload
The pipeline ran when a file is uploaded is "formUploadFile"; so you could reflector existing one and amend to add required changes.

A: To upload allowed file types use below link.
http://sitecorejunkie.com/2014/06/16/restrict-certain-files-from-being-uploaded-through-web-forms-for-marketers-forms-in-sitecore-an-alternative-approach/
here you can get idea that how you can restrict mime types in WFFM.
To send attachment in email you can create custom send email action in Sitecore and use below code
// send email with attachments
public static bool SendEmailWithAttachments(string To, string From, string Subject, string Message, string atchmnt1, string atchmnt2, string atchmnt3) {
    bool result = true;
    try {
        MailMessage mailMsg = new MailMessage();
        // mailaddress of sender
        MailAddress mailFrom = new MailAddress(From);
        mailMsg.From = mailFrom;
        // mail addresses for recipients
        string[] mailAddressList = To.Split(',');
        foreach (string str in mailAddressList) {
            try {
                MailAddress mailTo = new MailAddress(str.Trim());
                mailMsg.To.Add(mailTo);
            }
            catch { }
        }
        mailMsg.Subject = Subject;
        mailMsg.Body = Message;
        mailMsg.IsBodyHtml = true;
        if (!string.IsNullOrEmpty(atchmnt1)) {
            mailMsg.Attachments.Add(ReadAttachment(atchmnt1));
        }
        if (!string.IsNullOrEmpty(atchmnt2)) {
            mailMsg.Attachments.Add(ReadAttachment(atchmnt2));
        }
        if (!string.IsNullOrEmpty(atchmnt3)) {
            mailMsg.Attachments.Add(ReadAttachment(atchmnt3));
        }
        var smtp = new SmtpClient(Sitecore.Configuration.Settings.MailServer, Sitecore.Configuration.Settings.MailServerPort);
        smtp.Send(mailMsg);
    }
    catch {
        result = false;
    }
    return result;
}
// get attachement by media item id
public static Attachment ReadAttachment(string value) {
    MediaItem mediaItem = null;
    ItemUri itemUri = ItemUri.Parse(value);
    if (itemUri != null) {
        Item item = Database.GetItem(itemUri);
        if (item != null) {
            mediaItem = new MediaItem(item);
        }
    }
    // create attachment using media item properties
    Attachment attachment = new Attachment(mediaItem.GetMediaStream(), string.Join(".", new string[] { mediaItem.Name, mediaItem.Extension}), mediaItem.MimeType);
    return attachment;
}


text:
Q: Windows грузит процессор во время простоя По неизвестным для меня причинам, Windows грузит процессор во время простоя. Компьютер гремит как паровоз, на мои действия реагирует или с очень длительными задержками или не реагирует вообще. При этом обновления я приостановил через параметры. Что может так нагружать процессор особенно во время простоя? Во время работы таких приколов не было? ОС Windows 10 Enterprise LTSC. В активном режиме работает только касперский, но никакой активности с его стороны в момент простоя не было. Вирусов на компьютере тоже нет.
Помогите, пожалуйста

A: Смотрим процесс который загружает систему. Если процесс не системный, то идём по его адресу и выкладываем на VirusTotal на анализ. Если же это системный процесс то возможны 2 варианта:

*

*Так работает ОС. Возможно выполняет фоновые операции, а Win10 любит делать что-то на фоне, например кушать вашу ОЗУ.

*Это зловред(возможно майнер). Оно прописывается у вас в системном процессе(обычно это может быть svchost.exe) и занимается гадкой деятельностью. Убивать svchost - плохая идея, вместе с ним упадёт система. Тут только выискивать подозрительные приложения.

A: Вариант 1: Проверить систему другим антивирусом (желательно в безопасном режиме и другим антивирусом). Как это делается, можно легко нагуглить. Возможно засел какой-то майнер, который не видится Касперским.
Вариант 2: Win10 очень любит в режиме простоя оптимизировать компьютер: производить дефрагментацию жесткого диска, перестраивать индексы, сканировать встроенным защитником файлы и т.д. (решение частично пересекается с вариантом 3, но так же гуглится способы отключения)
Вариант 3: Если в диспетчере задач необходимо посмотреть, что загружает процессор. Если что-то похожее на ntoskrnl.exe, тогда вам сюда: https://fossbytes.com/how-to-fix-high-ram-and-cpu-usage-of-windows-10-system-ntoskrnl-exe-process/ или сюда https://mywebpc.ru/windows/ntoskrnl-exe-system-gruzit-cpu-pamyat-windows-10/
Возможны и другие варианты, т.к. слишком мало входной информации.


text:
Q: Cant import file in typescript in React I am getting much errors like :
Compiled with problems:
ERROR in ./src/components/SearchSMS/Letters.tsx 122:71-81

export 'default' (imported as 'ChatWindow') was not found in './ChatWindow.js' (possible exports: __esModule)

But my PHPStorm IDE doesnt show my any error. And i made import properly.
Like :
import ChatWindow, {messageI} from "./ChatWindow";
or
import ChatWindow, {messageI} from "./ChatWindow.js";

export default function ChatWindow(props: propsI) {
...
}

my package.json looks like :
{
  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.4",
    "@types/react-router": "^5.1.20",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.3.0",
    "react-scripts": "^5.0.0",
    "web-vitals": "^3.0.0"
  },
  "scripts": {
    "start": "react-scripts --openssl-legacy-provider start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@types/node": "^18.13.0",
    "@types/react-dom": "^18.0.10",
    "ts-migrate": "^0.1.35",
    "typescript": "^4.9.5"
  }
}

my tsconfig.json looks like
{
{
  "compilerOptions": {

    "plugins": [{ "name": "typescript-plugin-css-modules" }],

    "target": "ES2018",
    "jsx": "preserve",

    "module": "CommonJS",

    "outDir": "./build",

    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,

    "strict": true,

    "skipLibCheck": true,
     //and others commented settings
  },
  "exclude": ["node_modules"],
  "lib": ["esnext"],
  "ts-node": {
    "esm": true
  }
}

I tried to move from js to typescript in my project.
Actually, i even don't see compiled files when i delete and try.
tsc
or
npx tsc

A: I found cause of my problem. This was because "ts-migrate" package build
every single ts-tsx file right in same place. And when i import the file, it gets imported not from ts file, but from bad or old built js file.
Imagine you have Home.ts and Home.js file, and when you make
import Home from './Home';

you get import from Home.js, but not Home.ts


text:
Q: Psql \i  How to get around the permission denied error when reading from a file on Windows 10? Operating system: Windows 10
Database: Postgres 13
When trying to execute an sql file mydatabase=>\i C:\tmp\sqlfile.sql I get a

C:: Permission denied

error. The file permissions have been set to read / write for all. No matter where I put the file, bin directory, public directory, tmp directory, I get the same error.
I have created a user bill and log in as Bill, and I still get the same error. The '\' has been replaced with '/' with no success. The postgres account does not work either.
Is there a system setting that needs to be set to allow Postgres to read a file?


text:
Q: alertdialog problems with item divider I am having a problem with alert dialog.  When I create an alert dialog, the default behavior is to display without a divider. I want to get something exactly like the image below

My code is displaying something different like an extra line at the bottom of last list item which I don't want.
 AlertDialog.Builder builder = new AlertDialog.Builder(context);
        AlertDialog alertDialogObject = builder.create();
        builder.setItems(valueList, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
                editField.setText(valueList[item]);
                editField.setError(null);
                editField.requestFocus();
            }
        });
        alertDialogObject = builder.create();
        ListView listView=alertDialogObject.getListView();
        listView.setDivider(new ColorDrawable(Color.LTGRAY)); // set color
        listView.setDividerHeight(2); // set height
        alertDialogObject.show();

Can someone help with this? I want to get dialog alert like the first picture above?

A: It looks like a footer decoration in a ListView, so try to disable footer dividers, then add an empty footer, it should remove the line from the bottom:
listView.setFooterDividersEnabled(false);
listView.addFooterView(new View(context));

A: Here's an example with a divider
//create dialog
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setTitle(title);
    builder.setItems(valueList, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int item) {
            //do something
        }
    });
    AlertDialog alert =builder.create();
    //set dividers
    ListView listView =alert.getListView();
    listView.setDivider(context.getResources().getDrawable(R.drawable.extraDull));
    listView.setDividerHeight(1);
    //show
    alert.show();

Notice the difference in this code with what you have... look near builder.create()
also you could add this to your color folder
<drawable name="extraDull">#808080</drawable>


text:
Q: Eclipse IDE Error code -13 Hey guys I'm having some problems with Eclipse. Here's a screen:

Here's my error log and .ini:
http://pastebin.com/VZ8pf6s9
I have JDK and JRE version 1.8

A: You have a 64-bit Eclipse and a 32-bit JRE (in C:\Program Files (x86)\Java\jre1.8.0_45) . They have to match. I suggest you get the 32-bit Eclipse as it's something you unzip rather than uninstall/install.


text:
Q: regex validation using javascript - French Alphabets not working in IE6 We have HTML form which will allow french alphabets. So we have added validation to check only alphabets and not numbers. We have used regular expression to achieve this using
javascript validation. I have pasted the regex code below for reference.
I have used below options to check alphabets that include french alphabets
[^A-Za-zA-ÿ\\s]

[^A-ÿ\\s]

It works fine in all modern browsers. But in ie6 it is not working.
In IE6 i got below error message:
"Invalid range in character set"
Is there any other solution to fix the above problem. Also please let me know if u need any other details.

A: "french alphabet" doesn't include all character from A to ÿ but only:
dec  char
128  Ç
129  ü
130  é
131  â
133  à
135  ç
136  ê
137  ë
138  è
140  î
144  É
145  æ
146  Æ
147  ô
150  û
151  ù

These 3 are not in ascii table:
œ
Œ
È

A: Detect browser version and write the regex (for user can enter characters only and not numbers) in reverse like [0-9] for ie6.
if ($.browser.msie && $.browser.version.substr(0,1)<7) {
      regex here
}

A: Don't think you want A through ÿ, as there's a lot of characters in that range, like "÷".  Otherwise, I would hope that IE6 supports denoting Unicode characters like so: "ÿ" = \u00FF.
Edit: (Oh wait, you're excluding [A-ÿ]? I'm confused.)


text:
Q: How can i build my own font-size selection plugin in tinyMCE 4.x? I want to build a font-size selection plugin with TinyMce 4 editor. I also want to add vertical jquery slider with input box so that user can easily change font-size or can also able to change manually by adding font-size in input box.
Anyone has any idea about this how can i build a plugin for it???
Please see the attached snap.
SNAP:
Click Here View Snap
I have tried to add slider like a button but it does not seem to work.
OR
Is there any plugins like that which can be installed with TinyMce?


text:
Q: How to avoid NaN in a time series model I build a time series model in microsoft analysis service 2008 r2. There is no problem to create the model and process. But when I make a pridiction query, there is NaN in the result. How can I avoid this? If there is no way to avoid the NaN, how can I save the result to SQL server? I used SQLBulkCopy class to insert the data into SQL table for better performance. Any suggestion is appreciate but need have good performance. The predication result is big. It has around 5 milion rows of data.
Does anybody have a good suggestion?


text:
Q: wkhtmltopdf not found - Golang Ubuntu After trying lot of solutions for this error, I am posting this issue here. I have written a  method which converts html to pdf and returns pdf bytes as output.
import (
"bytes"
"github.com/SebastiaanKlippert/go-wkhtmltopdf"
)

func HtmlToPdf(htmlData *string) ([]byte, error) {
pdfg, err := wkhtmltopdf.NewPDFGenerator()
if err != nil {
    return nil, err
}
pdfg.AddPage(wkhtmltopdf.NewPageReader(bytes.NewReader([]byte(*htmlData))))
//nolint: gomnd
pdfg.Dpi.Set(600)
jb, err := pdfg.ToJSON()
if err != nil {
    return nil, err
}
pdfgFromJSON, err := wkhtmltopdf.NewPDFGeneratorFromJSON(bytes.NewReader(jb))
if err != nil {
    return nil, err
}

err = pdfgFromJSON.Create()
if err != nil {
    return nil, err
}
pdfBytes := pdfgFromJSON.Bytes()

return pdfBytes, nil }

Calling this method returns error wkhtmltopdf not found
I have tried the following solutions

*

*which wkhtmltopdf
/usr/local/bin/wkhtmltopdf
and then setting the WKHTMLTOPDF_PATH: /usr/local/bin/wkhtmltopdf in environment section of my code

*Using setPath at the top of HtmlToPdf Method like
wkhtmltopdf.SetPath("/usr/local/bin/wkhtmltopdf")
In this case the error changes to fork/exec /usr/local/bin/wkhtmltopdf: no such file or directory

*Also tried after moving the wkhtml files to /usr/local/go/bin/ and using path
/usr/local/go/bin/wkhtmltopdf

*Converting any url to pdf using command line also works fine.
Note : Hitting wkhtmltopdf --version in terminal gives wkhtmltopdf 0.12.6 (with patched qt) and package is installed using go get github.com/SebastiaanKlippert/go-wkhtmltopdf
Any other solutions?

A: hello in my case u should install wkhtmltopdf ,but if u are using MacOS so just install on terminal

brew install wkhtmltopdf

and make sure path directory same like you installed wkhtmltopdf


text:
Q: IIS rewrite rule with HTTP status code 301 I need to write a IIS rewrite rule which matches the following condition

*

*example.com

*www.example.com

*http://www.example.com

*https://www.example.com

*http://example.com

*https://example.com
this all should redirect to https://www.example.com/somepage/
The condition is that from SEO point of view only one 301 redirection should be identified. Any pointer is appreciated
Following redirection were tried works but leads to two hops instead of one
    <rule name="no path" enabled="true" patternSyntax="ECMAScript" stopProcessing="true">
      <match url="(.*)" />
      <conditions>
        <add input="{REQUEST_URI}" pattern="^\/?$" ignoreCacom="true" />
        <add input="{HTTP_HOST}" pattern="^(www.)?example.com$" ignoreCacom="true" />
      </conditions>
      <action type="Redirect" url="https://www.example.com/somepage" redirectType="Permanent" />
    </rule>
    <rule name="with path and http" enabled="true" patternSyntax="ECMAScript" stopProcessing="true">
      <match url="(.*)" />
      <conditions>
        <add input="{PATH_INFO}" pattern="\/somepage" negate="true" ignoreCacom="true" />
        <add input="{REQUEST_URI}" pattern="^\/.+$" ignoreCacom="true" />
        <add input="{HTTP_HOST}" pattern="^(www.)?example.com$" ignoreCacom="true" />
        <add input="{HTTPS}" pattern="^OFF$" />
      </conditions>
      <action type="Redirect" url="https://www.example.com{REQUEST_URI}" redirectType="Permanent" />
    </rule>
    <rule name="with path and https" enabled="true" patternSyntax="ECMAScript" stopProcessing="true">
      <match url="(.*)" />
      <conditions>
        <add input="{PATH_INFO}" pattern="\/somepage" negate="true" ignoreCacom="true" />
        <add input="{REQUEST_URI}" pattern="^\/.+$" ignoreCacom="true" />
        <add input="{HTTP_HOST}" pattern="^example.com$" ignoreCacom="true" />
        <add input="{HTTPS}" pattern="^ON$" />
      </conditions>
      <action type="Redirect" url="https://www.example.com{REQUEST_URI}" redirectType="Permanent" />
    </rule>
    <rule name="with somepage, no www" enabled="true" patternSyntax="ECMAScript" stopProcessing="true">
      <match url="(.*)" />
      <conditions>
        <add input="{PATH_INFO}" pattern="\/somepage" ignoreCacom="true" />
        <add input="{HTTP_HOST}" pattern="^example.com$" ignoreCacom="true" />
      </conditions>
      <action type="Redirect" url="https://www.example.com{REQUEST_URI}" redirectType="Permanent" />
    </rule>
    <rule name="with somepage and https, no www" enabled="true" patternSyntax="ECMAScript" stopProcessing="true">
      <match url="(.*)" />
      <conditions>
        <add input="{PATH_INFO}" pattern="\/somepage" ignoreCacom="true" />
        <add input="{HTTP_HOST}" pattern="^www.example.com$" ignoreCacom="true" />
        <add input="{HTTPS}" pattern="^OFF$" />
      </conditions>
      <action type="Redirect" url="https://www.example.com{REQUEST_URI}" redirectType="Permanent" />
    </rule>

enter code here

A: Are these rules achieve your requirement?
With this rule order. http(s)://(www.)example.com/a.aspx with path will be redirected to https://www.example.com/a.aspx
https://www.example.com/a.aspx will not be redirected to avoid infinite redirection loop.
http(s)://(www.)example.com/  will be redirected to https://www.example.com/somepage.
Since it is impossible to merge everything into a rule. We need at least 3 rule to achieve this.
   <rule name="https://www.example.com">
                    <match url="(.*)" />
                    <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
                        <add input="{REQUEST_URI}" pattern="^/.+$" />
                        <add input="{HTTP_HOST}" pattern="www.example.com" />
                        <add input="{HTTPS}" pattern="^on$" />
                    </conditions>
                    <action type="None" />
                </rule>
                <rule name="no path" stopProcessing="true">
                    <match url="(.*)" />
                    <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
                        <add input="{URL}" pattern="^(/)?$" />
                        <add input="{HTTP_HOST}" pattern="^(www\.)?example.com$" />
                    </conditions>
                    <action type="Redirect" url="https://www.example.com/somepage/" />
                </rule>
                <rule name="with path" stopProcessing="true">
                    <match url="(.*)" />
                    <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
                        <add input="{REQUEST_URI}" pattern="^/.+$" />
                        <add input="{HTTP_HOST}" pattern="^(www\.)?example.com$" />
                        <add input="{REQUEST_URI}" pattern="^/somepage" negate="true" />
                    </conditions>
                    <action type="Redirect" url="https://wwww.example.com{REQUEST_URI}" />
                </rule>


text:
Q: Showing a function is not Riemann integrable Let $m,n \in \mathbb{Z_{+}}$ and let $f(x)=\begin{cases} x^m+x^n \text{ if } x \in [0,1]\cap\mathbb{Q}\\ 0 \text{ if } x \in [0,1] \setminus \mathbb{Q} \end{cases}$.
I thought of a similar function $f(x)=\begin{cases} x^m \ \text{ if } x \in [0,1]\cap\mathbb{Q}\\ 0 \text{ if } x \in [0,1] \setminus \mathbb{Q} \end{cases}$.
I've shown the second function is not Riemann integrable.  I was trying to produce a similar argument, but I was told it was not so straightforward.

A: Show that the set of discontinuity points of $f$ carries full mass of $1$, and thus $f$ is not Riemann integrable.
First, consider $x\in(0,1]\cap \mathbb{Q}$. Now $f(x)=x^{n}+x^{m}:=r>0$ and thus $0\notin B(f(x),r)$, where $B(a,r)$ denotes the open $r$-radius ball around $a$. But $B(x,\epsilon)\cap ([0,1]\setminus\mathbb{Q})\neq\emptyset$ for all $\varepsilon>0$, so $f(B(x,\varepsilon))\not\subseteq B(f(x),r)$ for every $\varepsilon>0$, as $f(y)=0$ for all $y\in [0,1]\setminus\mathbb{Q}$. Hence $f$ is not continuous at $x$.
Consider then $x\in [0,1]\setminus\mathbb{Q}$ and a sequence $(q_{i})_{i=1}^{\infty}\subseteq [0,1]\cap\mathbb{Q}$ so that $q_{i}\to x$. Now $f(q_{i})=q_{i}^{m}+q_{i}^{n}\to x^{m}+x^{n}\neq 0=f(x)$, which shows that $f$ is not continuous at $x$.
We have shown that the discontinuity points of $f$ contains $(0,1]$, which has Lebesgue measure of $1$, and thus $f$ is not Riemann integrable.

A: If it is riemann integrable then integral must be $0$ (why?), so $\int_{0}^{1} (x^m+x^n)dx=0$ so $\frac{1}{m+1}+\frac{1}{n+1}=0$ so $m+n+2=0$


text:
Q: having a hidden swf Is there a way to have a hidden swf ( flex application ) on a page and still have it be reachable from javascript and debuggable from flash builder?  I have need to use flash to manipulate js but it needs to be reachable from js to be started.

A: I don't know if you have some other meaning in mind when you say "hidden" (if so, please explain) but if you simply mean an invisible element on the page, then sure. Just set the width and height tiny in the embed tags, and don't put any graphics in the swf.
User ExternalInterface to communicate back and forth between JavaScript an a swf embedded on the page.

A: as below:
<div style="position:absolute;top:100px;left:0;width:1px;height:1px;z-index:1">
<embed pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="1" height="1" flashvars="local=true&&refererdomain=yinyuetai.com" bgcolor="#FF0000" allowfullscreen="true" allowscriptaccess="always" wmode="window" id="" name="" src="flashlocalstorage.swf?rev">
</div>

the embed(in IE is:object) set: width:1px;height:1px, and the parent element set: position:absolute;top:;left:;.
It isn't complete disappear, but in common condition no one can find it.


text:
Q: Getting 500 error while requesting to webservice using Ajax AutoCompleteExtender Scenario:
I'm working on a webform(MVC) project in which I had to use Web Service in Ajax AutoCompleteExtender control for searching purpose. First of all I checked HelloWorld() service which is working fine but when I create my custom web service named as GetParentID and make a request on it. It shows me 500 error message which is defined in below snap:

Below is my Default.aspx.cs code:
 <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<ajaxToolkit:AutoCompleteExtender
    ID="AutoCompleteExtender1"
    runat="server"
    ServiceMethod="GetParentID"
    ServicePath="~/Services.asmx"
    TargetControlID="TextBox1"
    MinimumPrefixLength="1"
    UseContextKey="false"
    CompletionInterval="0"
    EnableCaching="true"
    CompletionSetCount="30"
    FirstRowSelected="true">

</ajaxToolkit:AutoCompleteExtender>

Below is my Service.asmx.cs code:
[System.Web.Script.Services.ScriptMethod()]
    [System.Web.Services.WebMethod]
    public string[] GetParentID(string prefixText, int count)
    {
        DataTable dt = new DataTable();
        DataColumn dc = new DataColumn("Name", typeof(String));
        dt.Columns.Add(dc);

        DataRow dr = dt.NewRow();

        dr[0] = "Adil";
        dr[0] = "Ahmer";
        dr[0] = "Kamran";
        dr[0] = "Fasih";
        dr[0] = "Azeem";
        dr[0] = "Rana";
        dr[0] = "Humza";
        dr[0] = "Waleed";
        dr[0] = "Faizan Rafiq";
        dr[0] = "Mohsin";
        dr[0] = "Ahsan";
        dr[0] = "Arshad Ahmed";
        dr[0] = "Uncle Majboor";

        dt.Rows.Add(dr);

        //DataTable dt = null;
        DataView dv = null;
        List<string> suggestions = new List<string>();
        //dt = (DataTable)HttpContext.Current.Session["ParentID"];

        if ((dt != null))
        {
            dv = dt.Copy().DefaultView;
            dv.RowFilter = "Name like  '%" + prefixText + "%' ";
            dv.Sort = "ID Asc";

            string c = prefixText;
            double Num = 0;
            bool isNum = double.TryParse(c, out Num);
            int indx = 0;

            foreach (DataRowView dvr in dv)
            {
                if (indx <= count)
                {
                    suggestions.Add(AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(dvr["Name"].ToString(), dvr["Name"].ToString()));
                    indx += 1;
                }

            }
        }
        return suggestions.ToArray();
    }

I don't know how to deal with asmx web services. This is my first try. Mostly I make a request using javascript / jquery ajax calls. Below is my prerequisites which I'm using in my this application. Also I attached complete github repository link so you guys easily help me on this matter.
github
Solution created on VS 2013
Dot net framework 4.5
AjaxControlToolKit
AjaxControlToolkit.Installer.17.1.1.0

A: That is because you are calling that web method using AJAX. Only Web services with a [ScriptService] attribute on the class definition can be called from script.
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
//    [System.Web.Script.Services.ScriptService]

So just uncomment the line and it will start working.
[System.Web.Script.Services.ScriptService]


text:
Q: Check if string contact value from array I have two arrays like this:
var code = ["MDLS", "MS03", "MS04", "MDLX", "MDL3", "MDLY"]
var text = ["Tesla Model S", "Tesla Model S", "Tesla Model S", "Tesla Model X", "Tesla Model 3", "Tesla Model Y"]
var myString = String()

Normally I do this to check if a it contains what I am looking for:
if let value = data[indexPath.row].optionCodes?.contains("MDL3") {
    if value == true {
        print("Yes, optionCodes contains MDL3")
        myString = "Tesla Model 3"
    } else {
        print("No")
    }
}

if let value = data[indexPath.row].optionCodes?.contains("MS03") {
    if value == true {
        print("Yes, optionCodes contains MS03")
        myString = "Tesla Model S"
    } else {
        print("No")
    }
}

... and so on

In stead of wring a whole bunch of if let checks, how can I do all of these in one?

A: I would make a dictionary.
let code = ["MDLS", "MS03", "MS04", "MDLX", "MDL3", "MDLY"]
let text = ["Tesla Model S", "Tesla Model S", "Tesla Model S", "Tesla Model X", "Tesla Model 3", "Tesla Model Y"]
let d = Dictionary(uniqueKeysWithValues: zip(code,text))

After that, it's basically a one-liner: just look up your code in the dictionary:
let testtext = "MDL3"
if let result = d[testtext] {
    print("got it!", result)
}

You can do your contains thing by looping thru d.keys.


text:
Q: Runtime Exception Nativescript-Angular I am a newbie to nativescript-angular though I exhibit proficiency in Angular2 owing to a number of developed applications.
I am using this sidedrawer which comes with home, about, and contact component.
In addition I created a search component that will be responsible for accepting user input and search specific search engines for the search term.
I successfully ran my nativescript app on an android connected device (Lollipop) however I get:

*

*D/AccessibilityManager(17308): at com.tns.Runtime.callJSMethodNative(Native Method)

*When I navigate to the search component, the search component stays for a couple of seconds (say 2 seconds) and returns to the home component by itself.

The following highlights my configurations
Android build tools: 25.0.0
Typescript: 2.0.9
The latest nativescript modules
What I have done so far (removed and reinstall):
node_modules
hooks
platform android
BUILD SUCCESSFUL
Total time: 6 mins 10.37 secs
Project successfully built
Successfully deployed on device with identifier 'I7LVZ97L99999999'.
D/dxoptimizer.hcq( 1100): Got unexpected exception:
java.io.WriteAbortedException: Read an exception;
java.io.NotSerializableException: org.json.JSONObject
D/dxoptimizer.hcq( 1230): Got unexpected exception:
java.io.WriteAbortedException: Read an exception;
java.io.NotSerializableException: org.json.JSONObject
D/AccessibilityManager(17308): at com.tns.Runtime.callJSMethodNative
(Native Method)
D/AccessibilityManager(17308): at
com.tns.Runtime.dispatchCallJSMethodNative(Runtime.java:865)
D/AccessibilityManager(17308): at
com.tns.Runtime.callJSMethodImpl(Runtime.java:730)
D/AccessibilityManager(17308): at
com.tns.Runtime.callJSMethod(Runtime.java:716)
D/AccessibilityManager(17308): at
com.tns.Runtime.callJSMethod(Runtime.java:697)
D/AccessibilityManager(17308): at
com.tns.Runtime.callJSMethod(Runtime.java:687)
JS: Angular 2 is running in the development mode.
Call enableProdMode() to enable the production mode.
D/dxoptimizer.hcq( 1100): Got unexpected exception:
java.io.NotSerializableException: org.json.JSONObject
java.io.WriteAbortedException: Read an exception;
D/dxoptimizer.hcq( 1230): Got unexpected exception:
java.io.WriteAbortedException: Read an exception;
java.io.NotSerializableException: org.json.JSONObject
JS: result: 0
D/dxoptimizer.hcq( 1230): Got unexpected exception:
java.io.WriteAbortedException: Read an exception;
java.io.NotSerializableException: org.json.JSONObject
D/dxoptimizer.hcq( 1100): Got unexpected exception:
java.io.WriteAbortedException: Read an exception;
java.io.NotSerializableException: org.json.JSONObject
D/dxoptimizer.hcq( 1230): Got unexpected exception:
java.io.WriteAbortedException: Read an exception;
java.io.NotSerializableException: org.json.JSONObject
D/dxoptimizer.hcq( 1100): Got unexpected exception:
java.io.WriteAbortedException: Read an exception;
java.io.NotSerializableException: org.json.JSONObject
D/dxoptimizer.hcq( 1230): Got unexpected exception:
java.io.WriteAbortedException: Read an exception;
java.io.NotSerializableException: org.json.JSONObject

******SEARCH COMPONENT *********

export class SearchComponent implements OnInit {

private text: string = 'Search Page';
private resultList: Array; //Holds the returned search results
private metaData: any; //Holds data necessary for paginating search results
private query: string;
private isLoading: boolean;
private database: any;
private isEditing: boolean;

constructor( private location: Location,private page: Page,private
routerExtensions: RouterExtensions, private webService: WebService){
this.isLoading = false;
this.query = "";
this.resultList = [];
//this.resultList = JSON.parse(ApplicationSettings.getString("resultList","
[]"));
console.log("result: "+this.resultList.length);

//Called on navigate back because constructor does not get called
on navigate back
//this.location.subscribe((path)=>{
//this.resultList = JSON.parse(ApplicationSettings.getString
("resultList"," []"));
//});
}
ngOnInit(){

  this.isEditing = true;
}

navBack(){
this.hideKeyboard();
this.routerExtensions.backToPreviousPage();
}

hideKeyboard(){
let searchBar = this.page.getViewById("searchBox");
setTimeout(function(){
searchBar.dismissSoftInput();
}, 100);
}
search(){

//var textview: TextView = <TextView> args.object;
//if(isAndroid){
//textview.android.clearFocus();
//}
this.hideKeyboard();
this.isLoading = true;
this.text = "searching";

 permissions.requestPermission("android.Manifest.permission.INTERNET"
 ,"INTERNET PERMISSION NEEDED")
       .then(()=>{
                  this.webService
                      .googleSearch(this.query)
                      .subscribe( (resp:Response) => {
                                      this.resultList = resp.json().items;

                                      console.log(this.resultList);

                                      this.metaData = resp.json().queries;

                                      console.log(this.metaData);
                                      this.text = "Finished Searching!!!";
                                      this.isLoading = false;
                                      this.isEditing = false;
                                     },
                            err => {
                                    console.log(err);
                                    alert(JSON.stringify(err));
                             }
                         );
       })
       .catch(()=>{
         this.text = "No Permissions";
       })
}

onCancel(){
this.query = "";
this.navBack();
}

onItemTap(){

ApplicationSettings.setString("resultList",JSON.stringify(this.resultList));
//Navigate to details view
}
}


text:
Q: Implementing testing automation for asp.net I have planned to implement automated testing for our web application .I want the tool to be open source, test cases should be written in C sharp.
So i choose to use selenium Web-driver and N-unit. I have a set of questions.
Can i only unit testing with this setup? Cannot do function testing?

A: I'll avoid answering your first question as it's not suited for StackOverflow :)

Can i only unit testing with this setup? Cannot do function testing?

You can use Selenium with a wide range of tasks.

*

*I started off doing unit testing of individual components of our web application.

*Then I moved on to functionally testing the end-to-end behavior.

*Currently I'm doing massive stress testing with hundreds of concurrent browser sessions.

All using Selenium.

Should i have to write all test cases as methods?

As far as I know (and I don't know a lot), the most flexibility is attained when you conceptualize your testing architecture this way.


text:
Q: IE9 simple click/scroll issue Personally, I am not experiencing this issue (Windows 7 with native IE9) but another computer is. Possibly Windows 7 but definitely IE9. Initially, the scroll buttons do not work on their machine. If they change their document and browser renderer to IE8 or IE7 if works fine then. If they change it back to IE9, it works. If they close out of the tab and reopen it fresh, it doesn't work again. Their console log is empty except for a syntax error deep within jQuery 1.4 which appears in all browsers and which I THINK is benign.
So my question is, can anyone replicate the issue or can find any reason why this is happening? Code and link to follow:
http://www.friedmanllp.com/home2.php

$(function() {
    var ele   = $('#scroller');
    var speed = 25, scroll = 5, scrolling;

    $('#scroll_up').click(function() {
        //console.log("Up");
        // Scroll the element up

        var topPos = $('#scroller').scrollTop();
        console.log(topPos);
        $("#scroller").animate({
            scrollTop: topPos - 200
        }, 800);
    });

    $('#scroll_down').click(function() {
        //console.log("Down");
        // Scroll the element down

        var topPos = $('#scroller').scrollTop();
        console.log(topPos);
        $("#scroller").animate({
            scrollTop: topPos + 200
        }, 800);
    });

    $('#scroll_up, #scroll_down').bind({
        click: function(e) {
            // Prevent the default click action
            e.preventDefault();
        },
        mouseleave: function() {
            if (scrolling) {
                window.clearInterval(scrolling);
                scrolling = false;
            }
        }
    });
});

A: You should try removing (or commenting out) any console.log() references in your code.
Without developer tools open IE will throw a fit as the console doesn't exist. With developer tools open the console DOES exist so no errors are thrown. I once spent a loooong time trying to debug a similar issue :)


text:
Q: Need Help For Foreign Key         db.execSQL(" CREATE TABLE " + KK_AIRLINEBOOK + " (" + KEY_ID
                + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_SrNo + " INTEGER, " + KEY_BNAME + " TEXT , "
                 + KEY_Bookingdate
                + " TEXT, " + KEY_Pickupaddress + " TEXT, " + KEY_City
                + " TEXT, " + KEY_AirportType + " TEXT, "+ KEY_Trip + " TEXT, " + KEY_Cabr + " TEXT , "
                + KEY_FlightDate + " TEXT, " + KEY_FlightTime + " TEXT, " + KEY_CabDate
                + " TEXT, " + KEY_PickupTime + " TEXT, " + KEY_TotalSeats
                + " INTEGER, " + KEY_Charges + " INTEGER , "
                +  "FOREIGN KEY ," + KEY_SrNo + " REFERENCES  KK_REGISTRATION , " + KEY_ID +");");

Log Cat:
05-04 20:06:36.034: E/SQLiteLog(26155): (1) near ",": syntax error
05-04 20:06:36.364: E/AndroidRuntime(26155): FATAL EXCEPTION: main
05-04 20:06:36.364: E/AndroidRuntime(26155): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.raintek.customerhome/com.raintek.customerhome.Login}: android.database.sqlite.SQLiteException: near ",": syntax error (code 1): , while compiling: CREATE TABLE Airline (id INTEGER PRIMARY KEY AUTOINCREMENT, srno INTEGER, bname TEXT , bookingdate TEXT, pickupaddress TEXT, city TEXT, AirportType TEXT, trip TEXT, cab TEXT , flightdate TEXT, flighttime TEXT, cabdate TEXT, pickuptime TEXT, totalseats INTEGER, charges INTEGER , FOREIGN KEY ,srno REFERENCES  KK_REGISTRATION , id);
05-04 20:06:36.364: E/AndroidRuntime(26155):    at dalvik.system.NativeStart.main(Native Method)
05-04 20:06:36.364: E/AndroidRuntime(26155): Caused by: android.database.sqlite.SQLiteException: near ",": syntax error (code 1): , while compiling: CREATE TABLE Airline (id INTEGER PRIMARY KEY AUTOINCREMENT, srno INTEGER, bname TEXT , bookingdate TEXT, pickupaddress TEXT, city TEXT, AirportType TEXT, trip TEXT, cab TEXT , flightdate TEXT, flighttime TEXT, cabdate TEXT, pickuptime TEXT, totalseats INTEGER, charges INTEGER , FOREIGN KEY ,srno REFERENCES  KK_REGISTRATION , id);

how to use foreign key in android sqlite this is my code but it shows syntax error near "FOREIGN KEY" what is wrong in above code please help me
Thank You

A: The format for FOREIGN KEY is as follows:
FOREIGN KEY(srno) REFERENCES KK_REGISTRATION(id)

You have commas.


text:
Q: new macbook - trying to run Rails, now I get "internal:gem_prelude>:1:in `require': cannot load such file -- rubygems.rb (LoadError)" I bought a new Macbook Pro and used migration assistant to move from my old iMac.
When I try to run Rails or even bundle install, I get:
internal:gem_prelude>:1:in `require': cannot load such file -- rubygems.rb (LoadError)
from <internal:gem_prelude>:1:in `<compiled>'

I do get the following:
$ ruby -v
ruby 1.9.3p374 (2013-01-15 revision 38858) [x86_64-darwin12.2.0]

My user on the iMac was burtondav, on the Macbook Pro it is davidburton.  I don't know if that's the cause.
Thanks for the help!

A: Try to go throught the informations provided here http://docs.rubygems.org/read/chapter/3

A: You may try symlinking
ln -s /Users/davidburton /Users/burtondav

but a proper solution would be to reinstall ruby & rubygems.


text:
Q: How to increment the count value in DB when button is clicked in laravel? I have Home.blade.php when I click the vote button in that page, the count value should increment in the candidate table.
Here my Home.blade.php
@foreach ($file as $show)

President

Name : {{$show->name}}

                                 <button type="button" class="vote">VOTE</button>

      @endforeach

I have table name called the candidate, when vote button is clicked, the count should be incremented in database. And i have controller called HomeController pls help me.
Thank you
class Homecontroller extends Controller
{
    public function pre()
    {
         $file = DB::table('candidate')
                     ->select('name','branch')
                     ->where('candidate.post_id', '=', 1)
                     ->get();

        return view('/home')->with('file',$file);

     }
}

@foreach ($file as $show)

President

Name : {{$show->name}}

<button>VOTE</button>

      @endforeach

i have used funtion redirect to controller
in controller i have used this function
        public function Count(){
        DB::table('candidate')->increment('count',1);
        return view('/home');
        }

still its not working
this is my Route
Route::get('/home','Homecontroller@count');


text:
Q: How to get ahead of queue? I want to make guys stand in line when they try to book tickets on my site, especially when a lot of people are trying at the same time.
I'm wondering (hypothetically) if there's a way for people to skip this queue and get straight to booking?
Here's the code:
      <script type="text/javascript">
            var time_done = 263;
            var time_retry = 30;
            var time_todo = 7786;
    var todo_pix = 100;
    var done_pix = 0;
    var width = 100;
    var ppu = 0;
    var interval = 0;

    function progress_queue()
    {
        width = document.getElementById('contain').width;
        if(time_done > -1)
        {
            if(!interval)
            {
                ppu = width / (time_todo+time_done);
                update_qtime();
            }
            interval = (1000*time_todo)/todo_pix;
            document.getElementById('done').style.width = parseInt(done_pix) + 'px';
            document.getElementById('todo').style.width = parseInt(todo_pix) + 'px';
                document.getElementById('jhide').style.visibility = "visible";
            todo_pix--;
            done_pix++;
            if (time_retry > 3) setTimeout('progress_queue()', interval);
        }
    }

    function update_qtime()
    {
        time_todo--;
        time_done++;
        todo_pix = time_todo*ppu;
        done_pix = time_done*ppu;
        setTimeout('update_qtime()', 1000);
    }
</script>

A: Things like ticket queues should be done through a server-side language like PHP -- not client-side languages like Javascript.
If I'm reading your code correctly, all they'd need to do would be to either disable Javascript or set a breakpoint in Firebug (or whatever), and then use Firebug/whatever to set the visibility of #done to visible.


text:
Q: YAWS responds with errors under light load. "Unhandled reply fr. do_recv() {error,econnaborted}" Hello fellow Erlangers :)
Just another Erlang enthusiast playing with the language here. I have a very simple YAWS app module which works fine when accessed by single clients. However, if I try to span multiple clients to simulate light traffic, those clients start receiving errors. Any idea what can be causing it?
Code spawning the clients:
-module(concurrent).
-export([measure/0, get/0]).

get() ->
  Result = httpc:request("http://localhost:8080/blah"),
  io:format("Result: ~p.\n", [Result]).

get_spawner(0) -> io:format("Done.\n");
get_spawner(Times) ->
  spawn(concurrent, get, []),
  get_spawner(Times - 1).

measure() ->
  io:fwrite("Starting inets...\n"),
  inets:start(),
  io:fwrite("Done\n"),

  io:fwrite("Creating blah...\n"),
  httpc:request(put, { "http://localhost:8080/blah", [], "", "" }, [], []),
  io:fwrite("Done\n"),

  get_spawner(9),

  io:fwrite("Stopping inets...\n"),
  inets:stop(),
  io:fwrite("Done\n"),

  init:stop().

I observed that it all works just fine for 8 concurrent clients, but when I span 9 or more clients, they start receiving the following message back from the server:
=ERROR REPORT==== 24-Jan-2017::12:30:04 ===
** Generic server httpc_manager terminating
** Last message in was {request,
                           {request,undefined,<0.74.0>,0,http,
                               {"localhost",8080},
                               "/blah",[],get,
                               {http_request_h,undefined,"keep-alive",
                                   undefined,undefined,undefined,undefined,
                                   undefined,undefined,undefined,undefined,
                                   undefined,undefined,undefined,undefined,
                                   undefined,undefined,"localhost:8080",
                                   undefined,undefined,undefined,undefined,
                                   undefined,undefined,undefined,undefined,
                                   undefined,[],undefined,undefined,undefined,
                                   undefined,"0",undefined,undefined,
                                   undefined,undefined,undefined,undefined,[]},
                               {[],[]},
                               {http_options,"HTTP/1.1",infinity,true,
                                   {essl,[]},
                                   undefined,false,infinity,false},
                               "http://localhost:8080/blah",[],none,[],
                               1485261004189,undefined,undefined,false}}
** When Server state == {state,[],httpc_manager__handler_db,
                            {cookie_db,undefined,8209},
                            httpc_manager__session_db,httpc_manager,
                            {options,
                                {undefined,[]},
                                {undefined,[]},
                                0,2,5,120000,2,disabled,false,inet,default,
                                default,[]}}
** Reason for termination ==
** {'EXIT',
       {shutdown,
           {gen_server,call,
               [httpc_handler_sup,
                {start_child,
                    [<0.61.0>,
                     {request,#Ref<0.0.6.64>,<0.74.0>,0,http,
                         {"localhost",8080},
                         "/blah",[],get,
                         {http_request_h,undefined,"keep-alive",undefined,
                             undefined,undefined,undefined,undefined,
                             undefined,undefined,undefined,undefined,
                             undefined,undefined,undefined,undefined,
                             undefined,"localhost:8080",undefined,undefined,
                             undefined,undefined,undefined,undefined,
                             undefined,undefined,undefined,[],undefined,
                             undefined,undefined,undefined,"0",undefined,
                             undefined,undefined,undefined,undefined,
                             undefined,[]},
                         {[],[]},
                         {http_options,"HTTP/1.1",infinity,true,
                             {essl,[]},
                             undefined,false,infinity,false},
                         "http://localhost:8080/blah",[],none,[],
                         1485261004189,undefined,undefined,false},
                     {options,
                         {undefined,[]},
                         {undefined,[]},
                         0,2,5,120000,2,disabled,false,inet,default,default,
                         []},
                     httpc_manager]},
                infinity]}}}

=ERROR REPORT==== 24-Jan-2017::12:30:04 ===
Error in process <0.74.0> with exit value:
{{case_clause,
     {undefined,
         {error,
             {'EXIT',
                 {shutdown,
                     {gen_server,call,
                         [httpc_handler_sup,
                          {start_child,
                              [<0.61.0>,
                               {request,#Ref<0.0.6.64>,<0.74.0>,0,http,
                                   {"localhost",8080},
                                   "/blah",[],get,
                                   {http_request_h,undefined,"keep-alive",
                                       undefined,undefined,undefined,
                                       undefined,undefined,undefined,
                                       undefined,undefined,undefined,
                                       undefined,undefined,undefined,
                                       undefined,undefined,"localhost:8080",
                                       undefined,undefined,undefined,
                                       undefined,undefined,undefined,
                                       undefined,undefined,undefined,[],
                                       undefined,undefined,undefined,
                                       undefined,"0",undefined,undefined,
                                       undefined,undefined,undefined,
                                       undefined,[]},
                                   {[],[]},
                                   {http_options,"HTTP/1.1",infinity,true,
                                       {essl,[]},
                                       undefined,false,infinity,false},
                                   "http://localhost:8080/blah",[],none,[],
                                   1485261004189,undefined,undefined,false},
                               {options,
                                   {undefined,[]},
                                   {undefined,[]},
                                   0,2,5,120000,2,disabled,false,inet,default,
                                   default,[]},
                               httpc_manager]},
                          infinity]}}}}}},
 [{httpc,handle_request,9,[{file,"httpc.erl"},{line,574}]},
  {concurrent,get,0,
      [{file,
           "c:/Users/piotr_justyna/Documents/rets/performance_tests/concurrent.erl"},
       {line,5}]}]}

On the server side I am getting this:
=ERROR REPORT==== 24-Jan-2017::12:28:55 ===
Unhandled reply fr. do_recv() {error,econnaborted}

I'm sure it's something straightforward, just can't figure out what it is. Is it the number of concurrent connections that causes it? Can you help shed more light on this?
Regards,
Piotr

A: Your code spawns a number of httpc:request/1 calls, but then immediately afterwards it stops inets:
...
get_spawner(9),
io:fwrite("Stopping inets...\n"),
inets:stop(),
...

Because inets is shut down, requests that are still in progress are getting shut down prematurely, as you can see in the error report:
** Reason for termination ==
** {'EXIT',
       {shutdown,
           {gen_server,call,
               [httpc_handler_sup,

You need to make the parent of all the spawned requests wait for those requests to finish before calling inets:stop/0. One way to do that would be to pass the parent pid to each spawned child and once httpc:request/1 returns, have the child send a message to the parent. The parent would spawn all N children, then sit in a loop waiting to receive N completion messages from the children, and only after receiving all completion messages would it call inets:stop/0.
The reason it works for 8 requests but not 9 is due to a race condition around the lack of waiting prior to calling inets:stop/0. The default size of the Yaws pool of request handling acceptor processes happens to be 8. When your code sends 8 requests, the pool handles it quickly enough to beat your code's call to inets:stop/0, but with 9, there's a slight delay as one acceptor handles two requests, and that slight timing change is enough to allow your inets:stop/0 call to clobber one or more of your client processes. You can modify the Yaws acceptor pool size via the acceptor_pool_size configuration variable.
If you're serious about load testing you might consider using an industrial-strength solution like tsung instead of rolling your own.


text:
Q: Does a single _type with sparse fields have the same effect on the index as multiple types (in ElasticSearch)? How much do sparse fields apply when an index has only one type?  I'm in the position of making an index with a large number of small-ish documents all of the same type, and with a number of fields.  Only a fraction of the fields are populated thought all of the documents are of the same type.  According to this post there are concerns when the postings are sparse.  This seems to suggest though it might only be a problem if the index has many types.  What if the index only has one type?

Fields that exist in one type will also consume resources for
  documents of types where this field does not exist. This is a general
  issue with Lucene indices: they don't like sparsity. Sparse postings
  lists can't be compressed efficiently because of high deltas between
  consecutive matches. And the issue is even worse with doc values: for
  speed reasons, doc values often reserve a fixed amount of disk space
  for every document, so that values can be addressed efficiently. This
  means that if Lucene establishes that it needs one byte to store all
  value of a given numeric field, it will also consume one byte for
  documents that don't have a value for this field.

Ref: Index-vs-Types

A: Sparsity is not strictly related to many types. In the context of the blog post (types vs. indices) using multiple types instead of multiple indices does indeed come with the downside of having sparse fields: if one defines 3 types in an index where each type has one field: field1 in type type1, field2 in type type2 and field3 in type type3, every document added to this index, no matter to which type it belongs, it will have all those three fields in it (at Lucene level). But for every type only the field belonging to that type will have value. Which means that each document of the index will be 1/3 populated.
This is, also, why Elasticsearch requires the fields with the same name, but in different types, to have the same field type: because at Lucene level, this is all one field for all documents in that index, no matter the type.
The same happens with one type in one index and documents having 3 fields. If those fields barely have values (like in your case), still sparsity happens.


text:
Q: Swapping array elements without temporary variable When I use following code for swapping in quick-sort it is working.
void s(int *a, int *b)
{
   int t = *a;
   *a = *b;
   *b = t;
}

But when I use following code to swap elements for quick-sort, it is not working.
void s(int *a, int *b)
{
    *a = *a + *b;
    *b = *a - *b;
    *a = *a - *b;
}

I can't figure out what is wrong with the code.
I am adding my quick-sort code below for clarification.
void  qs(int *a, int l, int h){
   if( l<h){
      int pi = pa(a, l, h);
      qs(a, l, pi-1); qs(a, pi+1, h);
   }
}
int pa(int *a, int l, int h){
    int p = a[h], lt = l-1, i;
    for(i=l; i<=h-1; i++) if(a[i]<=p) s(&a[++lt], &a[i]);
    s(&a[lt+1], &a[h]);
    return lt+1;
}

A: *a = *a + *b;
*b = *a - *b;
*a = *a - *b;

That code is a classic trick for swapping numbers that does work.  The issue has to be in what values are being passed in.  You need to verify that the pointers you are working with are not the same and that you are not having an issue with overflow.

A: There are two problems with the second function. One, Yu Hao had identified, but has since removed, is that you have the potential for signed integer overflow.
Assuming you are only dealing with numbers that do not cause overflow, the second problem is that if the two pointers point to the same object, the object will end up with the value of 0, regardless of what value it started with.
Suppose you have variable c initialized to 17, and you call swap with swap(&c, &c):
   .-----------.
  \|/          |
+--'----+    +---+    +---+
| c: 17 |    | a |    | b |
+--.----+    +---+    +---+
  /|\                   |
   `--------------------'

Since inside swap(), both a and b point to c, the result of the last assignment will put the value 0 into c, because *a = *a - *b would be equivalent to c = c - c.
To fix the overflow issue, you can make sure the sum never overflows by making sure the arguments have opposite signs. To fix the "point to same object" issue, just check of that inside the swap function.
void swap (int *a, int *b) {
    /*...as you had it...*/
}

void s (int *a, int *b) {
    if (a != b) {                /* not same object */
        if (*a > 0 != *b > 0) {
            swap(a, b);          /* not same sign */
        } else {
            *a = -*a;
            swap(a, b);
            *b = -*b;
        }
    }
}

As you can see, this is already considerably more complicated than employing the first version of your swap function. If you are worried that using another variable might make the program deficient in some way, put those fears aside. Nearly all compilers used for commercial development will recognize a swap, and generate the optimal code for it.

A: the swapping is correct, probably you have a bug in your overall quicksort. or compiler optimizes something

A: While doing a quick sort, in the partition method call, you would be calling the swap on the same position sometimes.
So, this line in the swap method:
*a = *a + *b;

would mean that both *a and *b now have (*a + *b) as its the same position that the change is getting reflected in.
Better to have a check of a!=b before you swap.

A: This code works for me.
#include <stdio.h>
void swap(int*, int*);
int main()
{
   int x, y;
   printf("Enter the value of x and y\n");
   scanf("%d%d",&x,&y);
   printf("Before Swapping\nx = %d\ny = %d\n", x, y);
   swap(&x, &y);
   printf("After Swapping\nx = %d\ny = %d\n", x, y);
   return 0;
}

void swap(int *a, int *b)
{
*a = *a + *b;
*b = *a - *b;
*a = *a - *b;
}

tried it on, http://www.compileonline.com/compile_c_online.php
So, my point is the swapping is correct and I think you have a problem with your quick sort code.

A: I would use the first way to swap values.
The second one appears as though it should work. but is limited in scope and is not as good:

*

*if both *a and *b point to the same value you get 0 as the value

*you can overflow with large values

*it is not as efficient, using 3 assignment and 3 addition operations

It should work, unless your compiler is optimizing something for you, or you are running into case 1 or 2 above...
for example:
a = 2
b = 3
*a = *a + *b; // *a = 2 + 3 = 5
*b = *a - *b; // *b = 5 - 3 = 2
*a = *a - *b; // *a = 5 - 2 = 3


text:
Q: RxJava2 multithreading or something goes wrong Im kind of beginner at rxjava and i'm facing a problem.
I have two network calls.
Observable<ClassA> getClassA(){
  return networkExecutor.getClassAFromApi();
}
Observable<ClassB> getClassB(){
  return networkExecutor.getClassBFromApi();
}

now I need both of these in order for code to proceed, so i do a zip on them. Also I want to save those values temporary in private Class scope variables lets say cA and cB;
 getClassA().zipWith(getClassB, (classA, classB) -> {
  cA = classA;
  cB = classB;
  return true;
}

the problem is, when later on i repeat the same step, cA and cB is the old value instead of the new one.
for example first time I call zip method hashes of cA and cB are xxx1, xxx2
when i call the same method second time, new objects are generated from network with hashes xxx3 and xxx4.
when i call this class getter i get cA xxx1 instead i should already get the xxx3.

A: You can use some of the do operators for after the event to clear up hash fields, or clear them before you proceed with new request.
Look up Do operators. I would probably use doAfterNext() operator and reset the fields as necessary.

A: The problem was in architecture, instead of setting components globaly, you should keep them in the stream creating custom class to hold the values, and take them in.
onNext(CustomClassObject object){
    // object.getClassA;
}


text:
Q: Custom UIScrollView backing a UITableView I have some custom scrolling behavior I would like to use in a few different places. Let's say the scroll view should provide for the following three behaviors:

*

*change color as the user scrolls, dependent on the content offset.

*expose an imageView property which is displayed in the background. The consumer can set the image.

*let a delegate know when the content offset exceeds some fixed value.

I have a working implementation using a UIScrollView subclass. But now I would like the same functionality in a UITableView, which of course is backed by a standard UIScrollView.
How might I re-use the same code in both places? The closest I have come so far is to turn off the tableview's scrolling and also force its height to always match its content size. Then I can add it to my custom scroll view like any other view. This works, but has some drawbacks.
Could I implement this using a category? A protocol? Can I 'swap out' UITableView's scroll view somehow for my own? Any other techniques I might be overlooking?

A: I have an idea for you.
Make a class for implementing the UIScrollViewDelegate methods - let's say (of course choose a better name...):
@interface ScrollViewDelegateHelper : NSObject <UIScrollViewDelegate>

Make a class for implementing all the UITableViewDelegate methods (and of course dataSource methods if you like), let's say:
@interface TableViewDelegateHelper : ScrollViewDelegateHelper <UITableViewDataSource, UITableViewDelegate>

The TableViewDelegateHelper extends ScrollViewDelegateHelper, so all the scroll events can be written in one file.
And you can use ScrollViewDelegateHelper in both cases, one time as the delegate for your custom UIScrollView, and the second time as the parent of the delegate of your TableView
Hope it helps.


text:
Q: Mysterious Issue in Replicating Binary files in C Hey community i'm having trouble in replicating binary files from the command line have a look at my try. The code under copies the first character on the srcFile and stops somehow, can you guys help me figure the way i can fix this and the reason it happens?
#include <stdio.h>
#include <stdlib.h>
#define BUFSIZE 8500
int main(int argc, char** argv)
{
char buffer[BUFSIZE];
size_t currBit;

FILE *srcFile = fopen(argv[1], "r+b");

if (!srcFile)
{
    printf("source file doesnt exist or problem with allocating the memory");
    return 1;
}
FILE *dstFile = fopen(argv[2], "r+b");
if (dstFile)
{
    printf("Destination file already exists\nfor overwriting enter 1 \nfor exit enter 2\n");
    _flushall();
    switch (getchar())
    {
    case '1':
        fclose(dstFile);
        dstFile = fopen(argv[2], "w+b");
        if (!dstFile)
        {
            printf("Problem with allocating the memory");
        }
        while ((currBit = fread(buffer, sizeof(char),BUFSIZE, srcFile) > 0))
        {
            fwrite(buffer, sizeof(char), currBit, dstFile);
        }

        break;
    case '2':
        system("pause");
        return 0;
        break;
    default:
        printf("next time you should enter numbers as following");
    }
}
else
{
    dstFile = fopen(argv[2], "w+b");
    while ((currBit = fread(buffer, sizeof(char), BUFSIZE, srcFile) > 0))
    {
        fwrite(buffer, sizeof(char), currBit, dstFile);
    }
    if (!dstFile)
    {
        printf("Problem with allocating the memory");
    }
}

fclose(srcFile);
fclose(dstFile);

getchar();
return 0;
}

Input Source file:
10100101
Expected Output From Destination File:
10100101
Destination File Output:
1

A: while ((currBit = fread(buffer, sizeof(char),BUFSIZE, srcFile) > 0))

Look at where the > is... You are comparing with zero before assigning to currBit, so you are always assigning a boolean value (1/0). Move > to the outermost layer of parentheses.

A: 'while ((currBit = fread(buffer, sizeof(char), BUFSIZE, srcFile) > 0))'

Misplaced brackets in the compound expression result in 'currBit' being loaded with a boolean result.


text:
Q: Swagger for non Maven Java Projects I am planning to integrate Swagger to my existing non Maven Java Web Project with
JAX-RS and Jersey-1.X. Can someone help me out with the initial set up as to what dependencies - sawgger*jar files are needed to accomplish the feat.
As per the swagger's GitHub Page: its unclear to me as to what are the required libraries . Please check this link.. All the instructions here are purely Maven based.