text:
Q: In a Cybercafe - how to make the Ubuntu 13.10 to be auto deepfreeze? I have installed 10 Ubuntu 13.10 in a Cybercafe for daily about 300 users to use the PC, but its a nightmare with Ubuntu cause people just use Internet and make the system hell.
How can I deep freeze it? On reboot it go back to yesterday always? So that it works like one day use but always goes back to my first installation on each reboot?

A: AuFS can solve this problem for you. Here is an example of people merging the filesystem with a RAM disk so changes go away on reboot.
If you don't have much memory, you could do the same using a loopback file or partition to store the changes, and re-format the loopback file/partition once a day.

A: *

*Ensure that each machine has one account, an admin account with a fairly strong password. Do not give this password to users.

*Log in as the admin and enable guest login, it should be under the user settings in system preferences. Then log out.

*When users arrive, they can login as 'guest' without a password, and use the computer as if they had an account.

*When they log out, all the changes they made are erased. No reboots required!

A: Just use Guest Sessions and autologin.
sudo gedit /etc/lightdm/lightdm.conf

And change this:
autologin-guest=false

To this:
autologin-guest=true

A: Why not format a little hard disk (or SSD) as a Live USB and boot from it ?
See: http://www.ubuntu.com/download/desktop/create-a-usb-stick-on-ubuntu
and select your little hard disk as "Disk to use".
With a SSD you could even consider rebooting for every new user.

A: fsprotect is a set of scripts that protect existing filesystems. fsprotect is excellent for public computers like those in libraries, internet cafés, etc.
Using aufs they pack a tmpfs filesystem forcing changes to be written to the tmpfs filesystem.
The root filesystem is protected by an initramfs script. Other filesystems are protected by an init script. All protected filesystems become read-only ensuring their immutability even on power-offs.
To install fsprotect in all currently supported versions of Ubuntu open the terminal and type:
sudo apt-get install fsprotect

The benefits of using fsprotect are:

*

*Filesystems are protected and no change is ever written to the disk.

*Protected filesystems are mounted read-only. This means that they aren't damaged when the computer is turned off improperly.

*It is very easy to use.

*In some cases it makes the filesystem access faster.

The drawbacks of using fsprotect are:

*

*Filesystem changes cannot be more than a predefined limit in bytes (set by you).

*Since tmpfs is heavily used, you need to have adequate swap space.


text:
Q: Delete COM object through tcom I have an application which use tcom library to access COM object. In the end of my program, I'm trying to delete the COM object. Following is my reference.
http://wiki.tcl.tk/11900
Here's my program
  package require tcom

  # create COM objec
  set application [::tcom::ref createobject "MyApplication"]

  # unbind and release COM object
  ::tcom::unbind  $application
  set application {}
  $application Quit
  unset application

And the result turns out to be
  object does not implement method or property Quit

How to delete the COM object correctly?

A: I don't know anything about tcl but I do know about COM.  Your object application does not implement a method Quit as it says.
however
unset application

will delete the COM object and unload it from memory.
If the object also has a close or exit method you could call that first, but you would need to check the docs for application object.

A: It looks to me as if you have these 2 lines the wrong way round:
  set application {}
  $application Quit

You reset application and then try and use it.
However as Donal points out below this would not result in the error message that you are getting and I suspect that your application MyApplication does not implement actually implement a Quit method.
You can use tcom to find out what methods and properties an interface defines, for example the following code does this for Excel.
package require tcom
set excel [::tcom::ref createobj Excel.Application]

set iface [::tcom::info interface $excel]
foreach {method} [$iface methods] {
    puts $method
}

puts "--"
foreach {property} [$iface properties] {
    puts $property
}

$excel Quit
unset excel

This should allow you to see the methods and their parameters and the properties that MyApplication actualy does expose, if there isn't a Quit method then you'll need to go back to the owner of the application and find out what method, if any, needs to be invoked through the com interface to terminate the application.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I launch an instance of an application using Python? I am creating a Python script where it does a bunch of tasks and one of those tasks is to launch and open an instance of Excel. What is the ideal way of accomplishing that in my script?

A: or
os.system("start excel.exe <path/to/file>")

(presuming it's in the path, and you're on windows)
and also on Windows, just start <filename> works, too - if it's an associated extension already (as xls would be)

A: I like popen2 for the ability to monitor the process.
excelProcess = popen2.Popen4("start excel %s" % (excelFile))
status = excelProcess.wait()

https://docs.python.org/2/library/popen2.html
EDIT: be aware that calling wait() will block until the process returns.  Depending on your script, this may not be your desired behavior.

A: The subprocess module intends to replace several other, older modules and functions, such as:

*

*os.system

*os.spawn*

*os.popen*

*popen2.*

*commands.*

.
import subprocess

process_one = subprocess.Popen(['gqview', '/home/toto/my_images'])

print process_one.pid

A: As others have stated, I would suggest os.system. In case anyone is looking for a Mac-compatible solution, here is an example:
import os
os.system("open /Applications/Safari.app")

A: While the Popen answers are reasonable for the general case, I would recommend win32api for this specific case, if you want to do something useful with it:
It goes something like this:
from win32com.client import Dispatch
xl = Dispatch('Excel.Application')
wb = xl.Workbooks.Open('C:\\Documents and Settings\\GradeBook.xls')
xl.Visible = True    # optional: if you want to see the spreadsheet

Taken from a mailing list post but there are plenty of examples around.

A: os.system("open file.xls")

A: I like os.startfile("path to file") as it opens the file as if you've double clicked to open.
I found that with os.system("start excel filename") it opened it like a file opened from the web and you had to enable editing.


