text:
Q: Why doesn't my shell program open the file it received as argument in function "cat" I included the code below, sorry to bother you with so much code. Argument parsing is ok, i checked it out with watches. I've put some printfs to check out where the problem may be and it seems that it doesn't open the file cat receives as argument. It is called from a shell as "cat -b file"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#define TRUE 0
#define FALSE 1

void yes(int argc, char *argv[]);
int cat(int argc, char *argv[]);

//#include "cat.h"
//#include "yes.h"
//#include"tee.h"

char buf[50],c[10], *p2,*p, *pch;

int count;
char *matrix[20];

void yes(int argc, char *argv[])
{
    int i;
// if (argc >= 2 && *argv[1] == '-')
    //  {
    //printf("ERROR!");
    //}
    //if (argc == 1)
    // {
    while (1)
        if (puts("y") == EOF)
        {
            perror("yes");
            exit(FALSE);
        }
    // }

    while (1)
        for (i = 1; i < argc; i++)
            if (fputs(argv[i], stdout) == EOF || putchar(i == argc - 1 ? '\n' : ' ') == EOF)
            {
                perror("yes");
                exit(FALSE);
            }
    //exit(TRUE);
}

int main(int argc, char *argv[])
{
    //p=(char *)malloc(sizeof(char)*50);
    do
    {
        fprintf (stderr, "$ ");
        fgets (buf,50,stdin);
        p=buf;
        fprintf (stderr, "Comanda primita de la tastatura: ");
        fputs (buf, stderr);
        int i=0,j=0;
        //strcpy(p,buf);
        strcpy(c,"\0");
        while (buf[i] == ' ')
        {
            i++;
            p++;
        }
        if (buf[i] == '#')
            fprintf (stderr, "Nici o comanda, ci e un comentariu!\n");
        else
        {
            j=0;
            while (buf[i] != ' ' && buf[i] != '\n')
            {
                i++;
                j++;
            }
            strncpy (c,p,j);
            fprintf (stderr, "%s\n",c);
            if (strcmp (c,"yes") == 0)
            {
                p2 = p+j+1;
                pch = strtok (p2," ");
                count = 0;
                while (pch != NULL)
                {
                    //printf ("%s\n",pch);
                    matrix[count] = strdup(pch);
                    pch = strtok (NULL, " ");
                    count++;
                }
                yes(count, matrix);
                fprintf (stderr, "Aici se va executa comanda yes\n");
            }
            else if (strcmp (c,"cat") == 0)
            {
                p2 = p+j+1;
                pch = strtok (p2," ");
                count = 0;
                while (pch != NULL)
                {
                    //printf ("%s\n",pch);
                    matrix[count] = strdup(pch);
                    pch = strtok (NULL, " ");
                    count++;
                }
                cat(count,matrix);
                fprintf (stderr, "Aici se va executa comanda cat \n");
            }
            else if (strcmp (c,"tee") == 0)
            {
                //tee();
                fprintf(stderr, "Aici se va executa comanda tee\n");
            }

            fprintf (stderr, "Aici se va executa comanda basename\n");

            strcpy(buf,"\0");
        }
    }
    while (strcmp(c, "exit") != 0);
    fprintf (stderr, "Terminat corect!\n");
    return 0;
}
int cat(int argc, char *argv[])
{
    int c ;

    opterr = 0 ;
    optind = 0 ;

    char number = 0;
    char squeeze = 0;
    char marker = 0;

    fprintf(stderr,"SALUT< SUNT IN FUNCTIZE>\n");
    while ((c = getopt (argc, argv, "bnsE")) != -1)
        switch (c)
        {
        case 'b' :
            number = 1;
            break;
        case 'n' :
            number = 2;
            break;
        case 'm' :
            marker = 1;
            break;
        case 's' :
            squeeze = 1;
            break;
        case 'E' :
            marker = 1;
            break;
        }
    if (optind + 1 != argc)
    {
        fprintf (stderr, "\tWrong arguments!\n") ;
        return -1 ;
    }

    FILE * fd = fopen (argv[optind], "r");
    printf("am deschis fisierul %s ",argv[optind]);
    if (fd == NULL)
    {
        printf("FISIER NULL asdasdasdasdasd");
        return 1;
    }

    char line[1025];
    int line_count = 1;

    while (!feof(fd))
    {
        fgets(line, 1025, fd);
        printf("sunt in while :> %s",line);
        int len = strlen(line);
        if (line[len - 1] == '\n')
        {
            if(len - 2 >= 0)
            {
                if(line[len - 2] == '\r')
                {
                    line[len - 2] = '\0';
                    len -= 2;
                }
                else
                {
                    line[len - 1] = '\0';
                    len -= 1;
                }
            }
            else
            {
                line[len - 1] = '\0';
                len -= 1;
            }
        }

        if (squeeze == 1 && len == 0)
            continue;
        if (number == 1)
        {
            fprintf (stdout, "%4d ", line_count);
            line_count++;
        }
        else if (number == 2)
        {
            if (len > 0)
            {
                fprintf (stdout, "%4d ", line_count);
                line_count++;
            }
            else
                fprintf (stdout, "     ");
        }
        fprintf(stdout, "%s", line);
        if (marker == 1)
            fprintf(stdout, "$");
        fprintf(stdout, "\n");
    }

    fclose (fd);

    return 0 ;
}

A: The problem is that when you are using fgets it includes the newline into the string. Thus when you are passing the file name, it is appended with a \n character which was enter when entering the command. So the file name passed is incorrect. Get ride of the new line maybe on these lines (just a pointer):
char *filename = strtok(argv[optind], "\n");
if( filename == NULL)
{
   /*What the .... */
   Handle error!
}
FILE * fd = fopen (filename, "r");
printf("am deschis fisierul %s ",argv[optind]);
if (fd == NULL)
{
    printf("FISIER NULL asdasdasdasdasd");
    return 1;
}

Hope this helps!
PS: Debugging process
When  fopen fails it sets the errno. To get exact error use strerror(errno); or perror. So adding perror("fopen"); in if(fd == NULL) showed fopen : No such file or directory. Next printing the file name as fprintf(stderr, "\n |%s|\n", argv[optind]); showed file name with newline character i.e.
|hello.txt
|

... then saw fgets. Ah! the new line from there


text:
Q: Converting string with new lines into json array I have the following string(with new lines after each value):
"
value1
value2
value3
"
I need to convert it to a json array(using python) in the following format:
{"keywords": [{"keyword": "value1"},{"keyword": "value2"},{"keyword": "value3"}]}

I tried all kinds of methods, always resulting in invalid json.
Any suggestions?

A: Split the string into an array, map it to a dictionary of keyword:line, and convert it into json.
import json

def map_line(line):
    return {"keyword": line}

lines = "value1\nvalue2\nvalue3".split("\n")

result = json.dumps({"keywords": list(map(map_line, lines))})

A: import json
sample_data = '{"keywords": [{"keyword": "value1"},{"keyword": "value2"},{"keyword": "value3"}]}'
for idx, key in enumerate(json.loads(sample_data)):
    for idx2, key2 in enumerate(json.loads(sample_data)[key]):
        print(key2)

Output:
{'keyword': 'value1'}
{'keyword': 'value2'}
{'keyword': 'value3'}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Loop with .cget function? I want to change the "for i in range()"-value with a button.
the "cget" function doesn´t work. It gives me the following error: "function' object cannot be interpreted as an integer"
Does anyone have an idea on how to get this to work?
My not working code:
import tkinter as tk
from time import sleep
root = tk.Tk()

def test_btn_clicked():
    if test_btn.config('text')[-1] == '2'
        test_btn.config(text='5')

    else:
         test_btn.config(text='2')

test_btn = tk.Button(root, text="2", command=text_btn_clicked)
test_btn.pack()

def func1():
    for i in range(test_btn.cget('text')):
        sleep(5)
        #do_something

test_func_btn = tk.Button(root, text="start", command=func1)
test_func_btn.pack()

root.mainloop()


text:
Q: Howto: force MySQL to ignore errors in ALTER TABLE in an SQL file on import I know similar questions have been asked, and answers state to use the --force or -f parameter in the console window, which I just can't use.
My PHP script generates an .sql file for updating a database of a new shop with the data of an old shop (different but similar systems, almost identical database structures).
This .sql file then needs to be imported in the new database using phpMyAdmin (or similar software running in a web browser), so I just can't use any console options.
I already use CREATE TABLE IF NOT EXISTS and INSERT IGNORE INTO to avoid errors on multiple imports, but I still don't have a solution for ignoring ALTER TABLE table ADD column statements.
My thoughts on this now go in a direction, where the force option might be set in the beginning of the .sql file like a variable using the /!xxxxx syntax like /!40101 SET NAMES utf8 */;, but I can't seem t find any information on that.
Does anyone know the syntax to use if any exists?
Thanks a lot in advance!


text:
Q: Make a button unclickable after one click I'm trying to create a button that becomes deactivated after the first click; however I have no clue how to do it.
This is what I have now:
<input type="button" id="btnSearch" value="Search" onclick="Fuction();" />

This button will NOT submit a form. Could someone help me? I'm totally new to this. I've tried following the answer in other threads but got lost.

A: Separating javascript from HTML:
HTML:
<input type="button" value="Click me!" id="form-button"/>

Javascript:
document.getElementById('form-button').onclick = function () {
    this.disabled = true;
}

A: Not the preferred way of course, but this will get you the result you are after.
function Fuction() {
  document.getElementById('btnSearch').disabled = 'disabled';
}

A: Set disabled attribute in the end of your handler:
function Fuction(button) {
    // your code

    button.disabled = true;
}

Markup:
<input type="button" id="btnSearch" value="Search" onclick="Fuction(this);" />

A: Just call event.preventDefault() in the functions implicitly added event variable to first stop the propagation. To disable it afterwards just call setAttribute("disabled", true); on the element. Something like
function aMeaningfulName(e) {
    e.preventDefault();
    e.target.setAttribute("disabled", true);

    // your logic here
}


text:
Q: JodConverter application is not working in webapplication I am converting docx file to pdf file using JODconverter. The same code is working fine from standalnoe java application but its not working when I am using the same inside webapp and throwing
SEVERE: Servlet.service() for servlet CmisWebClient threw exception
java.lang.ClassNotFoundException: com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1680)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526)
    at org.ap.cmis.web.CmisWebClient.doPost(CmisWebClient.java:98)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:643)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Unknown Source)

Thanks a lot


text:
Q: PHP Fatal error not reproducible in an identical environment I have two environments, running the same stack, that give different PHPUnit test results.
In my vagrant based environment, our PHPUnit test suite passes with no issues.
In my VPS based environment, we're seeing the following php fatal error:
PHPUnit 5.5.1 by Sebastian Bergmann and contributors.

.......................................S.S.....PHP Fatal error:
Class Mock\Product\Promotion\DataProviderMock contains 5 abstract methods
and must therefore be declared abstract or implement the
remaining methods (Olive\Product\Promotion\DataProviderInterface::hasPromotion, Olive\Product\Promotion\DataProviderInterface::isSticky, Olive\Product\Promotion\DataProviderInterface::getValuePromotion, ...)
in /tmp/popeye/olive/tests/mock/Mock/Product/Promotion/ProviderMock.php on line 11

