text:
Q: Lua: how to use debug.getlocal local function ThisIsAFunction()
    local test1 = "im a local var"
    local asd = "im also a local var"
end

How would I use debug.getlocal to get the value of the local functions inside "ThisIsAFunction"

A: Something like this should work:
local function printLocals()
  local i = 1
  while true do
    local name, value = debug.getlocal(2, i)
    if not name then break end
    print(name, i, value)
    i = i + 1
  end
end

local function ThisIsAFunction()
  local test1 = "im a local var"
  local asd = "im also a local var"
  printLocals()
end

ThisIsAFunction()

This should print:
test1   1   im a local var
asd 2   im also a local var

Note that getlocal can only get values for the function/frame that is already on the stack (that's why you need to call printLocals from the function you want to inspect).
You can use getinfo to inspect the function (from outside), but you need to be executing the function to inspect, so you need to make an explicit call to printLocals or use a debug hook to do an implicit one.


text:
Q: Lists created in subsites are not visible in parent intranet site I`m deeply confused as why lists created in subsite example:
http://intranet.abc.com/projects are visible in its respective site content:
http://intranet.abc.com/projects/_layouts/15/viewlists.aspx

Saved all lists as template and uploaded to the solution section under Site Settings (Top Level)
Still trying to add a new app from the site content of Intranet parent site example: http://intranet.abc.com/_layouts/15/viewlists.aspx, doesn't gives option to add new app based on the lists created in subsites.
Wondering what more to do in order to import the lists to the main site apart from uploading in the solution section.

redpajama_set_name: RedPajamaStackExchange


text:
Q: KMM iOS mismatch type ChallengeHandler Type mismatch: inferred type is ChallengeHandler /* = (NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge, (NSURLSessionAuthChallengeDisposition /* = Long */, NSURLCredential?) -> Unit) -> Unit */ but ChallengeHandler /* = (NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge, (NSURLSessionAuthChallengeDisposition /* = Int */, NSURLCredential?) -> Unit) -> Unit */ was expected

Basically above error logs happen when migrate to latest client ktor 2.0.3 and using kotlin 1.7.10.
Is this a bug from ktor? how can we deal with this issue? should we just postponed update latest ktor until this issue fixed?
I think platform.darwin.NSInteger is recognized as Long, thus it got mismatch.
when you search inside NSURLSessionAuthChallengeDisposition this is platform.darwin.NSInteger but somehow IDE recognized as Long not Int, so I guess this is a bug?
Run the build also failure by same error above
Can't do anything. tried to create extension to use Int, still same..
Tried to cast manually to Int also still error.
Can't build too because of this error.
Anyone have solutions?

A:
This can actually compiles just fine on native iOS. Should just ignore the error and provide an explanation in the comments section.


text:
Q: Floating Div boxes limited by magic Heres the link to the page In question....
http://team2648.com/OTIS2/DivTest.html
So If you look at that page, If your browser is small enough, you see that below the box with the red background, there is a bit of space, Why doesn't the box below float up?

The HTML Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

        <title>OTIS v1.5</title>

        <link href="css/reset.css" rel="stylesheet" type="text/css" media="all" />
        <link href="css/default.css" rel="stylesheet" type="text/css" media="screen" />
        <link href="css/styling.css" rel="stylesheet" type="text/css" media="screen" />

        <link rel="stylesheet" href="css/validationEngine.jquery.css" type="text/css" media="screen" charset="utf-8" />

        <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
        <meta name="author" content="Techplex Engineer" />
        <meta name="keywords" content="" />
        <meta name="description" content="" />

Online Team Information System

A Web Database Application for Team Profile Management

 My

 Dashboard

 Profile

 Information

 Emergency Contact

 Management

 Users

 Email

 Blog

 Report a Bug

 Logout

                        Logged in as:

                        Blake

Welcome to your personal dashboard Blake

                            Your current Bio:
<textarea rows="10" cols="50"> </textarea>

                            IMPORTANT

Your Public Profile is pending moderation.

                            You have:

        42 of 30 fundraising hours

fundraised $160 of $300

        3 of 5 community service hours

        0 of 40 build hours

                            <form name="controlsForm">
                                <input id="cblogin" type="checkbox" name="loginbox"  onClick=""/> Disable Login

                                <input id="cbreg" type="checkbox" name="regbox"  onClick=""/> Disable Registration

                            </form>

                    This system was designed, built and is maintained by Blake for Infinite Loop Robotics
OTIS(Online Team Information System) © 2010 Techplex Labs

You can view the css here:
http://team2648.com/OTIS2/css/styling.css
but the relevant part is this:
div.widget{
width: 200px;
float: left;

/*    text-align: center;*/
border: 1px solid black;
padding: 8px;
margin: 8px;

/*    margin-left:8px;
font-weight:400;*/
-moz-border-radius:11px;
-khtml-border-radius:11px;
-webkit-border-radius:11px;
border-radius:5px;
background:#fff;
border:2px solid #e5e5e5;
-moz-box-shadow:rgba(200,200,200,1) 0 4px 18px;
-webkit-box-shadow:rgba(200,200,200,1) 0 4px 18px;
-khtml-box-shadow:rgba(200,200,200,1) 0 4px 18px;
box-shadow:rgba(200,200,200,1) 0 4px 18px;
/*    padding:16px 16px 40px;*/
}
div#disclaimer
{
margin-top: 10px;
border: 1px dotted black;
font-size:10px;
background-color: #D7D7D7;
}
div.clear
{
clear: both;
}
div#profilestats
{
border:2px solid #FF9999;
}
div#cal
{
width: 400px;
padding-bottom: 0px;
}

A: The reason why this happening is because both profilestats div and cal div are float:left. Try a float:right; on cal div so that the next div which is floated left(stats) can take the available space below profilestats.

A: I don't know if you have this as you like, but with the comments, I see when you make the full window smaller, the box with the calendar in it (cal) moves below the red Important box (profilestats).
IF you wish this to be closer (close the gap between these) what is causing the space is the DIV.widget in styling.css, margin:8px; besides that, I see nothing causing space at this point with that change - I tested this in IE8 and removing that CSS element setting did indeed push them directly conjunctual with no space between.
Now if what you mean is moving the "stats" up directly below the "profilestats" then that is another matter which can be resolved a couple of different ways.

*

*put "profilestats" and "stats" in a div together (with "cal" and "logins" in
another div together, and float both "container" divs left.

*Use the float:left and float: right on the left and right
elements, but that will introduce a space between if the width is
extended (browser width) unless addressed through additional css.

In this case, I would opt for #1 as the css is easier to control.
NOTE: be cautious of margins on IE6 in float left elements at times it can be inconsistent.


text:
Q: Reutilizar partes de código que se repiten varias veces Para reutilizar código estoy creando ficheros independientes a los que simplemente llamo donde lo necesite con require. Funciona bien y no hay problema, pero tengo muchas partes de código, de 10 lineas, que me gustaría poder reutilizar también sin necesidad de crear un fichero independiente por cada trozo de código que quiero poder usar en distintos puntos.
¿Existe alguna forma de reunir todas esas partes de código que quieres reutilizar en UN sólo fichero? Con las funciones por ejemplo no uso más que un fichero y cuando quiero llamar a una en concreto lo hago por su nombre. Sé que puedo reutilizar código generando una función que me cree un array y después recorrerlo, pero me resulta bastante tedioso.

A: Para la función que comentas lo mejor es utilizar motores de plantillas como PUG, mediante mixins puedes reutilizar el código que desees. Te dejo un ejemplo por si te interesa.
MIXIN que añade un elemento li con el argumento que le pasas:
mixin pet(name)
  li.pet= name
ul
  +pet('cat')
  +pet('dog')
  +pet('pig')

el output será

cat

dog

pig

Si te interesa puedes ver más en PUG


text:
Q: Tikz calendar in spanish I've found this example and I'm trying to arrange the template to this year, my language and my country. My question is how can I get the days and months in Spanish. I've found this question in stackexchange, and and I've tried to apply the manner stated to rename the days and months, without success.
The code is:
\documentclass[landscape,a4paper,spanish,10pt]{article}
\usepackage[latin1]{inputenc}
\usepackage[spanish]{babel}
\usepackage[T1]{fontenc}
\usepackage{tikz}
\usepackage[spanish]{translator}

\deftranslation[to=spanish]{January}{Enero}
\deftranslation[to=spanish]{February}{Febrero}
\deftranslation[to=spanish]{March}{Marzo}
\deftranslation[to=spanish]{April}{Abril}
\deftranslation[to=spanish]{May}{Mayo}
\deftranslation[to=spanish]{June}{Junio}
\deftranslation[to=spanish]{July}{Julio}
\deftranslation[to=spanish]{August}{Agosto}
\deftranslation[to=spanish]{September}{Septiembre}
\deftranslation[to=spanish]{October}{Octubre}
\deftranslation[to=spanish]{November}{Noviembre}
\deftranslation[to=spanish]{December}{Diciembre}
\deftranslation[to=spanish]{Mon}{Lun}
\deftranslation[to=spanish]{Tue}{Mar}
\deftranslation[to=spanish]{Wed}{Mié}
\deftranslation[to=spanish]{Thu}{Jue}
\deftranslation[to=spanish]{Fri}{Vie}
\deftranslation[to=spanish]{Sat}{Sab}
\deftranslation[to=spanish]{Sun}{Dom}
\usepackage{fancyhdr}
\usepackage{fix-cm}
\usepackage[landscape, headheight = 2cm, margin=.5cm,top = 3.2cm, nofoot]{geometry}
\usetikzlibrary{calc}
\usetikzlibrary{calendar}
\renewcommand*\familydefault{\sfdefault}
\def\year{2015}
\def\termin#1#2{
\node [anchor=north west, text width= 3.4cm] at
($(cal-#1.north west)+(3em, 0em)$) {\tiny{#2}};
}
\renewcommand{\headrulewidth}{0.0pt}
\setlength{\headheight}{10ex}
\chead{
\fontsize{60}{70}\selectfont\textbf{\year}
\Large\textbf{Calendario}\hfill
}
\cfoot{\footnotesize\texttt{http://www.texample.net/}}

\begin{document}
\pagestyle{fancy}
\begin{center}
\begin{tikzpicture}[every day/.style={anchor = north}]
\calendar[
dates=\year-01-01 to \year-06-30,%primera hoja, desde Enero a Junio
name=cal,
day yshift = 3em,
day code=
{
\node[name=\pgfcalendarsuggestedname,every day,shape=rectangle,
minimum height= .53cm, text width = 4.4cm, draw = gray]{\tikzdaytext};
\draw (-1.8cm, -.1ex) node[anchor = west]{\footnotesize%
  \pgfcalendarweekdayshortname{\pgfcalendarcurrentweekday}};
},
execute before day scope=
{
\ifdate{day of month=1}
{
  \pgftransformxshift{4.8cm}
  % Print month name
  \draw (0,0)node [shape=rectangle, minimum height= .53cm,
    text width = 4.4cm, fill = red, text= white, draw = red, text centered]
    {\textbf{\pgfcalendarmonthname{\pgfcalendarcurrentmonth}}};
}{}
\ifdate{workday}
{
  \tikzset{every day/.style={fill=white}}
  \ifdate{between=2014-12-24 and 2015-03-06}{%
    \tikzset{every day/.style={fill=gray!30}}}{}
}{}
\ifdate{Saturday}{\tikzset{every day/.style={fill=red!10}}}{}
\ifdate{Sunday}{\tikzset{every day/.style={fill=red!20}}}{}
\ifdate{equals=01-01}{\tikzset{every day/.style={fill=red!20}}}{}
\ifdate{equals=05-01}{\tikzset{every day/.style={fill=red!20}}}{}
\ifdate{equals=05-21}{\tikzset{every day/.style={fill=red!20}}}{}
\ifdate{equals=2015-04-03}{\tikzset{every day/.style={fill=red!20}}}{}
\ifdate{equals=2015-04-04}{\tikzset{every day/.style={fill=red!20}}}{}
\ifdate{equals=2015-06-29}{\tikzset{every day/.style={fill=red!20}}}{}
},
 execute at begin day scope=
 {
\pgftransformyshift{-.53*\pgfcalendarcurrentday cm}
 }
];
\termin{\year-01-01}{Año Nuevo}
\termin{2015-04-03}{Viernes Santo}
\termin{2015-04-04}{Sábado Santo}
\termin{2015-04-05}{Domingo de Resurrección}
\termin{\year-05-01}{Día del Trabajo}
\termin{\year-05-21}{Combate Naval de Iquique}
\termin{2015-06-29}{San Pedro y San Pablo}
\end{tikzpicture}
\pagebreak
\begin{tikzpicture}[every day/.style={anchor = north}]
\calendar[
dates=\year-07-01 to \year-12-31,
name=cal,
day yshift = 3em,
day code=
{
\node[name=\pgfcalendarsuggestedname,every day,shape=rectangle,
  minimum height= .53cm, text width = 4.4cm, draw = gray]{\tikzdaytext};
\draw (-1.8cm, -.1ex) node[anchor = west]
{
  \footnotesize\pgfcalendarweekdayshortname{\pgfcalendarcurrentweekday}
};
},
execute before day scope=
{
\ifdate{day of month=1} {
\pgftransformxshift{4.8cm}
\draw (0,0)node [shape=rectangle, minimum height= .53cm,
  text width = 4.4cm, fill = red, text= white, draw = red, text centered]
{
  \textbf{\pgfcalendarmonthname{\pgfcalendarcurrentmonth}}
 };
}{}
\ifdate{workday}
{
\tikzset{every day/.style={fill=white}}
\ifdate{between=2015-07-13 and 2015-07-26}{%
  \tikzset{every day/.style={fill=gray!30}}}{}
}{}
\ifdate{Saturday}{\tikzset{every day/.style={fill=red!10}}}{}
\ifdate{Sunday}{\tikzset{every day/.style={fill=red!20}}}{}
\ifdate{equals=09-18}{\tikzset{every day/.style={fill=red!20}}}{}
\ifdate{equals=09-19}{\tikzset{every day/.style={fill=red!20}}}{}
\ifdate{equals=10-12}{\tikzset{every day/.style={fill=red!20}}}{}
\ifdate{equals=09-18}{\tikzset{every day/.style={fill=red!20}}}{}
\ifdate{equals=09-19}{\tikzset{every day/.style={fill=red!20}}}{}
\ifdate{equals=10-12}{\tikzset{every day/.style={fill=red!20}}}{}
\ifdate{equals=07-16}{\tikzset{every day/.style={fill=red!20}}}{}
\ifdate{equals=08-15}{\tikzset{every day/.style={fill=red!20}}}{}
\ifdate{equals=10-31}{\tikzset{every day/.style={fill=red!20}}}{}
\ifdate{equals=11-01}{\tikzset{every day/.style={fill=red!20}}}{}
\ifdate{equals=12-08}{\tikzset{every day/.style={fill=red!20}}}{}
\ifdate{equals=12-25}{\tikzset{every day/.style={fill=red!20}}}{}
},
execute at begin day scope=
{
\pgftransformyshift{-.53*\pgfcalendarcurrentday cm}
}
];
\termin{\year-07-16}{Nuestra Señora del Carmen}
\termin{\year-08-15}{Asunción de la Virgen}
\termin{\year-09-18}{Fiestas Patrias}
\termin{\year-09-19}{Día del Ejército}
\termin{2015-10-12}{Encuentro de dos Mundos}
\termin{\year-10-31}{Día de las Iglesias Evangélicas}
\termin{\year-11-01}{Día de Todos los Santos}
\termin{\year-12-08}{Inmaculada Concepción}
\termin{\year-12-25}{Navidad del Señor}
\end{tikzpicture}
\end{center}

\end{document}

and when compiling, you get:


text:
Q: Get selected value from externally created dropdownlist I'm creating a dynamic menu that fetches dishes from a database and displays them to the user so he can add them to his order. Whenever I retrieve a row from the database I send it to my menuItems class so the columns can be read and the display format is created and inserted into a cell:
 foreach (DataRow dr in drc){
            //extract the dish data from the row into a cell
            TableCell c1 = menuItem.makeItemCell(dr);
            //display it
            tr.Controls.Add(c1);
            table1.Controls.Add(tr);
}

c1 will be a cell that has the dish information along with a quantity dropdownlist and an "add to order" button:
      public static TableCell makeItemCell(DataRow dr)
    {
        TableCell tc = new TableCell();
        Image img = new Image();

        img.ImageUrl = (string)dr["img"];
        tc.Controls.Add(img);

        //rest of information adding is omitted for brevity
        String myLiteral = "<p>" + "Name: " + (string)dr["NameofDish"] + "</br>";
        tc.Controls.Add(new LiteralControl(myLiteral));

        //add quantity label and dropdownlist populated with possible quantity values
        Label lb = new Label();
        lb.Text = "Quantity: ";
        DropDownList ddl = new DropDownList();
        for (int i = 0; i < 13; i++)
        {
            String t = i.ToString();
            ddl.Items.Add(new ListItem(t, t));
        }

        //create the add to order button
        Button btn = new Button();
        btn.Text = "Add to order";

        tc.Controls.Add(lb);
        tc.Controls.Add(ddl);
        tc.Controls.Add(btn);

        return tc;
    }

My problem is with handling the button click event. All my tries to bind it with an event handler (on the menuItems class or the codebehind itself) have failed. I could only manage to update the postbackURL of the button when it's created in the cell like this
btn.PostBackUrl = "./menu.aspx?dish=" + (string)dr["ID"] + "&quantity=" + ddl.SelectedValue;

But the .selectedvalue value is rendered when the cell is created hence is always 0
My question is this: how can I handle the button click event in a way that I can get hold of the dishID and the selected value.
((((I would prefer an event handling solution rather than querystrings if possible))))
Thank you!
EDIT:
My whole problem is that the cell and its components are created in the external class and sent back to my code. How do I access the dropdownlist variable from my codebehind if I don't have the element id or anything


text:
Q: GNU gcc compiler cannot handle partial include statements Imagine that I have a C-project in the following folder:
C:\microcontroller\stm32\myProject
I have two important folders inside myProject:
 - source => here are all my .c and .h files
 - build  => gcc will write all the object files in here
Note: as you can see, the backward slashes indicate that this is happening on a Windows pc.
The figure below gives an overview:

I will not display my complete makefile here, because that would lead us too far. The rules inside the makefile for all .c => .o files are similar.  Let us just focus on the compilation of one specific file: fileA2.c:
--------------------- COMPILATION OF FILE fileA2.c -------------------

Building ./build/folderA/fileA2.o

arm-none-eabi-gcc C:\\microcontroller\\stm32\\myProject\\source\\folderA\\fileA2.c
               -o C:\\microcontroller\\stm32\\myProject\\build\\folderA\\fileA2.o
               -c
               -MMD
               -mcpu=cortex-m7
               -...
               -IC:/microcontroller/stm32/myProject/source/folderA
               -IC:/microcontroller/stm32/myProject/source/folderB

Notice that the gcc call ends with two include flags: one for folderA and one for folderB. This enables gcc to use any of the header files from these folders (fileA1.h, fileA2.h or fileB1.h) if fileA2.c has an import statement.
Let us now consider the source code in fileA2.c. We assume that this file needs to include fileA2.h and also fileB1.h.
/*******************************/
/* SOURCE CODE fileA2.c        */
/*******************************/

// Some include statements
#include "fileA2.h"
#include "fileB1.h"

// Code
...

These include statements work perfectly. The gcc compiler retrieves the files fileA2.h and fileB1.h in the given folders. But I noticed that the following does not work:
/*******************************/
/* SOURCE CODE fileA2.c        */
/*******************************/

// Some include statements
#include "fileA2.h"
#include "folderB/fileB1.h"

// Code
...

The last include statement is a 'partial path' to the file. I get the error when compiling:
fatal error: folderB/fileB1.h: No such file or directory
How can I get gcc to handle this?
PS: It is not my own habit to use 'partial paths'. But they appear a lot in the libraries from the silicon vendor of my chip, so I have to live with it.

A: You specify two paths to look for includes other than the current directory for the source file:
           -IC:/microcontroller/stm32/myProject/source/folderA
           -IC:/microcontroller/stm32/myProject/source/folderB

You get the error because neither
C:/microcontroller/stm32/myProject/source/folderA/folderB/fileB1.h nor
C:/microcontroller/stm32/myProject/source/folderB/folderB/fileB1.h exists.
To address the error, you can add the following path:
           -IC:/microcontroller/stm32/myProject/source

A: When using double-quotes to include a header file the compiler first looks in the same directory as the current file. If the header file is not found then it continues with the standard include search paths.
So when the compiler compiles the file source/folderA/fileA2.c the first directory the compiler will look for include files is the source/folderA directory. In the first example the fileB1.h will not be found there, but since you added source/folderB to the standard search path it will be found there as source/folderB/fileB2.h.
In the second example there is no folderB/fileB1.h file on source/folderA so the compiler will search the standard search path. When it comes to source/folderB it will again try folderB/fileB2.h (i.e. source/folderB/folderB/fileB2.h) and it will still not be found, nor will it be found anywhere else.
You need to add -IC:/microcontroller/stm32/myProject/source to be able to find folderB/fileB1.h.

A: Apart of the two correct responses you have received before this, you have the third chance to specify the path to the file in the #include directive from the curren directory, as with
`#include "../folderB/fileB1.h"


text:
Q: How to compare two string arrays and store the matching values in another string array? string[] a = { 2; a; 3; b; 4; c}
string[] b = { 2; a; 6; c}

I want to compare this two arrays and remove the all digit(2,3,4,6)values and store match string values in another array.
I want the result like this:
string[] c = {a; c;}

I was tried this but it was adding all the values.
string[] result = a.Union(b).ToArray();

A: Use Intersect and Where:
string[] result = a.Intersect(b).Where(c => !char.IsDigit(c[0])).ToArray();

Based on your comment to remove or replace the colon (;):
string[] result = a.Intersect(b).Where(c => !char.IsDigit(c[0]))
                                .Select(c => c.Replace(';',' ')).ToArray();

A: you need Intersect not Union
string[] result  = a.Intersect(b).ToArray();

A: The easiest solution would be to use Linq to do the job
int tmp;
var c = a.Where(x => b.Contains(x) && !int.TryParse(x, out tmp)).ToArray();


text:
Q: Use of convolutions to compute the distribution of the sample mean? Let's consider N i.i.d continuous random variables from some arbitrary distribution. Why do we have to approximate the distribution of the sample mean using the CLT? Why can't we explicitly compute its distribution using convolutions and then study its properties?

A: Because convolutions of a large number of functions are often not so easy to manipulate. For example, if $(X_n)$ is i.i.d. uniform on $(0,1)$, then the density of $S_n=X_1+X_2+\cdots+X_n$ has $n$ different (polynomial) expressions on the intervals $(k-1,k)$ for $1\leqslant k\leqslant n$ and it is impossible to use them to prove any sensible asymptotics about $S_n$.


text:
Q: Why does Windows not show my full 4GB of RAM after upgrade
Possible Duplicate:
Why does Windows only show about 3.5 GB of my more than 4 GB of RAM?

I decided to add 2 GB to my laptop.
Before i have 2 GB.
So, after adding i suppose to have whole 4 GB.
But i have avaible only 3,2 GB. Resource monitor in Win7 (32bit) said, that 700+ MB are reserved by BIOS and periphery hardware.
So, what is it and how to free some memory if it can be free without bad circumstates?
Thanks for explanation!

A: http://answers.microsoft.com/en-us/windows/forum/windows_7-hardware/not-showing-all-ram-in-win7-he-32-bit/5ab5c647-8a50-40d0-9fc6-f9db813a66a4
32-Bit releases do not have the ability to utilize more than the 3.75GB of RAM.  This is due in part to other hardware components (such as the video card) utilizing some of the RAM, as well as a limitation within the architecture itself.  Nothing can be done to increase the amount of usable RAM short of installing a 64-bit version of the OS.


text:
Q: Systemctl shows the service as disabled but I can see it running I am running kali linux.
When I do sudo systemctl start ssh and try to verify with sudo ss -tlp I get the following:
kali@kali:~$ sudo ss -antlp
State                   Recv-Q                  Send-Q                                   Local Address:Port                                   Peer Address:Port                 Process
LISTEN                  0                       128                                            0.0.0.0:22                                          0.0.0.0:*                     users:(("sshd",pid=12926,fd=3))
LISTEN                  0                       128                                               [::]:22                                             [::]:*                     users:(("sshd",pid=12926,fd=4))

So the service is running, however if I run sudo systemctl list-unit-files  | grep ssh I get the following:
kali@kali:~$ sudo systemctl list-unit-files  | grep ssh
ssh.service                                                      disabled
ssh@.service                                                     static
ssh.socket                                                       disabled
rescue-ssh.target                                                static
ssh.socket                                                       disabled

So it is not running, what am I missing here:

*

*Is ssh and ssh.service not the same thing ?

*When I run sudo systemctl start ssh am I running a service or something else ?

A: I misunderstood the output of systemctl list-unit-files.
My service is running as per ss -tlp output, but it is not enabled by default at run time, as shown by systemctl list-unit-files.
Running sudo systemctl enable ssh marks the service as enabled at start up and the output of systemcetl list-unit-files shows that.


text:
Q: How do you control how the Couchbase Java client serializes Dates? Here's my code (Couchbase Java SDK 3)
Cluster cluster = Cluster.connect("localhost", "Administrator", "password");
Collection c = cluster.bucket("default").defaultCollection();
c.upsert("myDocumentId", new Date());

When I look at the resulting document in Couchbase, I see the java.util.Date has been converted to epoch milliseconds:
1602791214674

What I want instead is for the date to be formatted like yyyy-mm-dd.
How can I make that happen?

A: By default, the Couchbase Java client uses Jackson to serialize and deserialize JSON. Unless you tell it otherwise, it will use an ObjectMapper with default settings. By default, Jackson serializes java.util.Date objects by converting them to milliseconds since the epoch.
You have a couple of choices. If you're using a POJO to represent your document content, you can apply Jackson annotations to the date fields to control how they are [de]serialized. Here's an article that shows how to use the @JsonFormat annotation to control how a date field is serialized.
Alternatively, you can configure an ObjectMapper to change the default way dates are serialized. Here's how you tell the Couchbase Java SDK to use your custom ObjectMapper:
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

ClusterEnvironment env = ClusterEnvironment.builder()
    .jsonSerializer(JacksonJsonSerializer.create(objectMapper))
    .build();

Cluster cluster = Cluster.connect("localhost",
    ClusterOptions.clusterOptions("Administrator", "password")
        .environment(env));

Collection c = cluster.bucket("default").defaultCollection();
c.upsert("myDocumentId", new Date());

cluster.disconnect();

// since we created a custom environment, we're responsible for shutting it down
env.shutdown();

This will give you a document that looks like:
"2020-10-15T19:59:45.685+0000"

If you want a different format, you can configure Jackson to serialize dates however you want.


text:
Q: Why my "name" and "prodi" could not show up in queue I'm fairly new to learning C and my English isn't that good either but I need help in my code.
struct mahasiswa{
    char name;
    char prodi;
    int nim;
}Mhs[maxsize];

void inQueue(){
    if(!isFull()){
        char name, prodi;
        int nim,i;
        printf("Input name mahasiswa: ");
        scanf("%s",&name);
        printf("Input NIM mahasiswa: ");
        scanf("%d",&nim);
        printf("Input Prodi mahasiswa: ");
        scanf("%s",&prodi);
        Mhs[Queue.akhir].name = name;
        Mhs[Queue.akhir].nim = nim;
        Mhs[Queue.akhir].prodi = prodi;
        ++Queue.akhir;
        ++size;
        menu();
    }else {
        printf("Data penuh");
        menu();
    }
}

void tampil(){
    if(!isEmpty()){
        int i;
        for(i=0;i<Queue.akhir;i++){
        printf("\nNIM   : %d\n",Mhs[i].nim);
        printf("\nProdi : %s\n",Mhs[i].prodi);
        printf("\nName  : %s\n",Mhs[i].name);
        }
    }else {
        printf("\nemptydata k");
    }
    menu();
}

My int data could show up, but not with the string.

A: You need to actually store strings in your structs:
#define MAX_LEN 20
struct mahasiswa {
    char name[MAX_LEN];
    char prodi[MAX_LEN];
    int nim;
} Mhs[maxsize];

Then you can read input as follows:
        char name[MAX_LEN];
        scanf("%s", name);

The & needs to be removed as the array decays to a pointer already.
To avoid problems due to buffer overflow, you should also add a length limit:
        scanf("%19s", name);

That only reads and stores up to 19 characters + 0 byte which is maximum length for an array of size 20.
Then, you cannot assign a string just with an assignment as you do with integers.
You need to use a function (don't forget to #include <string.h>):
        strcpy(Mhs[Queue.akhir].name, name);

As an alternative, you could drop the local array name at all and directly read into the structure:
        scanf("%19s", Mhs[Queue.akhir].name);

Same needs to be done for other strings.


text:
Q: vector cannot be initialized by {} Hi I am a newbie in C++ and I just cannot initialize a vector using {}, even if the code is copied with a book. For example, when I do these
vector <string> articles {"a", "an", "the"};

And
vector <string> articles = {"a", "an", "the"};

I got these  error message respectively:
Error: expected a ";"

And
Error: initialization with "{...}" is not allowed for object of type "std::vector<std::string, std::allocator<std::string>>"

Would anyone help me out? I believe it should be a simple mistake that I couldn't find out.

A: uniform initialization is introduced since C++11, You should use a recent compiler that supports this new feature.
If your compiler does not support this feature, you may try the following:
string arrOfString[3] =  {"a", "an", "the"};
vector<string> articles(arrOfString, arrOfString +3);

EDIT:
with MSVC11, you can do (by courtesy of @chris):
string arrOfString[3] =  {"a", "an", "the"};
vector<string> articles(std::begin(arrOfString), std::end(arrOfString));


text:
Q: relativeLayout.setBackground(ContextCompat.getDrawable(context, R.drawable.sample_drawable)); is crashing the app on API 19 I have a simple layout file for which I want to use a drawable in the background of main container
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/mlv_balance_detail_container"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    **android:background="@drawable/sample_drawable"** //this was causing crash in 4.4.2 API 19
    android:padding="@dimen/dimen_16dp">

    <TextView
        android:id="@+id/tv_policy_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="sans-serif"
        android:letterSpacing="0.04"
        tools:text="text"
        android:textColor="#1d252d"
        android:textSize="14sp"
        android:textStyle="normal" />

    <TextView
        android:id="@+id/tv_total_balance"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tv_policy_text"
        android:layout_marginTop="8dp"
        android:fontFamily="sans-serif"
        android:letterSpacing="0.04"
        tools:text="some text"
        android:textColor="#1d252d"
        android:textSize="12sp"
        android:textStyle="normal" />

</RelativeLayout>

Then I tried setting the background from code using
container.setBackground(ContextCompat.getDrawable(context, R.drawable.sample_drawable));

It is still crashing, can anyone help me out here?
Thanks,

A: I found a working solution for this problem, although I would still look for a better answer but for the time being, I am using an ImageView inside a FrameLayout and setting app:srcCompat property of Imageview which is backward compatible.
<?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="fitXY"
                android:src="@drawable/sample_drawable" />

        </FrameLayout>

    //rest of my layout as it is

    </RelativeLayout>


text:
Q: Laravel 5.3 auth methods implementation / overwriting Which classes, and which methods are responsible in Laravel 5.3 for default user login / logout / register and password reset functions? And where can i find it? I want to modificate such things like default redirectPath, flash messages after success e.t.c

A: I believe these are the correct controllers and methods you are looking for. Keep in mind that most or all of the methods are not found directly in the respective controllers, but inside traits that these controllers use. But they are easy to locate either by opening up the controller and stepping into the trait that it uses, or by just searching for the name of the method in PHPStorm or any other IDE or editor.

App\Http\Controllers\Auth\LoginController@showLoginForm
App\Http\Controllers\Auth\LoginController@login
App\Http\Controllers\Auth\LoginController@logout
App\Http\Controllers\Auth\ForgotPasswordController@sendResetLinkEmail
App\Http\Controllers\Auth\ForgotPasswordController@showLinkRequestForm
App\Http\Controllers\Auth\RegisterController@showRegistrationForm
App\Http\Controllers\Auth\RegisterController@register

Example
Let's say you want to locate the showLoginForm() method.

*

*Open up {root}/app/Http/Controllers/Auth/LoginController.php

*Notice that it uses Illuminate\Foundation\Auth\AuthenticatesUsers

*Open up Illuminate\Foundation\Auth\AuthenticatesUsers

*The first method you see should be showLoginForm()
 /**
 * Show the application's login form.
 *
 * @return \Illuminate\Http\Response
 */
public function showLoginForm()
{
    return view('auth.login');
}

A: In Laravel 5.3 there are few controllers in app\Http\Controllers\Auth:
LoginController
RegisterController
ResetPasswordController
ChangePasswordController
ForgotPasswordController

You can safely override default auth methods in these controllers. What exactly method you want to override depends on your needs. For example, if you need to redirect users depending on their role, you need to override sendLoginResponse() method by creating and modifying it in LoginController.


text:
Q: Can natural number be an ordered pair? I'm supposed to prove that natural number $n$ cannot be an ordered pair. The definition for ordered pair is $(x,y) = \{\{x\},\{x,y\}\}$ and for the definition of natural numbers we use the definitions of set theory.
I don't know if this should be done with induction or what. Any clues are helpful. Thanks!

A: Note that an ordered pair has between $1$ and $2$ elements. This limits the number of cases to exactly $1$ and $2$.
Or, you can note that $\varnothing$ is never an element of an ordered pair, and an ordered pair is never empty.

Note that if you are using Zermelo's natural numbers, then $2=\{1\}=\{\{0\}\}=\{\{\varnothing\}\}=\langle\varnothing,\varnothing\rangle$. But the above assumes that you're working with the standard von Neumann definition where $n=\{0,\dots,n-1\}$.


text:
Q: Automated aab upload form GitHub to Google Playstore failing with cryptic message (Invalid value track_config) I am trying to automatically upload the aab file of my app to Google Play Store internal (test channel) from GitHub. The process is automated and worked a week ago. Now the GitHub upload step fails with message
Adding 1 artifacts to release on 'internal' track
Error: Invalid value at 'track_config.releases[0].status' (type.googleapis.com/google.play.publishingapi.v3.Release.Status), ""

Googling for this message, I found the hint the app ID could differ but they are same in play store and in aab.
Version code in aab is properly incremented (66 in store, 69 in aab).
Does anybody have an idea what else could be wrong here or how to get more details about the error?
EDIT: The GitHub step I am running is as follows
  - name: Upload Deployable to Play Store
    uses: r0adkll/upload-google-play@v1
    with:
      track: internal
      serviceAccountJsonPlainText: ${{ secrets.ANDROID_PLAYSTORE_ACCOUNT_KEY }}
      packageName: de.ilapark.charge.pp
      releaseFiles: build/app/outputs/bundle/release/*.aab
      whatsNewDirectory: dist/whatsnew

A: explicitly setting status to draft solved this issue for me.
the README for upload-google-play lists a couple of values that might be better suited for your use case then draft

A: Track names in request path and request body must match.
Just add to the Track object (the "body") the string value of TrackValue and it will work : TrackValue = track,
    var updatedTrack = this.Service.Edits.Tracks.Update(
    new Track()
    {
        TrackValue = track,
        Releases = new List<TrackRelease>
        {
            new TrackRelease
            {
    Name = versionName,
    VersionCodes = apkVersionCodes,
    Status = "completed",
    ReleaseNotes = new List<LocalizedText>() { note }
            }
        }
    },
    packageName,
    edit.Id,
    track);

A: Just add
track: internal
status: draft


text:
Q: MPI_Send/MPI_Recv: count of elements or buffer size? I noticed a strange thing with MPI_Send and MPI_Recv buffer size which I can't understand. The documentation says that the count argument of these functions describes a number of elements of datatype type:
int MPI_Send(void *buf, int count, MPI_Datatype datatype, int dest,
             int tag, MPI_Comm comm);

count [in] number of elements in send buffer (nonnegative integer)

int MPI_Recv(void *buf, int count, MPI_Datatype datatype, int source,
             int tag, MPI_Comm comm,  MPI_Status *status);

count [in] maximum number of elements in receive buffer (integer)

Suppose we have 2 processes, the first (root) process allocates an array of n integers and fills it with some data
int* temp = (int*) malloc(n * sizeof(int));
for (int i = 0; i < n; i++) temp[i] = ...;

then sends it to the second process with rank = 1.
MPI_Send(temp, n, MPI_INT, 1, 0, MPI_COMM_WORLD);

The second process receives this array of n integers.
MPI_Recv(temp, n, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_INGNORE);

But after MPI_Recv the temp array appeared truncated. When I changed count argument from n to n * sizeof(int), I received a correct array. But n * sizeof(int) describes buffer size in bytes, not in elements as documentation says. Is it a common behavior or a simple misunderstanding? P.S. I use MPICH2 x86 as MPI implementation and 32-bit VS08 on Windows 7.

A: According to
https://www.open-mpi.org/doc/v1.8/man3/MPI_Recv.3.php ,
count argument holds the number of elements in the buffer.

count
  Maximum number of elements to receive (integer).

Number of bytes must be calculated by multiplying number of elements (count) and size of each element (given by the constant of type MPI_Datatype).


text:
Q: How to get a hash from variadic arguments in C++? I want to create a random number generation util for C++ and I want to create a method SetSeed that would generate and set a seed from input variadic arguments.
I have such methods:
void SetSeedDirectly(int seed);

template<typename... Args>
void SetSeed(Args... args);

And the SetSeed method must generate a seed from args and call the SetSeedDirectly method. But I don't know how to generate a seed. I guess that I should use std::hash to generate a hash(seed) from args.
I know how to get a hash from one value, but not from multiple values.
I've tried to use tuple:
template <typename... Args>
void SetSeed(Args... args) {
  std::tuple<Args...> t(args...);
  std::hash<std::tuple<Args...>> h;
  size_t seed = h(t);
  this->SetSeedDirectly(static_cast<uint32_t>(seed));
}

But for some reason it doesn't work and compiler outputs errors like this:
'std::hash<std::tuple<int,std::string>>::hash(void)': function was implicitly deleted because a base class invokes a deleted or inaccessible function 'std::_Conditionally_enabled_hash<_Kty,false>::_Conditionally_enabled_hash(void)'

Hope for your help!
Thanks in advance!


text:
Q: inherited function inaccessable in C++ I am writing a small program in Visual C++ 2010.
This is code of the base class:
class BaseInfo {

private:
    std::map <std::string, std::string> info;
    std::vector<std::string> extra_info_key;
public:
    uint get_id ();
    //Other function is hidden
};

uint BaseInfo::get_id () {
    return (uint)atoi ((info["ID"]).c_str());
}

Then I make a derived class, which is announced as:
class test:BaseInfo {
public:
    void f();
};

void test::f (test& inf) {
    cout<<inf.get_id()<<endl;
}

But I got an error:

function "BaseInfo::get_id is inaccessible.

I am confused, it seems all is in the c++ rules.

A: You're using private inheritance, that's why.
Change:
class test : BaseInfo

to:
class test : public BaseInfo

For more info about public, protected and private inheritance, look here


text:
Q: Cancel a promise from the 'then' I just switched to promises and I'm sure I got something wrong but I can't figure out what.
In the following code, I'd like to cancel the promise if _getDevice() returns null (it's a mongodb.findOneAsync() under the hood).
From my perspective if _getDevice returns null, the promise should be cancelled and I should see the 'CANCEL REPLY' log. But instead I'm getting the 'SAVE REPLY' log.
I'm using the bluebird library.
var promise = Promise.props({
    device: _getDevice(event.deviceId),
    events: _getEvents(event.deviceId, event.date)
}).cancellable();

promise.then(function (result) {
    if (! result.device) {
        return promise.cancel()
    }

    var device = new Device(result.device);
    var events = result.events;

    // ...

    return db.collection(collections.devices).saveAsync(device.toMongoDocument());
}).then(function () {
    console.log('SAVE REPLY');
    return req.reply(null);
}).catch(Promise.CancellationError, function (err) {
    console.log('CANCEL REPLY')
    return req.reply(null);
}).catch(function (error) {
    return req.reply(error);
});

A: You cannot cancel a promise from the then callback, as the execution of that callback means that the promise has been resolved. It's impossible to change the state afterwards.
What you probably want to do is throw an error from the handler, resulting in the rejection of the new promise that was returned from then().
You even might do that before the two promises are joined, so that the getEvents promise is cancelled when the getDevice promise fails:
Promise.props({
    device: _getDevice(event.deviceId).then(function(device) {
        if (!device)
            throw new Promise.CancellationError(); // probably there's a better error type
        else
            return new Device(device);
    },
    events: _getEvents(event.deviceId, event.date) // assuming it is cancellable
}).then(function (result) {
    var device = result.device;
    var events = result.events;

    // ...

    return db.collection(collections.devices).saveAsync(device.toMongoDocument());
}).then(function () {
    console.log('SAVE REPLY');
    return req.reply(null);
}).catch(Promise.CancellationError, function (err) {
    console.log('CANCEL REPLY')
    return req.reply(null);
}).catch(function (error) {
    return req.reply(error);
});

A: I don't think the accepted answer is entirely correct; see Cancelling Long Promise Chains -- it is possible to cancel a promise from within then(). However I am not sure what exactly the issue is with the original question (the behavior wasn't really described).
Try putting .cancellable() at the end of the second promise as well.


text:
Q: HTML5 video source changing I have a video tag like this. All this videos have to play dynamically one after other
I tried writing some javascript functions in eventlistner "progress" of the video, but not working.How to play these videos automatically?anybody please suggest any codes in javascript or jquery
<div id="divVid">
            <video id="video1" width="320" height="240" autoplay >
               <source src="vid_future technology_n.mp4#t=20,50" >
               Your browser does not support the video tag.
            </video>
    </div>

JS Code (Updated from comment section)
document.getElementById("video1")
.addEventListener("progress",
  function () {
   var i = 0;
   var vid = document.getElementById("video1");
    if (vid.paused) {
     if (vid.currentSrc == myvids[i]) {
       vid.currentSrc = myvids[i + 1]; } i = i + 1;
    }
});

A: The set of <source> elements provide alternative formats for the video for different devices, not a playlist.
If you want to have a playlist, then listen for an ended event and change the src with JavaScript.

In response to edits to the question:

*

*No, really change the src. You are trying to change the currentSource which is defined as being readonly

*I said ended. Don't touch progress, you what to play the next video when the last one is finished, not when a tiny chunk of it has played

*The list of <source> elements still isn't a playlist. Don't try to use them as such. Keep the list of videos somewhere else (e.g. a JS array).


text:
Q: How to fix function returns address of local variable error in C? I have this method which reads a file but when I try to run it, it gives me an error for the return (char *) buffer.
Error: warning: function returns address of local variable [-Wreturn-local-addr]
char * readFile(char* filename, size_t chunk) {
    FILE *proc;
    size_t len = chunk;
    char * buffer[len];
    proc = fopen(filename, "r");
    if(proc) {
        if(buffer)
            fread(buffer, 1, len, proc);
        fclose(proc);
        return (char *) buffer;
    }return "error";
}

Should I be creating the buffer before the method outside the main for this method?
PS: I am aware this might be a duplicate question.

A: To begin with, judging from return "error", you want buffer to be an array of characters, not an array of pointers to characters. Fix this first.
As for the local variable issue, simply modify the function into this:
void readFile (const char* filename, size_t chunk, char buffer[chunk])

This forces the caller to deal with the allocation and your function only needs to focus on its designated task.


text:
Q: Cloud masking Rapid Eye images I am trying to delete clouds (ideally also their shadows) from Rapid Eye images (5 bands; blue, green, red, red edge, near-infrared).
I have tried to set a threshold for the red band and mask accordingly, inspired by this question but it doesn't pick up the clouds, but only other areas (such as parts of a lake and vegetation and also a few of the clouds shadows). I have also tried to modify the algorithm: ee.Algorithms.Landsat.simpleCloudScore() without success (don't know if it would even be possible to modify landsat algorithms and apply to other images).
Is there any other convenient way to mask the clouds?


text:
Q: Fill being ignored with group + facet_wrap in ggplot2 / geom_bar I suspect I might be using group incorrectly here, but I can't seem to understand why the fill color is getting ignored in the example below.
df <- data.frame(a = factor(c(1,1,2,2,1,2,1,2)),
                 b = factor(c(1,2,3,4,5,6,7,2)),
                 c = factor(c(1,2,1,2,1,2,1,2)))
p <- ggplot(df, aes(x=b)) +
  geom_bar(aes(y =  ..density.., group = c, fill=a), binwidth = 1) +
  facet_wrap(~ c) +
  scale_y_continuous(labels = percent_format()) +
  scale_color_hue()
p

Any help would be greatly appreciated.
Thanks in advance,
--JT

A: I think I understand what plot you're after now. I'd do something like this:
df <- data.frame(a = c(1,1,2,2,1,2,1,2),
             b = c(1,2,3,4,5,6,7,2),
             c = c(1,2,1,2,1,2,1,2))

df <- within(df, { f <- 1 / ave(b, list(c), FUN=length)})
df[, 1:3] <- lapply(df[, 1:3], as.factor)

ggplot(df, aes(x = b)) + geom_bar(stat = "identity", position = "stack",
           aes(y = f, group = c, fill = a), binwidth = 1) + facet_wrap(~ c) +
           scale_y_continuous(labels = percent_format())

This gives the plot:


text:
Q: Regex exclude word from matches Does anyone know what am I doing wrong?
I have this sentence:
hi [user=1234]John Jack[/user] take me home

and I need regex which select only John Jack
My regex:
(\[user=\d\d\d\d](.+?)\[\/user\])(?!(\[user=\d\d\d\d\])|(\[\/user\]))

I want exclude [user=1234] and [/user]
This (\[user=\d\d\d\d](.+?)\[\/user\]) selects [user=1234]John Jack[/user] but I want only John Jack
Full example:

hi [user=1234]John Jack[/user] take me home. [user=12] Jonno Ha
  [\user] where you are [differentTag] hm?  [/differentTag]. Peter Im
  here with [user=1]Danny Di [\user]

A: Alternative to the answer from @matoni with "lookahead" and "lookbehind" syntax, you can use grouping (which are already defined in your pattern) and extract an appropriate group:
    String s = "hi [user=1234]John Jack[/user] take me home ...";
    Pattern p = Pattern.compile("\\[user=\\d+\\](.+)\\[/user\\]");
    Matcher m = p.matcher(s);
    while (m.find()) {
        System.out.println(m.group(1));
    }

A: (.+?) is group indexed as 2 and it should hold John Jack so you should be able to obtain it via matcher.group(2).
Demo:
String text = "hi [user=1234]John Jack[/user] take me home. [user=12] Jonno Ha [\\user] where you are [differentTag] hm? [/differentTag]. Peter Im here with [user=1]Danny Di [\\user]";
Pattern p = Pattern.compile("(\\[user=\\d\\d\\d\\d](.+?)\\[\\/user\\])(?!(\\[user=\\d\\d\\d\\d\\])|(\\[\\/user\\]))");
Matcher m = p.matcher(text);
if(m.find()){
    System.out.println(m.group(2));
}

Output: John Jack

If you wanted to find more users you need to change if to while and fix your regex because

*

*currently you are searching for users with 4 digit IDs so it will fail to match [user=12] or [user=1]. So instead of \d\d\d\d you can use \d+.

*you are using [user=ID]..[/user] but also [user=ID]..[\user] (both / and \].

BTW since Java doesn't use /regex/flags syntax, / is not considered as special character so you don't need to escape it.
Also I am not sure why you need (?!(\\[user=\\d\\d\\d\\d\\])|(\\[\\/user\\])) at the end of your regex, it doesn't really do anything in example you showed so it looks like it can be removed. Also we don't need to surround earlier part with parenthesis because look-ahead doesn't add anything to whole match which is already placed in group 0, so we don't need separate group which will duplicate that match. After removing those those extra parenthesis (.+?) will be indexed as group 1.
Modified and simplified solution can look like:
String text = "hi [user=1234]John Jack[/user] take me home. [user=12] Jonno Ha [\\user] where you are [differentTag] hm? [/differentTag]. Peter Im here with [user=1]Danny Di [\\user]";
Pattern p = Pattern.compile("\\[user=\\d+](.+?)\\[(/|\\\\)user]");
Matcher m = p.matcher(text);
while(m.find()){
    System.out.println(m.group(1).trim());
}

Output:
John Jack
Jonno Ha
Danny Di

A: Try this:
String s = "hi [user=1234]John Jack[/user] take me home";
// assuming user id has always 4 decimals
Pattern p = Pattern.compile("(?<=\\[user=\\d{4}\\]).+(?=\\[/user\\])");
Matcher m = p.matcher(s);
m.find();
System.out.println(s.substring(m.start(), m.end()));

Note, you can not use in "lookbehind" pattern of variable length like (?<=.+). So if you know, that user id has at max e.g. 11 places, then you can use:
Pattern.compile("(?<=\\[user=\\d{4,11}\\]).+(?=\\[/user\\])");

For more details about regex see: Pattern javadoc

A: Full decoding:
public class RegExpPattern_002 {

   public static void main( String[] args ) {
      final String text =
         "hi [user=1234]John Jack[/user] take me home."
         + " [user=12] Jonno Ha [/user]"
         + " where you are [differentTag] hm? [/differentTag]."
         + " Peter Im here with [user=1]Danny Di [/user]";
      final Pattern p = Pattern.compile(
         "([^\\[]*)\\[(\\w+)(=([^\\]]+))?\\]([^\\[]*)\\[/(\\w+)\\]" );
      final Matcher m = p.matcher( text );
      while( m.find()) {
         final String preText   = m.group( 1 );
         final String attrOpen  = m.group( 2 );
         final String value     = m.group( 4 );
         final String content   = m.group( 5 );
         final String attrClose = m.group( 6 );
         assert attrClose.equals( attrOpen );
         System.err.printf(
            "pre = '%s', attr = '%s', value = '%s', content = '%s'\n",
            preText, attrOpen, value, content );
         System.err.println("-----------------------------");
      }
   }
}

Execution log:
pre = 'hi ', attr = 'user', value = '1234', content = 'John Jack'
-----------------------------
pre = ' take me home. ', attr = 'user', value = '12', content = ' Jonno Ha '
-----------------------------
pre = ' where you are ', attr = 'differentTag', value = 'null', content = ' hm? '
-----------------------------
pre = '. Peter Im here with ', attr = 'user', value = '1', content = 'Danny Di '
-----------------------------

A:
I assume you no need any java code, otherwise please comment me to delete the answer

to exclude[user=1234] and [/user] you can use:
[^\]\[a-zA-Z=\d\/]
and for matching other parts:
[a-zA-Z ]*[^\]\[a-zA-Z=\d\/][a-zA-Z]*

and for input:
hi [user=1234]John Jack[/user] take me home. [user=12] Jonno Ha [\user] where you are [differentTag] hm? [/differentTag]. Peter Im here with [user=1]Danny Di [\user]

you can use:
[a-zA-Z ]*[^\]\[a-zA-Z=\d\/\\]+[a-zA-Z ]*

It matches all things except all inside []
[a-zA-Z ]*[^\]\[a-zA-Z=\d\/\\]+[a-zA-Z ]*
It excludes:
[user=1234]
[/user]
[user=12]
[\user]
[differentTag]
[/differentTag]
[user=1]
[\user]

and if you want to match only the user name before [/user] or [\user] you cat try:
[a-zA-Z ]+(?=\[(?:\\|\/)user\])

[a-zA-Z ]+(?=\[(?:\\|\/)user\])
it matches:
John Jack
Jonno Ha
Danny Di

and more efficient than above:
(?<=])[a-zA-Z ]+(?=\[(?:\\|\/))

and still matches:
John Jack
Jonno Ha
Danny Di


text:
Q: How do I Assign a random number to a variable? Before I say anything else, I would like to mention that I am almost completely new to coding,  and only have a very rudimentary understanding of python.
Now that that's out of the way, my problem is that I am (attempting) to code a text adventure game, along the lines of D&D. I'm stuck at an early stage- namely, how to assign a random integer between 1 and 18 to a variable.
I've seen some ways of doing this, but the value of the variable changes each time it's called up. This can't happen. The reason for this is because I want the stats (Strength, Wisdom, Intelligence, Dexterity, Charisma, and Constitution) to be a randomly generated but fixed number, that can be called upon and have it the same each time.
I've tried mucking around with things like Str = random.randomint(1,18), using the random module.
The closest I've come is using the lambda function, so that when I call up the variable it generates a random number which is different each time. None of these have rally worked, and I would really like to know what I'm doing wrong.

A: I see you are very close with what you have:
Str = random.randomint(1,18) should be Str = random.randint(1,18)
This is the line which assigns the random int to the variable Str, and when you ask for Str you should get the same number each time.
If you keep calling Str = random.randint(1,18) it will change Str each time. so only do it once.
If you know or understand about classes you should use them to contain your characters/items/spells/adventures/monsters etc. which can have properties and attributes and inventories etc etc, much like in the game itself, you group all the things under different types.
Note: You mention you used lambda, that might mean that you have assigned Str to a function which returns a random variable each time, meaning each time you asked for Str you would actually be asking for the function to return a random number.

A: Welcome to coding.
I've been a web developer for a while and I've also recently started to sink my teeth into better things than php (in my opinion).  I would also use:
Str = random.randomint(1,18)

Are you using an IDE? I found they're great when you're first learning a new language due to the code completion.  It really helps you get to know your way around the language faster, due to not having to go to various websites to look up syntax.  Good luck! Text based adventure games are a great way to start learning!


text:
Q: search and replace multiple words in AS3 I've got this code in my AS3 :
var str:String = mySharedObject.data.theDate;
var search:String = "monday";
var replace:String = "";

function strReplace(str:String, search:String, replace:String):String {
 return str.split(search).join(replace);
}

Is it possible to tell the code to search for "monday or tuesday or wednsday, or thursday, or friday" and replace them with "_" ?
And, secondly, is it possible to tell the code to search for "January" and replaced it by "01", "February" by "02"...etc ? (in one line if it's possible) ?
Thx

EDIT
I'd like to do something as simple as that :
str.replace( "monday"||"tuesday"||"wednsday" , "" );

Or
var search:String ="tuesday","wednsday","thursday";

But it's not working..

A: What you want is a regular expression which is implemented in the RegExp class in AS3. The pattern passed into String.replace() can be a RegExp which can be used to do type of matching you want.
A simple regular expression to match English language work days could look like this:
(Monday|Tuesday|Wednesday|Thursday|Friday)

which is Regular Expression for "match Monday or Tuesday or Wednesday or Thursday or Friday". Note that this almost certainly isn't the best regex for this but it's simple and it works. There's a link where you can learn more about regexes at the bottom of this answer.
This regex can be put into a function that takes the string to search, the string to replace matches with and a string called flag. flag is a list of options that modify how the regex works. The docs for the RegExp construction provide complete details. This function might look like:
private function replaceDay(str:String, replace:String, flag:String = ''):String
{
    var search:RegExp = new RegExp("(Monday|Tuesday|Wednesday|Thursday|Friday)", flag);
    return str.replace(search, replace);
}

You can then test it out (I've run it all in Flash Builder successfully):
// Replace a single, normally capitalized day name
var monday:String = "Monday the 1st";
trace(replaceDay(monday, "REDACTED"));  // REDACTED the 1st

// Replace multiple normally capitalized day names
var mondayAndTuesday:String = "Either Monday or Tuesday works for me";
trace(replaceDay(mondayAndTuesday, "", "g"));  // Either  or  works for me

// Replace a single day name regardless of capitalization
var lowerCaseWednesday:String = "wednesday";
trace(replaceDay(lowerCaseWednesday, "yadsendew", "i"));  // yadsendew

var weirdCaseThursday:String = "tHurSdaY";
trace(replaceDay(weirdCaseThursday, "It's actually 'Thursday'.", "i"));  // It's actually 'Thursday'.

// Replace multiple day names regardless of capitalization
var friday:String = "FriDAY FRIDAY friday";
trace(replaceDay(friday, "Something", "ig")); // Something Something Something

As for your question about replacing month names with numbers that is possible as well. The last example in the docs for String.replace() shows how to use a function as the replace value. Since StackOverflow prefers one post, one question you should remove it from this post and post another question.

For more info on regular expressions check out http://www.regular-expressions.info/


text:
Q: WCF Service inaccessable when attaching VS 2010 profiler I'm receiving the following error after I attach the visual studio 2010 profiler to my wcf service.

The requested service,
  'net.tcp://host:port/path/myservice.svc'
  could not be activated. See the
  server's diagnostic trace logs for
  more information.

The service works great otherwise, and as soon as I stop profiling, I can connect and use the service again.
The closest I could find to a similar situation online was here, but the Net.Tcp Listener Adapter does not stop on my server, and restarting it does not help either. Neither does an iisreset.
I'm receiving the following entry in the event log:

Failed to initialize the
  AppDomain:/LM/W3SVC/1/ROOT/MyService
Exception: System.Web.HttpException
Message: Could not load file or
  assembly 'MyService' or one of its
  dependencies. An attempt was made to
  load a program with an incorrect
  format. InnerException:
  System.Configuration.ConfigurationErrorsException
Message: Could not load file or
  assembly 'MyService' or one of
  its dependencies. An attempt was made
  to load a program with an incorrect
  format.
InnerException:
  System.BadImageFormatException
Message: Could not load file or
  assembly 'MyService' or one of
  its dependencies. An attempt was made
  to load a program with an incorrect
  format.

Does this sound like the profiler is creating a bad dll when instrumenting? If so, how would I get around that?

A: There were a couple issues at work here.
1) the binaries were being instrumented as 32 bit instead of 64 bit. This seemed to be a problem with the visual studio profiler, but also could have been a symptom of issue 2) I was attempting to profile remotely instead of on the physical machine which isn't supported.
I installed the command line tools on the test server and am looking to profile that way.


text:
Q: Collapse all #regions only(!) in C# (Visual Studio) There's a number of keyboard shortcuts and menu commands to automatically expand or collapse all foldables in the current document. Ctrl+M,
Ctrl+L toggles all foldables recursively, from the top namespace down to the inner methods and comments. Basically everything that has a [+] icon in the left margin. Ctrl+M, Ctrl+O does it bit less, but it still touches methods and comments inside the class.
I'm looking for a function that specifically only regards #region foldables and nothing else. Not namespaces, classes, comments, or methods. I really only want to fold those areas that are explicitly marked as such with the #region keyword.
Is there any hidden shortcut or an extension for that?
I'd prefer a keyboard solution, for Visual Studio 2015 (RC for now).
In case somebody asks why: I want to get an overview of the file, but immediately see all the details when I decide to look inside one region.

Update:
Solution in 2020
As this question has received many answers, some of them useless, others outdated, the working solution for Visual Studio 2019 can be found in this underappreciated answer here: https://stackoverflow.com/a/58999093/143684 Link to VS 2022 version in the comments.

A: Ctrl+M+O will collapse all.
Ctrl+M+L will expand all. (in VS 2013 - Toggle All outlining)
Ctrl+M+P will expand all and disable outlining.
Ctrl+M+M will collapse/expand the current section.
These options are also in the context menu under Outlining.
Right click in editor -> Outlining to find all options. (After disabling outlining, use same steps to enable outlinging.)

A: Looks like the closest thing is Ctrl+M, Ctrl+S
Which will collapse the current region you are in, while Ctrl+M, Ctrl+E will expand the current region you are in.
List of default keyboard shortcuts:
https://msdn.microsoft.com/en-us/library/da5kh0wa(v=vs.140).aspx

A: To collapse regions : Tools > Options > Text Editors > C# > Advanced >
Check "Collapse #regions when collapsing to definitions"

A: Update for VS2022: https://github.com/mdmower/CollapseRegionExtension/releases/tag/v1.5 (thanks @ygoe)

I know this is an old question, but here's an update for visual studio 2019:
The Quick Tasks solution from @ygoe's answer does not work for Visual Studio 2019, because that version changed the way the Quick Task bar searches. Plus it was never the preferred solution to the original question, since you needed to type a quick action instead of having a keyboard shortcut.
I found a different solution on the marketplace which does exactly the collapsing and expanding of all regions in the currently opened file with keyboard shortcuts: Collapse Region
From the extension page:

Default key bindings are (Ctrl+R, Ctrl+Num+) and (Ctrl+R, Ctrl+Num-).
Can be changed in Tools->Options->Environment->Keyboard.

A: The Visual Studio extension Productivity Power Tools 2015 from Microsoft has a feature called Quick Launch Tasks that adds new commands to the Quick Launch menu. One of them is CollapseRegions and it does exactly that.
The opposite command is ExpandRegions and it expands all regions for quick browsing of the entire file. These commands can be used pretty quickly by pressing the CtrlQ hotkey and typing Coll resp. Exp, then pressing Enter (supposed you don't have other commands with the same prefix).

A: I recommend using the free Visual Studio extension "Menees VS Tools Extension for Visual Studio."  Just search for it in Tools --> Extensions and Updates in Visual Studio.  Once installed you just have to hit Ctrl+M+K and just the regions will be collapsed.  Here is their website https://marketplace.visualstudio.com/items?itemName=BillMenees.MeneesVSTools2013
To edit the settings look under Tools --> Options --> Menees VS Tools --> General.

A: in Visual Studio 2017 I have to activate 'Collapse #regions when collapsing to definitions' in
Tools -> Options -> Text Editor -> C# -> Advanced
explicitly to collapse all when pressing Ctrl+M+O

A: tick the Checkmark in Settings -> TextEditor -> C# -> Advanced -> (section Outlining) Collapse #regions when collapsing definitions.
then  right click in the editor > outlining > collapse to definitions

A: For Visual Studio 2022, here is the tool that works well:
https://marketplace.visualstudio.com/items?itemName=EngineDesigns.CollapseAllRegions
CTRL-M CTRL-R
to collapse all #region groups.

A: I dont know if this is new, but there is a setting for the c# text edior:
Settings -> TextEditor -> C# -> Advanced -> Collapse #regions when collapsing definitions.
When its set CtrlM CtrlO will collapse the #regions.

A: Not sure about previous Visual Studio versions, but in VS 2022 we have new shortcut
 CTRL + M + M
It will collapse any part of code like namespace, class, region etc.,
Steps:

*

*Go to #region piece of code.

*Select #region or click on #region anywhere in that word.

*From Keyboard click  CTRL + M + M
If you want for entire namespace to collapse, you can do same steps by selecting or clicking namespace.

A: Select All via Ctrl A and then Ctrl M M
i.e. Press M twice while holding down Ctrl


text:
Q: strange GDB error unable to trace I am getting this strange error in gdb and i'm unable to trace the exact line of code to trace the bug. Does someone knows about this type of bug? Here is what i get in gdb
*** -[CALayer sublayers]: message sent to deallocated instance 0x911c2a0
(gdb) po 0x911c2a0
Program received signal SIGTRAP, Trace/breakpoint trap.
0x020993a7 in ___forwarding___ ()
The program being debugged was signaled while in a function called from GDB.
GDB has restored the context to what it was before the call.
To change this behavior use "set unwindonsignal off"
Evaluation of the expression containing the function (_NSPrintForDebugger) will be   abandoned.
(gdb) info symbol 0x911c2a0
No symbol matches 0x911c2a0.
(gdb)

A: You can try the following in order to see where the faulty CALayer was allocated:
(gdb) info malloc 0x911c2a0

I don't know if gdb plays well with zombie objects, but obviously, it seems that it has some limitations.

A: You have a memory management bug, obviously.
And you aren't tracing the exact line at all. To get a stack trace, type bt, or just look into the Debugger window (Run → Debugger).
(po means "Print Objective-C object". Since that particular instance has been deallocated, po-ing will cause further error.)

A: Try debugging with NSZombieEnabled set to YES executable environment:

To activate the NSZombieEnabled
  facility in your application:
Choose Project > Edit Active
  Executable to open the executable Info
  window. Click Arguments. Click the add
  (+) button in the "Variables to be set
  in the environment" section. Enter
  NSZombieEnabled in the Name column and
  YES in the Value column. Make sure
  that the checkmark for the
  NSZombieEnabled entry is selected.

You also might want to add a couple of breakpoints to help you debug them:
fb -[_NSZombie init]
fb -[_NSZombie retainCount]
fb -[_NSZombie retain]
fb -[_NSZombie release]
fb -[_NSZombie autorelease]
fb -[_NSZombie methodSignatureForSelector:]
fb -[_NSZombie respondsToSelector:]
fb -[_NSZombie forwardInvocation:]
fb -[_NSZombie class]
fb -[_NSZombie dealloc]

A: I've got the solution to the problem. The problem was due to a view Controller. The view controller was released and then after the method was called. But strange gdb didn't show anything about viewController relese....Neither turning on NSZombie helped.


text:
Q: How does C type syntax avoid circular definition? This statement and example is from Essential C by Nick Parlante.
One nice thing about the C type syntax is that it avoids the circular definition problems which come up when a pointer structure needs to refer to itself. The following definition defines a node in a linked list. Note that no preparatory declaration of the node pointer type is necessary.
   struct node {
      int data;
      struct node* next;
   };

How does the C compiler know what is struct node* when it is still inside the struct node.
There is another example of circular definition, wherein a type struct treenode* is used before it is defined further down.
typedef struct treenode* Tree;
struct treenode {
    int data;
    Tree smaller, larger;   // equivalently, this line could say
                            // "struct treenode *smaller, *larger"
};

How does the C compiler know what is struct treenode* when it hasn't been defined yet.
Related SO Question: How does C resolve circular definition when a pointer in struct points to the struct itself? (This is related, it doesn't answer the "How" question).
Edit: I am assuming that C compiler is able to do this in a single pass.

A: The C standard stipulates in §6.2.5 Types ¶28 (emphasis added):

A pointer to void shall have the same representation and alignment requirements as a
  pointer to a character type.48) Similarly, pointers to qualified or unqualified versions of
  compatible types shall have the same representation and alignment requirements. All
  pointers to structure types shall have the same representation and alignment requirements
  as each other. All pointers to union types shall have the same representation and
  alignment requirements as each other. Pointers to other types need not have the same
  representation or alignment requirements.

Consequently, the C compiler knows how to handle any structure pointer type because all structure pointers must have the same representation and alignment requirements.  That applies whether you embed a struct node * or a struct value * — whether or not the compiler was previously aware of the type struct value.  This also helps with 'opaque types' — you can have pointers to structure types where the compiler does not know the content of the structure.
What you can't do is embed a struct node (rather than struct node *) within the definition of struct node.  You can embed a previously known structure type as a value within the structure.  You can also define a structure type within another:
struct node
{
    int data;
    struct node *next;
    struct key_value
    {
        int key;
        char *value;
    } kv;
};

Unlike C++, the struct key_value type is available without problems of scope — it is not restricted to use in the type struct node.  This is not good coding practice, but it is permissible.

A: You can declare a pointer to an incomplete type - the size and representation of a pointer does not depend on size or representation of the pointed-to type.
It also helps that, per the language standard, that pointers to all struct types have the same size and representation

A: You can define a pointer, whose size is known by the compiler, to an instance of the struct itself but it is illegal to define a struct inside a struct of the same type in type declaration.
If you attempt to declare a struct rather than a struct*, you would get a compiler error.


text:
Q: Python3 Flask Twitter OAuth I've been trying to use twitter with Flask OAuth and im running Python 3. I've followed this tutorial: http://pythonhosted.org/Flask-OAuth/ and tried some workarrounds but it doesn't work.
This is what I've got so far:
from flask import *
from flask_oauthlib.client import OAuth
from User import User

oauth = OAuth()
twitter = oauth.remote_app(
    base_url='https://api.twitter.com/1.1/',
    request_token_url='https://api.twitter.com/oauth/request_token',
    access_token_url='https://api.twitter.com/oauth/access_token',
    authorize_url='https://api.twitter.com/oauth/authorize',
    consumer_key='My Consumer Code',
    consumer_secret='My Secret Code',
    name='twitter'
)

app = Flask(__name__)
current_user = User()
@app.route('/')
def home_show():
    return render_template('home.html')

@app.route('/about')
def about_show():
    return render_template('about.html')

@app.route('/app')
def app_show():
    if not current_user.is_authenticated():
        return redirect('/')
    else:
        return twitter.authorize(callback=url_for('oauth_authorized',
      next=request.args.get('next') or request.referrer or None))

@twitter.tokengetter
def get_twitter_token(token = None):
    if current_user.is_authenticated():
        return session.get('twitter_token')
    else:
        return None

@app.route('/oauth-authorized', methods=['GET'])
@twitter.authorized_handler
def oauth_authorized(resp):
    next_url = request.args.get('next') or url_for('index')
    if resp is None:
        flash(u'You denied the request to sign in.')
        return redirect(next_url)

    session['twitter_token'] = (
        resp['oauth_token'],
        resp['oauth_token_secret']
    )
    session['twitter_user'] = resp['screen_name']

    flash('You were signed in as %s' % resp['screen_name'])
    return redirect(next_url)

if __name__ == '__main__':
    app.run(debug=True)

It crashes on
   return twitter.authorize(callback=url_for('oauth_authorized',next=request.args.get('next') or request.referrer or None))

and this is the trace:
    Traceback (most recent call last):
      File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/flask/app.py", line 1836, in __call__
        return self.wsgi_app(environ, start_response)
      File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/flask/app.py", line 1820, in wsgi_app
        response = self.make_response(self.handle_exception(e))
      File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/flask/app.py", line 1403, in handle_exception
        reraise(exc_type, exc_value, tb)
      File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/flask/_compat.py", line 33, in reraise
        raise value
      File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/flask/app.py", line 1817, in wsgi_app
        response = self.full_dispatch_request()
      File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/flask/app.py", line 1477, in full_dispatch_request
        rv = self.handle_user_exception(e)
      File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/flask/app.py", line 1381, in handle_user_exception
        reraise(exc_type, exc_value, tb)
      File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/flask/_compat.py", line 33, in reraise
        raise value
      File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/flask/app.py", line 1475, in full_dispatch_request
        rv = self.dispatch_request()
      File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/flask/app.py", line 1461, in dispatch_request
        return self.view_functions[rule.endpoint](**req.view_args)
      File "/Users/Karl/Python/tweettosleep/hello.py", line 40, in app_show
        return twitter.authorize(callback=url_for('oauth_authorized',next=request.args.get('next') or request.referrer or None))
      File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/flask_oauthlib/client.py", line 455, in authorize
        token = self.generate_request_token(callback)[0]
      File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/flask_oauthlib/client.py", line 527, in generate_request_token
        type='token_generation_failed'
    flask_oauthlib.client.OAuthException: Failed to generate request token

A: I've already found the answer, there is actually nothing wrong with the code. Sorry if it's a little bit messed up. The problem was that my consumer_key for twitter isn't valid. I have no idea why. Still figuring out.
So the point is, if you get the same Traceback, there might be a possibility that your twitter consumer_key is not correct!


text:
Q: Oracle transportable tablespace not bring packages and procedures Is there some way to bring packages and procedures of a schema during the transportable tablespace export/import? in me research it seems all plsql for all users is actually stored by by the SYS user in SYSTEM tablespace. If i am exporting foo tablespace (transport_tablespaces=foo) used by schema foo, those objects (packages, procedures and functions) don't come with the tablespace foo because it is in system tablespace.
The only way I've found to import those object (packages, procedures and functions) is, after finish the transportable tablespace import, make a new export of the schema in the source database with the option content=metadata_only and then, reimport it in target database. Is the the only way? (two steps).

A: No option for that with the transportable tablespace feature.
Full Transportable Export/Import can do it.
Introduction to Full Transportable Export/Import

You can use the full transportable export/import feature to copy an
entire database from one Oracle Database instance to another.

Limitations on Full Transportable Export/import

Full transportable export/import can export and import user-defined
database objects in administrative tablespaces using conventional Data
Pump export/import, such as direct path or external table.
Administrative tablespaces are non-user tablespaces supplied with
Oracle Database, such as the SYSTEM and SYSAUX tablespaces.

Full Transportable Export and Import

Full transportable export/import greatly simplifies and accelerates
the process of database migration. Combining the ease of use of Oracle
Data Pump with the performance of transportable tablespaces, full
transportable export/import gives you the ability to upgrade or
migrate to Oracle Database in a single operation if your source
database is at least Oracle Database 11g Release 2 (11.2.0.3).


text:
Q: How to create a new database in Oracle Database 11g using SQL Developer command line? I installed Oracle Database 11g Express Edition Release 11.2.0.2.0 - 64bit Production on a Linux virtual machine. The linux machine doesn't have a desktop environment which eliminates the possibility of using the SQL Developer software. According to Oracle, SQLcl is a command-line interface for Oracle Database that combines the power of SQL*Plus and SQL Developer. I have now installed SQLcl (SQL Developer command line) and am able to run it on the linux vm.
The bin folder (inside sqlcl folder) contains the script sql which runs sqlcl. After running sql, I'm prompted for a username and password. Once complete, I see SQL> in the CLI.
I have found various resources online on how to create columns and tables. However, I have not found information on how to create a database using SQLcl. Is there a SQLcl command to automatically create a database? If not, what is another way to create a database in Oracle? Thanks.

A: When you installed XE.... it automatically created a database called "XE". You can use your login "system" and password that you set to login.
Key info

*

*server: (you defined)

*port: 1521

*database: XE

*username: system

*password: (you defined)
Also Oracle is being difficult and not telling you easily create another database. Normally, You have to use SQL or another tool to create more database besides "XE".


text:
Q: Prove that the function $\varphi(g_1, \cdots , g_k)=(g_{\sigma(1)}, \cdots ,g_{\sigma(k)}) $ is a homomorphism. Let $G_1. ..., G_k$ be any groups and $\sigma \in S_k$ a permutation. Prove  that the function $$
\varphi: G_1 \times \cdots \times G_k \rightarrow G_{\sigma(1)} \times \cdots \times G_{\sigma(k)}
$$ $$
\varphi: \hspace{0.2cm} (g_1, \cdots , g_k) \hspace{0.2cm} \mapsto \hspace{0.5cm}(g_{\sigma(1)}, \cdots ,g_{\sigma(k)})
$$ is a homomorphism.
Progress: Let $(x_1,...,x_k), (y_1,...,y_k)\in G_1\times...\times G_k$ then $$ \varphi((x_1,...,x_k)(y_1,...,y_k))=\varphi(x_1 y_1,...,x_k y_k)=???=(x_{\sigma(1)}, \cdots ,x_{\sigma(k)})(y_{\sigma(1)}, \cdots, y_{\sigma(k)})$$
How to fill in the ??? step?

A: It is probably clear that
$\varphi: G_1 \times G_2 \times G_3 \times\cdots \times G_k \rightarrow G_2 \times G_1 \times G_3 \times \cdots \times G_k $ given by $\varphi(g_1,g_2,g_3,\dots,g_k)=(g_2,g_1,g_3,\dots,g_k)$ is an isomorphism.
It is also clear that $1$ and $2$ are not special and can be replaced by any pair $i$ and $j$ with $i\ne j$.
Now use that every permutation in $S_k$ is a product of transpositions to prove the general case.


text:
Q: Массив string в MySql У меня есть бд MySql для пользователей, мне нужно к ним сделать список ссылок, у каждого юзера он свой. У меня также есть класс Account, и в нём Links; Так вот
Links[] l = new Links[6];

Нужно запихнуть в MySql в одно поле links в строке с логином, чтобы они и там были, и в программе расшифровывались нормально.
Желательно без лишних файлов в папке с программой.

A: Если хотите хранить одним полем в базе, то можете записывать ссылки в базу через ";" или "\n", а потом в основной программе сделать так
string linksInDb = "взять; из; базы;";
List<string> links = linksInDb.Split(';').ToListArray();

Но правильным вариантом будет хранить в базе в отдельной таблице так:
UserId     Link
id         ссылка
id         ссылка
...        ...

ссылки можно хранить тоже в отдельной таблице, и подставлять только айдишник, что позволит не писать ссылки по нескольку раз, а просто использовать Id нужной ссылки.


text:
Q: Can we explicitly start a system service in Android? In my android project we are facing an issue -
'When an Edit Text box is focused and appropriate action is taken', the keyboard does not appear up.
This issue occurs like once in 50 times.
We analyzed the issue and found that -
Input Method Service is not running when this issue occurs. (We checked logs) Input Methods Service is used to get instance of Input Manager, which is further used for other things.
I have to do more analysis
So I have two questions -

*

*Could it be a problem related to memory management ? I mean is it possible that the system is killing the service when certain memory situation occurs ?

*If the service is killed and not running, can we explicitly start this service through our code in application?
Please Help.


text:
Q: Polymer/PolymerTS: Pass object to custom element I'm currently creating a web app that uses Typescript instead of Javascript to see how Typescript feels. I also am learning Polymer to kill two birds with one stone. To get this working, I'm using PolymerTS to get this to work, and up until this point it's been working just fine. However, I've hit a barrier.
I have two elements, we can call them 'my-foo' and 'my-bar':
<link rel="import" href="path/to/my-bar.html">

<dom-module id="my-foo">
    <template>
        <my-bar myBarProperty="{{myFooProperty}}"></my-bar>
    </template>
</dom-module>

Now the value 'myFooProperty' is a value that has been deserialized from JSON into a custom Typescript class. I can get all its properties to display if I data-bind them, e.g.
<h1>{{myFooProperty.name}}</h1>

But passing it into the second custom element does not work, i.e. "myBarProperty" is null or an empty map. The element is loaded correctly (any html not data-specific is loaded and displayed) but the value itself isn't set. Any insight on why this is? Maybe this isn't possible?
Relevant *.ts files:
my-foo.ts:
@component("my-foo")
class MyFoo extends polymer.Base {
    @property({ type: Object, notify: true })
    myFooProperty: any;

    constructor() {
        super();
        apiCallThatReturnsPromise().then(value => {
            this.myFooProperty = value;
        });
    }
}

MyFoo.register();

my-bar.ts:
@component("my-bar")
class MyBar extends polymer.Base {
    @property({ type: Object, notify: true, value: function() { return {}; } })
    myBarProperty: any;
}

MyBar.register();

Edit 1: I did see if not deserializing the JSON and passing just the raw data would fix my problem, but it did not.

A: Use my-bar-property.
Source: https://www.polymer-project.org/1.0/docs/devguide/properties.html#property-name-mapping


text:
Q: Pyinstaller and Pandas Error when exporting I have a working project with tkinter and Pandas but whenever I try to export it using Pyinstaller it will show an error when I Import pandas to my project.
    57986 WARNING: Cannot read QLibraryInfo output: raised Expecting value: line 1 column 1 (char 0) when decoding:
Traceback (most recent call last):
  File "<string>", line 11, in <module>
ImportError: DLL load failed: The specified procedure could not be found.
Traceback (most recent call last):
  File "c:\python36\lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "c:\python36\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Python36\Scripts\pyinstaller.exe\__main__.py", line 9, in <module>
  File "c:\python36\lib\site-packages\PyInstaller\__main__.py", line 111, in run
    run_build(pyi_config, spec_file, **vars(args))
  File "c:\python36\lib\site-packages\PyInstaller\__main__.py", line 63, in run_build
    PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs)
  File "c:\python36\lib\site-packages\PyInstaller\building\build_main.py", line 838, in main
    build(specfile, kw.get('distpath'), kw.get('workpath'), kw.get('clean_build'))
  File "c:\python36\lib\site-packages\PyInstaller\building\build_main.py", line 784, in build
    exec(text, spec_namespace)
  File "<string>", line 17, in <module>
  File "c:\python36\lib\site-packages\PyInstaller\building\build_main.py", line 241, in __init__
    self.__postinit__()
  File "c:\python36\lib\site-packages\PyInstaller\building\datastruct.py", line 158, in __postinit__
    self.assemble()
  File "c:\python36\lib\site-packages\PyInstaller\building\build_main.py", line 500, in assemble
    module_hook.post_graph()
  File "c:\python36\lib\site-packages\PyInstaller\building\imphook.py", line 410, in post_graph
    self._load_hook_module()
  File "c:\python36\lib\site-packages\PyInstaller\building\imphook.py", line 377, in _load_hook_module
    self.hook_module_name, self.hook_filename)
  File "c:\python36\lib\site-packages\PyInstaller\compat.py", line 736, in importlib_load_source
    return mod_loader.load_module()
  File "<frozen importlib._bootstrap_external>", line 399, in _check_name_wrapper
  File "<frozen importlib._bootstrap_external>", line 823, in load_module
  File "<frozen importlib._bootstrap_external>", line 682, in load_module
  File "<frozen importlib._bootstrap>", line 265, in _load_module_shim
  File "<frozen importlib._bootstrap>", line 684, in _load
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "c:\python36\lib\site-packages\PyInstaller\hooks\hook-PyQt5.py", line 23, in <module>
    collect_system_data_files(pyqt5_library_info.location['PrefixPath'],
  File "c:\python36\lib\site-packages\PyInstaller\utils\hooks\qt.py", line 67, in __getattr__
    qli = json.loads(json_str)
  File "c:\python36\lib\json\__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "c:\python36\lib\json\decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "c:\python36\lib\json\decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

This is my Firstime exporting to an exe. I have reinstalled pyinstaller pyqt5, pandas, and still none.
Im using

*

*Windows 10

*python 3.6

*I used Pip to install the libraries

libraries: pandas, pyinstaller.

A: collect_system_data_files(pyqt5_library_info.location['PrefixPath']

This shows error started while collecting system data file. Try installing PyQt5 and then run PyInstaller.

A: I had the very same problem. After hours of messing around I believe that deleting a older version of python that was on my computer was what fixed it, all though I can't be absolutley sure, since I did many things. I would suggest trying to uninstall other versions of python if you have them, and then uninstalling and reinstalling the dependencies of your program through pip. Then make sure you are able to run your python script myProgram.py from the cmd: C:\<path to the location of myProgram>\>python myProgram.py. Resolve any errors that might occur before trying to use pyinstaller, which solved this particular error for me.


text:
Q: Google Cloud SDK error while deploying app: error 403 operation not allowed I am using Google Cloud SDK for publishing and trying to host my first basic site. Whenever I try to deploy app, it shows error 403: appengine.applications.get permission is required. I've tried each and every thing: searched a lot but still not able to find any solution. Also after changing project name and then browsing the site, it still shows error 404 ,requested url not found on the server.
link- udacitywork1.appspot.com
INDEX.HTML

    <title>Hello, udacity!</title>
    <link rel="stylesheet" type="text/css" href="/css/style.css">

Hello,Udacity!

APP.YAML CODE
runtime: python27
api_version: 1
threadsafe: true

handlers:
- url: /
  static_files: www/index.html
  upload: www/index.html

- url: /(.*)
  static_files: www/\1
  upload: www/(.*)

Please help! Thanks in advance!

A: Changing the project name locally to a project which doesn't exist on GAE is not gonna work - you'll get the 403 errors. The project must be visible in your developer console before you can reference it in the gcloud commands.
From the Before you begin section in the Quickstart for Python App Engine Standard Environment:

Before running and deploying this quickstart, you must set up a Cloud
  Platform project for App Engine and then install the Cloud SDK:

*

*Create a new Cloud Platform project and App Engine application using the Cloud Platform Console:
Go to App Engine
When prompted, select the region where you want your App Engine application located. After your App Engine application is
  created, the Dashboard opens.


text:
Q: Formula to get date field in Excel sheet SQL Server query I have data in Excel sheet and I need to update SQL Server DB table by using Excel sheet data, I am able to write SQL Server Query and get the data. However I am not getting date field in date format, it's rendered as a normal number.

A: In cell B2 try this -
="Select " & TEXT(A2,"DD/MM/YYYY")

A: Try this
="select '" & TEXT(A2, "dd/mm/yy") & "' from Table "


text:
Q: Issues with upgrading a site from .net 2.0 to 3.5 I want to upgrade my company website from 2.0 to 3.5. I think it should be fairly painless as all the old methods are still supported (just depreciated) in newer versions of .net. Is that correct?

A: We had no issues at all upgrading all of our apps from 2.0 to 3.5
I doubt you'll have any issues because .NET 3.0 and 3.5 are "additive" releases - meaning the core functionality of .NET 2.0 remains the same, these just add features.
This brief article explains it a little more clearly: https://web.archive.org/web/20211020133927/https://www.4guysfromrolla.com/articles/112107-1.aspx
As a side note, we also had no problems going from 2.0 straight to 4.0.  Microsoft has been doing a pretty good job of keeping the upgrades painless.
I would like to throw in a caveat - if you're using third party components, I can't vouch for how easily they survive the upgrade process, but given the additive nature of the releases through 3.5 I think you'll be fine.


text:
Q: How to draw a textured cube in WGPU using indices? I'm trying to draw a Minecraft-like textured cube in WGPU. I have a vertex buffer and an index buffer. I'm using Repeat for adress_mode on the texture sampler. I use texture coordinates greater or smaller than 0 to repeat the dirt texture. The front, right and left faces render properly. However, the texture coordinates of the back and top faces are messed up. I didn't add the bottom face yet as I wanted to get these working first. The back texture gets drawn twice and inside out and the top one is completely messed up.
Here's the code:
#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
pub struct Vertex {
    pub position: [f32; 3],
    pub tex_coords: [f32; 2]
}

/// We arrange the vertices in counter-clockwise order: top, bottom left, bottom right.
pub const VERTICES: &[Vertex] = &[
    // FRONT
    Vertex {position: [-1.0, -1.0, 0.0], tex_coords: [0.0, 1.0]}, // 0
    Vertex {position: [1.0, -1.0, 0.0], tex_coords: [1.0, 1.0]}, // 1
    Vertex {position: [1.0, 1.0, 0.0], tex_coords: [1.0, 0.0]}, // 2
    Vertex {position: [-1.0, 1.0, 0.0], tex_coords: [0.0, 0.0]}, // 3

    // RIGHT
    Vertex {position: [1.0, -1.0, -2.0], tex_coords: [2.0, 1.0]}, // 4
    Vertex {position: [1.0, 1.0, -2.0], tex_coords: [2.0, 0.0]}, // 5

    // LEFT
    Vertex {position: [-1.0, -1.0, -2.0], tex_coords: [-1.0, 1.0]},
    Vertex {position: [-1.0, 1.0, -2.0], tex_coords: [-1.0, 0.0]},
];

pub const INDICES: &[u16] = &[
    // FRONT
    0, 1, 2,
    2, 3, 0,

    // RIGHT
    1, 4, 5,
    5, 2, 1,

    // LEFT
    6, 0, 3,
    3, 7, 6,

    // BACK
    6, 4, 5,
    5, 7, 6,

    // TOP
    3, 2, 5,
    5, 7, 3
];

My texture sampler:
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
    address_mode_u: wgpu::AddressMode::Repeat,
    address_mode_v: wgpu::AddressMode::Repeat,
    address_mode_w: wgpu::AddressMode::Repeat,
    mag_filter: wgpu::FilterMode::Nearest,
    min_filter: wgpu::FilterMode::Nearest,
    mipmap_filter: wgpu::FilterMode::Nearest,
        ..Default::default()
});

A: Look at the first triangle of your BACK face: it uses vertices 6, 4, and 5. In that order, those vertices are:
Vertex {position: [-1.0, -1.0, -2.0], tex_coords: [-1.0, 1.0]}, // 6
Vertex {position: [1.0, -1.0, -2.0], tex_coords: [2.0, 1.0]}, // 4
Vertex {position: [1.0, 1.0, -2.0], tex_coords: [2.0, 0.0]}, // 5

The u texture coordinates span a range from -1 to 2 horizontally. So, they span 3 copies of the repeating texture, and 3 copies will be drawn in the space of your cube face.
It seems that you're trying to share vertices between different cube faces, and wrap the texture around them continuously. But the problem is that, in texture space, there is always going to be a "seam" at one of the edges of your block where instead of repeating again you start over from a low number (-1 in your code) — it's the same kind of problem as texture mapping a sphere. So, at least one edge must have non-shared vertices.
However, in the long run, you will probably want to stop sharing any vertices between different cube faces. This is because in order to do lighting, vertices must (usually) include normal vectors, and normals are different for each face. As a general rule in computer graphics, vertices can be shared between triangles when they are representing a smoothly curved (or flat) surface, but at any sharp edge, like the edges and corners of a cube, you must make separate vertices for each face.
You can still share vertices between the two triangles that make up one cube face.