text:
Q: strstr() function like, that ignores upper or lower case I have two strings. Lets say `
str1="One Two Three";

and
str2="two";

I would like to know if there is any function that checks for a match of the second string in the first one,and returns me a pointer to the first occurrence, something like strstr(), but which doesn't treat the same letter, upper or lowercase, as two different characters.
For my example, the function should find a match for str2 in the first string, despite the uppercase "T", of "Two".

A: After accept answer
Inspired by @Clifford and @Weather Vane, thought I'd try rolling up a solution that only used standard library functions.
char* stristr3(const char* haystack, const char* needle) {
  do {
    const char* h = haystack;
    const char* n = needle;
    while (tolower((unsigned char) *h) == tolower((unsigned char ) *n) && *n) {
      h++;
      n++;
    }
    if (*n == 0) {
      return (char *) haystack;
    }
  } while (*haystack++);
  return 0;
}

Somewhat tricky to match the corner cases of strstr() with inputs like "x","", "","x", "",""

A: Here is a slightly more efficient version, that does not call tolower() twice per character in the haystack string:
#include <ctype.h>

char *stristr4(const char *haystack, const char *needle) {
    int c = tolower((unsigned char)*needle);
    if (c == '\0')
        return (char *)haystack;
    for (; *haystack; haystack++) {
        if (tolower((unsigned char)*haystack) == c) {
            for (size_t i = 0;;) {
                if (needle[++i] == '\0')
                    return (char *)haystack;
                if (tolower((unsigned char)haystack[i]) != tolower((unsigned char)needle[i]))
                    break;
            }
        }
    }
    return NULL;
}

A: From the manpage for strstr:
STRSTR(3)           Linux Programmer's Manual           STRSTR(3)

NAME
       strstr, strcasestr - locate a substring

SYNOPSIS
       #include <string.h>

       char *strstr(const char *haystack, const char *needle);

       #define _GNU_SOURCE

       #include <string.h>

       char *strcasestr(const char *haystack, const char *needle);

DESCRIPTION
       The  strstr()  function  finds the first occurrence of the substring needle in
       the string haystack.  The terminating '\0' characters are not compared.

       The strcasestr() function is like strstr(3), but  ignores  the  case  of  both
       arguments.

RETURN VALUE
       These functions return a pointer to the beginning of the substring, or NULL if
       the substring is not found.

So what you're looking for is strcasestr.

A: Implementation of stristr()
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

char *stristr (const char *str, const char *strSearch) {
    char *sors, *subs, *res = NULL;
    if ((sors = strdup (str)) != NULL) {
        if ((subs = strdup (strSearch)) != NULL) {
            res = strstr (strlwr (sors), strlwr (subs));
            if (res != NULL)
                res = str + (res - sors);
            free (subs);
        }
        free (sors);
    }
    return res;
}

int main()
{
    char *str1 = "One Two Three";
    char *str2 = "two";
    char *sptr = stristr(str1, str2);
    if (sptr)
        printf ("Substring is at index %d\n", sptr - str1);
    return 0;
}

A: While some compiler's C libraries include extensions with case insensitive versions of the standard string functions, such as GNU's strcasestr(), the naming of such functions is not standardised even when included.
One way of overcoming the lack of a standard implementation is of course to implement your own:
char* stristr( const char* str1, const char* str2 )
{
    const char* p1 = str1 ;
    const char* p2 = str2 ;
    const char* r = *p2 == 0 ? str1 : 0 ;

    while( *p1 != 0 && *p2 != 0 )
    {
        if( tolower( (unsigned char)*p1 ) == tolower( (unsigned char)*p2 ) )
        {
            if( r == 0 )
            {
                r = p1 ;
            }

            p2++ ;
        }
        else
        {
            p2 = str2 ;
            if( r != 0 )
            {
                p1 = r + 1 ;
            }

            if( tolower( (unsigned char)*p1 ) == tolower( (unsigned char)*p2 ) )
            {
                r = p1 ;
                p2++ ;
            }
            else
            {
                r = 0 ;
            }
        }

        p1++ ;
    }

    return *p2 == 0 ? (char*)r : 0 ;
}

The test code below outputs:
Two Three
Two Three
NULL
cdefg
CDEFG
CdEfG
NULL
zzzz
NULL

zzzzz
NULL

int main(void)
{
    char* test = stristr( "One TTwo Three", "two" ) ;
    printf( "%s\n", test == 0 ? "NULL" : test  ) ;

    test = stristr( "One Two Three", "two" ) ;
    printf( "%s\n", test == 0 ? "NULL" : test  ) ;

    test = stristr( "One wot Three", "two" ) ;
    printf( "%s\n", test == 0 ? "NULL" : test  ) ;

    test = stristr( "abcdefg", "cde" ) ;
    printf( "%s\n", test == 0 ? "NULL" : test  ) ;

    test = stristr( "ABCDEFG", "cde" ) ;
    printf( "%s\n", test == 0 ? "NULL" : test  ) ;

    test = stristr( "AbCdEfG", "cde" ) ;
    printf( "%s\n", test == 0 ? "NULL" : test  ) ;

    test = stristr( "1234567", "cde" ) ;
    printf( "%s\n", test == 0 ? "NULL" : test  ) ;

    test = stristr( "zzzz", "zz" ) ;
    printf( "%s\n", test == 0 ? "NULL" : test  ) ;

    test = stristr( "zz", "zzzzz" ) ;
    printf( "%s\n", test == 0 ? "NULL" : test  ) ;

    test = stristr( "", "" ) ;
    printf( "%s\n", test == 0 ? "NULL" : test  ) ;

    test = stristr( "zzzzz", "" ) ;
    printf( "%s\n", test == 0 ? "NULL" : test  ) ;

    test = stristr( "", "zzzz" ) ;
    printf( "%s\n", test == 0 ? "NULL" : test  ) ;

    test = stristr("AAABCDX","AABC") ;
    printf( "%s\n", test == 0 ? "NULL" : test  ) ;

    return 0;
}

A: If you're on windows, you can use StrStrI. It works the same as the GNU strcasestr or the other manually-implemented stristr code in other answers here.
E.g.:
const char needle[] = "and";
const char haystack[] = "me and you";

const char* pAnd = StrStrIA(haystack, needle); // explicitly call ascii version as windows defaults to wchar
printf("%s\n", pAnd); // Prints "and you";

A: The best way to solve this without writing any function may be by first converting both the string to lowercase/uppercase using "tolower"/"toupper" and then use "strstr" :)

A: Try this function :
char* stristr(const char* String, const char* Pattern)
{
      char *pptr, *sptr, *start;

      for (start = (char *)String; *start; start++)
      {
            /* find start of pattern in string */
            for ( ; (*start && (toupper(*start) != toupper(*Pattern))); start++)
                  ;
            if (!*start)
                  return 0;

            pptr = (char*)Pattern;
            sptr = (char*)start;

            while (toupper(*sptr) == toupper(*pptr))
            {
                  sptr++;
                  pptr++;
                  /* if end of pattern then pattern was found */
                  if (!*pptr)
                        return (start);
            }
      }
      return 0;
}


text:
Q: Batch create text files, each new file with different text pulled from two different text files I'm trying to create multiple text files from  2 template text file; however, in each newly generated file there should be added a new line of text pulled from excel row.
for example:
template1 text file content
Line1
Line2

Line 3

template2 text file content
Line4

Line5

And Excel file has several rows, each with different text, e.g.
Row1text
Row2text
Row3text

So what I need to do is pull from Excel rows the text and add it to the newly generated text file, based on text template file,
so the result would be like this
GeneratedText1.txt
Line1
Line2

Line 3

Row1text

Line4

Line5

GeneratedText2.txt
Line1
Line2

Line 3

Row2text

Line4

Line5

GeneratedText3.txt
Line1
Line2

Line 3

Row3text

Line4

Line5

As many as there are rows in excel, so many the text files should be generated. The names of the new files should be also predefined somewhere. What's the best way to do it? Some command line would help?
Here is what I have managed so far:
@echo off

setlocal EnableDelayedExpansion

set i=1
for /f %%l in (input.cvs) do (
  >GeneratedText!i!.txt type template1.txt
  >>GeneratedText!i!.txt echo %%l
  set /a i+=1
)

endlocal

A: The following code will merge two text template files with data from your excel sheet. You need to determine the cell range, and how to name your output files.
Option Explicit

Sub Create_Text_Files()
Dim strLineIn   As String
Dim lRow        As Long

    ' Determine Excel Range (Rows & Colums!!
    For lRow = 2 To 5          '<<< Set your Range!!
        Close #1    ' Just in case left open during testing
        Close #2
        Close #3
        Open "C:\temp\TemplateFile1.txt" For Input As #1
        Open "C:\temp\TemplateFile2.txt" For Input As #2
        'Determine how to name your output files.
        Open "C:\temp\TemplateOut" & lRow & ".txt" For Output As #3         ' Set Output File Name

        'Write out TemplateFile1.txt
        Do While Not EOF(1)         ' Loop until end of file
            Line Input #1, strLineIn
            If EOF(1) Then Exit Do      ' Avoid blank line
            Print #3, strLineIn
        Loop
        Close #1

        'Get your Excel data and write out
        Print #3, Cells(lRow, 1)            ' Change if multi column
        'Write out TemplateFile2.txt
        Do While Not EOF(2)         ' Loop until end of file
            Line Input #2, strLineIn
            If EOF(2) Then Exit Do      ' Avoid blank line
            Print #3, strLineIn
       Loop
       Close #2
       Close #3
    Next lRow
End Sub

A: This should create files with the two template files and a line from the excel.txt file between them, as you have shown.
The filenames are derived from the excel line and should not contain poison characters.
This is untested:
@echo off
for /f "delims=" %%a in (excelfile.txt) do (
   type "template1.txt" >"%%a.txt"
      >>"%%a.txt" echo(
      >>"%%a.txt" echo(%%a
      >>"%%a.txt" echo(
   type "template2.txt" >>"%%a.txt"
)


text:
Q: How can I check if client exists in database before inserting data into database in .NET Core A little assistance on how I can check if client already exists in the database before adding him or her into the database using a for loop in ASP.NET Core Web API.
I have a list of clients and I'm are trying to insert them into the database, but before I do that, I want to check if that client already exists. I am stuck here on how to do it - please help
This is my code:
foreach (Client client in clientList)
{
    await _dbconnection.clients.AddAsync(client);
}

await _dbconnection.SaveChangesAsync();

A: try this code
foreach (Client client in clientList)
{
   var exist= await _dbconnection.clients.Any(x=> x.Id==client.Id)
    if (!exist) _dbconnection.clients.Add(client);
}

await _dbconnection.SaveChangesAsync();


text:
Q: MVC 3: Multiple Vars In my HomeController Index action, I want to have two SQL queries:
var model = db.Task.Where(n => (n.UserId == UserID) && (n.Completed == false) && (n.Due < dateTime));
return View(model);

var map = db.Events.Where(n => (n.UserId == UserID) && (n.Start < dateTime));
return View(map);

In the code above, the second Var is underlined green. How do I go about performing both these queries and passing the results through to the home page?
Many thanks.

A: You can't return from a function and expect the code after the return to execute.
Make sure you have a single model for the view that includes all of the needed information.
For example:
var model = db.Task.Where(n => (n.UserId == UserID) && (n.Completed == false) && (n.Due < dateTime));
model.Map = db.Events.Where(n => (n.UserId == UserID) && (n.Start < dateTime));
return View(model);

This code will not compile unless you have a Map member defined on your model.
Though instead of two DB calls, better approach would be to have all the data populated in one call.

A: Two options, either create a class to hold both of your variables:
public class IndexModel {
    IEnumerable<ModelA> Model { get; set; }
    IEnumerable<MapMode> Map { get; set; }
}

And in your action:
return View(new IndexModel{ Model = model, Map = map });

Or put one of the items into the view data bag.
ViewBag.Map = map;
return View(model);


text:
Q: check if a String is already in a LinkedHashMap (as a value) I'd like to check if the value of a LinkedHashmap already contains a String, and if not, add it to the ArrayList.
windowSize is between 1 and 7 (predefined)
String wholeString = "HausA HausB";

final Map<String, ArrayList<String>> generateMap = new LinkedHashMap<String, ArrayList<String>>();
final int limit = wholeString.length() - windowSize;
    for (int i = 0; i < limit; i++) {
        String first = wholeString.substring(i, i + windowSize);
        String second = wholeString.substring(i + windowSize, i
                + windowSize + 1);

        int endKey = i + windowSize;
        if (!generateMap.containsKey(first)) {
            generateMap.put(wholeString.substring(i, endKey),
                    new ArrayList<String>());
        }
                    //check here if the String 'second' is already mapped to the key'
                    if (i < limit && !generateMap.get(first).equals(second)) {
            generateMap.get(first).add(second);
        } else {
            generateMap.get(first).add(null);
        }
    }

   for (Entry<String, ArrayList<String>> e : generateMap.entrySet()) {
        System.out.println(e.getKey() + " -> " + e.getValue()+ "\n");
   }

The Output now:
HausA -> [ ]
ausA  -> [H]
usA H -> [a]
sA Ha -> [u]
A Hau -> [s]
Haus  -> [B]
HausB -> [ ]

How it should be:
HausA -> [ ]
ausA  -> [H]
usA H -> [a]
sA Ha -> [u]
A Hau -> [s]
Haus  -> [A,B] //<---
HausB -> [ ]

Thank you for your appreciated help.

A: See how this fits...
final String wholeString = " HausA HausB";
final Map<String, Set<String>> generateMap = new LinkedHashMap<String, Set<String>>();
final int windowSize = 5;

final int limit = wholeString.length() - windowSize;
for (int i = 0; i < limit; i++) {
  final int endKey = i + windowSize;
  final String
      first = wholeString.substring(i, endKey),
      second = wholeString.substring(endKey, endKey + 1);
  if (!generateMap.containsKey(first))
    generateMap.put(first, new HashSet<String>());
  generateMap.get(first).add(second);
}

for (Entry<String, Set<String>> e : generateMap.entrySet()) {
  System.out.println(e.getKey() + " -> " + e.getValue());
}


text:
Q: rule based replacement of s with ſ (long s) Is there a way in any LaTeX (LuaLaTex, LuaHBTeX, pdfTeX …) to automatically typeset a document written with standard «s» with long s (ſ) instead where appropriate? The rules seem to be mostly language independent and can be found here.
This is basically the opposite of this question.
I am aware of the OpenType character variant method and produce long s in Latex but those do not answer this question.
MWE
\documentclass{article}

\usepackage[german,english]{babel}

\begin{document}
\section{s}
In German, the s stands (please no automatic replacement)
\begin{description}
    \item[At the end of a word]
        \foreignlanguage{german}{Das Haus, des Landes}
    \item[At the end of a syllable]
        \foreignlanguage{german}{dasselbe, Eispalast, Häuschen}
    \item[word gap s if the following word is self standing]
        \foreignlanguage{german}{Donnerstag, lostreten, deswegen}
    \item[a word gap s in case of a following suffix syllable which begins with a consonant]
        \foreignlanguage{german}{Häuslein, Wachstum, nachweisbar, Weisheit}
    \item[in loan word prefix syllables dis- and des-]
        \foreignlanguage{german}{Distribution, Desinfektion}
    \item[before d, k, m, n and w]
        \foreignlanguage{german}{Dresden, brüsk, Osman, Mesner, Oswald}
\end{description}
\section {ſ}
In German, the ſ stands (in the following example words s should be replaced by ſ   )
\begin{description}
    \item[at the beginning of a word]
        \foreignlanguage{german}{so, sieben}
    \item[at the beginning and inside of syllables]
        \foreignlanguage{german}{saufen, Wunsch, erstaunen}
    \item[at the end of a syllable except composita]
        \foreignlanguage{german}{Gasse, Wasser, Bissen, fassen}
    \item[before p, t and ch (sch trigraph)]
        \foreignlanguage{german}{Knospe, fast, löschen}
\end{description}
\section{ſſ}
The double ſſ stands (double replacement desired):
\begin{description}
    \item[if there is as short vowel before the first s and any vowel is following the second s]
        \foreignlanguage{german}{Adresse, müssen, Tasse, vergessen}
    \item[if a following e is omitted by an apostroph]
        \foreignlanguage{german}{ich lass' es sein}
    \item[in flexed forms of words that end with -as, -is, -nis and -us]
        \foreignlanguage{german}{die Ananasse, Wallisser Aprikosen, des Zeugnisses, des Busses}
\end{description}
\section{ß}
The Esszet ligature ſs ß stands:
\begin{description}
    \item[at the end of a word]
        \foreignlanguage{german}{muss, nass, Biss}
    \item[at the end of a syllable]
        \foreignlanguage{german}{hässlich, vergesslich}
    \item[before a consonant]
        \foreignlanguage{german}{lasst, hasst, wisst, verpasst, verlässlich}
    \item[after a long vowel]
        \foreignlanguage{german}{grüssen, Strasse, fliessen}
    \item[after a diphtong]
        \foreignlanguage{german}{heissen, aussen, scheusslich}
\end{description}
joking: It's that easy!

Rules courtesy of \texttt{www.deutsch-kurrentschrift.de}
\end{document}

A: I'm working on a new feature in babel for luatex meant for changes like this, although it's based on the language, so it has its limitations (after all, babel is about languages). It's based on lua patterns and here is an example:
\documentclass{article}

\usepackage[german]{babel}

\babelfont{rm}{FreeSerif}

\babelprehyphenation{german}{s[a-eg-z]}
  { string = ſ,
    {}
  }

\begin{document}

abcs abcsde abcsfe

\end{document}

It prints "abcs abcſde abcsfe".
Edit. To be honest, I've found some rules a bit vague, and on  other hand, some rules are clearly impossible to carry out in a more or less simple way (how to know if a word is a loan word?). So, the solution is partial, but I hope it can help for similar cases, and also as a starting point which can be used to make tests and feature requests (after all, and as I said, I'm working on it, so it's a good time!). Well, and even contribute . Some rules are defined with \babelprehyphenation and some others with \babelposthyphenation. (I think there also rules related to hyphenation, and with \babelposthyphenation the discretionaries can be modified.)
ſ before p or t
\babelprehyphenation{german}{s[pt]}
{ string = ſ,
  {}
}

Before ch
\babelprehyphenation{german}{sch}
{ string = ſ,
  {},
  {}
}

At the beginning of words
Here a special rule is necessary, which marks explicitly the text to be caught with empty matches. They are added automatically in other patterns.
\babelposthyphenation{german}{^()s()}
{
  string = ſ
}

Beginning of a syllable
Assuming a discretionary marks a syllable boundary. Special cases would require additional rules.
\babelposthyphenation{german}{|s}
{
  {},
  string = ſ
}


text:
Q: almacenar varios array en LocalStorage Javascript Estoy almacenando datos de un formulario en el localstorage, mi idea es hacer una lista de cada vez que se envie ese formulario, se guarde en un array todos sus datos.
Logro hacerlo, peero lo q me esta pasando es que cada vez que envio la informacion al localstorage, se me reescribe la anterior.
        var datosDeCadaEquipoRecuperado =

       [estado,hdmi,av,fuente,control,accesorios,
      idLocalEquipo,terminal,identificacion];

           localStorage.setItem('transito',
        JSON.stringify(datosDeCadaEquipoRecuperado));

y cada vez que ejecuto el formulario se guarda la informacion correctamente, pero no persiste la anterior
pude enviar todos los datos al localstorage sin reescribir con esta funcion que encontre. la comparto para el que le sirva. Si tienen otro metodo, seria bueno que aporten.
        function
         SaveDataToLocalStorage(estado,hdmi,av,fuente,
         control,accesorios,idLocalEquipo,terminal,identificacion)
        {
       var a = [];
   //   Analizar los datos serializados nuevamente en una serie de objetos
       a = JSON.parse(localStorage.getItem('transito')) || [];
   //  envio los nuevos datos (ya sea un objeto o cualquier otra cosa) en la
     matriz
     a.push(estado,hdmi,av,fuente,control,
     accesorios,idLocalEquipo,terminal,identificacion);
   //  Alerta al valor de la matriz
     alert(a);
    //  tiene que ser un objeto [matriz de objetos]
      //   Vuelva a serializar la matriz de nuevo en una cadena y guárdela en
     localStorage
    localStorage.setItem('transito', JSON.stringify(a));

     var DataDelLocalStorage = JSON.parse(localStorage.getItem('id'));
    console.log(localstorage);
     }

A: Tienes que añadir los nuevos datos a los anteriores:
var datosDeCadaEquipoRecuperado = [1, 2, 3]; // los datos que sean

// localStorage.getItem() devuelve null si la clave no existe
var datos_existentes = localStorage.getItem('transito');
datos_existentes = datos_existentes === null ? [] : JSON.parse(datos_existentes);

datos_existentes.push(datosDeCadaEquipoRecuperado);
// o
// datos_existentes.push({tiempo: new Date().getTime(), datos: datosDeCadaEquipoRecuperado});

localStorage.setItem('transito', JSON.stringify(datos_existentes));


text:
Q: ASP.NET 4 migrate to routing / mapping Previously I was using Rewriter.net to rewrite my urls. I used a format like:
<rewrite url="~/(.*)_p(\d+).aspx\??(.*)" to="~/product.aspx?pid=$2&$3"/>

So a page url would look like ~/productname_p21.aspx with an optional querystring.
I'm upgrading the application to ASP.NET 4 and I would like to use the URL routing in System.Web.Routing, so I can get rid of the 3rd party library Rewriter.net.
I came up with this:
RouteTable.Routes.MapPageRoute("product", "product/{name}/{pid}", "~/product.aspx");

That's all fine, except for the fact that I want to put a 301 permanently moved status on the old-style URL's. How can I accomplish this with the .NET Routing library?
Thanks

A: A possible way of handling this situation:
Redirect Routes and other Fun With Routing And Lambdas
ASP.NET MVC tips: Routing Engine to aid SEO / 301 Redirect / Tracking


text:
Q: Usage of file protocol in HTTP request Reading file using HTTP Request is suggested for Passing variables between threads.

For example you could use the Save Responses to a file listener or perhaps a BeanShell PostProcessor in one thread, and read the file using the HTTP Sampler "file:" protocol, and extract the information using a PostProcessor

Which is working, but should the warning in doc be ignored?

Note: the FILE protocol is intended for testing purposes only. It is handled by the same code regardless of which HTTP Sampler is used.

Is/when it safe/good practice to use file protocol or is it deprecated/bad practice?

A: *

*Using Beanshell PostProcessor is a definitely bad practice, since JMeter 3.1 you should be using JSR223 Test Elements and Groovy language

*Writing and reading files might cause massive disk IO overhead which can become the bottleneck for your script especially when it comes to high loads. Moreover in-memory operations will be much faster than writing/reading the file to/from the file system

Assuming all above:
although there is nothing wrong with using file protocol if you need to read the data from a file on the file system, it's better to avoid these interim files and pass the data between threads using memory, the options are in:

*

*Use __setProperty() function in 1st thread group to store the value and __P() function in other Thread Groups to read the previously stored value

*Use Inter-Thread Communication Plugin which can be used for passing variables between threads, even if they live in different Thread Groups (see SynchronizationExample.jmx for a practical use case). Inter-Thread Communication Plugin can be installed using JMeter Plugins Manager


text:
Q: Display data in jqGrid Footer row in MVC Application I need help display data in the jqGrid footer row.  This is my configuration on the Server.  Notice the userdata = (Hours) line.
// Format the data for the jqGrid
        var jsonData = new
        {
            total = totalPages,
            page = page,
            records = totalRecords,
            rows = (
                  from a in activities
                  select new
                  {
                      id = a.ActivityId,
                      cell = new string[] {
                      a.ActivityId.ToString(),
                      DateTime.Parse(a.Date.ToString()).ToShortDateString(),
                      a.Person.Name.ToString(),
                      a.ActivityName.ToString(),
                      a.Hours.ToString()
                    }
                  }).ToArray(),
            userdata = (Hours)
        };

        // Return the result in json
        return Json(jsonData, JsonRequestBehavior.AllowGet);

The userData amount that I need displayed in the footer is coming through in the JSON.  I am using Fiddler to view it.  Here is a screenshot of the fiddler view:
alt text http://shirey.technologyblends.com/Content/images/json.jpg
I need to display this value of "12" in the footer.  This the HTML I am using to read the JSON:
        jQuery("#list").jqGrid({
        url: gridDataUrl + '?startDate=' + startDate.toJSONString() + '&endDate=' + endDate.toJSONString(),
        datatype: "json",
        mtype: 'GET',
        colNames: ['Activity ID', 'Date', 'Employee Name', 'Activity', 'Hours'],
        colModel: [
          { name: 'ActivityId', index: 'ActivityId', width: 40, align: 'left' },
          { name: 'Date', index: 'Date', width: 50, align: 'left' },
          { name: 'Person.Name', index: 'Person.Name', width: 100, align: 'left', resizable: true },
          { name: 'ActivityName', index: 'ActivityName', width: 100, align: 'left', resizable: true },
          { name: 'Hours', index: 'Hours', width: 40, align: 'left' }
          ],
        loadtext: 'Loading Activities...',
        multiselect: true,
        rowNum: 20,
        rowList: [10, 20, 30],
        imgpath: gridimgpath,
        height: 'auto',
        width: '700',
        pager: jQuery('#pager'),
        sortname: 'ActivityId',
        viewrecords: true,
        sortorder: "desc",
        caption: "Activities",
        footerrow: true, userDataOnFooter: true, altRows: true
    }).navGrid('#pager', { search: true, edit: false, add: false, del: false, searchtext: "Search Activities" });

A: Try to use following
var jsonData = new {
    total = totalPages,
    page = page,
    records = totalRecords,
    rows = (
        from a in activities
        select new {
            id = a.ActivityId,
            cell = new string[] {
                a.ActivityId.ToString(),
                DateTime.Parse(a.Date.ToString()).ToShortDateString(),
                a.Person.Name.ToString(),
                a.ActivityName.ToString(),
                a.Hours.ToString()
            }
        }).ToArray(),
        userdata = new {
            Hours = 12
        }
    };

then the userdata part of the JSON data will be
  "userdata":{"Hours":12}

which follows to displaying of the bold value 12 in the column Hours of the footer part of the jqGrid table.


text:
Q: How do I get location from the following array? This is what the array looks like:
[GeoPlace {
  city: [Getter],
  province_state: [Getter],
  country: {
    long_name: 'Greece',
    short_name: 'GR'
  },
  formatted_address: 'Greece',
  location: {
    lat: 39.074208,
    lng: 21.824312
  },
  location_type: 'APPROXIMATE',
  location_bounds: {
    northeast: [Object],
    southwest: [Object]
  }
}]

This is what my code looks like:
if(!_.isNil(res) && _.isNil(err)) {
  console.log(res);
}

I want to be able to get just the location showing in the console.log.


text:
Q: Jquery scroll to top animate Hi I know this question has been asked and answered a lot but even with that I can't seem to figure out where i'm going wrong. I'm trying to create a scrollTop animation using the "back to top" button at the end of the page but it doesn't seem to be working.
The code is as follows:
HTML

Back to top
.

JQUERY

The URL is http://mike-griffin.com/about-me.html
Any help at all would be greatly appreciated. Thank you in advance!

A: The scrollbar that is appearing belongs to your .container element, not the body.
Observe the behavior when you remove the css property:
overflow-x: hidden;

from the .container style.
Or to fix:

A: The code you posted here should work, but that's not the code that you have on your website.
On the website you have this:
$(function(){
    $(".go-to-top").click(function(event){
        event.preventDefault();
        $("body").animate({"scrollTop": "0px"}, 1000);
    })
});

To make it work, change $("body") to $("html, body"). Reason for this is browser compatibility - some browsers apply the scroll position to document.documentElement (html) while others apply it to document.body (body).


text:
Q: Html/php/mysql forms are not submitting and redirecting issue i'm working on a dashboard for my users. I set it up by ranks and each rank can do there own thing. Now, I have three problems. One and two are about forms and another is about a redirection problem. These forms are not submitting into the database and I don't know why. The two forms are below. The third problem is redirecting. Since the system is setup by ranks I don't want ranks accessing other ranks dashboards. Its not redirecting the other ranks away from there dashboard as its all one login and when those ranks login it redirects them to there correct dashboard, but if say a partner goes to the admin dashboard, it lets them in which I don't want. Also I forgot to mention that when the user is logged in, it lets them back to the login page if they go to the login url which I don't want, I want it to redirect them to there dashboard. The forms are below.
First Form:
<?php

$id = $_GET['id'];
$result = $db->query("SELECT * FROM users WHERE Id = '.$id.'");

if(isset($_POST['submit']))
{
  $username1 = $_POST['username'];
  $email1 = $_POST['email'];
  $password1 = $_POST['password'];
  $f_name = $_POST['f_name'];
  $l_name = $_POST['l_name'];
  $rank1 = $_POST['rank'];
  $skype1 = $_POST['skype'];

  $db->query("UPDATE users SET (Email, Username, FName, LName, Rank, SkypeID) VALUES(''.$email1.'', ''.$username1.'', ''.$f_name.'', ''.$l_name.'', ''.$rank1.'', ''.$skype1.'') WHERE Id = ".$id."");
}

?>

<?php
$id = $_GET['id'];
$result = $db->query("SELECT * FROM users WHERE id='$id'");
while($row = $result->fetch_assoc())
{
  $username = $row['Username'];
  $email = $row['Email'];
  $fname = $row['FName'];
  $lname = $row['LName'];
  $rank = $row['Rank'];
  $skype = $row['SkypeID'];
}
?>
<form method="POST">
  Username: <input type="text" name="username" value="<?php echo ($username); ?>">

  Email: <input type="email" name="email" value="<?php echo ($email);?>">

  Passowrd: <input type="password" name="password">

  First Name: <input type="text" name="f_name" value="<?php echo ($fname);?>">

  Last Name: <input type="text" name="l_name" value="<?php echo($lname); ?>">

  Rank: <input type="text" name="rank" value="<?php echo ($rank); ?>">

  Skype: <input type="text" name="rank" value="<?php echo ($skype); ?>">
  <button type="submit" name="submit">Update User</button>
</form>

Second Form:
<?php
if(isset($_POST['submit']))
{
  $c_name = $_POST['c_name'];
  $v_link = $_POST['v_link'];
  $v_title = $_POST['v_title'];
  $v_desc = $_POST['v_desc'];
  $v_tags = $_POST['v_tags'];
  $m_sources = $_POST['m_sources'];
  $s_requests = $_POST['s_requests'];

  if(empty($c_name) or empty($v_link) or empty($v_title) or empty($v_title) or empty($v_desc) or empty($v_tags))
  {
    echo 'You must fill in the first 5 fields.';
  }
  else
  {
    $getRank = $db->query("SELECT * FROM users WHERE username = ".$_SESSION['username']."");
    while ($row = $getRank->fetch_assoc($getRank))
    {
      $usename = $row['username'];
      $rank = $row['rank'];
    }
    $db->query("INSERT INTO submitted_forms (username, rank, channel_username, video_link, video_title, video_description, video_tags, music_sources, special_requests) VALUES (''.$username.'', ''.$rank.'', ''.$c_name.'', ''.$v_link.'', ''.$v_title.'', ''.$v_desc.'', ''.$v_tags.'', ''.$m_sources.'', ''.$s_requests.'')");
    echo 'Form submitted successfully.';
    }
  }
?>

<form method="POST">
  Channel name: <input type="text" name="c_name" required>*

  Video Link: <input type="text" name="v_link" required>*

  Video Title: <input type="text" name="v_title" required>*

  Video Description: <input type="text" name="v_desc" required>*

  Video Tags: <input type="text" name="v_tags" required>*

  Music Sources: <input type="text" name="m_sources">

  Special Requests: <input type="text" name="s_requests">

  <button type="submit" name="submit">Submit</button>

</form>

Now, heres the code I use to redirect a user away from the dashboards if its not there dashboard. It redirects not logged in users, but not like other users. Its supposed to only allow admins in.
<?php session_start();
if(isset($_SESSION['admin']))
{
$_SESSION['username'];

} else {
  header("location: ../index.php");
} ?>

Now, heres the login script. I want it to redirect the ranks to there dashboard if they're logged in, I don't know how to implant this.
<?php
require 'core/config.php';

if(isset($_POST['submit']))
{
  $username = $db->real_escape_string($_POST['username']);
  $password = md5($_POST['password']);

  if(empty($username) or empty($password))
  {
    echo 'You must fill in both boxes!';
  } else {
    $query = $db->query("SELECT * FROM users WHERE username = '".$username."'");
    while($row = $query->fetch_assoc())
    {
      $dbpassword = $row['Password'];
    }

    if($password !== $dbpassword)
    {
      echo 'Password was incorrect.';
    } else {
      $query1 = $db->query("SELECT * FROM users WHERE username='".$username."'");
      while($rows = $query1->fetch_assoc())
      {
        $rank = $rows['Rank'];
      }

      if($rank === 'admin')
      {
        $_SESSION['admin'] = '1';
        $_SESSION['username'] = $username;

        echo '';
      }
      elseif ($rank === 'partner')
      {
        $_SESSION['partner'] = '1';
        $_SESSION['username'] = $username;

       echo '';
      }
      elseif ($rank === 'trainee')
      {
         $_SESSION['trainee'] = '1';
         $_SESSION['username'] = $username;

        echo '';
      }
      else
      {
        echo 'Account not found.';
      }
    }
  }
}
?>

A: try this in your login script:
<?php
require 'core/config.php';

//assuming that you have already start your session at the very top

if(isset($_POST['submit']))
{
$username = $db->real_escape_string($_POST['username']);
$password = md5($_POST['password']);

if(empty($username) or empty($password))
{
echo 'You must fill in both boxes!';
} else {
$query = $db->query("SELECT * FROM users WHERE username = '".$username."'");
while($row = $query->fetch_assoc())
{
  $dbpassword = $row['Password'];
}

if($password !== $dbpassword)
{
  echo 'Password was incorrect.';
} else {
  $query1 = $db->query("SELECT * FROM users WHERE username='".$username."'");
  while($rows = $query1->fetch_assoc())
  {
    $rank = $rows['Rank'];
  }

  if($rank === 'admin')
  {
    $_SESSION['rank'] = $rank;
    $_SESSION['username'] = $username;

    echo '';
  }
  else if ($rank === 'partner')
  {
    $_SESSION['rank'] = $rank;
    $_SESSION['username'] = $username;

   echo '';
  }
  else if ($rank === 'trainee')
  {
     $_SESSION['rank'] = $rank;
     $_SESSION['username'] = $username;

    echo '';
  }
  else
  {
    echo 'Account not found.';
  }
 }
}
}
?>

in your management/index.php or in the page where supposed to only allow admins in.
 <?php session_start();
  if(isset($_SESSION['rank']) and $_SESSION['rank'] == "admin")
  {
  $_SESSION['username'];

  } else {
  header("location: ../index.php");
  } ?>

and with you saving, you just maybe forget the right quotations:
<?php
 if(isset($_POST['submit']))
 {
 $c_name = $_POST['c_name'];
 $v_link = $_POST['v_link'];
 $v_title = $_POST['v_title'];
 $v_desc = $_POST['v_desc'];
 $v_tags = $_POST['v_tags'];
 $m_sources = $_POST['m_sources'];
 $s_requests = $_POST['s_requests'];

 if(empty($c_name) or empty($v_link) or empty($v_title) or empty($v_title) or empty($v_desc) or empty($v_tags))
 {
   echo 'You must fill in the first 5 fields.';
 }
 else
 {
  $getRank = $db->query("SELECT * FROM users WHERE username = '$_SESSION[username]'");
while ($row = $getRank->fetch_assoc($getRank))
 {
   $usename = $row['username'];
   $rank = $row['rank'];
 }
 $db->query("INSERT INTO submitted_forms (username, rank, channel_username, video_link, video_title, video_description, video_tags, music_sources, special_requests) VALUES ('$username', '$rank', '$c_name', '$v_link', '$v_title', '$v_desc', '$v_tags', '$m_sources', '$s_requests')");
echo 'Form submitted successfully.';
 }
 }
?>


text:
Q: How to interpret the residual plots of Poisson Mixed-effect Regression (glmmTMB )and remove outliers? I ran a Poisson mixed-effect model (glmmTMB) to examine the eye fixations on words while reading. Based on my study design, I built a Poisson model and got the residual plots as beneath. "CONDITION" is a between-subject categorical variable with 3 types, and "fixation_count" is a count variable. It seems that my model has no issue with dispersion but the KS test and outlier tests were significant.
Q1. May I know how to understand the significant KS test and outlier tests? How to identify the outliers and remove them?
Q2. May I know how to understand the residual vs. predicted plot? Is there something wrong with the plot?
Q3. How to understand the red vertical lines in the DHARMa plot and the outlier test plot? Should the line be at the center of the histogram?
model<- glmmTMB(fixation_count~ CONDITION+ (1|PARTICIPANT) +
   (1| WORD) +  offset(log(TRIAL_TIME_1)),
    data = my_data, ziformula=~1, family = poisson)
summary (model)
res <- simulateResiduals(model, plot = TRUE)
testOverdispersion (model)
testResiduals(res)


text:
Q: Getting elements at multiple indices in a NumPy array I am trying to access specific rows and columns of a NumPy array as the documentation explains but I think I am missing something.
I have the following array:
arr = np.random.randint(10, size=(6, 4))
array([[1, 9, 6, 4],
       [8, 5, 0, 3],
       [3, 7, 3, 2],
       [1, 4, 8, 0],
       [5, 5, 8, 0],
       [0, 6, 4, 9]])

And I want to get the first and last row; and the first, third and last column, so I am trying:
arr[(0, -1),(0, 1, 3)]

But this is producing the following error:
IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (2,) (3,)

I think I am misunderstanding this type of integer indexing. I would expect this output:
array([[1, 9, 4],
       [0, 6, 9]])

I can do it this way but it feels really awkward:
arr[(0,-1),:][:,(0,1,3)]

How can I get the i-th elements of different dimensions?

A: You are looking for np.ix_:
arr[np.ix_((0, -1),(0, 1, 3))]

Results in
array([[1, 9, 4],
       [0, 6, 9]])

A: One way is to explicitly specify the index of each element of the result, where the key difference is that the row specification should be 2d:
>>> np.random.seed(444)
>>> arr = np.random.randint(10, size=(6, 4))
>>> arr
array([[3, 0, 7, 8],
       [3, 4, 7, 6],
       [8, 9, 2, 2],
       [2, 0, 3, 8],
       [0, 6, 6, 0],
       [3, 0, 6, 7]])

>>> rows = [[0],
...         [-1]]
>>> cols = [0, 1, -1]
>>> arr[rows, cols]
array([[3, 0, 8],
       [3, 0, 7]])

This example takes advantage of broadcasting for the row index.  In other words, you can take advantage of the fact that the rows are repeating themselves for the remaining two columns in addition to the 0th.

To use advanced indexing one needs to select all elements explicitly. ... However, since the indexing arrays above just repeat themselves, broadcasting can be used.  An example where you could not take advantage of broadcasting, and would need to specify each individual index, would be something like:

rows = [[1, 2],
        [3, 4]]
cols = [[2, 3],
        [1, 0]]

In that case, you're selecting elements at (1, 2), (2, 3), ...
See this example from the docs.
You might notice that this is exactly what is produced by np.ix_ (though I'm not saying it's not a useful function):
>>> rows, cols = np.ix_((0, -1),(0, 1, 3))


text:
Q: App migration on Google play, new package for same app We have this problem
Our app was originally created by an external company (therefore a key owned by them is needed for signing the .apk file every time we want to upload a new version)
Now we started to develop our app by ourselves and want to release this app but at the same time keep all the traffic and the reputation of the former app.
The app/service/name will be the same.
We basically just want to get rid of the first app package and upload new one to be independent from the external company who developed the first version.
The questions are:
1) Since we have a lot of links (blog - press release - website) on the internet pointing at the "first app", is there a possibility to keep the same old link for the new app or alternatively get a redirect?
2) If the 1)solution is not working, is there the possibility to keep two identical apps for a limited time period necessary to inform our users they have to download the new app and inform all the press websites to change link?
Thanks in advance for you help!

A: Could you not purchase the key from them? If the package name + key are the same then you will have no issues, most companies are not to bothered about giving the keys away once they no longer need them...


text:
Q: Plot a local image using bokeh image_url by running python with the -m option I have to run a bokeh script as a module using the -m option from the top directory, because it needs to import some other portable module under the same directory
python -m bokeh_module.bokeh_sub_module

The directory tree is shown below. By running the above command, it doesn't show the image no matter where the png file is placed, is there a way to resolved the issue? Thank you for any help.
.
├── other_module
│   ├── __init__.py
│   └── other_sub_module.py
├── bokeh_module
│   ├── __init__.py
│   ├── image.png # not showing
│   └── bokeh_sub_module.py
└── image.png # not showing either

bokeh_sub_module.py
from other_module import other_sub_module
from bokeh.plotting import figure, show

# do something with other_sub_module
p = figure(match_aspect=True)
p.image_url( ['image.png'], 0, 0, 1, 1 ) # not showing
p.image_url( ['./bokeh_module/image.png'], 0, 0, 1, 1 ) # not showing either
show(p)

By the way, if I run python bokeh_sub_module.py from the bokeh_module directory, the image.png inside the same directory can be found with no problems.

A: image_url requires URLs, and neither of your calls to image_url use URLs.
Try to use absolute URLs and add file:// in front of them.


text:
Q: Sort set with specific elements at beginning ascending I have a set of objects with a name attribute. Some of this objects should be showed at the beginnig of the set in ascending order and the rest should also be sorted in ascending order after the elements at the beginning. The comments at the sets are the content of the sets.
Here are some examples:
Expected output is ("abc", "hello", "a", "c", "f", "test")
Set<Props> props = handler.getProps(); //("test", "abc", "c", "f", "hello", "a")
Set<Props> unnecessaryProps = handler.getUnnecessaryProps(); //("hello", "abc")

Comparator comparator = new Comparator<Props>() {

    @Override
    public int compare(Props e1, Props e2) {
        if (e1.equals(e2)) {
            return 0;
        }
        if (unnecessaryProps.contains(e1)) {
            return -1;
        }
        if (unnecessaryProps.contains(e2)) {
            return 1;
        }
        return e1.compare(e2);
        }
    };
}

Can anyone help me please?

A: TreeSet has a constructor with a comparator parameter. You can use it to create sorted sets. Then you can add two sorted sets to a LinkedHashSet to keep the right order.

*

*Create a set of name fields (unlist) to filter props by the elements in the unnecessaryProps

*Create a comparator cmp that compares Props by name field:
Comparator.comparing(Props::getName)

*Create two TreeSets using this comparator in the constructor:
new TreeSet<>(cmp)

*Now you have two sorted sets by name: [a, c, f, test] and [abc, hello]

*Add the two sets in a LinkedHashSet in the right order.

Set<String> unlist = unnecessaryProps.stream().map(Props::getName).collect(Collectors.toSet());

Set<Props> output = new LinkedHashSet<>();
Comparator<Props> cmp = Comparator.comparing(Props::getName);

Set<Props> propstr = new TreeSet<>(cmp);
propstr.addAll(props.stream().filter(p -> !unlist.contains(p.getName())).collect(Collectors.toSet()));

Set<Props> unstr = new TreeSet<>(cmp);
unstr.addAll(unnecessaryProps);

output.addAll(unstr);
output.addAll(propstr);

System.out.println(output);

Output:
[abc, hello, a, c, f, test]

I assume the Props class has a toString() method to print the name values:
public class Props {
    // ...

    @Override
    public String toString() {
        return name;
    }
}


text:
Q: Configuring a Hudson job to run on both Windows and Linux based OS's I'm new to Hudson and am working on setting up a job that will build an HG repository of C++ source on multiple platforms.  (Linux, Solaris, FreeBSD, and Windows)
I've got all the platforms working except Windows and it revolves around the fact that I have the Hudson job executing a Python script via the shell.  (i.e. In the Hudson job configuration under the "Build" section I have "Execute Shell" => "Command" => python ./build_project.py)
[win32] $ /bin/sh -xe C:\Users\build\AppData\Local\Temp\hudson3063181706777016948.sh
The system cannot find the path specified
FATAL: command execution failed

Is there a way, outside of creating another job to run just the Windows build, to have Hudson execute the build_project script as Shell for the Unix type OSes and execute it as a batch file when the target is a Windows slave?

A: Another option is to use the python plugin: http://wiki.hudson-ci.org/display/HUDSON/Python+Plugin
With this you simply specify the python file that should be executed.

A: I recommend installing Cygwin on your windows boxes so that they can run UNIX shell scripts. That's what we do and it works very well.

A: Create an ant script, build.xml in your workspace that contains:

<target name="default">
    <exec executable="python">
        <arg value="./build_project.py"/>
    </exec>
</target>

Then in Hudson, instead of the "Execute Shell" do a "Invoke Ant" instead. Make the target "default" (no quotes). You'll have to install/point to ant in your Hudson->Manage Hudson->Configure System->Ant section(not in the job, in the main Hudson config) but it should work.


text:
Q: Add the row with the difference between colunms on a pandas dataframe Data source (csv):
Year;Month;website;status,XXX;Requests
2021;1;web.com;2XX;94557605
2021;1;web.com;3XX;18113
2021;1;web.com;4XX;412104
2021;1;web.com;5XX;1944
2021;2;web.com;2XX;65915413
2021;2;web.com;3XX;8176
2021;2;web.com;4XX;98080
2021;2;web.com;5XX;404
2021;3;web.com;2XX;73385551
2021;3;web.com;3XX;8204
2021;3;web.com;4XX;51097
2021;3;web.com;5XX;866
2021;4;web.com;2XX;19161899
2021;4;web.com;3XX;3113
2021;4;web.com;4XX;92152
2021;4;web.com;5XX;1110
2021;5;web.com;2XX;68930518
2021;5;web.com;3XX;3753
2021;5;web.com;4XX;80019
2021;5;web.com;5XX;69806
2021;1;api.com;2XX;94557605
2021;1;api.com;3XX;18113
2021;1;api.com;4XX;412104
2021;1;api.com;5XX;1944
2021;2;api.com;2XX;65915413
2021;2;api.com;3XX;8176
2021;2;api.com;4XX;98080
2021;2;api.com;5XX;404
2021;3;api.com;2XX;73385551
2021;3;api.com;3XX;8204
2021;3;api.com;4XX;51097
2021;3;api.com;5XX;866
2021;4;api.com;2XX;19161899
2021;4;api.com;3XX;3113
2021;4;api.com;4XX;92152
2021;4;api.com;5XX;1110
2021;5;api.com;2XX;68930518
2021;5;api.com;3XX;3753
2021;5;api.com;4XX;80019
2021;5;api.com;5XX;69806

I have created a pandas pivot-table base on the data source above:

The goal is to create a new Dataframe with the following information:

*

*new row with the diff. with previous month for each "Year,Month,website,status.xxx".

Example : Month(n-1)-(n) -> Month(1)-(2) -> 94557605 - 65915413 for website:web.com,status.xxx:2XX
Please, help me with any suggestions.
Thx in advance for the help.

A: pivoted = df.pivot(index=['Year', 'Month'], columns=['website', 'status,XXX'])
piv_diff = pivoted.diff(-1)
out = pivoted.join(piv_diff, lsuffix='_val', rsuffix='_diff').T.reorder_levels([-2, -1, -3]).sort_index(ascending=[False, True, False])
print(out)

Output:
Year                                    2021
Month                                      1           2           3           4           5
website status,XXX
web.com 2XX        Requests_val   94557605.0  65915413.0  73385551.0  19161899.0  68930518.0
                   Requests_diff  28642192.0  -7470138.0  54223652.0 -49768619.0         NaN
        3XX        Requests_val      18113.0      8176.0      8204.0      3113.0      3753.0
                   Requests_diff      9937.0       -28.0      5091.0      -640.0         NaN
        4XX        Requests_val     412104.0     98080.0     51097.0     92152.0     80019.0
                   Requests_diff    314024.0     46983.0    -41055.0     12133.0         NaN
        5XX        Requests_val       1944.0       404.0       866.0      1110.0     69806.0
                   Requests_diff      1540.0      -462.0      -244.0    -68696.0         NaN
api.com 2XX        Requests_val   94557605.0  65915413.0  73385551.0  19161899.0  68930518.0
                   Requests_diff  28642192.0  -7470138.0  54223652.0 -49768619.0         NaN
        3XX        Requests_val      18113.0      8176.0      8204.0      3113.0      3753.0
                   Requests_diff      9937.0       -28.0      5091.0      -640.0         NaN
        4XX        Requests_val     412104.0     98080.0     51097.0     92152.0     80019.0
                   Requests_diff    314024.0     46983.0    -41055.0     12133.0         NaN
        5XX        Requests_val       1944.0       404.0       866.0      1110.0     69806.0
                   Requests_diff      1540.0      -462.0      -244.0    -68696.0         NaN


text:
Q: Should I skip authorization, with CanCan, of an action that instantiates a resource? I am writing a web app to pick random lists of cards from larger, complete sets of cards.  I have a Card model and a CardSet model.  Both models have a full RESTful set of 7 actions (:index, :new, :show, etc).  The CardSetsController has an extra action for creating random sets: :random.
# app/models/card_set.rb
class CardSet < ActiveRecord::Base
  belongs_to :creator, :class_name => "User"
  has_many :memberships
  has_many :cards, :through => :memberships

# app/models/card.rb
class Card < ActiveRecord::Base
  belongs_to :creator, :class_name => "User"
  has_many :memberships
  has_many :card_sets, :through => :memberships

I have added Devise for authentication and CanCan for authorizations. I have users with an 'editor' role.  Editors are allowed to create new CardSets.  Guest users (Users who have not logged in) can only use the :index and :show actions.  These authorizations are working as designed.  Editors can currently use both the :random and the :new actions without any problems.  Guest users, as expected, cannot.
# app/controllers/card_sets_controller.rb
class CardSetsController < ApplicationController
  before_filter :authenticate_user!, :except => [:show, :index]
  load_and_authorize_resource

I want to allow guest users to use the :random action, but not the :new action.  In other words, they can see new random sets, but not save them.  The "Save" button on the :random action's view is hidden (as designed) from the guest users.  The problem is, the first thing the :random action does is build a new instance of the CardSet model to fill out the view.  When cancan tries to load_and_authorize_resource a new CardSet, it throws a CanCan::AccessDenied exception.  Therefore, the view never loads and the guest user is served a "You need to sign in or sign up before continuing" message.
# app/controllers/card_sets_controllers.rb
def random
  @card_set = CardSet.new( :name => "New Set of 10", :set_type => "Set of 10" )

I realize that I can tell load_and_authorize_resource to skip the :random action by passing :except => :random to the call, but that just feels "wrong" for some reason.
What's the "right" way to do this?  Should I create the new random set without instantiating a new CardSet?  Should I go ahead and add the exception?
Update
I didn't include my Ability class above.  I've updated it to include the ':random' action, but it still isn't working quite right.
class Ability
  include CanCan::Ability

  def initialize( user )
    user ||= User.new # User hasn't logged in

    if user.admin?
      can :manage, :all if user.admin?
    else
      # All users, including guests:
      can :read, [Card, CardSet]
      can :random, CardSet

      # All users, except guests:
      can :create, [Card, CardSet] unless user.role.nil?
      can :update, [Card, CardSet] do |c|
        c.try( :creator ) == user || user.editor?
      end

      if user.editor?
        can [:create, :update], [Card, CardSet]
      end
    end
  end
end

A: I found my problem.  CanCan was not the issue at all!  The following line in my CardSet controller was throwing the exception and redirecting my guest (not logged in) users to the log in page:
before_filter :authenticate_user!, :except => [:show, :index]

I changed it to read:
before_filter :authenticate_user!, :except => [:show, :index, :random]

And now the code works as intended: Guest users can view the new random sets created, but cannot 'Save' them unless they first log in.
So, my real problem was with Devise (or, actually, my Devise configuration) and not with CanCan at all.

A: Well, the right thing would be to use CanCan ability class to define the correct authorization rules.
in Ability.rb
  def initialize(user)
#everyone
    can [:read, :random], [CardSet]
#everyone who is editor
    if user.editor?
      can [:new, :create], [CardSet]

etc

The problem is, the first thing the :random action does is build a new instance of the CardSet model to fill out the view. When cancan tries to load_and_authorize_resource a new CardSet, it throws a CanCan::AccessDenied exception.

While CanCan authorizes controller action, building a new instance in random action (i.e. CardSet.new) is not in the scope of CanCan. You probably get the error because you have no rules defined in Ability.rb for random action. My example above should solve your problem


text:
Q: buildingTag() always returns false Whenever I try to create a conditional stage with buildingTag(), the stage always gets skipped, even when the current commit is a tag. Here is my Jenkinsfile:
pipeline {
  agent {
    docker {
      image 'node:10'
    }

  }
  stages {
    stage('Build') {
      steps {
        sh 'yarn install'
        sh 'node scripts/build.js'
      }
    }
    stage('Lint') {
      steps {
        sh 'yarn lint'
      }
    }
    stage('Deploy') {
      when {
        buildingTag()
      }
      environment {
      }
      steps {
        sh 'node scripts/deploy.js'
        sh 'node scripts/publish.js'
      }
    }
  }
}

A: Likely due to this bug:
https://issues.jenkins-ci.org/browse/JENKINS-55987
Workaround is:
            when {
                expression {
                    return !isVersionTag(readCurrentTag())
                }
            }

with:
def boolean isVersionTag(String tag) {
    echo "checking version tag $tag"

    if (tag == null) {
        return false
    }

    // use your preferred pattern
    def tagMatcher = tag =~ /\d+\.\d+\.\d+/

    return tagMatcher.matches()
}

// workaround https://issues.jenkins-ci.org/browse/JENKINS-55987
def String readCurrentTag() {

    return sh(returnStdout: true, script: "git describe --tags").trim()
}

A: buildingTag() requires that the TAG_NAME environment varible is set.
This is not set automatically in a simple (not multibranch) pipeline.
pipeline {
    agent any
    environment {
        // To get the tag like shown soru's answer:
        // TAG_NAME = sh(returnStdout: true, script: "git describe --tags").trim()

        // In my case I already have a tag saved as an environment variable:
        // gitlabBranch=refs/tags/tagname
        TAG_NAME = "${env.gitlabBranch.split('/')[2]}"
    }
    stages {
        stage('buildingTag') {
            when { buildingTag() }
            steps {
                echo 'buildingTag works here.'
            }
        }
    }
}

A: I also come across this problem. All you need to do enable Advanced clone behaviours -> Fetch tags in the project settings, and set TAG_NAME environment variable in the Jenkins file.
1- Advanced clone behaviours

2- Fetch tags

3- And set TAG_NAME variable in pipeline (buildingTag function requires this)
pipeline {
  environment {
    TAG_NAME = sh(returnStdout: true, script: "git --no-pager tag --points-at HEAD").trim()
  }
  agent {
...

4- Use Jenkins's buildingTag function to check whether commit has tag or not
...
  stage("Publish Release Artifact") {
    when {
      buildingTag()
    }
...

A: I have been using soru's solution, but I had problems when I was building a branch that is tagged, so I tried this and it seems to work:
def boolean isVersionTag(String tag) {
    echo "checking version tag $tag"

    if (tag == null) {
        return false
    }

    // use your preferred pattern
    def tagMatcher = tag =~ /\d+\.\d+\.\d+/

    return tagMatcher.matches()
}

def String readCurrentTag() {
    return sh(returnStdout: true, script: 'echo ${TAG_NAME}').trim()
}


text:
Q: dango-crispy-forms error keeps interferring with project even after uninstallation I was trying to embed django crispy forms into my project which gave me an "Module not found" error which I couldn't figure. So, I uninstalled it, but even after uninstallation, this thing throws me this error when I run the local server and even migrate.
Terminal-------
(newvenv) root@localhost:~/my_website/python-getting-started# python manage.py runserver
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f286ba630d0>
Traceback (most recent call last):
  File "/root/my_website/newvenv/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper
    fn(*args, **kwargs)
  File "/root/my_website/newvenv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run
    autoreload.raise_last_exception()
  File "/root/my_website/newvenv/lib/python3.6/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception
    raise _exception[1]
  File "/root/my_website/newvenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 337, in execute
    autoreload.check_errors(django.setup)()
  File "/root/my_website/newvenv/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper
    fn(*args, **kwargs)
  File "/root/my_website/newvenv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/root/my_website/newvenv/lib/python3.6/site-packages/django/apps/registry.py", line 89, in populate
    app_config = AppConfig.create(entry)
  File "/root/my_website/newvenv/lib/python3.6/site-packages/django/apps/config.py", line 90, in create
    module = import_module(entry)
  File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'crispy_formshello'

settings.py ----
"""
Django settings for gettingstarted project.

Generated by 'django-admin startproject' using Django 2.0.

For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'CHANGE_ME!!!! (P.S. the SECRET_KEY environment variable will be used, if set, instead).'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'hello',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'gettingstarted.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'gettingstarted.wsgi.application'

# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Asia/Kathmandu'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/

STATIC_URL = '/static/'

Can't help this problem......


text:
Q: Cannot add foreign key here? So I'm trying to create tables and I can't for the life of me understand why i keep getting and error saying "Cannot add foreign key to constraint".
The types are the same, the parent is a primary key, and they're NULLness is the same.
The problem is in the line in the create table for CDSingers where it says:
foreign key (track_num) references CDTracks (track_num),

(it's near the end)
It's the only table that won't be created and it's because of this line.
Please help.
(some of the other tables have been ommitted since they aren't connected)
create table CD
(
num int NOT NULL,
producer varchar(100) NOT NULL,
cd_number varchar(100) NOT NULL,
title varchar(100) NOT NULL,
type varchar(100) ,
band_name varchar(100) ,
production_date DATE NOT NULL,
price double CHECK (price >= 0),
foreign key (type) references MusicType (type),
foreign key (band_name) references Band (band_name),
primary key (num),
unique (producer, cd_number)
);

create table CDTracks
(
num int NOT NULL,
track_num int NOT NULL,
song_name varchar(100) NOT NULL,
minute int NOT NULL,
foreign key (num) references CD (num),
primary key (num, track_num)
);

create table Singer
(
id int NOT NULL,
singer_firstname varchar(100) NOT NULL,
singer_lastname varchar(100) NOT NULL,
primary key (id)
);

create table CDSingers
(
num int NOT NULL,
track_num int NOT NULL,
singer_id int NOT NULL,
foreign key (num) references CDTracks (num),
foreign key (track_num) references CDTracks (track_num),
foreign key (singer_id) references Singer (id),
primary key (num, track_num, singer_id)
);

A: You declare composite foreign keys like this:
foreign key (num, track_num) references CDTracks (num, track_num),


text:
Q: Incorrect command error for composer network deploy I'm following this tutorial on macOS.
$ composer -v
v0.20.1

$ composer network deploy -a dist/iot-perishable-network.bna -A admin -S adminpw -c PeerAdmin@hlfv1 -f networkadmin.card

Incorrect command. Please see the list of commands above, or enter "composer network --help".

Available composer network commands in the list mentioned above: download, install, list, loglevel, ping, reset, start, upgrade

A: You are using Composer v0.20.1, the tutorial you are referring to is using Composer v0.15.0.
The deploy command has been removed since Hyperledger 0.19.0.
See https://github.com/hyperledger/composer/releases/tag/v0.19.0 :

The following commands are no longer valid:
composer runtime install
composer network deploy
composer network update
composer network undeploy

You now have to use the following commands instead :
composer network install
composer network start
composer network upgrade

See https://hyperledger.github.io/composer/latest/reference/commands for last valid commands.


text:
Q: Spaghetti code visualisation software? a smoking pile of spaghetti just landed on my desk, and my task is to understand it (so I can refactor / reimplement it).
The code is C, and a mess of global variables, structure types and function calls.
I would like to plot graphs of the code with the information:
- Call graph
- Which struct types are used in which functions
- Which global variable is used in what function
Hopefully this would make it easier to identify connected components, and extract them to separate modules.
I have tried the following software for similar purposes:
- ncc
- ctags
- codeviz / gengraph
- doxygen
- egypt
- cflow
EDIT2:
- frama-c
- snavigator
- Understand
The shortcomings of these are either
a) requires me to be able to compile the code. My code does not compile, since portions of the source code is missing.
b) issues with preprocessor macros (like cflow, who wants to execute both branches of #if statements). Running it through cpp would mess up the line numbers.
c) I for some reason do not manage to get the software to do what I want to do (like doxygen; the documentation for call graph generation is not easy to find, and since it does not seem to plot variables/data types anyway, it is probably not worth spending more time learning about doxygen's config options). EDIT: I did follow a these Doxygen instrcutions, but it did only plot header file dependencies.
I am on Linux, so it is a huge plus if the software is for linux, and free software. Not sure my boss understands the need to buy a visualizer :-(
For example: a command line tool that lists in which functions a symbol (=function,variable,type) is referenced in would be of great help (like addr2line, but for types/variable names/functions and source code).
//T

A: My vote goes to gnu global. It has all the features of ctags/cscope combined as well as the possibility to generate fully indexed html which allows you to browse the code in your favorite browser. Fire it up in apache and you have a web-service that anyone can access including full search capabilities.
It integrates nicely into emacs/vim/even the bash-shell, and you can use it directly from the shell-prompt.
To see it in action on the linux kernel, visit this
Combine that with a tool for cyclomatic complexity plugin for eclipse which calculates the complexity of your code. besides the cyclomatic complexity it can handle:

*

*McCabe's Cyclomatic Complexity

*Efferent Couplings

*Lack of Cohesion in Methods

*Lines Of Code in Method

*Number Of Fields

*Number Of Levels

*Number Of Locals In Scope

*Number Of Parameters

*Number Of Statements

*Weighted Methods Per Class

...and you should have everything you need.

A: If you like command line ;) maybe you could try cscope, it does static analysis of code and can tell you where are referenced some symbols/variables/functions... Not the Holy Graal, but it can be pretty usefull to browse unknown source code.
There are also some GUI that can handle csope results (Vi, Emacs, JEdit...).
On the other hand, Eclipse with the CDT plugin can also help you to navigate into the spaghetti code you have to maintain.

A: It's not free and afaik not linux but cppDepend might be worth evaluating - at least until someone comes up with a more suitable suggestion :)
http://www.cppdepend.com/ [Demo video here]

A: If you'd like to know in which functions a symbol is declared or referenced you can try LXR. It's not console based, but is quite usable.


text:
Q: SQL query one table multiple choices I need help for designing an SQL statement. It will be created on the fly in a Web Server back end, depending on the request. This will filter a database for the desired results.
To describe my need in simplest form:
One table, two fields, 50 staff, 30 skills.
Example:
staff_id, skill_id
1,        1
1,        2
1,        3
1,        4
2,        2
2,        3
2,        4
3,        2
4,        3

Q: Who has Skill 3
A:  Staff 1,2,4
(This is easy)
Q: Who has Skill 2 AND 3
A: Staff 1,2
The actual query will have a request for 5 or 6 Skills

A: Considering that the number of skills varies from time to time, the best way to handle this via temp table..Here is the pseudocode...syntax needs to be fixed.
create procedure my_procedure(string of skillsets)
begin
create table #tmp_skillsets(skillset smallint)
foreach skillset in skillsets
    insert into #tmp_skillsets(convert_to_smallint(skillset))

select distinct staff from myTable, #tmp_skillset
where myTable.skillset = #tmp_skillsets

end

Call this procedure like: "exec my_procedure("1456") or "exec my_procedure("179248503")

A: I think this should work:
SELECT DISTINCT staff_id
FROM oneTable t
WHERE EXISTS (SELECT 1 FROM oneTable ti WHERE t.staff_id = ti.staff_id AND ti.skill_id = 2)
  AND EXISTS (SELECT 1 FROM oneTable ti WHERE t.staff_id = ti.staff_id AND ti.skill_id = 3)


text:
Q: How to force two users to autologin at boot into two separate xfce sessions? On boot, I would like more than one user to be auto logged in on virtual terminals.

A: Try to install KDE Display Manager for X11
# apt-get install -y kdm

You need to modify configuration file:
/etc/kde4/kdm/kdmrc
[X-:0-Core]
ServerVT=8
AutoLoginEnable=true
AutoLoginAgain=true
AutoLoginDelay=10
AutoLoginUser=user1
AutoLoginPass=pass1

[X-:1-Core]
ServerVT=9
AutoLoginEnable=true
AutoLoginAgain=true
AutoLoginDelay=10
AutoLoginUser=user2
AutoLoginPass=pass2

For each user you should specify the desktop manager:
# cat /home/user{1,2}/.dmrc
[Desktop]
Session=enlightenment

[Desktop]
Session=cinnamon


text:
Q: How to update extended User Model using Django Forms? I am new to Django and need a help.
I want to allow users to update their account data using form, but struggle with associating Django User model with my UserProfile model, which extends default model with some additional fields.
I found, that solution is to create my own model form, but unfortunately I'm not exactly sure how to implement it.
models.py:
class UserProfile(models.Model):
    user = models.OneToOneField(User)
    description = models.CharField(max_length=100, default='')
    city = models.CharField(max_length=100, default='')
    website = models.URLField(default='')
    phone = models.IntegerField(default=0)
    image = models.ImageField(upload_to='profile_image', blank=True)

    def __str__(self):
        return self.user.username

def create_profile(sender, **kwargs):
    if kwargs['created']:
        user_profile = UserProfile.objects.create(user=kwargs['instance'])

post_save.connect(create_profile, sender=User)

forms.py:
class EditProfileForm(UserChangeForm):
    image = forms.ImageField(required=False)
    city = forms.CharField(required=False)

    class Meta:
        model = User
        fields = (
            'email',
            'first_name',
            'last_name',
            'password',
            'image',
            'city'
        )

views.py:
def edit_profile(request):
    if request.method == 'POST':
        form = EditProfileForm(request.POST, instance=request.user)

        if form.is_valid():
            form.save()
            return redirect(reverse('accounts:view_profile'))
    else:
        form = EditProfileForm(instance=request.user)
        args = {'form': form}
        return render(request, 'accounts/edit_profile.html', args)

edit_profile.html:
<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Submit</button>
</form>

A: You are looking for Inline formsets. Just read the docs, it's pretty simple.


text:
Q: How to save video in ios extension file like .mp4 .webm in Flutter Am having bit a problem saving videos and i want to download it for sure if the video is downloaded and can be shown public in gallery or photos in ios.
code so far
final down = await getTemporaryDirectory(); // from path_provider
File saveFile = File(down.path +
             "/${mediaUrl.substring(mediaUrl.lastIndexOf("/")).replaceAll("/", "")}");

await DioMethods.d
              .download(response["url"].toString(), saveFile.path);
await GallerySaver.saveVideo(saveFile.path).then((value) =>
              Loadings.snackBarmessage(
                  title: mediaUrl
                      .substring(mediaUrl.lastIndexOf("/"))
                      .replaceAll("/", ""),
                  message: "Saved Successfully"));

error logs if the file is .webm
[VERBOSE-2:ui_dart_state.cc(209)] Unhandled Exception: Invalid argument(s): File on path is not a video.

A: If would like to view the files on your mobile, you can use this gallery_saver plugin to save your video file in Gallery.
final video = await controller.stopVideoRecording();
await GallerySaver.saveVideo(video.path);


text:
Q: Bell button as input I got a simple bell system from elcom. It works with 12V AC.
When I measure the voltage at the switch it is 1V when not pressed.
When I measure the switch sides to the power input of the bell system I get 0V on one side and 16V AC on the other. Now I want to use the switch as input on an Wemos D1 mini.
When I simply wire the switch to gnd and an input it works if the switch is not attached to the bell system.
If it is attached and I also attach the Wemos the bell rings which is a sign that this will not work in combination. At least I did not yet burn my microcontrolller which I get might easily happen :-)
Any ideas how I can have the switch attached to my bell system and to the wemos D1?
I power the D1 from the same 12V AC using a regulator board. The powering of the D1 already works but I can not guarantee the start order.


text:
Q: Cluster standard errors for ordered logit R polr - values deleted in estimation I am quite new to R and used to pretty basic application.
Now I have encountered a problem I need help with:
I am looking for a way to cluster standard errors for an ordered logistic regression (my estimation is similar to this example)
I already tried robcov and vcovCL and they give me similar error messages:

*

*Error in meatCL(x, cluster = cluster, type = type, ...) :    number
of observations in 'cluster' and 'estfun()' do not match

*Error in u[, ii] <- ui :    number of items to replace is not a multiple of  replacement length

Many thanks in advance!
Edit:
I found some more information about the missing values but that does not seem to be the problem - because it persists even if I work around it using this answer, or when use a dataset without NA's. Just as in the example below. The problem seems to be that polr does not give me the residuals as part of the output. How can I work around this?
 dat <- read.dta("https://stats.idre.ucla.edu/stat/data/ologit.dta")
    length(dat$apply)
    twenty <- seq(from=1, to=20, by=1)
    dat$clustervar<-sample(twenty, size=400, replace=TRUE)

    m <- polr(apply ~ pared + public + gpa, data = dat, Hess=TRUE)
    vcovCL <- function(x, cluster.by, type="sss", dfcw=1){
      # R-codes (www.r-project.org) for computing
      # clustered-standard errors. Mahmood Arai, Jan 26, 2008.

      # The arguments of the function are:
      # fitted model, cluster1 and cluster2
      # You need to install libraries `sandwich' and `lmtest'

      # reweighting the var-cov matrix for the within model
      require(sandwich)
      cluster <- cluster.by
      M <- length(unique(cluster))
      N <- length(cluster)
      stopifnot(N == length(x$residuals))
      K <- x$rank
      ##only Stata small-sample correction supported right now
      ##see plm >= 1.5-4
      stopifnot(type=="sss")
      if(type=="sss"){
        dfc <- (M/(M-1))*((N-1)/(N-K))
      }
      uj  <- apply(estfun(x), 2, function(y) tapply(y, cluster, sum))
      mycov <- dfc * sandwich(x, meat=crossprod(uj)/N) * dfcw
      return(mycov)
    }
    vcovCL(dat, m, dat$clustervar)