The fix is simple (implement the methods in the class), however before making the fix I would like to understand why the behavior is different in the two environments.
I assume the difference in the two environments is somewhere in my PHP configuration.
I have checked that there are no differences in the environments in the output between php-config or php composer.phar show  -t.
There are some differences between the output of php -i which might be related.
Here is a diff of php -i with the vagrant environment (which does not see the error) on the left and the VPS environment (which does see the error) on the right:
$ diff php-i.vagrant php-i.vps
4c4
< System => Linux vagrant-box 4.4.0-62-generic #83-Ubuntu SMP Wed Jan 18 14:10:15 UTC 2017 x86_64
---
> System => Linux staging-01 4.4.0-81-generic #104-Ubuntu SMP Wed Jun 14 08:17:06 UTC 2017 x86_64
109c108
< apc.shm_size => 32M => 32M
---
> apc.shm_size => 192M => 192M
112c111
< apc.ttl => 0 => 0
---
> apc.ttl => 86400 => 86400
144,145c143,144
< display_errors => STDOUT => STDOUT
< display_startup_errors => On => On
---
> display_errors => Off => Off
> display_startup_errors => Off => Off
154c153
< error_reporting => 32767 => 32767
---
> error_reporting => 22527 => 22527
746c745
< opcache.fast_shutdown => 0 => 0
---
> opcache.fast_shutdown => 1 => 1
754c753
< opcache.interned_strings_buffer => 4 => 4
---
> opcache.interned_strings_buffer => 16 => 16
757c756
< opcache.max_accelerated_files => 2000 => 2000
---
> opcache.max_accelerated_files => 16229 => 16229
760c759
< opcache.memory_consumption => 64 => 64
---
> opcache.memory_consumption => 192 => 192
771c770
< opcache.validate_timestamps => On => On
---
> opcache.validate_timestamps => Off => Off
793c792

Are there any PHP gurus reading this who might be able to explain why we see this error in only one environment?
Many thanks!

A: I suspect it's due to the difference in one of these settings related to errors:
144,145c143,144
< display_errors => STDOUT => STDOUT
< display_startup_errors => On => On
---
> display_errors => Off => Off
> display_startup_errors => Off => Off
154c153
< error_reporting => 32767 => 32767
---
> error_reporting => 22527 => 22527


text:
Q: Кодировка в названии прикрепленного вложения IBM Notes Добрый день.
Имеется веб-сервис, который импортирует файл .doc в документ NotesDocument. Проблема в том, что если название файла на русском, то в названии вложения получаю иероглифы. Само содержание корректное.
File directory = new File("C:\\Attachments 1C");
String filename = "Безымянный.png"
String path = directory + "\\" + filename;
Stream outStream = sess.createStream();
sess.setConvertMIME(true);
MIMEEntity body = newDoc.createMIMEEntity("rtBody");

Stream inStream = sess.createStream();
if (inStream.open(path, "UTF-8")) {
    if (inStream.getBytes() > 0) {
        do {
            byte[] buffer = inStream.read(32767);
            outStream.write(buffer);
        } while (!inStream.isEOS());
        inStream.close();

        MIMEEntity child = body.createChildEntity();

        String fileSuffix = path.substring(path.lastIndexOf(".")+1);

        child.setContentFromBytes(outStream, fileSuffix, MIMEEntity.ENC_IDENTITY_8BIT);

        MIMEHeader header = child.createHeader("Content-Disposition");
        header.setHeaderVal("attachment; filename=\"" + filename + "\"");
        header = child.createHeader("Content-ID");
        header.setHeaderVal(path);
        outStream.truncate();
    }else
        return "Пустой файла";
}else
    return "Не удалось открыть файл";

Например, если filename = "Безымянный.png", то к документу newDoc он прикрепляется под названием "Áåçûìÿííûé.png".

A: Проблема решилась с помощью MimeEncode:
String filenameEndoded = MimeUtility.encodeText(filename,"UTF-8","B");


text:
Q: Convert row with columns of data into column with multiple rows in Excel I hv rows of data:-
TAG   SKU   SIZE   GRADE   LOCATION
A001  123    12      A       X1
A002  789    13      B       X3
A003  456    15      C       X5

I need to convert it into:-
A001   123  SIZE 12
A001   123  GRADE A
A001   123  LOCATION X1
A002   789  SIZE 13
A002   789  GRADE B
A002   789  LOCATION X3
A003   456  SIZE 15
A003   456  GRADE C
A003   456  LOCATION X5

I used the below (based on Ben McCormack's suggestion posted on Nov 23 '09) but it doesn't produce the above result :-
Sub NormalizeSheet()
Dim wsOriginal As Worksheet
Dim wsNormalized As Worksheet
Dim strKey As String
Dim clnHeader As Collection
Dim lngColumnCounter As Long
Dim lngRowCounterOriginal As Long
Dim lngRowCounterNormalized As Long
Dim rngCurrent As Range
Dim varColumn As Variant

Set wsOriginal = ThisWorkbook.Worksheets("Original")     'This is the name of your original worksheet'
Set wsNormalized = ThisWorkbook.Worksheets("Normalized") 'This is the name of the new worksheet'
Set clnHeader = New Collection

wsNormalized.Cells.ClearContents        'This deletes the contents of the destination worksheet'

lngColumnCounter = 2
lngRowCounterOriginal = 1
Set rngCurrent = wsOriginal.Cells(lngRowCounterOriginal, lngColumnCounter)

' We'll loop through just the headers to get a collection of header names'
Do Until IsEmpty(rngCurrent.Value)
    clnHeader.Add rngCurrent.Value, CStr(lngColumnCounter)
    lngColumnCounter = lngColumnCounter + 1
    Set rngCurrent = wsOriginal.Cells(lngRowCounterOriginal, lngColumnCounter)
Loop

'Here we'll reset our Row Counter and loop through the entire data set'
lngRowCounterOriginal = 2
lngRowCounterNormalized = 1
lngColumnCounter = 1

Do While Not IsEmpty(wsOriginal.Cells(lngRowCounterOriginal, lngColumnCounter))

    Set rngCurrent = wsOriginal.Cells(lngRowCounterOriginal, lngColumnCounter)
    strKey = rngCurrent.Value ' Get the key value from the current cell'
    lngColumnCounter = 2

    'This next loop parses the denormalized values for each row'
    Do While Not IsEmpty(wsOriginal.Cells(lngRowCounterOriginal, lngColumnCounter))
        Set rngCurrent = wsOriginal.Cells(lngRowCounterOriginal, lngColumnCounter)

        'We're going to check to see if the current value'
        'is equal to NULL. If it is, we won't add it to'
        'the Normalized Table.'
        If rngCurrent.Value = "NULL" Then
            'Skip it'
        Else
            'Add this item to the normalized sheet'
            wsNormalized.Range("A" & lngRowCounterNormalized).Value = strKey
            wsNormalized.Range("B" & lngRowCounterNormalized).Value = clnHeader(CStr(lngColumnCounter))
            wsNormalized.Range("C" & lngRowCounterNormalized).Value = rngCurrent.Value
            lngRowCounterNormalized = lngRowCounterNormalized + 1
        End If

        lngColumnCounter = lngColumnCounter + 1
    Loop
    lngRowCounterOriginal = lngRowCounterOriginal + 1
    lngColumnCounter = 1    'We reset the column counter here because we're on a new row'
Loop

End Sub

A: Here's an approach going from worksheet to worksheet directly. This might be necessary if the dataset is too big and available memory too small for using arrays. It's likely to be slow.
It uses the same call parameters as reOrgV1, and pretty much the same logic.
It's updated to add "DEFECTS" to the properies. The input looks like:
TAG     SKU   SIZE GRADE LOCATION DEFECTS
A001    123    12   A       X1      3
A002    789    13   B       X3      5
A003    456    15   C       X5      7

Here's the code.
Public Sub reOrgV2(inSource As Range, inTarget As Range)
'' This version works directly on the worksheet
'' and transfers the result directly to the target
'' given as the top-left cell of the result.

'' **** Changed to add "Defects"
    Dim resNames()
    Dim propNum As Integer
    Dim srcRows As Integer
    Dim resRows As Integer
    Dim i As Integer
    Dim j As Integer
    Dim g As Integer

    '' Shape the result
    resNames = Array("Size", "Grade", "Location", "Defects")
    propNum = 1 + UBound(resNames)

    '' Row counts
    srcRows = inSource.Rows.Count
    resRows = srcRows * propNum

    '' re-org and transfer source to result range
    inTarget = inTarget.Resize(resRows, 4)
    g = 1
    For i = 1 To srcRows
        For j = 0 To 3
            inTarget.Item(g + j, 1) = inSource.Item(i, 1)      '' Tag
            inTarget.Item(g + j, 2) = inSource.Item(i, 2)      '' SKU
            inTarget.Item(g + j, 3) = resNames(j)              '' Property
            inTarget.Item(g + j, 4) = inSource.Item(i, j + 3)  '' Value
        Next j
        g = g + propNum
    Next i
End Sub

This is the revised call sourcing the wider range.
'' Call ReOrgV2 with input and output ranges
Public Sub test4()
    Dim i As Integer
    i = Range("InData!A:A").Find("").Row - 2
    reOrgV2 Range("InData!A2").Resize(i, 6), [OutData!A1]
End Sub

A: You can use ADO with Excel. Roughly:
Sub ColsToRows()
Dim cn As Object
Dim rs As Object
Dim strFile As String
Dim strCon As String
Dim strSQL As String
Dim s As String
Dim i As Integer, j As Integer

    ''This is not the best way to refer to the workbook
    ''you want, but it is very convenient for notes
    ''It is probably best to use the name of the workbook.

    strFile = ActiveWorkbook.FullName

    ''Note that if HDR=No, F1,F2 etc are used for column names,
    ''if HDR=Yes, the names in the first row of the range
    ''can be used.
    ''This is the Jet 4 connection string, you can get more
    ''here : http://www.connectionstrings.com/excel

     strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Docs\TestBook.xls " _
            & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"

    ''Late binding, so no reference is needed

    Set cn = CreateObject("ADODB.Connection")
    Set rs = CreateObject("ADODB.Recordset")

    cn.Open strCon

    strSQL = "SELECT [TAG], [SKU], 'SIZE ' & [SIZE] As S, " _
           & "'GRADE ' & [GRADE] As G, 'LOCATION ' & [LOCATION] As L " _
           & "FROM [Sheet1$] a " _
           & "ORDER BY [Tag] "

    rs.Open strSQL, cn, 3, 3

    ''Pick a suitable empty worksheet for the results

    With Worksheets("Sheet3")

        j = 1 '' Row counter

        Do While Not rs.EOF
            For i = 2 To 4
                .Cells(j, 1) = rs!Tag
                .Cells(j, 2) = rs!SKU
                .Cells(j, 3) = rs(i)
                j = j + 1
            Next
            rs.MoveNext
        Loop
    End With

   ''Tidy up
   rs.Close
   Set rs = Nothing
   cn.Close
   Set cn = Nothing

End Sub

A: Here's a really simple solution that assumes the dataset isn't huge. It takes the input range into an array, transforms it into a result array, then moves the array to the specified target. The target is defined by the top left cell.
When it's possible, this approach is orders of magnitude faster than working directly with cells on worksheets.
The test function at the bottom needs you to put an input set on sheet InData and have a sheet OutData defined for the results but your input and output ranges can be anywhere you want.
Option Explicit