This gives me:
Error: N == length(x$residuals) is not TRUE
Called from: vcovCL(dat, m, dat$clustervar)

A: I had success following the help page for ?sandwich::vcovCL which shows that the first arg to the function is a model object. Needed to use the :: operator to mask the function you offered:
 m <- polr(apply ~ pared + public + gpa, data = dat, Hess=TRUE)
 ( clval <- sandwich::vcovCL(m, dat$clustervar) )
                                  pared       public         gpa unlikely|somewhat likely
pared                       0.085218306  0.005588259  0.04584255               0.15545404
public                      0.005588259  0.092283173 -0.01890725              -0.05875859
gpa                         0.045842552 -0.018907254  0.07067573               0.22455931
unlikely|somewhat likely    0.155454041 -0.058758588  0.22455931               0.72408670
somewhat likely|very likely 0.165079639 -0.058282514  0.23631756               0.75713049
                            somewhat likely|very likely
pared                                        0.16507964
public                                      -0.05828251
gpa                                          0.23631756
unlikely|somewhat likely                     0.75713049
somewhat likely|very likely                  0.80749182

You may need to use the diag of that matrix if you want Wald tests. I think that is what coeftest will deliver:
coeftest( m, vcov = clval)

t test of coefficients:

        Estimate Std. Error t value  Pr(>|t|)