Public Sub reOrgV1(inSource As Range, inTarget As Range)
'' This version uses VBA arrays to do the work.
'' Takes a source range, reorganizes it to the target
''    given as the top-left cell of the result.

    Dim srcArray As Variant
    Dim resArray As Variant
    Dim resNames()
    resNames = Array("SIZE", "GRADE", "LOCATION")

    Dim srcRows As Integer
    Dim resRows As Integer
    Dim i As Integer
    Dim j As Integer
    Dim g As Integer

    '' Move range into source array
    srcArray = inSource.Value
    srcRows = UBound(srcArray, 1)
    resRows = srcRows * 3

    ''Build result array
    ReDim resArray(1 To resRows, 1 To 3)

    '' transfer source to result array
    g = 1
    For i = 1 To srcRows
        For j = 0 To 2
            resArray(g + j, 1) = srcArray(i, 1)
            resArray(g + j, 2) = srcArray(i, 2)
            resArray(g + j, 3) = resNames(j) & " " & srcArray(i, j + 3)
        Next j
        g = g + 3
    Next i

    '' Move the results to the target range
    inTarget.Resize(resRows, 3).Value = resArray
End Sub

Public Sub test1()
    reOrgV1 Range("InData!A2:E4"), Range("OutData!A1")
End Sub