pared   1.047690   0.291922  3.5889 0.0003738 ***
public -0.058786   0.303781 -0.1935 0.8466565
gpa     0.615941   0.265849  2.3169 0.0210210 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

The other question that prompted the successful search of Rhelp and finding the answer by Achim Zeileis is here


text:
Q: In C++, can you have a class member be a passed-in reference? I have a 'StripManager' class that is responsible for updating the data of an already-existing 'Strip' class.  As such, the manager needs a reference to the strip.  Now I know I can pass in a pointer to the 'Strip' class to the constructor of the 'StripManager' class, but I'm wondering if there's any way to do that using references instead of pointers.  I just have always preferred dealing with references since you use them like the actual class instance rather than having to deal with pointer notation, etc.
So can this be done?
Here's some pseudo-code...
class StripManager
{
  public:
    Strip &managedStrip;
    StripManager(Strip &stripToManage);
}

StripManager::StripManager(Strip &stripToManage)
{
    managedStrip = stripToManage;
}

A: A reference can only be initialized but not assigned. So you cannot reassign the reference itself. You can do it in member initialization list to initialize the reference member.
class StripManager
{
  public:
    Strip &managedStrip;
    StripManager(Strip &stripToManage);
};

StripManager::StripManager(Strip &stripToManage): managedStrip(stripToManage)
{}

A: You can initialize a reference, but not assign to it, so you need to use the member initializer list for this. It's good habit to use it instead of assignment in constructors anyway as it can be more efficient.
StripManager::StripManager(Strip &stripToManage) : managedStrip (stripToManage)
{
}

Note that having a reference member makes StripManager non-assignable (StripManager a(strip1), b(strip2); a = b; won't compile unless you write a custom assignment operator; even then, since you can't assign references, it's unclear what the semantics should be), which may or may not be a problem depending on your particular situation.


text:
Q: How to copy a LDAP entry and all the subtree on a Linux/openldap server? I want to duplicate an LDAP subtree : my software uses

ou=software,o=company,c=fr

and I want to have version 2 of the software to use

ou=software_v2,o=company,c=fr

I tried JXplore to copy the tree, which is fine for the development server, but I need to to the same on the production server, which is in a datacenter.
Is there any openldap command, any script to do this, or must I create it?
Best regards,
Cédric

A: Probably the best way to handle this is to export the sub-tree in question to an LDIF file, tweak the file to change the DNs to be what you need, import the LDIF file into the production environment. There are a variety of ways to create the LDIF file, with ldapsearch being the most available. The command needed to get the LDIF file can vary depending on the LDAP server in use, but should look something similar to this.
ldapsearch -b ou=software,o=company,c=fr -s sub -h host.ldap.server > software.ldif
This assumes you don't need to log in. Pipe output to a file. You can then open the file in whatever tool you wish and change all occurrences of "ou=software,o=" to "ou=software_v2,o=". This can then be used to import.
ldapadd -a -h host.ldap.server -f software.ldif
TLS usage, logins, and strange ports will require different options on both commands, but this should at least get you started.
(Edit) Those fields are base64 encoded. The one you quote in comments has "Côte d'Azur" in the DN. One way to get at the real text is to:

*

*Copy the DN to a simple text file, encode-old.txt

*Pipe it through the base64 command,  base64 -d encode-old.txt > decoded.txt

*Make the changes you need in the decode.txt file

*Pipe it back through the base64 command,  base64 decoded.txt > encode-new.txt

Obviously this won't scale that well, but it shows how to get at the real text. Processing the .ldif file with sed/awk or perl to make the needed changes programatically is probably your best best.

A: Although you already marked sysadmin1138's reply as "reply", I still want to contribute my idea.
Install "gq" on a system, connect it with an account which has enough privileges to the LDAP server and simply drag and drop your subtree (or: "save as new"). It is easy, it is fast and works.
gq is a LDAP browser (with editing function) which requires a X server.


text:
Q: VB.Net Class Inherit Sub New I'm currently trying to convert some basics in C# class methods into VB, and I'm having some difficulties.
Say we have two classes, baseClass and newClass
Public Class baseClass
    Public Sub New(ByVal obj As Object)
       '... do something here
    End Sub
End Class

Public Class newClass
    Inherits baseClass
    Public Sub New(ByVal obj as Object)
       '... do something here
    End Sub
end Class

However, whenever I tried to declear something like
dim nc as newClass(myObj)

I kept getting an error telling me that
First statement of this 'Sub New' must be a call to 'MyBase.New' or 'MyClass.New' because base class 'baseClass' of 'newClass' does not have an accessible 'Sub New' that can be called with no arguments.
When I was trying to do something like, if written in C#, like this
public partial class newClass : baseClass
{
  public newClass(Object obj) : baseClass(obj)
  {
     // do something here
  }
}

I understand that the debugger is telling me just add an empty public sub new() in baseClass, but that's not what I'm trying to do, I wanted it to invoke the other constructor, so hopefully someone can point me in the right direction, since I've been trying to find an easy conversion guide but I couldn't find any.
Any answer is much appreciated.

A: Public Class newClass
    Inherits baseClass
    Public Sub New(ByVal obj as Object)
        MyBase.New(obj)
    End Sub
end Class


text:
Q: Is this a good way to have class level member variables? I'm trying to violate the laws of objective C a little by having static (class level) variables that have setters and getters:
+(CGRect*)defaultOpFr:(CGRect*)set{
    static CGRect * defaultOpFr = nil;

    if (set) {
        if (!defaultOpFr) {
            defaultOpFr = malloc(sizeof(defaultOpFr));
        }
        defaultOpFr->size.width = set->size.width;
        defaultOpFr->size.height = set->size.height;
        defaultOpFr->origin.x = set->origin.x;
        defaultOpFr->origin.y = set->origin.y;
    }
    return defaultOpFr;
}

It seems to work, but I'm wondering if there's a better way. The idea is to call it with nil to retrieve the value, call it with a CGRect to set a new value.

A: Yup;  that'll work, but be completely against any kind of common pattern.
Why don't you simply have a standard setter/getter pair?  Even at the class level, that is fine:
static CGRect barf;
+ (CGRect) barf { return barf; }
+ (void) setBarf:(CGRect)aRect { barf = aRect; }

Done.