text:
Q: How to grey out the full browser window and display a form in the center? Have you come across those websites that grey out the full browser window and show you a notification or ask you to fill in a survey .. etc? This used to happen with myspace, if you mistyped in the email or password the full browser window would grey out (it's transparent though, you still can see the contents of the page through it) and a the login controls would display in the center of the browser window with an error message above them telling you that you mistyped the email or password. Unfortunately they removed this from myspace, I want the same code for a website I'm working on and was trying to avoid reinventing the wheel, do you know of any source to find this code instead of writing the whole thing again? I assume this is mostly CSS, Javascript is only used for showing/hiding, am I right?

A: You can also use only CSS and Javascript for this: Create a Modal Dialog Using CSS and Javascript and submodal

A: These are called 'modal' windows. To avoid reinventing the wheel, use existing libraries like JQuery. Googling 'jquery modal window' brings up lots of results that look like exactly what you want. You could either pick one of these if it does exactly what you want, or find one with good source to deconstruct.

A: If you're thinking of using a JavaScript framework, jQuery has the Block UI plugin. Very easy to use and configure.
Demos here

A: If you prefer prototype.js, there's Prototype Window Class, doing what you want, see alert dialog sample.

A: If you are working in asp.net and want a quick and easy tool for this get the ajax toolkit. Then use the modal popup control. Here is the example on the AJAX PAGE


text:
Q: Move a Shape within an Excel Worksheet based on Input Data I'm looking at making a timeline within Excel that moves a 'window' (the white oval) along the timeline based on the date.

What I'm looking at doing is in VBA:

*

*Setting a scale (where the whole arrow is a year)

*Setting the oval's initial position

*Setting the oval's new position (based on how far down the timeline the date is)

I'm completely new to VBA and was wondering if someone could please point me in the right direction?
Thanks!

A: Try...
Sub Macro1()

Dim shp As Shape
For Each shp In ActiveSheet.Shapes
    If shp.Type = 1 Then
        shp.Delete
    End If
Next shp

ActiveSheet.Shapes.AddShape Type:=msoShapeOvalCallout, Left:=100, Top:=100, Width:=200, Height:=150
ActiveSheet.Shapes(1).TextFrame2.TextRange.Characters.Text = "Hello people!"

Application.ScreenUpdating = True

Application.Wait (Now + TimeValue("00:00:03"))

For i = 1 To 25 Step 1
    ActiveSheet.Shapes(1).IncrementLeft -4
    ActiveSheet.Shapes(1).IncrementTop i
    Application.Wait (Now + 0.000009)
Next i

End Sub

A: How about?
Sub Macro1()

Dim shp As Shape
For Each shp In ActiveSheet.Shapes
    If shp.Type = 1 Then
        shp.Delete
    End If
Next shp

If ActiveSheet.Range("A1").Value = 1 Then
    ActiveSheet.Shapes.AddShape Type:=msoShapeOvalCallout, Left:=100, Top:=0, Width:=200, Height:=150
End If

If ActiveSheet.Range("A1").Value = 2 Then
    ActiveSheet.Shapes.AddShape Type:=msoShapeOvalCallout, Left:=100, Top:=50, Width:=200, Height:=150
End If

'and so on...
End Sub


text:
Q: How to monitor en0 network interface on a Mac, without having to use sudo? I have crafted a script (python+bash) which makes use of tcpdump to monitor and filter the TCP headers that flow through a network interface. It works smoothly for all interfaces but when it comes to ethernet en0 interface, Mac requires for tcpdump to be executed as root user (sudo).
Is there any programatic solution by which I can bypass the need to run it with sudo?
I find that tools like wireshark is able to do it without requesting the user for sudo password.
Any solution without requiring sudo would be great.

A:
Is there any programatic solution by which I can bypass the need to run it with sudo?

What do you mean by "programatic"?
The way Wireshark does this is that its installer

*

*creates an access_bpf group and puts the user into it;

*installs a StartupItem that changes the group owner of the current BPF devices to access_bpf and changes the permissions on them to rw-rw---- (as per the ls -l /dev/bpf* output in jonschipp's answer);

so that the user who installs Wireshark can run programs that use BPF (all programs using libpcap use BPF on OS X; tcpdump and Wireshark both use libpcap) without having to run them as root (at least as long as the program doesn't need a new BPF device; they're automatically created as needed, but they're created with permissions rw------- and owned by user and group root).
So if you've installed Wireshark, you can run not only Wireshark (and TShark, and the dumpcap program that both of them use to do packet capturing) as an ordinary user and capture traffic, you can also, for example, run tcpdump as an ordinary user and capture traffic.
I.e., it's not something in the Wireshark code that enables this, so it's not "programatic" in that sense, it's something installed by the Wireshark installer that enables this, and it enables it for all programs.

A: If you do not need to be in promiscuous mode then you can use tcpdump as a normal user. Use the '-p' option to disable promiscuous mode.
tcpdump -nni en0 -p

If you need to set your interface in promiscuous mode then you could enable the root account and become root via su and then proceed to run your script.
su root -
python myscript.py

Or
su -
python myscript.py

With sudo defaults it can be done like (presuming an admin account called Administrator)
su Administrator
sudo su
python myscript.py

If you're concerned about the password prompt sudo can avoid it by configuring the /etc/sudoers file to use the NOPASSWD option. You can then run your script as a normal user
without a password prompt.
You may also try giving the bpf device files read permission for other users.
Note: I haven't tested this.
$ ls -l /dev/bpf*
crw-rw----  1 root  access_bpf   23,   0 Aug  4 22:17 /dev/bpf0
crw-rw----  1 root  access_bpf   23,   1 Aug  4 22:16 /dev/bpf1
crw-rw----  1 root  access_bpf   23,   2 Aug  4 22:16 /dev/bpf2
crw-rw----  1 root  access_bpf   23,   3 Aug  4 22:16 /dev/bpf3

e.g.
chmod o+r /dev/bpf*


text:
Q: Rasterize in QGIS 3.0? How can I apply rasterizing process in QGIS 3.0. I know it is very simple quesiton. However I cannot find the rasterize tool.
EDIT
I rasterized a layer with GDAL\rasterize tool by using script which is:
parameters={"INPUT": layer,
                           "FIELD": "PolygonId",
                           "DIMENSIONS": 0,
                           "WIDTH": rps,
                           "HEIGHT": rps,
                           "RAST_EXT": "%f,%f,%f,%f" % (xmin, xmax, ymin, ymax),
                           "TFW": 1,
                           "RTYPE": 6,
                           "NO_DATA": 0,
                           "COMPRESS": 0,
                           "JPEGCOMPRESSION": 1,
                           "ZLEVEL": 1,
                           "PREDICTOR": 1,
                           "TILED": False,
                           "BIGTIFF": 2,
                           "EXTRA": '',
                           "OUTPUT": dosya}
processing.runAndLoadResults("gdal:rasterize",parameters)

However it does not work now.
I found the rasterize.py under this:
C:\OSGeo4W64\apps\qgis-dev\python\plugins\processing\algs\gdal\rasterize.py

I cannot use it again. What is the solution for rasterize by using at least these parameters;
Input, Field, Width, Height, Rasterize extension, Output


text:
Q: How to ensure correct type-checking in sequelize join-queries (with TypeScript)? Suppose we have two tables A and B associated like this:
A.hasMany(B);
B.belongsTo(A);

And we have this join query:
async getAll(): Promise<B[]> {
    return B.findAll({
         include: {
            model: A,
            attributes: ['id'],
            required: true
         }
    });
}

TypeScript says the return type for B.findAll() is B,
but this function is returning the type B & {"A": {id:number}} which is not B.
How to handle the fact that for TypeScript's compiler the return type is the same for join-queries and single-table-queries when is not the same at all?

A: Well, after a little research I found this article talking about TypeScript ORMs and type safety, and the conclusion is that maybe Sequelize is not the best option if type safety is a priority:
[...] Furthermore, when fetching associations using include, the return type does not include information about the nested shape of the fetched data, and to properly compile without errors, the developer must use ! non-null assertions and rejectOnEmpty parameters to override the compiler.


text:
Q: VS2005: Assembly '' is incorrectly specified as a file. I've added a reference to the log4net assembly dll to my project.
When I build I get a warning saying:

Warning Assembly 'Lib\log4net.dll' is
  incorrectly specified as a file.

I look up the help for this error on MSDN, and it says:

This warning is generated during
  application manifest generation when
  the build process detects that a file
  reference is actually a (managed or
  native) assembly.

This is exactly what I'm doing; the file reference is an assembly. What am I being told here?
How do I add a reference to an assembly dll, while not adding a reference to an assembly dll?

A: I was running into this problem myself.
This is what worked for me:
I had added an assembly as a reference and as an "Existing Resource." Deleting the file from the Solution Explorer, closing, then reopening the project worked.

A: Try setting the Build Action property of the source DLLs to None. It solved the issue for us.


text:
Q: Overleaf doesn't insert picture and shows empty rectangle This is the code snippet. The image is in the same location as the main .tex file and all I get is a rectangle with the name of the image.
\begin{figure}[htp]
        \centering
        \includegraphics[width=4cm]{B7oiUtYdkK-rb-case-3.png}
        \caption{Insertie cazul 3}
\end{figure}

A: This can happen when you have the document set to draft mode.
You may have set it as document class option like \documentclass[12pt,a4paper,draft]{article}, or maybe it is selected in the compiler options, as shown in this guide: https://www.overleaf.com/learn/how-to/Images_not_showing_up

The Fast [draft] mode skips some steps in order to speed-up
compilation, and often doesn't show included images.


text:
Q: Exempt an application from redshift? I'd like to use redshift on Ubuntu to redshift all but some whitelisted set of applications, e.g. Emacs, which I've configured to look the way I want already.  Is this possible?  If so, how do I specify the applications?

A: I don't think so, the only thing I saw was that you can start it with ...
redshift

(with some options) and disable it with ...
pkill -USR1 redshift

That seem to indicate there are no config options for enabling/disabling it per started software and that redshift works on a system wide base. The sample configuration does not have anything on it either. Something you might be able to work with: you can enable/disable it per viewport. Maybe you should group the software you do not want to use it with and make them open on viewport 2, and have redshift not do viewport 2.
So when you do
pkill -USR1 redshift && emacs

emacs would start without it and you would have to manually restart redshift. But putting that in front of any software you want it to start without seems a bit much.


text:
Q: My home directory is the same as "/var/www/" Apache Linux I am running a small webserver off of my RaspberryPi, and I have Apache2 installed on it. Everything works fine, and I can load html, php, and javascript from other computers, etc. However, the problem I am having with is that when I installed Apache, it made my home directory, the same as "/var/www/" where all the web pages are supposed to be stored. How can I change this, because I'm pretty sure the home directory should be separate from my server.
pi@raspberrypi:~$ pwd
/var/www
pi@raspberrypi:~$ cd /var/www
pi@raspberrypi:~$ ls
cookies.png  Desktop  hello.php  index.html  test.cpp  test.html  testImage
pi@raspberrypi:~$

EDIT: I'm running the default Raspbien OS.

A: /var/www/ is the default installation directory for Apache2.
https://help.ubuntu.com/12.10/serverguide/serverguide.pdf
Assuming you have Ubuntu installed, read over the documentation
You will stumble accross the following text:

1.2.1. Basic Settings This section explains Apache2 server essential configuration parameters. Refer to the Apache2 Documentation 3 for
  more details. • Apache2 ships with a virtual-host-friendly default
  configuration. That is, it is configured with a single default virtual
  host (using the VirtualHost directive) which can modified or used
  as-is if you have a single site, or used as a template for additional
  virtual hosts if you have multiple sites. If left alone, the default
  virtual host will serve as your default site, or the site users will
  see if the URL they enter does not match the ServerName directive of
  any of your custom sites. To modify the default virtual host, edit the
  file /etc/apache2/sites-available/default .

Perform
texteditor /etc/apache2/sites-available/default
replace texteditor  with your preferred editor. nano, vi etc..
Remember to make a backup prior to making changes.
After making changes you are happy with run:
service apache2 restart
to finalize the changes to your configuration file.
Edit:
Run the following:
usermod -d /path/to/new/homedir/ username
whilst logged in as a member of the super user group.

A: You can just edit your user line in /etc/passwd with new path for your home dir.
Or run usermod as mentioned above.


text:
Q: Local Storage value not storing on submit Not sure why this isn't working, but I have a form that I'm trying to store the input value of email into localStorage. But I also have it mixed in with some email validation, so I'm not sure if that could be causing it to fail and not store within the browser?
Here's what I have:
  $( "#loginform" ).submit(function(e) {
    var vaild_email = $('#loginform input[name=log]').val();
    if( /(.+)@(.+){2,}\.(.+){2,}/.test(valid_email) ){
      localStorage.setItem("email", valid_email);
      return true;
    } else {
      e.preventDefault(e);
    }
  });

Yeah, not sure if I'm missing something or just going about this all wrong?

A: Ok, so apparently, I'm running off of very little sleep because the root of all of these issues is I had misspelled my variable of valid_email.
Once I corrected that, everything is fine now.
Also worth noting that you cannot have a space between key and item.
Should be something like this:
localStorage.setItem("email",valid_email);
Not this:
localStorage.setItem("email", valid_email);
I'm gonna take a nap now.


text:
Q: Ionic Android "the redirect_uri is not supported" Facebook I am new in this of authentication with social networks, but I am developing an application with Ionic, Node, Mongo and Satellizer https://github.com/sahat/satellizer to make the auth with facebook and It's working fine on the browser but when I test it on android emulator I get this error:
https://drive.google.com/file/d/0B3vlNJIDJA6RTHlpeml5YjFxNUU/view?usp=sharing
My local configuration:
    // Satellizer configuration
   // Configuration common for all providers.
  var commonConfig = {
    // Popup should expand to full screen with no location bar/toolbar.
    popupOptions: {
      location: 'no',
      toolbar: 'no',
      width: window.screen.width,
      height: window.screen.height
    },
  };

    // Change the platform and redirectUri only if we're on mobile
  // so that development on browser can still work.
  if (ionic.Platform.isIOS() || ionic.Platform.isAndroid()) {
    commonConfig.redirectUri = 'http://localhost:3000';
  }

  api = "http://127.0.0.1:3000/";
  //api = "https://testing-miguelcrespo.c9.io/";
  $authProvider.loginUrl = api+'auth/login';
  $authProvider.signupRedirect = '/';

  $authProvider.facebook({
    clientId: '1553815514880424',
    url: api+"auth/facebook"
  });

My facebook app details:
APP ID: 1553815514880424
Site URL: http://localhost:3000/
App Domains: localhost

A: I had a similar issue with a web client and Google giving the same response. Will it work for you if you go for implicit flow. Try:
      $authProvider.google({
        clientId: '1553815514880424',
        url: api+"auth/facebook",
        responseType: 'token'
  });


text:
Q: Spring Data Mongo: dropCollection doesn't remove collection completely? Code:
template.dropCollection("products");

After code execution, I see that all documents from collection products were removed, but collection by itself still exists.
So, the question then is how to drop collection completely?
Note: spring-data-mongodb:2.2.10.RELEASE
Mongo DB 4.2.12.

A: There is a refresh button when you use MongoDB Compass.

Check the collection names, it is already dropped.
System.out.println(template.getCollectionNames());
template.dropCollection("products");
System.out.println(template.getCollectionNames());


text:
Q: kubernetes: how to write pod yaml file for mapping volumn from host to container I have a command to run docker,
docker run --name pre-core -itdp 8086:80 -v /opt/docker/datalook-pre-core:/usr/application app

In above command, /opt/docker/datalook-pre-core is host directory, /usr/application is container directory. The purpose is that container directory maps to host directory. So when container crashes, the directory functions as storage and data on it would be saved.
When I am going to use kubernetes to create a pod for this containter, how to write pod.yaml file?
I guess it is something like following:
apiVersion: v1
kind: Pod
metadata:
  name: app-ykt
  labels:
    app: app-ykt
    purpose: ykt_production
spec:
  containers:
  - name: app-ykt
    image: app
    imagePullPolicy: IfNotPresent
    ports:
      - containerPort: 80
    volumnMounts:
      - name: volumn-app-ykt
        mountPath: /usr/application
  volumns:
      - name: volumn-app-ykt
      ????

I do not know what's the exact properties in yaml I shall write in my case?

A: This would be a hostPath volume: https://kubernetes.io/docs/concepts/storage/volumes/
  volumes:
  - name: volumn-app-ykt
    hostPath:
      # directory location on host
      path: /opt/docker/datalook-pre-core
      # this field is optional
      type: Directory

However remember that while a container crash won't move things, other events can cause a pod to move to a different host so you need to be prepared to both deal with cold caches and to clean up orphaned caches.


text:
Q: Filtering bootstrap card visibility based on content inside card I can't figure out something that is probably quite simple to do. I have a grid with cards that look like this:

{{ book }}

{{ books[book]['author'] }}

I have an input field called search-authors and want to hide cards that do not contain whatever the value of search-authors is.
I'm trying to use this:
            $("#search-authors").on("keyup", function() {
              var value = $(this).val().toLowerCase();
                $(".card *").filter(function() {
                  $(".card").css('display', 'none')
                  .filter(':contains(' + value + ')')
                  .css('display', 'block');
                });
            });

This isn't working the way I expect it to. For example, typing just c shows only cards which contain c but typing co hides cards that contain co and did show up correctly typing just c.
Any pointers would be greatly appreciated!
Thanks

A: There's a couple of issues in your code.

*

*You need to select the .card elements, not their child elements, and hide/show them directly.

*Use the input event instead of keyup. The former allows people to paste content in with the mouse, the latter does not.

*You don't need to nest the filter() calls.

*You're using filter() like a loop, which is unnecessary. Call filter() directly on the .card collection and update the matching elements from there.

*:contains is case-sensitive by default, so converting the input to lowercase isn't enough. However, you can implement your own case-insensitive version of :contains (credit @HighwayOfLife in this answer)

With all that said, try this:

$.expr[':'].icontains = (a, i, m) => $(a).text().toUpperCase().indexOf(m[3].toUpperCase()) >= 0;

$("#search-authors").on("input", e => {
  $(".card").hide().filter(`:icontains(${e.target.value.trim()})`).show();
});

<input type="text" id="search-authors" />

ABC Book 1

DEF Author 1

ABC Book 2

DEF Author 2

UVW Book 1

XYZ Author 1

UVW Book 2

XYZ Author 2


text:
Q: How can I put a URL in a HTTP request (as the query string)? I am building a webapp using Node and my server needs to be forwarded the API call that a user wants to make. Basically in the frontend the user enters the API call they want to make. A request should then be sent to the server with the details of that call.
What is the best way to send that information?

A: This is a very simple example but let me know if you need more detail.
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

redirect

This will let you send the url trough the query string, in the other side you just get the string and decode it, it is base64 if you are using javascript you can use the function atob() to decode what we encode with btoa or any other base64 decoder if you are in other languages.
For more details you can check this page https://developer.mozilla.org/en/docs/Web/API/WindowBase64/Base64_encoding_and_decoding


text:
Q: Leading up to Young's Inequality I am trying to prove Young's Inequality by considering the function $$h(u) = \frac{u^p}{p} + \frac{C^q}{qu^q}$$ for $C,u>0$ and $p,q >1$. We also require $$\frac{1}{p}+\frac{1}{q}=1$$ so that $pq=p+q$. I starting by using straightforward calculus to show that $h$ has a global minimum at $u=C^{\frac{1}{p}}$.
Next, I would like to show that $C \leqslant h(u)$ for any $C,u>0$. If I can do this, I will be able to let $C=uv$ for $u,v\geqslant 0$ and arrive at Young's Inequality. However, I am having trouble doing so. I feel like there is something very simple that I'm just not seeing in connecting these steps. Any help would be greatly appreciated. Thanks.


text:
Q: Is the Gamma function superadditive? A function $f$ is superadditive if $f(x) + f(y) \le f(x+y)$. The question is:
Does a real number $a$ exists such that for all
real numbers with $x, y\ \ge \ a $
$$ \Gamma(x) + \Gamma(y) \le \Gamma(x+y) \quad ?$$

A: $a = 2$ will do, because (letting $x \ge y$ wlg),
$\Gamma(x+y) \ge \Gamma(x+2) = (x+1)x \Gamma(x) \ge 6 \Gamma(x) \ge \Gamma(x) + \Gamma(x) \ge \Gamma(x) + \Gamma(y)$.


text:
Q: If $f(x)$ and $g(x)$ are continuous on $[a,b]$ with the same range $[0,1]$, then $f(c)=g(c)$ for some $c\in [a,b]$
If $f(x)$ and $g(x)$ are continuous on $[a,b]$ with the same range $[0,1]$, then $f(c)=g(c)$ for some $c\in [a,b]$.

Let $h(x)=f(x)-g(x)$, $x\in [a,b]$. I want to use IVP. But I am in trouble to use it as $h(a)h(b)$ is not given as $<0$.
What to do? Please help.

A: You can suppose without loss of generality that $[a,b]=[0,1]$. So, there are basically three cases:
$(1)$ $\:\:f(0)=g(0)$. In this case, we are done.
$(2)$ $\:\:f(1)=g(1)$. In this case, we are done.
$(3)$ Now, study the function $f-g$. By the Intermediate Value Property, if $f(0)<g(0)$ and $g(1)<f(1)$, we are done. Maybe this isn't the case, however. Then, suppose that $f(0)<g(0)$ and $f(1)<g(1)$. Well, the only way that $f-g$ never becomes nonnegative is if $f<g$ on the whole interval $[0,1]$. This implies that $f(x)\ne 1$ for all $x\in [0,1]$, however, because if $f(x)=1$, then $g(x)\le f(x)$.
So, we conclude that there must exist some point $y\in [0,1]$ for which $g(y)\le f(y)$. The result follows by the Intermediate Value Property. Note that the case where $f,g$ are flipped follows from the exact same argument by symmetry.

A: Ad absurdum if there is no $c$ such that $f(c)=g(c)$, since $f$ and $g$ are continuous then with the Intermediate Value Property, $\forall x \in [a,b], f(x)>g(x)$ or $f(x)<g(x)$, without loss of generalty we will suppose the first case.
Since $g$ has range $[0,1],\forall x \in [a,b],g(x)\geq0$, so $\forall x \in [a,b],f(x)>g(x)\geq0$, finally $\forall x \in [a,b],f(x)>0$. So the range of $f$ is not $[0,1]$, we have a contradiction.
So the assertion is true.

A: Let $h$ defined by $h(x)=f(x)-g(x)$. Since the range of $f$ is $[0,1]$ there exists $u\in [a,b]$ with $f(u)=0$, $h(u)=-g(u)\leq 0$. There exists $v\in [a,b]$ with $f(v)=1$, $h(v)=1-g(v)\geq 0$. If $u\leq v$, the intermediate value theorem implies there exists $c\in [u,v]\subset [a,b]$ with $h(c)=f(c)-g(c)=0$. Similar argument if $v<u$.

A: Suppose, w.l.o.g., that $h(a)\geq0$. If we can find $x\in[a,b]$ such that
$h(x)\leq0$, we can conclude the desired result by the IVP. To arrive
at a contradiction, suppose
$$
h(x)=f(x)-g(x)>0\text{ for all }x\in[a,b].
$$
Now, pick $y\in[a,b]$ such that $g(y)=1$ to obtain $h(y)=f(y)-1>0$. Therefore, $f(y)>1$, a contradiction.


text:
Q: Why do I get 'HDIO_GET_IDENTITY failed' message when booting with external usb hard drive? I've installed Ubuntu 11.10 on an external USB (2.0) Hard Drive (/dev/sdb1) but when Ubuntu starts I get a message that says:

ata_id[279]: HDIO_GET_IDENTITY failed for '/dev/sdb': Invalid argument

where I made a mistake? The first HD contains Windows 7 (the official OS of my packard bell notebook).

A: This is a warning from hdparm as it can have problems communicating with external usb hard drives, so you can ignore that warning.
Source: 1, 2

A: I am getting the same error on a fresh install of Ubuntu 12.04 on an external USB hard disk.
The message is displayed for ~5 sec at boot but ubuntu does boot and run properly after that. I have also noticed some data loss but can't say for certain if its connected to this error.
According to to other help threads on the net this error only appears when Ubuntu is installed on an external USB drive.


text:
Q: AWS EC2 SSH: Permission denied (publickey) I've configured my EC2 instance, and connected with SSH. But when I created a new Security Group with port rules I couldn't access via SSH anymore. Currently, my custom Security Group rules are:
SSH   0.0.0.0/0
HTTP  0.0.0.0/0
HTTPS 0.0.0.0/0

When I try ssh -v -i bodruk.pem ubuntu@ec2-54-149-134-92.us-west-2.compute.amazonaws.com I have the following error:
OpenSSH_6.6.1, OpenSSL 1.0.1i 6 Aug 2014
debug1: Connecting to ec2-54-149-134-92.us-west-2.compute.amazonaws.com [54.149.
134.92] port 22.
debug1: Connection established.
debug1: identity file bodruk.pem type -1
debug1: identity file bodruk.pem-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_6.6.1
debug1: Remote protocol version 2.0, remote software version OpenSSH_6.6.1p1 Ubu
ntu-2ubuntu2
debug1: match: OpenSSH_6.6.1p1 Ubuntu-2ubuntu2 pat OpenSSH_6.6.1* compat 0x04000
000
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-ctr hmac-md5-etm@openssh.com none
debug1: kex: client->server aes128-ctr hmac-md5-etm@openssh.com none
debug1: sending SSH2_MSG_KEX_ECDH_INIT
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ECDSA e2:13:af:e1:1b:70:f9:70:3b:cd:1d:7f:14:de:ce:90
debug1: Host 'ec2-54-149-134-92.us-west-2.compute.amazonaws.com' is known and ma
tches the ECDSA host key.
debug1: Found key in /c/Users/Thiago/.ssh/known_hosts:2
debug1: ssh_ecdsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: Roaming not allowed by server
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Trying private key: bodruk.pem
debug1: key_parse_private2: missing begin marker
debug1: read PEM private key done: type RSA
debug1: Authentications that can continue: publickey
debug1: No more authentication methods to try.
Permission denied (publickey).

Already tried this solution, but doesn't work. I changed the Key Pair twice and deleted the known_hosts file with no success.
Any idea?

A: Can you telnet to the instance with the ssh port? (telnet 'ip' 'port')
If you can telnet, so the problem probably in the Key Pair or something in your computer. And if not, its probably something with the Security Group and network.

A: I ran into this issue recently and the funny part is my pem file was owned by root instead of my user.  When I did sudo chown user:group {pem file name}, I was able to ssh in without a problem.


text:
Q: SCIP compile and installation problems in linux I have been trying to compile and install SCIP under Linux but at the end of the compiling process appears the following error....
** Build complete.
** Find your SCIP binary in "/home/carloserwin/Documents/scipoptsuite-4.0.0/scip-4.0.0/bin".
** Enter "make test" to solve a number of easy instances in order to verify that SCIP runs correctly.

make[2]: Leaving directory '/home/carloserwin/Documents/scipoptsuite-4.0.0'
make[1]: Leaving directory '/home/carloserwin/Documents/scipoptsuite-4.0.0'
make[1]: Entering directory '/home/carloserwin/Documents/scipoptsuite-4.0.0'
ar: /home/carloserwin/Documents/scipoptsuite-4.0.0/zimpl-3.3.4/obj/O.linux.x86.gnu.shared.opt/blkmem.o: No such file or directory
make[1]: *** [Makefile.doit:238: scipoptlib] Error 1
make[1]: Leaving directory '/home/carloserwin/Documents/scipoptsuite-4.0.0'
make: *** [Makefile:98: scipoptlib] Error 2

when I write "make test", almost every test fails. After several attempts in Linux with no success, I tried to compile in Mac and it worked perfect, and all tests are ok. But I need to get it to work on Linux.
gcc version is 7-2.1
OS Linux openSUSE Tumbleweed, KDE 5.10.3
32-bit

A: It seems that the scipoptlib makefile uses the wrong directory to look for the zimpl objects. There seems to be some fix in the internal development version, maybe it will help:
diff --git a/Makefile.doit b/Makefile.doit
index 344f0ee..1d8077e 100644
--- a/Makefile.doit
+++ b/Makefile.doit
@@ -65,7 +65,7 @@ ZIMPLOBJECTS =          blkmem.o bound.o code.o conname.o define.o elem.o entry.

 ifeq ($(ZIMPL),true)
-SCIPOPTOBJFILES    +=  $(addprefix $(ZIMPLDIR)/obj/O.$(OSTYPE).$(ARCH).$(COMP).shared.$(ZIMPLOPT)/,$(ZIMPLOBJECTS))
+SCIPOPTOBJFILES    +=  $(addprefix $(ZIMPLDIR)/obj/O.$(OSTYPE).$(ARCH).$(COMP).$(LIBTYPE).$(ZIMPLOPT)/,$(ZIMPLOBJECTS))
 endif

 ifeq ($(LIBBUILD),$(LINKCC))


text:
Q: Getting Error when I add platform android in cordova phongegap project
I am using cordova 5.4.0 on windows. Everything works fine but when i
  add the platform through command cordova platform add android
  getting error

Adding android project...
Running command: cmd "/s /c "C:\Users\PRABHU\.cordova\lib\npm_cache\cordova-andr
oid\4.1.1\package\bin\create.bat C:\Users\PRABHU\hello\platforms\android com.exa
mple.hello HelloDemo --cli""
Error: cmd: Command failed with exit code ENOENT

I have install all the software Node js, winAnt, Java jdk, Android
  studio
  please help me to resolve this.


text:
Q: Neural-Style output flag I'm messing around with jcjohnson/neural-style. I have it up and running just fine. However, I cannot for the life of me make the -output_image or -init flags work. My gut says it's some very simple misunderstanding on my part.
-output_image is driving me especially nuts because it should just be a string to use as the filename, the script even appends the file formate in function that takes -output_image as an argument. I've tried single, double, and no quotes, as well as changing the order of the flags. My gut says it's something trivially simple because nobody is complaining about this on-line anywhere,but I'm a little in over my head because I'm not especially proficient with either bash, torch, or lua.
I'm using this simple script I hacked together that works just fine if I leave off both of the troublesome flags
#!/bin/bash

echo "####  Starting Job B  ####"
th neural_style.lua \
-gpu -1 \
-print_iter 1 \
-save_iter 10 \
-num_iterations 3000 \
-style_image a_style.jpg \
-content_image a_content.jpg \
-style_scale 0.15 \
-style_weight 25 \
-content_weight 1e3 \
-output_image a \
-init a_460.png \

The above throws "Invalid argument: "
if it helps, in the script 'neural_style.lua'
the flags are defined as
cmd:option('-init', 'random', 'random|image')
...
cmd:option('-output_image', 'out.png')

and used as
  local function maybe_save(t)
    local should_save = params.save_iter > 0 and t % params.save_iter == 0
    should_save = should_save or t == params.num_iterations
    if should_save then
      local disp = deprocess(img:double())
      disp = image.minmax{tensor=disp, min=0, max=1}
      local filename = build_filename(params.output_image, t)
      if t == params.num_iterations then
        filename = params.output_image   -- ## LOOK HERE ##
      end

      -- Maybe perform postprocessing for color-independent style transfer
      if params.original_colors == 1 then
        disp = original_colors(content_image, disp)
      end

      image.save(filename, disp) -- ## LOOK HERE ##
    end
  end

as well as
  if params.init == 'random' then
    img = torch.randn(content_image:size()):float():mul(0.001)
  elseif params.init == 'image' then
    img = content_image_caffe:clone():float()
  else
    error('Invalid init type') -- ## NOT THE ERROR THROWN #
  end
  if params.gpu >= 0 then


text:
Q: How do I save the states of an RNN to file from a Graph in TF? The following code is from the tensorflow serving API:
// Implementation of Predict using the SavedModel SignatureDef format.
Status SavedModelPredict(const RunOptions& run_options, ServerCore* core,
                         const PredictRequest& request,
                         PredictResponse* response) {
  // Validate signatures.
  ServableHandle<SavedModelBundle> bundle;
  TF_RETURN_IF_ERROR(core->GetServableHandle(request.model_spec(), &bundle));

  const string signature_name = request.model_spec().signature_name().empty()
                                    ? kDefaultServingSignatureDefKey
                                    : request.model_spec().signature_name();
  auto iter = bundle->meta_graph_def.signature_def().find(signature_name);
  if (iter == bundle->meta_graph_def.signature_def().end()) {
    return errors::FailedPrecondition(strings::StrCat(
        "Serving signature key \"", signature_name, "\" not found."));
  }
  SignatureDef signature = iter->second;

  MakeModelSpec(request.model_spec().name(), signature_name,
                bundle.id().version, response->mutable_model_spec());

  std::vector<std::pair<string, Tensor>> input_tensors;
  std::vector<string> output_tensor_names;
  std::vector<string> output_tensor_aliases;
  TF_RETURN_IF_ERROR(PreProcessPrediction(signature, request, &input_tensors,
                                          &output_tensor_names,
                                          &output_tensor_aliases));
  std::vector<Tensor> outputs;
  RunMetadata run_metadata;
  TF_RETURN_IF_ERROR(bundle->session->Run(run_options, input_tensors,
                                          output_tensor_names, {}, &outputs,
                                          &run_metadata));

  return PostProcessPredictionResult(signature, output_tensor_aliases, outputs,
                                     response);
}

This code runs a prediction with a stored model. In my case, this stored model is an RNN.
After the following line where the prediction is actually run:
TF_RETURN_IF_ERROR(bundle->session->Run(run_options, input_tensors,
                                      output_tensor_names, {}, &outputs,
                                      &run_metadata));

I want to save the states of the RNN to a file/memory so that I can access them at a later date after each prediction. I assume these states can be accessed via the variable:
bundle->meta_graph_def

but am unclear on exactly how to access specifically the state values of the RNN and then to save them to a file.

A: You have to get the values via the session, not after the fact. In your line
bundle->session->Run(run_options, input_tensors,
                                  output_tensor_names, {}, &outputs,
                                  &run_metadata)

You should not only request the result of the prediction, but also the state tensor. Note that the value of the state is not stored after the particular call to session->Run, only variables are stored, the state of the RNN is a computed value and dropped after the results you requested are returned.
I don't use the c++ interface, so forgive me for giving a code example in python, hopefully it's still of use (I bet this isn't the first time you've had to put up with reading a python example), in python this would look like:
prediction, state = sess.run([prediction_tensor, state_tensor], feed_dict=...)


text:
Q: Update record in firebase storage visible only after refreshing the page When editing a record in my collection in firebase and change the image, it will successfully update in Firebase and in Google Cloud Platform (storage), but in the template I am not able to see the change unless I refresh the page. The error I get is: Error: Can't set headers after they are sent.
router.get('/edit/:id', function(req, res) {
  var id = req.params.id;
  firebase.database().ref(`collection/` + id).once('value')
    .then(function(data) {
      res.render('myEditTemplate', {
        id: id,
        collectionRecords: data.val()
      });
    })
    .catch(function(error) {
      res.render('error', {
        error: error
      });
    });
});

router.post('/edit', upload.single('image'), function(req, res) {
  var id = req.body.id;
  var name = req.body.name;
  var image = req.file;

  if (!req.file) {
    console.log('no image has been uploaded');

    firebase.database().ref(`collection/` + id).update({
      'name': name,
    });
  } else {
    console.log('image successfully uploaded');

    var filePath = id + ".jpg";

    fs.rename(req.file.path, filePath, function(err) {
      if (err) {
        return res.render("error", {
          err: err
        });
      }

      var myPath = 'collection/' + filePath;
      var storageFile = bucket.file(myPath);
      var storageFileStream = storageFile.createWriteStream({
        metadata: {
          contentType: req.file.mimetype
        }
      });

      storageFileStream.on('error', function(err) {
        return res.render("error", {
          error: err
        });
      });

      storageFileStream.on('finish', function() {
        storageFile.makePublic(function(err, data) {

          if (err) {
            return res.render("error", {
              err: err
            });
          }
        });

        fs.unlink(filePath, function(err) {

          console.error(err);
        });

        firebase.database().ref(`collection/` + id).update({
          'name': name,
          'image_id': filePath
        });
      });
      fs.createReadStream(filePath).pipe(storageFileStream);
    });
  }
  res.redirect('/collection');
});

A: When you're getting such an error, it means you are sending the response to the client more than once (specifically, setting the headers).
The source of the error in this case is the fact you have res.redirect(...) and res.render(...).
router.post('/edit', upload.single('image'), function(req, res) {
  var id = req.body.id;
  var name = req.body.name;
  var image = req.file;
  ...
    // Eventually update the file in Google Cloud Storage
    // This happens in an async way.
  ...

  // This will be always called first
  res.redirect('/collection');
});

In case of an error coming from the async operations, you'll get the error you mentioned. It simply fails to render the error template, because you already did redirect(...).
Your current timeline looks like this:
           ___ Update the image in GC __
          /                             \
|--*-----*--*----------------------------*------>
   |        |                         Is there an error?
 Request    |                             If so, res.render(...)
            |                             Rendering the error template
      res.redirect(...)                   will always fail due to the
            |                             previous res.redirect(...)
            |
            V
     You do not see the new image
     at this moment, because it's
     simply not updated yet.

What it should happen is:
           ___ Update the image in GC __
          /                             \
|--*-----*-------------------------------*------>
   |                                  Is there an error?
 Request                                If so, show the error:
                                          res.render(...)
                                        If not, do the redirect:
                                        res.redirect(...)
                                         |
                                         V
                                     Since the page is going to load
                                     *after* the image was updated
                                     you will see the updated image.

The code will look like this:
router.post('/edit', upload.single('image'), function(req, res) {
  var id = req.body.id;
  var name = req.body.name;
  var image = req.file;

  if (!req.file) {
    console.log('no image has been uploaded');
    firebase.database().ref(`collection/` + id).update({
      'name': name,
    }).then(function() {
      res.redirect('/collection');
    }).catch(function(err) {
      res.render("error", {
        err: err
      });
    })
  } else {
    console.log('image successfully uploaded');
    var filePath = id + ".jpg";
    fs.rename(req.file.path, filePath, function(err) {
      if (err) {
        return res.render("error", {
          err: err
        });
      }

      var myPath = 'collection/' + filePath;
      var storageFile = bucket.file(myPath);
      var storageFileStream = storageFile.createWriteStream({
        metadata: {
          contentType: req.file.mimetype
        }
      });

      storageFileStream.on('error', function(err) {
        return res.render("error", {
          error: err
        });
      });

      storageFileStream.on('finish', function() {
        storageFile.makePublic(function(err, data) {
          if (err) {
            return res.render("error", {
              err: err
            });
          }
          res.redirect('/collection');
        });

        fs.unlink(filePath, function(err) {
          console.error(err);
        });

        firebase.database().ref(`collection/` + id).update({
          'name': name,
          'image_id': filePath
        });
      });
      fs.createReadStream(filePath).pipe(storageFileStream);
    });
  }
});


text:
Q: How to get bounding Box Over text In Images such as Japanese Vertical Fonts Bussiness Cards? Using Python Input
Expected Result
How to Have bounding box as shown in he expected result, the approach should also take that some cards may have vertical fonts while others may have horizontal font


text:
Q: Designing View Similar to the UITableView In Android I am developing an android application where I want a table view such as UITableView in iPhone. Has any one tried before. I checked here their are many requirement for similar but seems no one tried before. Please any one has solution on this give to me.
Thank You.

A: Try this one first: Android equivalent to iphone indexed UITableView
Or this one: http://blogingtutorials.blogspot.com/2010/12/iphone-uitable-view-in-android.html (I haven't checked it yet, but its screenshot is OK).


text:
Q: Hide MKUserLocation when MKMapView showsUserLocation == YES After setting mapView.showsUserLocation to true, is it possible to receive location updates without showing the MKUserLocation bubble? Returning nil in mapView:viewForAnnotation: simply shows the bubble, and returning any other kind of annotation shows an annotation, which I don't want.

A: Swift 3:
func mapView(_ mapView: MKMapView, didAdd views: [MKAnnotationView]) {
   if let userLocation = mapView.view(for: mapView.userLocation) {
        userLocation.isHidden = true
   }
}

A: You can hide the user location's view in the didAddAnnotationViews delegate method:
-(void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views
{
    MKAnnotationView *ulv = [mapView viewForAnnotation:mapView.userLocation];
    ulv.hidden = YES;
}


text:
Q: Keep service waking up periodically android I have an app which is based on a service. My goal is to make the service working even if the screen is off and the phone is sleeping. My problem is that I am using alarm manager to wake up the cpu periodically and sometimes, very often happens that the process just stops updating. Can you help me why ?
Here is my service code:
public class NotificationService extends Service {
static String updateOnWifi;
SharedPreferences sharedpreferences;
String url;
String firstEventDescription = "Zatial ziadna nehoda";
String secondEventDescription = "Zatial ziadna nehoda";
String mp3Link = "false";
static int NOTIFICATION = 10002;
NotificationManager nManager;
private Handler mHandler = new Handler();
private Timer mTimer = null;
MediaPlayer mediaPlayer;
boolean vibrate;
boolean updateWiFi;
boolean updateMe;
private PowerManager.WakeLock wl;

@Override
public IBinder onBind(Intent arg0) {
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    //Toast.makeText(this, "Updating", Toast.LENGTH_LONG).show();

    if (mTimer != null) {
        mTimer.cancel();
    } else {
        mTimer = new Timer();
    }
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "DoNjfdhotDimScreen");
    wl.acquire();
    sharedpreferences = getSharedPreferences("Settings", Context.MODE_PRIVATE);
    url = sharedpreferences.getString("url", "http://5.9.44.5/waze/appjson.php");
    Log.d("tag","new url "+url);
    int updateInterval = sharedpreferences.getInt("UpdateTimeout", 20);
    updateWiFi = sharedpreferences.getBoolean("Wifi", false);
    vibrate = sharedpreferences.getBoolean("Vibrate", true);
    boolean run = sharedpreferences.getBoolean("Running", false);
    if (run) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.SECOND, updateInterval);
        Intent i1 = new Intent(NotificationService.this, NotificationService.class);
        PendingIntent pi = PendingIntent.getService(NotificationService.this, 123, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        new DownloadJSON().execute();
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pi);
    }
    else{
        stopSelf();
    }
    //mTimer.scheduleAtFixedRate(new RepeatTask(), 0, updateInterval * 1000);
    return START_STICKY;
}

private void showNotification() {
    NotificationCompat.Builder builder =
            new NotificationCompat.Builder(this).setSmallIcon(R.mipmap.ic_launcher).setContentTitle("Downloading...").setContentText(firstEventDescription).setOngoing(true);
    Intent targetIntent = new Intent(this, MainActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(contentIntent);
    nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    nManager.notify(NOTIFICATION, builder.build());
}

@Override
public void onDestroy() {
    super.onDestroy();
    //Toast.makeText(this, "Cancelling", Toast.LENGTH_LONG).show();
    if (mediaPlayer != null) {
        mediaPlayer = null;
    }
    if (nManager != null) {
        nManager.cancel(NOTIFICATION);
    }
    mTimer.cancel();
}

private class DownloadJSON extends AsyncTask<Void, Void, Void> {
    @Override
    protected void onPreExecute() {

        showNotification();
        String abc = NetworkUtil.getConnectivityStatusString(NotificationService.this);
        Log.d("Tag", "provider: " + abc);
        if (abc.equalsIgnoreCase("mobile") || updateWiFi) {
            updateMe = true;
            showNotification();
        } else {
            updateMe = false;
            if (nManager != null) {
                nManager.cancel(NOTIFICATION);
            }
        }
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... params) {
        if (updateMe) {
            // Retrieve JSON Objects from the given URL address
            JSONObject jsonobject = JSONfunctions
                    .getJSONfromURL(url);
            if (jsonobject == null) {
                url = "http://5.9.44.5/waze/appjson.php";
            } else {
                try {
                    firstEventDescription = jsonobject.getString("text");
                    Log.d("Tag","First event: "+firstEventDescription);
                    if (firstEventDescription.equalsIgnoreCase("false")) {
                        firstEventDescription = secondEventDescription;
                    }
                    else {
                        secondEventDescription = firstEventDescription;
                    }
                    url = jsonobject.getString("url");
                    mp3Link = jsonobject.getString("mp3");
                    Log.d("Tag","url from server: " +url + " Notification display: " + firstEventDescription);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void args) {
        SharedPreferences.Editor editor = sharedpreferences.edit();
        editor.putString("url", url);
        editor.apply();
        if (!mp3Link.equalsIgnoreCase("false")) {
            showNotification();
            if (vibrate) {
                Vibrator v = (Vibrator) NotificationService.this.getSystemService(Context.VIBRATOR_SERVICE);
                v.vibrate(750);
            }
            mediaPlayer = MediaPlayer.create(NotificationService.this, Uri.parse(mp3Link));
            if (mediaPlayer != null) {
                mediaPlayer.start();
                mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        if (mediaPlayer != null) {
                            mediaPlayer.stop();
                            mediaPlayer.release();
                        }
                    }
                });
            }
            mp3Link = "false";
        }
        wl.release();
    }
}

class RepeatTask extends TimerTask {

    @Override
    public void run() {
        // run on another thread
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                new DownloadJSON().execute();
            }

        });
    }

}

}


text:
Q: Aspnet Core Spa Application with Angular 8 is not loading I'm struggling with deploying a aspnet core app with an angular spa inside.
I have this on my startup.cs
services.AddSpaStaticFiles(configuration =>
        {
            configuration.RootPath = "Backoffice/dist";
        });

app.UseStaticFiles();
app.UseSpaStaticFiles();

app.UseSpa(spa =>
        {
            // To learn more about options for serving an Angular SPA from ASP.NET Core,
            // see https://go.microsoft.com/fwlink/?linkid=864501

            spa.Options.SourcePath = "Backoffice";

            if (env.IsDevelopment())
            {
                spa.UseAngularCliServer(npmScript: "start");
                spa.Options.StartupTimeout = TimeSpan.FromSeconds(600);
            }
        });

From all the tuts I've seen online this looks pretty straightforward, but when I go to the root of my app the console gives me this errors:

Failed to load module script: The server responded with a
  non-JavaScript MIME type of "text/html". Strict MIME type checking is
  enforced for module scripts per HTML spec.

And the page stays blank, even after publish and deployed to production server.
But if I navigate to localhost/backoffice/dist the angular loads


text:
Q: Html canvas resize I have html canvas with drawing functionality.
On resize window I resize the canvas and redraw all elements from react state.
But the drawn elements is not resized and are not on the same place relative to canvas margins.
The drawing is free style with  pen, so I need to resize that drawing. Its, not rectangles and circles, I know how to resize that.


text:
Q: Crystal Reports Export to .csv comma delimited string inserting blank columns I have a issue and need some expert help!  I'm trying to export a .csv field directly from crystal reports and I keep getting blank columns in between my datasets.  The report is one formula only in the details section, that contains a string separated by comma's like below.  Any help or suggestions is greatly appreciated!
*Side note the requirements are an export directly to .csv so no export to data only then save to .csv will work.

A: Your approach implicitly converts numbers to text. This might results in extra commas due to thousand separators.
Instead, use explicit conversion such as
ToText({your number}, 2, "")

to avoid the extra commas.


text:
Q: Prevent jekyll from cleaning up generated JSON file? I've written a simple plugin that generates a small JSON file
module Jekyll

  require 'pathname'
  require 'json'

  class SearchFileGenerator < Generator
     safe true

     def generate(site)
       output = [{"title" => "Test"}]

       path = Pathname.new(site.dest) + "search.json"

       FileUtils.mkdir_p(File.dirname(path))
       File.open(path, 'w') do |f|
         f.write("---\nlayout: null\n---\n")
         f.write(output.to_json)
       end
       # 1/0
     end
   end
end

But the generated JSON file gets deleted every time Jekyll runs to completion. If I uncomment the division by zero line and cause it to error out, I can see that the search.json file is being generated, but it's getting subsequently deleted. How do I prevent this?

A: I found the following issue, which suggested adding the file to keep_files: https://github.com/jekyll/jekyll/issues/5162 which worked:
The new code seems to avoid search.json from getting deleted:
module Jekyll

  require 'pathname'
  require 'json'

  class SearchFileGenerator < Generator
     safe true

     def generate(site)
       output = [{"title" => "Test"}]

       path = Pathname.new(site.dest) + "search.json"

       FileUtils.mkdir_p(File.dirname(path))
       File.open(path, 'w') do |f|
         f.write("---\nlayout: null\n---\n")
         f.write(output.to_json)
       end
       site.keep_files << "search.json"
     end
   end
end

A: Add your new page to site.pages :
module Jekyll
  class SearchFileGenerator < Generator
    def generate(site)
      @site  = site
      search = PageWithoutAFile.new(@site, site.source, "/", "search.json")
      search.data["layout"] = nil
      search.content = [{"title" => "Test 32"}].to_json
      @site.pages << search
    end
  end
end

Inspired by jekyll-feed code.


text:
Q: Cannot access to own hosted gitlab I've installed gitlab on my own server but I can't access to gitlab's main page , in /etc/gitlab/gitlab.rb I've setted the following variables
external_url 'http://myip:8085/gitlab'

and
nginx['listen_port'] = 8085

If i try to acces to http://myip:8085/gitlab the browser doesn't found the
url , The connection has timed out
I've missed something??


text:
Q: When using res.send the entire file is not being sent On my back end, I am getting a stream that contains the data from a website that contains much more information than is being sent from my route. From this code:
feedparser.on('readable', function(){
    var stream = this;
    var meta = this.meta;
    var item;

    while(item=stream.read()){
        theNews = item;
        console.log(JSON.stringify(theNews));
    }
});

news.post('/', function(req, res){
    var currentNews = JSON.stringify(theNews);
    console.log(currentNews);
    res.send(currentNews);
});

the console.log in feedparser.on returns an object with many news articles. When I console log it in that scope, it shows all the articles properties such as title, description, link, etc... It takes up the entire cmd console log giving me over 80,000 characters because it includes multiple articles.
However, the console.log from news.post and the response it sends is only the oldest object in the stream which is one article. Why?
EDIT: NM I was able to figure it out. I had to set theNews as an array and then push item into it as it.

A: The stream was streaming the data as it grabbed it and it did it really rapidly so the output was multiple streams that looked like one file. In reality, I was only setting the variable to the last item streamed. By using an array and pushing into it I was able to get all the information.


text:
Q: laravel Job / Queue not been processed weird infinite loop I'm trying to create a queue but it doesn't work when I run php artisan queue:work all I get in my terminal is
[2017-11-30 19:56:27] Processing: App\Jobs\ProcessCSV
[2017-11-30 19:56:27] Processing: App\Jobs\ProcessCSV
[2017-11-30 19:56:27] Processing: App\Jobs\ProcessCSV
[2017-11-30 19:56:27] Processing: App\Jobs\ProcessCSV
[2017-11-30 19:56:27] Processing: App\Jobs\ProcessCSV
[2017-11-30 19:56:27] Processing: App\Jobs\ProcessCSV
[2017-11-30 19:56:27] Processing: App\Jobs\ProcessCSV
[2017-11-30 19:56:27] Processing: App\Jobs\ProcessCSV
[2017-11-30 19:56:27] Processing: App\Jobs\ProcessCSV
[2017-11-30 19:56:27] Processing: App\Jobs\ProcessCSV

It's like an infinite loop. The id in my jobs table just goes up and up too. It does work on my laptop but not on my desktop which is very strange. I put in onto my devleopment server and it doesn't work on there either.
My code is below and any help would be appreciated.
Controller
public function upload(Request $request) {
        if($request->file('imported-file')) {

            $user = "craig@boldy.co.uk";

            $file = $request->file('imported-file')->store('uploads', 'public');
            $this->dispatch(new ProcessCSV($file, $user));

            Session::flash('success', 'Your file was uploaded successfully. We will email you once the locations have be imported.');
            return back();

        } else {

            Session::flash('error', 'Please select a file to upload!!!!');
            return back();

        }

    }

Job
public function handle()
    {

        $data = Excel::load($this->file, function($reader) {})->get();

        $apiKey = '';

        foreach($data as $row) {

            if(!empty($row['postcode'])) {

                $url = "https://maps.googleapis.com/maps/api/geocode/xml?address=".urlencode($row['postcode'])."&region=uk&key=";
                $tmp = file_get_contents($url);
                $xml = simplexml_load_string($tmp);

                // print_r($xml); exit;

                if((string)$xml->status == 'OK' && isset($xml->result[0])) {

                    if(isset($xml->result[0]->geometry->location->lat)) {
                        $lat = (string)$xml->result[0]->geometry->location->lat;
                    }

                    if(isset($xml->result[0]->geometry->location->lng)) {
                        $lng = (string)$xml->result[0]->geometry->location->lng;
                    }

                }

                Import::updateOrCreate(
                    [
                        'sitecode' => $row['sitecode']
                    ],
                    [
                        'sitecode' => $row['sitecode'],
                        'sitename' => $row['sitename'],
                        'address_1' => $row['address_1'],
                        'address_2' => $row['address_2'],
                        'address_town' => $row['address_town'],
                        'address_postcode' => $row['postcode'],
                        'charity' => $row['charity'],
                        'latitude' => $lat,
                        'longitude' => $lng,
                        'approved' => 1
                    ]
                );

            }

        }

    }

A: instead of php artisan queue:work..you need to add option param --tries to avoid infinite looping.. it usually occurred if error happen in job. see laravel.log or failed-job table if using driver database. it will show the error
php artisan queue:work --tries=3


text:
Q: Pullback a model in generic extension to a model in ground Let $M\prec H_\theta$ be countable and $\mathbb P\in M$, then clearly $M[G]\prec H_\theta[G]$ for every $\mathbb P$-generic filter $G$ over $V$. then actually there exists a $\mathbb P$-name $\dot N$ such that $\dot N[G]=M[G]$, roughly speaking $\dot N=M\cap V^{\mathbb P}$($V^{\mathbb P}$ is the class of $\mathbb P$-names). Here by $M[G]$, I mean $\{\dot\sigma[G]:\dot\sigma\in M~ is~a~\mathbb P-name\}$. Is the converse true? More precisely:

Let $N\prec H_\theta[G]$ be countable is there a model $M\prec H_\theta^{V}$ including $\mathbb P$, such that $M[G]=N$?

A: First, let me point out that you don't need any properness at all
to find the model $M$, if you are willing to find it in the extension in which $N$ lives. Namely, assume $\theta$ is sufficiently reflective and that $N\prec
H_\theta[G]$. Now, simply let $M=N\cap H_\theta$. One can verify that $M\prec H_\theta$ by noting that $H_\theta$ is definable in $H_\theta[G]$ by the ground-model definability theorem, and from this it follows that $M\prec H_\theta$, since it will have the Skolem witnesses that suffice to verify the Tarski-Vaught criterion. Notice also that $M[G]=N$ and therefore
$M[G]\cap H_\theta=M$. This implies that forcing with $G$ over $M$
did not add any new ordinals, and therefore the usual arguments show that $G$ is $M$-generic. So $M$ is just the kind of model you seek.
The trick here is that we do not get $M$ in $V$, but only possibly
in $V[G]$.
But perhaps you have in mind the requirement that $M\in V$ in your
question, and in this case, the answer is no, you cannot always
achieve this, if you are allowed to select $N$ in $V[G]$.
Consider the case of adding a Cohen real $c$. Pick some very big
$\theta$ and consider $H_\theta$. Pick some countable $M\prec
H_\theta$ that does not exist in $V$. But since the forcing is
c.c.c., this elementary substructure lifts to the case $M[c]\prec
H_\theta[c]$. So $N=M[c]$ is a case where the restriction to the
ground model is not available in $V$.


text:
Q: how to avoid overlaying part of screen when maximizing window thinking about using some sidebar software , but I don't want the sidebar to be overlaid, not overlay other windows.
So how can I configure win7 window manager, so that when I maximize a window, it will not overlay part of screen that reserved for sidebar
or
does some one know about desktop gadget software that prevents self being covered by maximized window?


text:
Q: why does presentViewController:animated:completion: crash? I've got a strange crash on a customers iPhone (running iOS 5.1), I have no problems at all on iOS 6 with this code:
- (IBAction)projectButtonPressed:(id)sender
{
   MEProjectViewController *viewController = [[MEProjectViewController alloc] initWithNibName:@"MEProjectViewController" bundle:nil];
   MEProjectNavigationViewController *navigationController = [[MEProjectNavigationViewController alloc] initWithRootViewController:viewController];
navigationController.navigationBar.barStyle = UIBarStyleBlack;
   //iOS 6
   if ([self respondsToSelector:@selector(presentViewController:animated:completion:)])
       [self presentViewController:navigationController animated:YES completion:NULL];
   else
       [self presentModalViewController:navigationController animated:YES];
}

The crash log is showing the closing curly brace as the line causing the crash:
Incident Identifier: F261ECD3-29DF-4360-B5AB-6C1DD0906D6A
CrashReporter Key:   cce2db7ca2a68093009446fb47f71ea8c3991922
Hardware Model:      iPhone4,1
Process:         MagicEye-iPhone [855]
Path:            /var/mobile/Applications/1D9D4CB5-FA72-41A5-B9A7-D44BBB2417E2/MagicEye-iPhone.app/MagicEye-iPhone
Identifier:      MagicEye-iPhone
Version:         ??? (???)
Code Type:       ARM (Native)
Parent Process:  launchd [1]

Date/Time:       2013-01-07 20:14:12.348 +0000
OS Version:      iPhone OS 5.1 (9B179)
Report Version:  104

Exception Type:  EXC_CRASH (SIGABRT)
Exception Codes: 0x00000000, 0x00000000
Crashed Thread:  0

Last Exception Backtrace:
0   CoreFoundation                  0x378eb88f 0x37832000 + 759951
1   libobjc.A.dylib                 0x35df1259 0x35de8000 + 37465
2   CoreFoundation                  0x378eb789 0x37832000 + 759689
3   CoreFoundation                  0x378eb7ab 0x37832000 + 759723
4   UIKit                           0x3427e639 0x33f94000 + 3057209
5   UIKit                           0x3427e7a7 0x33f94000 + 3057575
6   UIKit                           0x3427e50f 0x33f94000 + 3056911
7   UIKit                           0x3420f0ed 0x33f94000 + 2601197
8   UIKit                           0x3417d4b3 0x33f94000 + 2004147
9   UIKit                           0x3405ae01 0x33f94000 + 814593
10  UIKit                           0x33fd0dbf 0x33f94000 + 249279
11  UIKit                           0x33ff5629 0x33f94000 + 398889
12  UIKit                           0x33fb9d7d 0x33f94000 + 155005
13  UIKit                           0x3407c4dd 0x33f94000 + 951517
14  UIKit                           0x33fc255d 0x33f94000 + 189789
15  UIKit                           0x33fc240b 0x33f94000 + 189451
16  UIKit                           0x3407c4a3 0x33f94000 + 951459
17  UIKit                           0x34031873 0x33f94000 + 645235
18  UIKit                           0x340311b7 0x33f94000 + 643511
19  UIKit                           0x3407ad89 0x33f94000 + 945545
20  UIKit                           0x340794eb 0x33f94000 + 939243
21  MagicEye-iPhone                 0x00069e21 -[MEMainViewViewController_iPhone projectButtonPressed:] (MEMainViewViewController_iPhone.m:203)
22  CoreFoundation                  0x378453fd 0x37832000 + 78845
23  UIKit                           0x33fb2faf 0x33f94000 + 126895
24  UIKit                           0x33fb2f6b 0x33f94000 + 126827
25  UIKit                           0x33fb2f49 0x33f94000 + 126793
26  UIKit                           0x33fb2cb9 0x33f94000 + 126137
27  UIKit                           0x33fb35f1 0x33f94000 + 128497
28  UIKit                           0x33fb1ad3 0x33f94000 + 121555
29  UIKit                           0x33fb14c1 0x33f94000 + 120001
30  UIKit                           0x33f9783d 0x33f94000 + 14397
31  UIKit                           0x33f970e3 0x33f94000 + 12515
32  GraphicsServices                0x3274f22b 0x3274a000 + 21035
33  CoreFoundation                  0x378bf523 0x37832000 + 578851
34  CoreFoundation                  0x378bf4c5 0x37832000 + 578757
35  CoreFoundation                  0x378be313 0x37832000 + 574227
36  CoreFoundation                  0x378414a5 0x37832000 + 62629
37  CoreFoundation                  0x3784136d 0x37832000 + 62317
38  GraphicsServices                0x3274e439 0x3274a000 + 17465
39  UIKit                           0x33fc5e7d 0x33f94000 + 204413
40  MagicEye-iPhone                 0x00028937 main (main.m:16)
41  MagicEye-iPhone                 0x000288d0 start + 40

Thread 0 name:  Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0   libsystem_kernel.dylib          0x35d6a32c 0x35d59000 + 70444
1   libsystem_c.dylib               0x31eb8208 0x31e6b000 + 315912
2   libsystem_c.dylib               0x31eb1298 0x31e6b000 + 287384
3   libc++abi.dylib                 0x354bdf64 0x354b7000 + 28516
4   libc++abi.dylib                 0x354bb346 0x354b7000 + 17222
5   libobjc.A.dylib                 0x35df1350 0x35de8000 + 37712
6   libc++abi.dylib                 0x354bb3be 0x354b7000 + 17342
7   libc++abi.dylib                 0x354bb44a 0x354b7000 + 17482
8   libc++abi.dylib                 0x354bc81e 0x354b7000 + 22558
9   libobjc.A.dylib                 0x35df12a2 0x35de8000 + 37538
10  CoreFoundation                  0x37841506 0x37832000 + 62726
11  CoreFoundation                  0x37841366 0x37832000 + 62310
12  GraphicsServices                0x3274e432 0x3274a000 + 17458
13  UIKit                           0x33fc5e76 0x33f94000 + 204406
14  MagicEye-iPhone                 0x00028930 main (main.m:16)
15  MagicEye-iPhone                 0x000288c8 start + 32

Thread 1 name:  Dispatch queue: com.apple.libdispatch-manager
Thread 1:
0   libsystem_kernel.dylib          0x35d5a3a8 0x35d59000 + 5032
1   libdispatch.dylib               0x34b44f04 0x34b41000 + 16132
2   libdispatch.dylib               0x34b44c22 0x34b41000 + 15394

Thread 2:
0   libsystem_kernel.dylib          0x35d6acd4 0x35d59000 + 72916
1   libsystem_c.dylib               0x31e73f36 0x31e6b000 + 36662
2   libsystem_c.dylib               0x31e73cc8 0x31e6b000 + 36040

Thread 3:
0   libsystem_kernel.dylib          0x35d6acd4 0x35d59000 + 72916
1   libsystem_c.dylib               0x31e73f36 0x31e6b000 + 36662
2   libsystem_c.dylib               0x31e73cc8 0x31e6b000 + 36040

Thread 4 name:  WebThread
Thread 4:
0   libsystem_kernel.dylib          0x35d5a004 0x35d59000 + 4100
1   libsystem_kernel.dylib          0x35d5a1fa 0x35d59000 + 4602
2   CoreFoundation                  0x378bf3ec 0x37832000 + 578540
3   CoreFoundation                  0x378be124 0x37832000 + 573732
4   CoreFoundation                  0x3784149e 0x37832000 + 62622
5   CoreFoundation                  0x37841366 0x37832000 + 62310
6   WebCore                         0x335010f0 0x33458000 + 692464
7   libsystem_c.dylib               0x31e7972e 0x31e6b000 + 59182
8   libsystem_c.dylib               0x31e795e8 0x31e6b000 + 58856

Thread 5 name:  com.apple.CFSocket.private
Thread 5:
0   libsystem_kernel.dylib          0x35d6a570 0x35d59000 + 71024
1   CoreFoundation                  0x378c363a 0x37832000 + 595514
2   libsystem_c.dylib               0x31e7972e 0x31e6b000 + 59182
3   libsystem_c.dylib               0x31e795e8 0x31e6b000 + 58856

Thread 0 crashed with ARM Thread State:
    r0: 0x00000000    r1: 0x00000000      r2: 0x00000001      r3: 0x00000000
    r4: 0x00000006    r5: 0x3edc8d98      r6: 0x00000002      r7: 0x2fe24a58
    r8: 0x00000000    r9: 0x00000000     r10: 0x3f560f60     r11: 0x00000024
    ip: 0x00000148    sp: 0x2fe24a4c      lr: 0x31eb820f      pc: 0x35d6a32c
  cpsr: 0x00000010

Any hints?

A: Finally found the Answer with the iOS 5.1 Simulator: Autolayout!
*** Terminating app due to uncaught exception 'NSInvalidUnarchiveOperationException', reason: 'Could not instantiate class named NSLayoutConstraint'

Although the Deployment Target is set of the target is set to 4.3 I didn't get any compiler warnings / errors that Autolayout is of course only available to iOS 6. You only get the compiler error when you select the view in the nib and set the Deployment to iOS 4.3 under Document Versioning there again. Quite confusing.