text:
Q: Validacion de formulario para registro de persona en base de datos con python Gente espero que puedan ayudarme con este tema que me esta presentado al realizar la validacion de formulario para el registro de persona en una base de datos.
en el formulario como que no me reconoce los input porque no me imprime el msj error que coloco en el validador, cuando le doy enter sin colocar ninguna letra ni caracter. Ejemplo:(if datosFinales["nombre"]=='':
errores["nombre"]='campo nombre vacio').
otro error que tengo es que al ingresar todo los datos del input en el formulario me da un error en la clase de validación exactamente me dice error de llave KeyError'constraseña', no logro finiquitar el registro.
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="root",
password="23640183",
database="proyectopoo"
)
cursor=mydb.cursor()

dbconfi={
'host':"localhost",
'user':"root",
'password':"23640183",
'database':"proyectopoo"
}

class db():
def __init__(self):
    self.conexion=mysql.connector.connect(**dbconfi)
    self.cursor=self.conexion.cursor()
    self.commit=self.conexion.commit()

def get_cursor(self):
    return self.cursor
def get_commit(self):
    return self.commit
def get_conexion(self):
    return self.conexion
dba=db()

from dba import dba

from validate_email import validate_email
class Validator():
def init(self):
pass
def vali_usuario(self,dic):
    datosFinales={}
    errores={}
    SpecialSym=['$','@','#','%','-','_']
    for x,y in dic.items():
        datosFinales[x]=y.strip()

    if datosFinales["nombre"]=='':
        errores["nombre"]='campo nombre vacio'
    if datosFinales["apellido"]=='':
        errores["apellido"]='campo apellido vacio'

    if datosFinales["email"]=='':
        errores["email"]="campo email vacio"
    elif validate_email(datosFinales["email"])==False:
        errores["email"]="el mail no es correcto"
    """elif db.buscar_usuario(datosFinales['email']) != None:
        errores['email']='el mail esta en uso'"""
    if datosFinales["celular"]=='':
        errores["celular"]='campo celular vacio'

    if len(datosFinales["contraseña"])< 4:
        errores["contraseña"]='la contraseña debe tener mas de 2 caracteres'
    if datosFinales["contraseña"]=='':
        errores["contraseña"]='la clave esta vacia'
    elif not any(char.isdigit()for char in datosFinales ["contraseña"]):
        errores["contraseña"]='la clave debe tener al menos un numeral'
    elif not any(char.isupper()for char in datosFinales ["contraseña"]):
        errores["contraseña"]='la clave debe tener al menos una mayuscula'
    elif not any(char.islower()for char in datosFinales ["contraseña"]):
        errores["contraseña"]='la clave debe tener al menos una minuscula'
    elif not any(char in SpecialSym for char in datosFinales ["contraseña"]):
        errores["contraseña"]='la clave debe tener al menos un $#%@'

    if errores=={}:
        sql="SELECT id from usuario where email=%s"
        val=(datosFinales['email'],)
        dba.get_cursor().execute(sql,val)
        resultado=dba.get_cursor().fetchone()
        if resultado is not None:
            errores['email']='el correo ya esta registrado'
            return errores
    return errores

validator=Validator()
formusuario={}
formusuario['nombre']=input('escriba el nombre del usuario: ')
formusuario['apellido']=input('escriba el apellido del usuario: ')
formusuario['email']=input('escriba el email del usuario: ')
formusuario['celular']=input('escriba el celular del usuario: ')

formusuario['ncontraseña']=input('escriba de nuevo la contraseña')

if validator.vali_usuario(formusuario)=={}:
usu=Usuario(formusuario['nombre'],formusuario['apellido'],formusuario['email'],formusuario['celular']
,formusuario['id_pais'],formusuario['contraseña'],formusuario[''])
usu.save()
print('registro exitoso')

else:
print(validator.vali_usuario(formusuario))
adjunto pastebin como segunto metodo de vista para la ayuda
https://pastebin.com/WYi9sFr1

A: debido a mi reputacion no puedo comentar. Aun asi creo que esto puede considerarse respuesta.
Miré tu codigo en la función vali_usuario, y me di cuenta de que creas el diccionario datosFinales, que está vacio.
En la linea datosFinales["nombre"]=='' estás consultando un diccionario vacio. Y como la clave que le pasas no existe, te envia un error.
Espero que lo que te dije sirva y bienvenido a StackOverflow c:


text:
Q: Using Chebyshev's inequality to obtain lower bounds I need help with a question I found in Master Stats. I'm unaware of Chebyshev's inequality hence I can't do this question, can anyone help.
Q) A company produces planks whose length is a random variable of mean 2.5m
and standard deviation 0.1m. Use Chebyshev's inequality to obtain a lower bound on the
probability that the length of planks does not differ more than 0.5m from the mean length.
Thanks in advance

A: Let $X$ be a random variable with mean $\mu$ and standard deviation $\sigma>0$. Then the Chebyshev Inequality says that if $k>0$, then
$$P(|X-\mu| \ge k\sigma)\le \frac{1}{k^2}.$$
In our case, $X$ is the length of a plank chosen at random from the company's production. Then $\mu=2.5$ and $\sigma=0.1$.  We want to find $k$ such that $k\sigma=0.5$. Thus $k=\frac{0.5}{\sigma}=\frac{0.5}{0.1}=5$. We conclude that
$$P(|X-2.5| \ge 0.5) \le \frac{1}{5^2}.$$
It follows that
$$P(|X-2.5| < 0.5) \ge 1-\frac{1}{5^2}.\tag{$\ast$}$$
This is not quite what we want, since we want to find a number $p$ such that $P(|X-2.5| \le 0.5)\ge p$.  One can argue that the probability that the difference is absolutely exactly $0.5$ is $0$, so that $(\ast)$ gives us the inequality we want. That gives a lower bound of $1-\frac{1}{5^2}=0.96$.  There is a probability of at least $0.96$ that the plank does not differ by more than $0.5$ from the mean $2.5$.
Typically, the Chebyshev Inequality gives very conservative estimates. In our case, though Chebyshev says that $P(|X-2.5|\ge 0.5) \le \frac{1}{5^2}$, the actual probability is likely to be substantially smaller than $\frac{1}{5^2}$. Thus the lower bound of $0.96$ is likely conservative. Informally, more than $96\%$ of the production will be "within spec."

redpajama_set_name: RedPajamaStackExchange


text:
Q: non-linear ui slider value/placeholder I want my ui slider to be at the second point of its array but have the textbox display the array value (20) when the page loads instead of its position (1).
placeholder & value html elements don't seem to work.
I have a fiddle for convenience: here
The HTML

<input type="text" id="slider-val" value="20" />

The JQuery
$(function() {
    var valMap = [10, 20, 40, 80];
    $("#slider").slider({
        range: "max",
        max: valMap.length - 1,
        value: 1,
        slide: function(event, ui) {
            if (valMap[ui.value] > 0) {
                $("#slider-val").val(valMap[ui.value]);
            } else {
                $("#slider-val").val("1/" + (valMap[ui.value - 2]) * -1);
            }
            $(valMap[ui.value]).val($('#slider-val').val());
        }
    });
    $("#slider-val").val($("#slider").slider("value"));
});

A: Replace the line:
$("#slider-val").val($("#slider").slider("value"));

with:
$("#slider-val").val(valMap[$("#slider").slider("value")]);

As you want to use the sliders value as an index in the valMap array.
jsFiddle


text:
Q: sql select column from except result I try to get column from except result, but all the time have error "Incorect syntax near ')'" even when I put Select * in first select. I work on SQL Management Studio. My code looks like
select ColumnResult from (
            select col1 as ColumnResult, col2 as Column2Result, col3 as Column3Result
            from SourceTable
            except
            select col1 as ColumnResult, col2 as Column2Result, col3 as Column3Result
            from SourceTable2)

A: You need to give you subquery an alias:
select ColumnResult from (
            select col1 as ColumnResult, col2 as Column2Result, col3 as Column3Result
            from SourceTable
            except
            select col1 as ColumnResult, col2 as Column2Result, col3 as Column3Result
            from SourceTable2) AS Src

A: You get error because each table have its own alias name so do it
select A.ColumnResult from (
                select col1 as ColumnResult, col2 as Column2Result, col3 as Column3Result
                from SourceTable
                except
                select col1 as ColumnResult, col2 as Column2Result, col3 as Column3Result
                from SourceTable2) as A


text:
Q: Trouble creating a virtual environment anaconda So I am sort of new to programming and I am trying to setup a virtual environment for my IDE. I'm creating the environment through anaconada and a few of my packages are causing me trouble when I try to install them.
When I run:
(environment_name) C:\Users\Me>conda install -c krisvanneste kivy

I get this error message:
    Solving environment: failed
UnsatisfiableError: The following specifications were found to be in conflict:
  - cantera
  - kivy
Use "conda info <package>" to see the dependencies for each package.

And if I run:conda info kivy nothing happens.
Also, when I run a simple Kivy script in Pycharm I get this error:
[INFO   ] [Logger      ] Record log in C:\Users\combustion13\.kivy\logs\kivy_18-05-31_20.txt
[INFO   ] [Kivy        ] v1.10.0
[INFO   ] [Python      ] v3.6.5 |Anaconda custom (64-bit)| (default, Mar 29 2018, 13:32:41) [MSC v.1900 64 bit (AMD64)]
[INFO   ] [Factory     ] 194 symbols loaded
[INFO   ] [Image       ] Providers: img_tex, img_dds, img_pil, img_gif (img_sdl2, img_ffpyplayer ignored)
[INFO   ] [Text        ] Provider: pil(['text_sdl2'] ignored)
[CRITICAL] [Window      ] Unable to find any valuable Window provider.
sdl2 - ImportError: DLL load failed: The specified module could not be found.
  File "C:\Users\combustion13\AppData\Local\conda\conda\envs\erad136env\lib\site-packages\kivy\core\__init__.py", line 59, in core_select_lib
    fromlist=[modulename], level=0)
  File "C:\Users\combustion13\AppData\Local\conda\conda\envs\erad136env\lib\site-packages\kivy\core\window\window_sdl2.py", line 26, in <module>
    from kivy.core.window._window_sdl2 import _WindowSDL2Storage

[CRITICAL] [App         ] Unable to get a Window, abort.
 Exception ignored in: 'kivy.properties.dpi2px'
 Traceback (most recent call last):
   File "C:\Users\combustion13\AppData\Local\conda\conda\envs\erad136env\lib\site-packages\kivy\utils.py", line 496, in __get__
     retval = self.func(inst)
   File "C:\Users\combustion13\AppData\Local\conda\conda\envs\erad136env\lib\site-packages\kivy\metrics.py", line 174, in dpi
     EventLoop.ensure_window()
   File "C:\Users\combustion13\AppData\Local\conda\conda\envs\erad136env\lib\site-packages\kivy\base.py", line 127, in ensure_window
     sys.exit(1)
 SystemExit: 1
[CRITICAL] [App         ] Unable to get a Window, abort.


text:
Q: How to extract values of sublists that have specific values in R I have a list that contains sublists ("double" objects) with headers. I want to extrat the values from one of those headers.
The image is the list:
List with sublist
But this is what is looks like:
df                                         list(3)
     [1]   result.1                        double(2)
           Number_cluster 2                double(1)
           Value_index 3                   double(1)
     [2]   result.2                        double(2)
           Number_cluster 6                double(1)
           Value_index 1                   double(1)
     [3]   result.3                        double(2)
           Number_cluster 5                double(1)
           Value_index 6                   double(1)

The value to be extracted is "Number_clusters"
If I could extract these values from my data.frame, it would be usefull also
Data.frame:
[v1]        [v2]                                [v3]
c(1,2,3)    c(Number_clusters = 1, index= 2)
c(1,2,3)    c(Number_clusters = 7, index= 7.4)

I have tried
unique(rapply(b, function(x) head(b, )))

But this only gives me the values, both "Number_clusters" and "Index", but index is not usefull for me
dput output:
 list(result.1 = c(Number_clusters = 2, Value_Index = 7.0754),
 result.2 = c(Number_clusters = 5, Value_Index = 7.142), result.3 = c(Number_clusters = 6, Value_Index = 11.235))


text:
Q: Black (blank) screen when using Navigator.pop() after using a custom page animation with PageRouteBuilder(). How do I fix this? I'm getting a black screen after I changed to a custom page animation with PageRouteBuilder(). Without using the custom animation, it works perfectly. But when I added the custom animation, the Navigator.push() still worked, but when the screen is popped, it returns a black screen.
Here is the code:

// This is the button to change the route.
// I'm using the condition statements to change the behaviour
// depending on the route from which it is clicked.
NavigationBarButton(
  icon: Icons.people,
  title: 'My Network',
  isActive: widget.activeScreen == MyNetworkScreen.screen_id ? true : false,
  onPressed: () {
    if (ModalRoute.of(context)!.settings.name == HomeScreen.screen_id) {
      Navigator.of(context).push(_noAnimationBuilder(
        page: MyNetworkScreen(),
        pageName: MyNetworkScreen.screen_id,
      ));
    } else if (ModalRoute.of(context)!.settings.name == MyNetworkScreen.screen_id) {
      // do nothing
    } else {
      Navigator.of(context).pushReplacement(_noAnimationBuilder(
        page: MyNetworkScreen(),
        pageName: MyNetworkScreen.screen_id));
    }
  },
),

// This is the animation.
Route _noAnimationBuilder({required Widget page, required String pageName}) {
  return PageRouteBuilder(
    pageBuilder: (context, animation, secondaryAnimation) => page,
    transitionsBuilder: (context, animation, secondaryAnimation, child) {
      return child;
    },
  );
}

A: It took a while to figure it out. The problem was because I was using named routes in my navigation but when I use the custom animation to create a new route, I didn't set the name of the new route.
I just had to change my code to look like:

Route _noAnimationBuilder({required Widget page, required String pageName}) {
  return PageRouteBuilder(
    pageBuilder: (context, animation, secondaryAnimation) => page,
    transitionsBuilder: (context, animation, secondaryAnimation, child) {
      return child;
    },
    settings: RouteSettings(name: pageName), // This is what I had to add.
  );
}

For the named routes, this is what my MaterialApp() file looks like:

class LinkedInClone extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'LinkedIn Clone',
      initialRoute: LoadingScreen.screen_id,
      routes: {
        // In each screen, I defined a static const String `screen_id` and used it to name the routes so if I don't misspell it.
        LoadingScreen.screen_id: (context) => LoadingScreen(),
        HomeScreen.screen_id: (context) => HomeScreen(),
        MessagingScreen.screen_id: (context) => MessagingScreen(),
        MyNetworkScreen.screen_id: (context) => MyNetworkScreen(),
      },
    );
  }
}


text:
Q: Quantization as a functor Can anyone give an mathematical elaboration of the following statement:

Quantization is a functor carrying the category of Hilbert space and linear maps to that of Symplectic manifolds satisfying some conditions specified by laws of Physics.


text:
Q: I want to read a console command into my current Console application from my code con lines=x
con cols=x

These are the console commands that I want to run in my current C# Console application so     that I can expand the console window above the max allowed from the
Console.SetWindowSize(x,x);

So basically I want to run a console command in my current console application.
Not in a new Process of command line.
I think i had console applications confused with command prompt(cmd)
    Console.SetWindowSize(Console.LargestWindowWidth,Console.LargestWindowHeight);

This seems like the safest way to get a better size for your application

A: Use Console.ReadLine to provide a kind of command prompt and parse the data which the users enters after that. Then you can check if the user entered con lines for example and set the window dimensions based on this.


text:
Q: How to specify a different repository for Docker push? I have a private repository here:
https://hub.docker.com/r/istvan/xxx/
When I build and image and trying to push it there it fails with the following:
docker login
sudo docker push istvan:xxx

The error is:
The push refers to a repository [docker.io/library/istvan]
2456c4c8fd2b: Preparing
5903f32c0854: Preparing
549bd34bfa87: Preparing
08586c0f628f: Preparing
2aebd096e0e2: Preparing
denied: requested access to the resource is denied

A: You need to tag the image that you are trying to push to include the repository name:
docker tag <image> <username>/<image-name>:<tag>

And then you push the tagged image:
docker push <username>/<image-name>:<tag>


text:
Q: Using .length() in Java I have to enter something like John Doe 12345 99 where First name is John, last name is Doe, ID is 12345, and wage is 99. It needs to be all in one string separated by spaces. So I have this:
  while(x < Info.length()){
      if(Info.charAt(x) == ' '){
          First = Info.substring(0,x);
          Last = Info.substring(x + 1, Info.length());
          IDNum = Integer.parseInt(Info.substring(x + 2, Info.length()));
          Wage = Double.parseDouble(Info.substring(x + 3, Info.length()));
          x = Info.length();
      }
   ++x;
}

I'm having trouble on the .length(); The example in the book only showed how to break up a string with two words in it. It's the length on IDNum and Wage. I'm not sure where to start them and end them. I think I need to change the ending for the length() when the Last calls it.

A: If it's separated by a space why not use the split() method:
String info = "John Doe 12345 99";
String[] seperatedInfo = info.split(" ");
String firstName = seperatedInfo[0];
String lastName = seperatedInfo[1];
int ID = Integer.parseInt(seperatedInfo[2]);
double pay = Double.parseDouble(seperatedInfo[3]);
System.out.println(firstName);
System.out.println(lastName);
System.out.println(ID);
System.out.println(pay);

Output:
John
Doe
12345
99

Also side note Java naming conventions for variables is to start with lower case and use camelCase

A: So, assuming you're not allowed to use something like String#split, which would be my personally preferred method, you could, instead, make use of the indexOf functionality, which supplies a couple of different ways to find the index of the a given character or String within a String.
So, something like...
String text = "John Doe 12345 99";
int index = text.indexOf(" ");
int lastIndex = 0;
while (index > -1) {
    String part = text.substring(lastIndex, index);
    System.out.println("[" + part + "]");
    lastIndex = index + 1;
    index = text.indexOf(" ", lastIndex);
}
if (lastIndex != 0) {
    String part = text.substring(lastIndex);
    System.out.println("[" + part + "]");
}

prints out...
[John]
[Doe]
[12345]
[99]

What I would do, is modify the above to maintain a "counter", which represents the current element you are "extracting" and then add that to the corresponding array element
Caveat: This will work for single "spaces" only, so just beware of that.  You could also make use of String#trim to trim of leading and trailing spaces, but would require you to manually disassemble the String (using String#substring)

A: There are several ways you can parse that String, I would start by spliting it; then assign the tokens as desired. Something like,
String info = "John Doe 12345 99";
String[] tokens = info.split("\\s+");
String first = tokens[0], last = tokens[1];
int id = Integer.parseInt(tokens[2]);
double wage = Double.parseDouble(tokens[3]);
System.out.printf("%d %s, %s %.2f%n", id, last, first, wage);

Which outputs
12345 Doe, John 99.00

Filling tokens without split is still the approach I would take if limited in the methods I can use. You know there are four tokens, and you can use successive calls to indexOf(char) to find spaces. Like,
String info = "John Doe 12345 99";
int p = 0, c = 0;
String[] tokens = new String[4];
while (c < 4) {
    int p1 = (c != 3) ? info.indexOf(' ', p) : info.length();
    tokens[c] = info.substring(p, p1);
    p = p1 + 1;
    c++;
}

The rest of the answer above does not need to change.

A: You can also use StringTokenizer class.
Example:
    String str = "John Doe 12345 99";
    String delimeter = " ";
    StringTokenizer stringTokenizer = new StringTokenizer(str, delimeter);
    while (stringTokenizer.hasMoreTokens()) {
        System.out.println(stringTokenizer.nextToken());
    }


text:
Q: Clean Architecture. UseCase usage? I was wondering what is the exact application of UseCase in Clean Architecture. Since, nowadays when you have a remote data source or rest API, the heavy processes are done on the server-side so you don't have any logic to implement in UseCase. All logic is state management, to handle loading errors, etc. and these have to be inside state management. Am I wrong? Do you have a scenario where UseCases are needed?

A: BLOCs control the state of widgets. Ideally, they don't have business logic. They just use UseCases.
UseCases (or Interactors) are a business logic of application. They use entities and abstract repositories. They're needed when you want to use the same business logic in several blocs. Instead of copy paste the piece of code from the existed bloc you just make 1 UseCase and use it in all the blocs you want.

*

*UseCase uses abstract repositories. It means that UseCase doesn't depend from data source. It could be Firestore, REST api, local database etc. UseCase just know that repository returns Entities. Business logic becomes independent from data source and easy to test.

*API calls are made in repository implementations. For example, we have abstract class "Repository" and it's implementations: "FirebaseRepository", "ApiRepository", "LocalRepository" etc. Thanks by polymorpthysm we can create UseCases and give them these repository implementations via constructors. It's recommended to use dependency injector like get_it.

*Bloc doesn't contain any business logic. In Clean Architecture terms bloc = controller + presenter. Bloc just uses UseCases and business logic can be reused between several blocs.

A: Imho even though there is hardly any logic to implement in UseCase, for example just passing params. Creating useCase will allow us freely change the repository based on our needs. For example, different apps use different logic in the repository.
Clean Architecture benefit is not only about layering logic, but how to increase reusability, testability, and scalability (easier to change and modify in the future)


text:
Q: Convert Qt Project to Dev C++ project? So basically I have a "PLAIN c++" Qt project created with:
qt-windows-opensource-5.2.0-mingw48_opengl-x86-offline

And I need to open it with "Dev C++ 4.9", quite simple que pro file looks like:
TEMPLATE = app
CONFIG += console
CONFIG -= app_bundle
CONFIG -= qt

SOURCES += main.cpp \
    palabra.cpp \
    menu.cpp \
    app.cpp \
    ahorcado.cpp

HEADERS += \
    palabra.h \
    menu.h \
    app.h \
    ahorcado.h \
    keypress.h

Need to do it ASAP.


text:
Q: Do not widen potential literal types in object literal I frequently use immutable objects composed of strings and numbers. For example:
const InternalServerError = {
    status: 500,
    message: 'Internal Server Error'
}

I never change the properties, so I would prefer the type of InternalServerError to use number and string literals, like this:
{
    status: 500,
    message: 'Internal Server Error'
}

However, TypeScript automatically widens the types in the inferred type of InternalServerError:
{
    status: number,
    message: string
}

I could cast each property to its literal type, like this:
const InternalServerError = {
    status: 500 as 500,
    message: 'Internal Server Error' as 'Internal Server Error'
}

But this has two problems:

*

*Repetition, especially for long strings

*It's possible to cast the value to the wrong literal type (500 as 501 for example) and the compiler will not complain, making this susceptible to typos.

What is the easiest (least boilerplate code or repetition) and most type safe (least possibility for uncaught type errors) way to achieve this?

A: You can create an helper function with generics to infer precise types (500 instead of number for example) :
function makeError<
    S extends number,
    M extends string
>(status: S, message: M): {status: S, message: M} {
    return {status, message}
}

const InternalServerError = makeError(500, 'Internal Server Error')
const NotFoundError = makeError(404, 'Not found')

// Code = 500
type Code = (typeof InternalServerError)['status']
// Message = Internal Server Error
type Message = (typeof InternalServerError)['message']


text:
Q: Is there a way to programmatically hide an carbon application on osx? I have a carbon C++ application and I would like to programmatically do the equivalent of Command-H (to hide the application) which is available in the Application menu for my app. I have explored the carbon API for TransitionWindow and HideWindow and while these can hide my window, they do not do the equivalent of Command-H. I looked into the AppleEvent reference on the offhand I needed to create an AppleEvent but I didn't see one for hide application. Any thoughts?

A: Sorry to answer my own question but the ShowHideProcess() API seems to do what I want. If there are better solutions I would love to hear them.

A: Just a note: hiding a Window is very different to hiding an Application.

A: You can also send a kHICommandHide ('hide') command event from the Carbon Event Manager (which is what that menu item does, and which calls ShowHideProcess() when processed) if you prefer, for instance if you'd like this action to be materialised by an event.

A:
I looked into the AppleEvent reference on the offhand I needed to create an AppleEvent but I didn't see one for hide application. Any thoughts?

I'm no expert but you can just use AppleEvent to set the visible property of a process to false – at least it works with an AppleScript
tell application "System Events"
    set visible of process "xyz" to false
end tell

On the other hand, your API seems to be the most direct way and the above code probably just uses it as well.


text:
Q: In mySQL, can you update a newly created table with fields from existing tables? I am new to mySQL and would like some help with a query I'm running. I'd like to update a newly created table with fields from existing tables. Here is what I'm working with.
UPDATE NEW_TABLE new, OLD_TABLE_1 one, OLD_TABLE_2 two, OLD_TABLE_3 three
SET
new.COLUMN_1 = one.COLUMN_1,
new.COLUMN_2 = one.COLUMN_2,
new.COLUMN_3 = one.COLUMN_3,
new.COLUMN_4 = two.COLUMN_1,
new.COLUMN_5 = two.COLUMN_2,
new.COLUMN_6 = three.COLUMN_1,
new.COLUMN_7 = three.COLUMN_2
WHERE
  three.COLUMN_1 = two.COLUMN_1 AND
  three.COLUMN_2 = one.COLUMN_1;

My data is all HR data. OLD_TABLE_1 is address information, OLD_TABLE_2 is medical information, and OLD_TABLE_3 is the original HR data.
In the where clause, three.COLUMN_1 has a relationship with two.COLUMN_1. Imagine that three.COLUMN_1 is the user's ID and it maps to a user's ID in two.COLUMN_1. Also imagine that three.COLUMN_2 is a user's home phone number that maps to a user's home phone number in one.COLUMN_1. When the data is entered into the new table, I only want data for a unique individual.
The reason for creating a new table is to optimize reporting. Drawing data from three tables is time consuming. I have large tables over 150GB in size. If I can load the data I need into a temp table, the query will run much quicker.
Any help would be greatly appreciated. Thanks in advance.

A: If this is a brand new table, you'd want to INSERT instead of UPDATE.
INSERT INTO NEW_TABLE
    (COLUMN_1, COLUMN_2, COLUMN_3, COLUMN_4, COLUMN_5, COLUMN_6, COLUMN_7)
    SELECT one.COLUMN_1, one.COLUMN_2, one.COLUMN_3, two.COLUMN_1, two.COLUMN_2, three.COLUMN_1, three.COLUMN_2
        FROM OLD_TABLE_1 one
            INNER JOIN OLD_TABLE_3 three
                ON one.COLUMN_1 = three.COLUMN_2
            INNER JOIN OLD_TABLE_2 two
                ON three.COLUMN_1 = two.COLUMN_1


text:
Q: Segue to page view controller prevents to take data from array I have problem with app that I am creating. At this app I have added page view controller. When segue is directed to Page view controller. Pages can be scrolled but, it cannot take data from array, which is defined. But when segue is directed to the view controller, it takes data from array, but not scrolling pages, because it is not directed to page view controlled.
1 - image


text:
Q: How To Run And Test a Windows Services In VS I created a windows service in VS:File->New Project->C#->Windows Services
But I don't know how to run and test it.VS says I have to install my windows services to run it.but I Just want to test it and I don't want to install it.Can anybody Help me???

A: To debug your Windows service, add the following in your Main():
if (!Environment.UserInteractive) {
    // We are not in debug mode, startup as service

    ServiceBase[] ServicesToRun;
    ServicesToRun = new ServiceBase[] { new MyServer() };
    ServiceBase.Run(ServicesToRun);
} else {
    // We are in debug mode, startup as application

    MyServer service = new MyServer();
    service.StartService();
    System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
}

And the following method in your class MyServer:
public void StartService() {
    this.OnStart(new string[0]);
}

Now hit F5 to debug, as any winform or console application.

A: When creating a Windows Service I usually put all functionality into a separate class library... for testing I create a "normal app" which makes use of the class library...
AFTER the functionality is tested and the bugs are gone I do build/install the Windows Service... there can be problems specific to Windows Service like permissions etc. - these need to be addressed accordingly (some logging is usually very helpful).
Debugging a Windows Service with VS is a bit different from debugging an application - for details see http://msdn.microsoft.com/en-us/library/7a50syb3.aspx

A: A windows service is not really a normal executable, it builds as exe but has to be installed and started with Services icon from Control Panel.
Once you got it installed and started you can use Visual Studio Debug menu, Attach to process and attach to the service to debug it, not the simplest and fastest way to debug because if you need to change anything you have to build it again and install it again, start and attach again.
Usually a nice approach is to anyway split and isolate the logic of the service in a class library (probably the service business logic) which can be used also from let's say a console application.
At this point you create a test console application which calls some methods and behaves kind of like the service from the Main method and you test and debug this one.
Once everything has been tested and verified and you are satisfied with the results you copy the code you have put in the Main method of the test console application in the Service class, probably in the OnStart method or similar, details depend on your specific design.
we do this also to debug and test WCF services which are hosted in a test console app during development and in a Windows Service in production.

A: you should use visual studio command prompt with the following command:
installutil "the path of the exe"
and the go to Services (start-> run-> services.msc) you will find the service. click on start and you're done.
P.S: to debug your service in vs: tools-> attach to process and find your service in the list)

A: You cannot debug service directly from VS. Need to attach the debugger to Windows Service.
To do it, in VS do following:

*

*From the Debug menu, select Attach To Process…

*Near the bottom of the window, select Show processes in all sessions.

*Left-click the compiled EXE to be run as the Windows Service in the list. Press Attach.

Result: you can place breakpoints at places in your functions, and you'll be able to debug the service execution.


text:
Q: Ошибка в скрипте Unity К обьекту прикрепил данный скрипт, цель: автоматическое смещени е обьекта по оси Y, в итоге ничего не срабатывает. В чем проблема?
 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;

 public class move : MonoBehaviour {
    void Start () {
        transform.position.y += 1;
    }

    void Update () {
        transform.position.y += 1;
    }
}

A: Вам выдаёт вполне очевидную ошибку - невозможно изменить значение, т.к. оно не является переменной.
transform.position - возвращает вам Vector3.
Vector3 в Unity является значимым типом, который нельзя изменять. Другими словами, вы можете создать вектор с какими-то значениями, например new Vector3(1, 1, 1), но после этого не сможете изменить в нём эти значения. Это связано с оптимизацией производительности и исключения некоторых частых ошибок.
Другими словами, в transform.position вам нужно назначать новый вектор, который будет равен вектору текущего положения + вектор смещения.
transform.position = transform.position + new Vector(0,1,0);

Перегруженный оператор += позволит вам сократить выражение. Он сам возьмёт текущее значение, прибавит к нему ваш вектор и потом назначит обратно.
transform.position += new Vector(0,1,0);


text:
Q: how to include css in view file I have included css in view file as below
<link rel="stylesheet" type="text/css" href="<?php echo $this->baseUrl('style/root.css'); ?>" />
<link rel="stylesheet" type="text/css" href="<?php echo $this->baseUrl('style/reset.css'); ?>" />

But it is giving this error ->
  <b>Message:</b> Invalid controller specified (style)  </p>

in application.ini, I have used this
resources.frontController.baseUrl = "/zendtest/public"
resources.view[] = "";

How do I solve this issue?

A: The code bellow worked for me , ( i suppose you have your css file  in 'Public/css/bootstrp.css' ) and paste the line in the head of your View.
<link href="<?php echo $this->baseUrl() . '/css/bootstrap.css'; ?>" media="all" rel="stylesheet" type="text/css" />

A: in any view file (.phtml extension) use something like this for javascript or css:
$this->headScript()->prependFile('/scripts/jquery.min.js');
$this->headScript()->appendFile('/scripts/fg.menu.js');

$this->headLink()->appendStylesheet('/css/form.css');
$this->headLink()->prependStylesheet('/css/jquery_ui_theme/jquery-ui.custom.css');

A: Take a look at the headLink() view helper, that will do exactly what you are looking for.


text:
Q: Minimagick gem fails to convert multipage PDF to several png images I am new to RoR and I'm trying to develop a slide sharing app through which users can upload and share a multipage PDFs containing a deck of slides (one slide per page). Viewers can then view these slides on a "show" page.
Behind the scenes I am trying to convert the multipage pdf into several .png files (1 pdf page -> 1.png file), and then display them in a carousel/slider fashion.
Here is my uploader:
# encoding: utf-8

class DocUploader < CarrierWave::Uploader::Base

# Include RMagick or MiniMagick support:
# include CarrierWave::RMagick
  include CarrierWave::MiniMagick

# Choose what kind of storage to use for this uploader:
  storage :file
# storage :fog

# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
  def store_dir
  #  'public/doc_uploads/'
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  process :filename
  process :generate_png

  def generate_png
    pdf = MiniMagick::Image.new(self.file.path)
    pdf.pages.each_with_index do |page, index|
      page.write("page#{index}.png")
    end
  end

  # Add a white list of extensions which are allowed to be uploaded.
  # For images you might use something like this:
    def extension_white_list
      %w(pdf)
    end

  # Override the filename of the uploaded files:
  # Avoid using model.id or version_name here, see uploader/store.rb for details.
  def filename
    'doc.pdf' if original_filename
  end

end

When I try to upload a multipage pdf document, it throws me this error:
     'identify /public/uploads/tmp/1443619784-406-3861/doc.pdf' failed with error: at the line pdf.pages.each_with_index do |page, index|
I have tried different solutions to converting the document, but none of them have worked for me so far. Why would a run of the mill .pdf file fail minimagick's validation? Is there anything I can do to avoid running into this issue? Any advice will be greatly appreciated!


text:
Q: Persisting an array to use on another html page I need to be able to display from information in an array.
A selection is chosen by checkboxes, which is stored in the temporarySelection, then the temporarySelection info is transferred to other arrays (eg. added to restaurantSelection, then cleared for the next choices).
I need to then be able to display these arrays on a separate html page.
There's 4 different arrays to transfer to the second html page, placeSelection, hotelSelection, restaurantSelections, and sightSelections.
I've had a look around, tried a few different things, but nothing seems to be working.
Any ideas?
I've already attempted to use localstorage in a function (although I may not hav got it quite right).
Looked into cookies but I've been told not to do this as it is unnecessary as only Javascript will be using it.
function chooseSelection(resultIndex) {

    var locationName = document.getElementById('locationName-' + resultIndex);

    if(!temporarySelection.includes(locationName.innerHTML)) {
        console.log('pushing ' + locationName.innerHTML + ' into
        temporarySelection')
        temporarySelection.push(locationName.innerHTML);
    } else {
        var index = temporarySelection.indexOf(locationName.innerHTML);
        console.log('Removing index number: ', index)
        temporarySelection.splice(index, 1);
    }
}

I hope that the second html page, the "results page" will show the arrays for placeSelection, hotelSelection, restaurantSelections, and sightSelections in 4 separate boxes.

A: Not sure how you are setting local storage. Below are the two small functions to set and get values for your array in store.
function setStore(temporarySelection){
    localStorage.setItem("temporarySelection", JSON.stringify(temporarySelection));
}

function getStore(){
        const temporarySelection  = localStorage.getItem("temporarySelection");
      if(temporarySelection)
      {
        return JSON.parse(temporarySelection)
      }
      else{
        return [];
      }
    }

Here is your code with these functions in use
function chooseSelection(resultIndex) {

    var locationName = document.getElementById('locationName-' + resultIndex);

    if(!temporarySelection.includes(locationName.innerHTML)) {
        console.log('pushing ' + locationName.innerHTML + ' into
        temporarySelection')
        temporarySelection.push(locationName.innerHTML);
    } else {
        var index = temporarySelection.indexOf(locationName.innerHTML);
        console.log('Removing index number: ', index)
        temporarySelection.splice(index, 1);
    }
    setStore(temporarySelection)
}

Now you can get your store values with getStore function in any page.


text:
Q: How to send data to iOS by use of PAN We are looking for a bluetooth solution to send 18Mb of data from some kind of sensor to an iPhone/iPad.
Bluetooth Low Energy is way to slow for this (4kb/s or something like that). Using classical Bluetooth however, requires an MFI program (Made For iPhone/iPad) enrolment. But for some default supported protocols in which PAN (Personal Area Network) this MFI enrolment isn't needed.
I spend the whole day doing research on the internet but couldnt find a implementation of PAN data transfer between a device and an iOS app. I am hoping I can somehow connect to a bluetooth device and send serial data to my app. So my last hope is (again) StackOverflow.
Does any of you have an implementation or example or at least a way to solve this problem?


text:
Q: Fabric-test setup error I am trying to setup fabric-test repo.
While running:
make docker

command from fabric-test/fabric folder I am receiving the following error:
**mkdir -p .build/image/tools

Building docker tools-image

docker build  -t hyperledger/fabric-tools -f .build/image/tools/Dockerfile .
Sending build context to Docker daemon 44.25 MB

Step 1/13 : FROM hyperledger/fabric-baseimage:amd64-0.4.8 as builder
Error parsing reference: "hyperledger/fabric-baseimage:amd64-0.4.8 as builder" is not a valid repository/tag: invalid reference format

Makefile:290: recipe for target '.build/image/tools/.dummy-amd64-1.2.0-snapshot-963ce19' failed

make: [.build/image/tools/.dummy-amd64-1.2.0-snapshot-963ce19] Error 1**

Has anyone faced this issue and resolved it?
I am relatively new to Hyperledger technologies.
Thanks in advance.
Edit : Resolved by updating the docker version. Older version of docker doesn't support multi-stage builds.

A: Resolved by updating the docker version. Older version of docker doesn't support multi-stage builds.


text:
Q: Difference between stack and listview in flutter I recently came to see that when displaying a list of widgets, stack and listView don't work the same way.
here is an example :
With this code the I got list of two items of listData widget ( a custom widget )
new ListView(

          children: <Widget>[

       new Container(
         child: ListData(
             margin: EdgeInsets.all(4.0),
             width: screenSize.width,
             title: "Breakfast with Harry",
             subtitle: "9 - 10am ",
             image: DecorationImage(image: AssetImage('assets/avatar-1.jpg'),
               fit: BoxFit.cover,))
       ),
       new Container(
           child: ListData(
               margin: EdgeInsets.all(4.0),
               width: screenSize.width,
               title: "Breakfast with Harry",
               subtitle: "9 - 10am ",
               image: DecorationImage(image: AssetImage('assets/avatar-1.jpg'),
                 fit: BoxFit.cover,))
       ),

          ],
          )

When replacing ListView with stack
new Stack(

          children: <Widget>[

       new Container(
         child: ListData(
             margin: EdgeInsets.all(4.0),
             width: screenSize.width,
             title: "Breakfast with Harry",
             subtitle: "9 - 10am ",
             image: DecorationImage(image: AssetImage('assets/avatar-1.jpg'),
               fit: BoxFit.cover,))
       ),
       new Container(
           child: ListData(
               margin: EdgeInsets.all(4.0),
               width: screenSize.width,
               title: "Breakfast with Harry",
               subtitle: "9 - 10am ",
               image: DecorationImage(image: AssetImage('assets/avatar-1.jpg'),
                 fit: BoxFit.cover,))
       ),

          ],
          )

I get only one item, and from the inspector it seems all the items are on top of each other.
Isn't stack and listview supposed to work the same way ?

A:
Isn't stack and listview supposed to work the same way?

No, not at all. Stack and ListView are very different.

*

*ListView is for a vertical/horizontal scrollable list. It is similar to Row/Column but its content is scrollable.

*Stack is to freely position multiple widgets under the same parent. It's commonly used to stack widgets on the top of each other.


text:
Q: suppose that $H \leq G$ and $N \unlhd G$ and $(|H|,|G:N|) = 1$ then prove that $H \leq N$ suppose that $H \leq G$ and $N \unlhd G$ and $(|H|,|G:N|) = 1$ then prove that $H \leq N$
I don't know how to start ! I know that I should prove that $H \subseteq N$!Can N be infinite subgroup?Can any one help me to prove this?

A: Hint: Consider the image of $H$ under the canonical projection $G\to G/N$.

A: Let $n=|H|$, $m=|G:N|$. Then for $h\in H$,
$$(hN)^n=h^nN=1N=N$$
so the order of $hN$ divides $n$, and it also divides $m$ by Lagrange's Theorem because $|G/N|=m$. But the only positive integer dividing both of these is $1$, so $|hN|=1$, i.e. $hN=N$ and $h\in N$. Therefore $H\le N$.


text:
Q: What to do if an exact permutation test is infeasible For permutation tests, it is often infeasible to enumerate all permutations. There are two approaches to solve this. The first uses a random number of permutations instead of all permutation (this is sometimes called approximate, or Monte Carlo). The second uses a parametric distribution to which the permutation distribution should converge to (this is called asymptotic).
I am wondering whether there are any guidelines on which of these approaches to prefer. I guess this is difficult to answer in general. So, let's take the Wilcoxon-Mann-Whitney (WMW) test as an example. For this example, my question is of practical relevance for many applied researchers as SPSS gives you the option to choose between the exact, the approximate, or the asymptotic approach. In case there is enough time to calculate the exact $p$-value, the choice is clear, but what to do if this is not the case? Should you use the approximate or the asymptotic approach?
For the approximate approach, SPSS uses 10000 random permutations per default. This default is also present in equivalent R packages. So, this makes the question even very concrete: What should be preferred (under which condition): The approximate version of the WMW test with 10,000 random permutations or the asymptotic approach?
In my experience, if the sample size is big enough that an exact value cannot be determined anymore, I would expect only minimal differences between the approximate and the asymptotic approach. But I would love to have a better answer to this question.


text:
Q: Specifying varnish's default virtual-host I'm using Varnish-3.0.5 on Scientific Linux 6.4 (64bit):
$ rpm -q varnish
varnish-3.0.5-1.el5.centos.x86_64
$ cat /etc/redhat-release
Scientific Linux release 6.4 (Carbon)
$ uname -a
Linux XXX.XXX.XXX 2.6.32-358.23.2.el6.x86_64 #1 SMP Wed Oct 16 11:13:47 CDT 2013 x86_64 x86_64 x86_64 GNU/Linux
$ curl XXX.XX.XX.XXX

  <title>Page Unavailable</title>

Page Unavailable

The page you requested is temporarily unavailable.

We're redirecting you to the homepage in 5 seconds.

(Error 503 Service Unavailable)

$

I trying to figure out how I can configure default virtual-host as I'm getting Error 503 Service Unavailable if at least one of my back-end(s) is down whenever I run curl against IP address. Do I need to specify IP address in req.http.host as well inside of vcl_recv() in order for me to stop getting 503? or how else do I specify which virtual-host is default?

A: Fist of all let me say that it's quite difficult to give advices without seen your actual VCL config.
To respond your actual question
You can set a default host at the beginning of your vcl_recv, note that your backend(s) should be configured to respond to that exact host
sub vcl_recv {
  /* set a default host if no host is provided on the request or if it is empty */
  if ( ! req.http.host
    || req.http.host == "") {
    set req.http.host = "your.default.host.tld";
  }
  # ...

}

I think you don't have to mess with IPs and req.http.host, you should better use curl to pass a host header to varnish (something like curl -H "Host: your.default.host.tld" http://XX.XX.XX.XXX/)

Some general suggestions on the topic:
Add misbehaving control logic to your VCL [1]
Are you setting your backend correctly?
Remember that varnish will uses "default" backend (or director) unless instructed to use other on your VCl logic
Add health probes and see what backends are failing
Use consistent health probes [2] and use commandline command varnishadm debug.health see the docs for a better understanding [3]
Add a restart logic to your vlc error
Something like this
sub vcl_error {
  # ...

  /* Try to restart request in case of failure */
  if (obj.status == 503 && req.restarts < 5) {
    set obj.http.X-Restarts = req.restarts;
    return(restart);
  }

  # Before any deliver
  return (deliver);
}

Add debug logic to your vlc error synthetic response
Remember that you can add debug headers on vcl_fetch passing backend error code to your varnish error response:
sub vcl_fetch {
  # ...

  set beresp.http.X-Debug-Backend-Code = beresp.status;

  # ...
}
sub vcl_error {
  # ...

  synthetic {""
  # Insert the following at the end of your current response

Backend Status code was "} + obj.http.X-Debug-Backend-Code + {"

  "};

  # ...

  return (deliver);
}

[1] https://www.varnish-cache.org/docs/3.0/tutorial/handling_misbehaving_servers.html
[2] https://www.varnish-cache.org/docs/3.0/reference/vcl.html#backend-probes
[3] https://www.varnish-cache.org/trac/wiki/BackendPolling#CLIcommands


text:
Q: Expected value of $\max\{X_1,\ldots,X_n\}$ where $X_i$ are iid uniform. Let $X_i\sim\mathrm{Uniform}(0,\theta)$ be iid, what is $E[\max\{X_1,\ldots,X_n\}]$? Apparently the answer is $$\frac{n}{n+1}\theta,$$
but I do not see why?
It seems intuitive in that you would "expect" them to be spaced out evenly, hence the maximum would be $\frac{n}{n+1}$-of-the-way along the interval, but how can we prove this mathematically? I feel like it should be simple, but evidently $$E[\max\{X_1,\ldots,X_n\}]\neq\max\{E[X_1],\ldots,E[X_n]\}.$$
Thanks.

A: Your intuition is correct.
To see this mathematically, suppose $X_1, \ldots, X_n$ are independent and uniformly distributed and  $M_n = \max(X_1,X_2,\ldots,X_n).$
The distribution function of the maximum is the joint probability that $X_k \leq x$ for all $k.$ This is a product of marginal probabilities since the variables are independent.
$$ F_M(x)=P(M_n \leq x) =P(X_1 \leq x,\ldots,X_n \leq x)=(x/\theta)^n$$
for $0 \leq x \leq \theta$.
Also $F_M(x) = 0$ for $x < 0$ and $F_M(x) = 1$ for $x > \theta$.
Hence, the probability density function on $[0,\theta]$ is
$$f_M(x)=F'_M(x)=nx^{n-1}\theta^{-n}$$
and the expected value is
$$E(M_n) = \theta^{-n}\int_0^{\theta}xnx^{n-1}\, dx=\frac{n}{n+1}\theta.$$

A: Here is a brute force answer:
With appropriate scaling, we can take $\theta =1$ without loss of generality.
Let $\sigma$ be a permutation of $1,...,n$ and $A_\sigma = \{ x \in [0,1]^n | x_{\sigma_1} > \cdots > x_{\sigma_n} \}$.
Note that $p ([0,1]^n \setminus (\cup_\sigma A_\sigma ) ) = 0$, and
$E (\max(X_1,...,X_n) 1_{A_\sigma} (X_1,...,X_n) ) = E (\max(X_1,...,X_n) 1_{A_{\sigma'}}(X_1,...,X_n) )$ for
any two permutations $\sigma, \sigma'$.
Hence $E \max(X_1,...,X_n) = n! E (\max(X_1,...,X_n) 1_{A_\sigma} (X_1,...,X_n))$ for any $\sigma$.
Let $\sigma$ be the identity permutation, then if $(X_1,...,X_n) \in A_\sigma$
we have $\max(X_1,...,X_n)  = X_1$ and so
\begin{eqnarray}
E (\max(X_1,...,X_n) 1_{A_\sigma} (X_1,...,X_n)) &=& \int_{x_1=0}^1 \int_{x_2=0}^{x_1} \cdots \int_{x_n=0}^{x_{n-1}} x_1 dx_n \cdots dx_1 \\
&=& {1 \over (n+1)(n-1)!}
\end{eqnarray}
Hence $E \max(X_1,...,X_n) = { n! \over (n+1)(n-1)!} = {n \over n+1}$.


text:
Q: Lambda function is outputting memory address instead of actual values when i run the code i get a memory location as an output
<function  at 0x00000200FF8A5E50>
val = (lambda colmns:(colmns.max + colmns.min)/2
print(val)

A: A lambda is just an anonymous function object and that's why it prints that way. In fact, as soon as you assign it to a variable... then why have a lambda in the first place? Might as well do
def foo(colmns):
    return (colmns.max + colmns.min)/2

And then it wouldn't be too surprising that print(foo) is <function 0x...>.


text:
Q: Autodesk Maya per pixel surface position and normals through whole scene how can I get in maya per pixel all surface positions and normals of the entire scene.
I don't want to stop at the first viewed surface of the camera. I need to get information about all object. I want to traverse the whole scene
For example a cube is in front of the sphere. The camera position just shows the cube - the sphere gets at that camera position by the cube. My output of every pixel position of my camera rendered image data gives me information of the surface position in world space and the normal of the cube at the first hit. Then again for the other side of the cube. Then the two surfaces of the sphere.
How can that be achieved?
Thanks


text:
Q: Add value to DataPoint by user How to add values to DataPoint which to be plotted in case I do not know number of possible entries?
     DataPoint[] db = new DataPoint[]{
            new DataPoint(5,4),
            new DataPoint(2,4),
            new DataPoint(4,4),
            new DataPoint(9,0),
            new DataPoint(0,3)} ;
    PointsGraphSeries<DataPoint> series = new PointsGraphSeries<DataPoint>(db) ;

A: Make a call to this method before you add DataPoint array to LineGraphSeries.
   private void generateDataForGraph() {
    int size = Amount.size();
     values = new DataPoint[size];
    for (int i=0; i<size; i++) {
        Integer xi = Integer.parseInt(Dates.get(i));
        Integer yi = Integer.parseInt(Amount.get(i));
       DataPoint v = new DataPoint(xi, yi);
        values[i] = v;
    }
 series = new LineGraphSeries<DataPoint>(values);
        graph2.addSeries(series);
}


text:
Q: Derivative of $\exp[(aX+Y)t]$ w.r.t $a$ where $X,Y$ are matrices of dimension $n\times n$ Let $X,Y\in\mathbb{R}^{n\times n}$ and define
$$
F(a,t) = \exp[(aX+Y)t].
$$
Then, compute
$$
\frac{\partial F}{\partial a} = ?
$$
My attempt: Let $M_a = aX + Y$, then
$$
\frac{\partial F}{\partial a} = \frac{\partial}{\partial a} ( I_n + M_a t + M_a^2 t^2 / 2! + M_a^3 t^3 / 3! + \dots ).
$$
Since $\partial M_a^k /\partial a = \sum_{j=0}^{k-1} M_a^j X M_a^{k-1-j}$, we obtain
$$
\frac{\partial F}{\partial a} = \sum_{k=1}^\infty \sum_{j=0}^{k-1} M_a^j X M_a^{k-1-j} \frac{t^k}{k!}.
$$
The question, therefore, is that whether it's possible to write this power series as a function?

A: $\def\m#1{\left[\begin{array}{c}#1\end{array}\right]}\def\p#1#2{\frac{d #1}{d #2}}$Given a scalar function, like $f(x)=\exp(x)$, and the matrices
$$\eqalign{
M = M(a)&= aXt + Yt,\qquad &\dot M = \dot M(a) = \p{M}{a} = Xt \\
F = F(a) &= f(M),
&\dot F = \dot F(a) = \p{F}{a} \\
}$$
Evaluating the function with a block-triangular argument yields
$$\eqalign{
B \;=\; f\left(\m{M&\dot M\\{0}&M}\right) \;=\; \m{F&\dot F\\0&F} \\
}$$
Block-matrix analogs of the standard basis vectors
$$\eqalign{
e_1 &= \m{1\\0} \quad &e_2 = \m{0\\1} \\
E_1 &= e_1\otimes I_n \qquad &E_2 = e_2\otimes I_n \\
}$$
can be used to extract the upper-right block, which one might call a closed-form solution
$$\eqalign{
\dot F = E_1^T B\, E_2 \\
}$$


text:
Q: How to bypass login using cookie in Selenium Java? I looked at multiple sources on the web. For example, https://www.guru99.com/handling-cookies-selenium-webdriver.html
Nothing works as they describe. After adding cookies with driver.manage().addCookie(ck), you still stay on the login page.
Could you, please provide, at least one working example on how to bypass the login screen to speed up the test execution suite in WebDriver Java?

A: I misunderstood the process. The sources I used all copy the same error. Thank you to @pburgr for the hint. The correct process is

*

*Login to the site with your username and password to record the cookies into the file.

*Open login page to get the domain cookies.

*Add cookies from the file to your request and go to the home page bypassing login process.
In the code that is available on the web, they go to the login page in step 3 instead of the home page.

A: as Vladimir said:
driver.get("http://demo.guru99.com/test/cookie/selenium_aut.php");
//read cookies from file and add it to browser
driver.manage().addCookie(cookie);
driver.navigate().refresh();


text:
Q: (C#) How to determine whether it is an enum type using Mono.Cecil? How to determine whether it is an enum type using Mono.Cecil??
It's easy to determine just using Type.IsEnum. But I can not find any similar functions in TypeDefinition...
Is there any way to determine?

A: There's an IsEnum property on TypeDefinition.
Oh, and before you ask your next question, here's how you parse an enum string back to it's int value, using Cecil...
int ParseEnum(TypeReference enumRef, string value)
{
    var enumDef = enumRef.Resolve();
    if (!enumDef.IsEnum)
        throw new InvalidOperationException();

    int? result = null;

    foreach (var v in value.Split(',')) {
        foreach (var field in enumDef.Fields) {
            if (field.Name == "value__")
                continue;
            if (field.Name == v.Trim())
                result = (result ?? 0) | (int)field.Constant;
        }
    }

    if (result.HasValue)
        return result.Value;

    throw new Exception(string.Format("Enum value not found for {0}", value));
}


text:
Q: How do I include external Libraries in CodeIgniter? I'm new to codeigniter, and I'm trying to integrate amazon's FPS into my page. There are a bunch of libraries and models that go with Amazon FPS, which I would need included to make the appropriate calls.
How do I include them in CodeIgniter?
I tried placing the entire Amazon folder inside the system/libraries directory, and then tried including libraries with $this->load->library( 'Amazon/FPS/Client' );
However, I run into problems with the relative path there, because Client.php contains the statement require_once ('Amazon/FPS/Interface.php'); ... which is in the same folder.
There has to be a better way to do all this - can anyone please help?
Thanks!!

A: There is nothing stopping you from directly including classes and working with them however you would in a vanilla PHP setup. If it works in PHP it will work in CodeIgniter.
include(APPPATH.'libraries/Amazon/FPS/Interface.php');

A: Peng Kong of a3m http://code.google.com/p/a3m/ has a nice way of doing it with plugins:
Example twitter_pi.php

require_once(APPPATH.'modules/account/plugins/libraries/jmathai-twitter-async/EpiCurl.php');
require_once(APPPATH.'modules/account/plugins/libraries/jmathai-twitter-async/EpiOAuth.php');
require_once(APPPATH.'modules/account/plugins/libraries/jmathai-twitter-async/EpiTwitter.php');
/* End of file twitter_pi.php /
/ Location: ./system/application/modules/account/plugins/twitter_pi.php */
In controller
$this->load->plugin('twitter');
$twitterObj = new EpiTwitter($this->config->item('twitter_consumer_key'), $this->config->item('twitter_consumer_secret'));
There is one problem with this in Codeigniter 2.0 there are no plugins

A: Oh yes codeigniter is nice and has also support for many librarys please have a look here
http://www.haughin.com/code/
Include the Amazon service like this $this->load->library('s3');

A: @user3526
Note that $this->load->library('classname') will create an instance of that loaded class, not just file (class) include.


text:
Q: Dynamic data loading in codeigniter Need help on codeigniter. I want to load dynamic data in div section which
   will be based on dropdown's(#assettype_id) selected value. I am using ajax
   method call (basically calling controller method) on dropdown change event. I
  am passing dropdown selected value as a parameter of ajax call and based on
  dropdown's value result will load on div tag.Below code is working perfectly on
  dropdown's first event change but when i select another value from dropdown
  data will not get changed?? I checked event is firing on every change but not
  loading new data based on selected value?? Why this is happening?? Thanks in
  advance. Please help me....

            <?php
              $js1 ='id="assettype_id", class="dropdown"';
              echo form_dropdown('assettype_id',$drpassettype, set_value('assettype_id'),$js1) ;
            ?>

 // data from ajax call will display here


text:
Q: Error occur while adding controller I am developing MVC 3 application and using razor syntax.(EF 4.0)
I am trying to add controller to my App. but whenever I try to add the controller I get the following error.
I am trying to add controller in test copy as well sourcesafe copy...

And the error is....

When I try add the controller in SourceSafe copy of the same application , below error comes...

How to solve it ?

A: Look into this article, your solution is most likely there.
Edit
Please take a look into this article dealing with specifically "Unsopported context type" during controller scaffolding: Unsupported context type in controller wizard.
Hope you can get ideas and solution from there...
Hope this helps


text:
Q: Neo4j performance in server mode I am learning neo4j. I am accessing neo4j via REST api(s) supported by the server mode. CRUD operations are implemented using neo4jOperations. For experimentation , I have benchmarked its read operations but I have found that methods : 'query' and 'queryForObjects' are taking huge execution time, although I am querying via a field which is indexed. Traversals are not complex.
I have : around 500K+ nodes, 900K+ relationships.
neo4j version : 3.0.8.
Is there any solution to improve the performance of query on neo4j in server mode?

A: Without looking at your actual queries and model it is hard to say why the performance would not be up to your expectations. Try to run the queries through the Neo4j browser and either EXPLAIN or PROFILE them, that may give you a hint of where the issue is.
Having said that, you really should move to version 3.2.1 and access the server over the bolt:/ protocol. That by itself should already significantly improve things.
Regards,
Tom


text:
Q: device function pointers I need a device version of the following
host code:
double (**func)(double x);

double func1(double x)
{
 return x+1.;
}

double func2(double x)
{
 return x+2.;
}

double func3(double x)
{
 return x+3.;
}

void test(void)
{
 double x;

 for(int i=0;i<3;++i){
  x=func[i](2.0);
  printf("%g\n",x);
 }

}

int main(void)
{
 func=(double (**)(double))malloc(10*sizeof(double (*)(double)));

 test();

 return 0;
}

where func1, func2, func3
have to be __device__ functions
and "test"
has to be a (suitably modified) __global__ kernel.
I have a NVIDIA GeForce GTS 450 (compute capability 2.1)
Thank you in advance
Michele
========================================================
A working solution
#define REAL double

typedef REAL (*func)(REAL x);

__host__ __device__ REAL func1(REAL x)
{
    return x+1.0f;
}

__host__ __device__ REAL func2(REAL x)
{
    return x+2.0f;
}

__host__ __device__ REAL func3(REAL x)
{
    return x+3.0f;
}

__device__ func func_list_d[3];
func func_list_h[3];

__global__ void assign_kernel(void)
{
    func_list_d[0]=func1;
    func_list_d[1]=func2;
    func_list_d[2]=func3;
}

void assign(void)
{
    func_list_h[0]=func1;
    func_list_h[1]=func2;
    func_list_h[2]=func3;
}

__global__ void test_kernel(void)
{
    REAL x;
    for(int i=0;i<3;++i){
        x=func_list_d[i](2.0);
        printf("%g\n",x);
  }
}

void test(void)
{
    REAL x;
    printf("=============\n");
    for(int i=0;i<3;++i){
        x=func_list_h[i](2.0);
        printf("%g\n",x);
  }
}

int main(void)
{
    assign_kernel<<<1,1>>>();
    test_kernel<<<1,1>>>();
    cudaThreadSynchronize();

    assign();
    test();

    return 0;
}

A: function pointers are allowed on Fermi.
This is how you could do it:
typedef double (*func)(double x);

__device__ double func1(double x)
{
return x+1.0f;
}

__device__ double func2(double x)
{
return x+2.0f;
}

__device__ double func3(double x)
{
return x+3.0f;
}

__device__ func pfunc1 = func1;
__device__ func pfunc2 = func2;
__device__ func pfunc3 = func3;

__global__ void test_kernel(func* f, int n)
{
  double x;

  for(int i=0;i<n;++i){
   x=f[i](2.0);
   printf("%g\n",x);
  }
}

int main(void)
{
  int N = 5;
  func* h_f;
  func* d_f;
  h_f = (func*)malloc(N*sizeof(func));
  cudaMalloc((void**)&d_f,N*sizeof(func));

  cudaMemcpyFromSymbol( &h_f[0], pfunc1, sizeof(func));
  cudaMemcpyFromSymbol( &h_f[1], pfunc1, sizeof(func));
  cudaMemcpyFromSymbol( &h_f[2], pfunc2, sizeof(func));
  cudaMemcpyFromSymbol( &h_f[3], pfunc3, sizeof(func));
  cudaMemcpyFromSymbol( &h_f[4], pfunc3, sizeof(func));

  cudaMemcpy(d_f,h_f,N*sizeof(func),cudaMemcpyHostToDevice);

  test_kernel<<<1,1>>>(d_f,N);

  cudaFree(d_f);
  free(h_f);

  return 0;
}


text:
Q: Code cannot remove selected Marker from Google Map Hi there I got the following code, where I am trying to add few marker randomly. Then in the second function, trying to delete selected marker. But my markerCoin [i].setMap(null); line seems to have no effect and it doesn't delete the selected marker. Also it does not produce any error.
var markerCoin=[]; // Global Variable

    function addMarker(){
  var max = Math.random() < 0.5 ? -0.0005 : 0.0005;
  var min=Math.random() < 0.5 ? -0.0001 : 0.0001;

  for (i = 0; i < 5; i++) {
    markerCoin [i] = new google.maps.Marker({
      position: new google.maps.LatLng(myLat+ ( Math.random() * (max - min) + min), myLng+ ( Math.random() * (max - min) + min)),
      map: map
    });

    targetLat[i]=markerCoin[i].getPosition().lat();
    targetLng[i]=markerCoin[i].getPosition().lng();

  }
}

function markerDelete() {
  var distance;

  for (i = 0; i < 5; i++) {
    if (targetLat[i]!=0) {
      distance = getDistanceFromLatLonInKm(myLat,myLng,targetLat[i],targetLng[i]);
    }

    if (distance <= 30) {
      alert(distance);
      markerCoin [i].setMap(null);**//it does not remove the marker.**
      targetLat[i]=0;
    }
  }
}

Any suggestions, what is that I am doing wrong?

A: This seems to work for me:
  var markerCoin=[];
  var targetLat=[];
  var targetLng=[];

  function addMarker(){
    var max = Math.random() < 0.5 ? -0.0005 : 0.0005;
    var min = Math.random() < 0.5 ? -0.0001 : 0.0001;

    for (i = 0; i < 5; i++) {
      markerCoin[i] = new google.maps.Marker({
        position: new google.maps.LatLng( myLat + ( Math.random() * (max - min) + min), myLng + ( Math.random() * (max - min) + min)),
        map: map
      });

      targetLat[i]=markerCoin[i].getPosition().lat();
      targetLng[i]=markerCoin[i].getPosition().lng();

    }
  }

  function markerDelete() {
    var distance;

    if (targetLat[i]!=0) {
      distance = getDistanceFromLatLonInKm(myLat,myLng,targetLat[i],targetLng[i]);
    }

    if (distance <= 30) {

      for (i = 0; i < 5; i++) {
        markerCoin[i].setMap(null);
        targetLat[i]=0;
      }
    }
  }

  addMarker();
  markerDelete();

Checkout this slightly modified JSFiddle.


text:
Q: How to get a list of selected rows in Syncfusion.WPF.DataGrid? I use Syncfusion in my WPF project. The following is a DataGrid with multiple selection modes:
<grid:SfDataGrid x:Name="dataGrid"
                 SelectionMode="Multiple"
                 Grid.Row="0"
                 SelectedItems="{Binding SelectedRows}"
                 BorderThickness="1"
                 NavigationMode="Row"
                 BorderBrush="Black"
                 CellStyle="{StaticResource ResourceKey=cellStyle}"
                 AutoGenerateColumns="False"
                 HeaderStyle="{StaticResource ResourceKey=headerStyle}"
                 ColumnSizer="AutoLastColumnFill"
                 ItemsSource="{Binding PagedSource, ElementName=dataPager}">
                        <grid:SfDataGrid.Columns>

                            <grid:GridCheckBoxSelectorColumn MappingName="SelectorColumn"
                                                             Width="30" />

                            <grid:GridTextColumn  AllowDragging="False"
                                                  HeaderText="Id"
                                                  MappingName="EquipmentId"
                                                  IsHidden="True" />
                            <grid:GridTextColumn  AllowDragging="False"
                                                  HeaderText="Code"
                                                  MappingName="EquipmentCode" />
                            <grid:GridTextColumn  AllowDragging="False"
                                                  HeaderText="Title"
                                                  MappingName="EquipmentTitle" />
                        </grid:SfDataGrid.Columns>

                    </grid:SfDataGrid>

I want to get a list of selected rows (their Ids that exist in the first hidden column) in the ViewModel. How can I achieve this?
Note: I use Microsoft.Toolkit.MVVM in my project.

A: i dont know if it helps but i know how to only get the selected item by using
this in xaml side
<grid:SfDataGrid x:Name="dataGrid" SelectionChanged="GetSelected">

this is in c# side
private void GetSelected(object sender, SelectionChangedEventArgs e)
        {
Object selectedItem = dataGrid.SelectedItem as Object;

        }

A: I used SelectedItems="{Binding SelectedItems, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" in the XAML code and then, I used the following property in the ViewModel:
  public class EquipmentIdentitySettingViewModel: ObservableObject {
  //...Some codes here
  private ObservableCollection < object > _selectedItems;

  public ObservableCollection < object > SelectedItems {
    get {
      return _selectedItems;
    }
    set {
      SetProperty(ref _selectedItems, value);
    }
  }
  public ICommand ApplyCommand {
    get;
  }
  public EquipmentIdentitySettingViewModel() {
    ApplyCommand = new RelayCommand(() => ApplyChanges());
  }
  private void ApplyChanges() {
    if (SelectedItems != null) {
      foreach(Equipment item in SelectedItems) {
        MessageBox.Show(item.EquipmentCode.ToString());
      }
    }
  }
}

The problem solved.


text:
Q: Create 2d linear list in matlab Very Simple Question that i couldn't find easily on the web so i thought i would ask here:
You can make a 1D linear array like this:
1:10 = 1 2 3 4 5 6 7 8 9 10
1:2:10 = 1 3 5 7 9

How can you easily initialise a 2D array ie.
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4

and also the same thing but for columns:
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4

Should be a command to do it in one line.

A: v = 1:5;
A = repmat(v, 4, 1);
B = repmat(v', 1, 4);

A and B will have what you need.
Another option is to use MATLAB indexing as follows:
v = 1:5;
A = v(ones(4, 1), :);
v = [1:5]';
B = v(:, ones(1, 4));

A: Alternatively i have learned that you can use meshgrid:
meshgrid(1:4, 1:4) =>

 1     2     3     4
 1     2     3     4
 1     2     3     4
 1     2     3     4

Thanks for the help and upvotes.


text:
Q: Unable to test mobile application using Test Script Recorder I am trying to test mobile application using jmeter Test Script Recorder but When i set proxy in my mobile and then I tried to captured, It shows all the time "No internet connection". I have set correct ip and port number.
Can anyone help me ?

A: There is more than one mobile operating system and troubleshooting options differ depending on vendor and OS.

*

*Double check that you actually started HTTP(S) Test Script Recorder and there are no modal dialogs with warnings/errors and nothing suspicious in jmeter.log file

*JMeter itself must have internet connectivity, if your machine is behind the corporate proxy - you will need to apply some extra configuration

*Check if you can record anything using web browser on mobile device. Start with HTTP-based simple site i.e. http://example.com

*If your application is using HTTPS protocol you will need to install JMeter's self-signed certificate onto the device, the file is called ApacheJMeterTemporaryRootCA.crt and it's being generated in "bin" folder of your JMeter installation when you start HTTP(S) Test Script Recorder and you need to transfer it to your device somehow (bluetooth, email, whatever) and follow your OS dialog to get it installed and trusted

*For certain Android versions you might need to use a 3rd-party tool like ProxyDroid in order to proxy HTTPS traffic

*For iOS devices you will need to "tell" that you trust JMeter's certificate under Settings -> General -> About -> Certificate Trust Settings
See the following materials for more information:

*

*HTTP(S) Test Script Recorder user manual entry (pay attention to HTTPS recording and certificates chapter)

*Apache JMeter proxy Step-by-step

*You can consider using a cloud-based proxy service, in this case you will not have to worry about certificates generation and installation and will have confidence that the device will have Internet connectivity. As a bonus you will have possibility to export recorded script in "SmartJMX" mode with automatic detection and correlation of any dynamic parameters.


text:
Q: how to create vector space for text categorization using svm I have some Issues in generating input training  vector set for LIBSVM .. I have 3 categories and their relevent training document with term weight as follows(Only assumption).
(Label/Category):1
    Term frequency Vector(TF*IDF)
    Document1->   1:0.25 2:1.056 3:2.356
    Document2->   2:1.25 3:0.145 4:1.543
    Document3->   1:1.00 2:2.145 5:3.543
(Label/Category):2
    Term frequency Vector(TF*IDF)
    Document4->   1:0.25 2:1.056 3:2.356
    Document5->   2:1.25 3:0.145 4:1.543
    Document6->   1:1.00 2:2.145 5:3.543
(Label/Category):3
    Term frequency Vector(TF*IDF)
    Document7->   1:0.25 2:1.056 3:2.356
    Document8->   2:1.25 3:0.145 4:1.543
    Document9->   1:1.00 2:2.145 5:3.543
Can any one say how to convert this into set of training vector for LIBSVM.Here 1:0.25 2:1.056 3:2.356 are term index and its weight.Term indices are maintained manually in global dictionary.
As well may I know how to convert the testing document into term vector?.
thanks in advance.

Hi Qnan.. I have prepared sample training vector space as you have suggested. Can you please tell me whether my vector formation is correct or not?..
(Label/Category):1
1 1:0.25 2:1.056 3:2.356 ->(training instance 1-for Document1)
1 2:1.25 3:0.145 4:1.543 ->(training instance 2-for Document2)
1 1:1.00 2:2.145 5:3.543 ->(training instance 3-for Document3)
(Label/Category):2
2 1:0.25 2:1.056 3:2.356 ->(training instance 4-for Document4)
2 2:1.25 3:0.145 4:1.543 ->(training instance 5-for Document5)
2 1:1.00 2:2.145 5:3.543 ->(training instance 6-for Document6)
(Label/Category):3
3 1:0.25 2:1.056 3:2.356 ->(training instance 7-for Document7)
3 2:1.25 3:0.145 4:1.543 ->(training instance 8-for Document8)
3 1:1.00 2:2.145 5:3.543 ->(training instance 9-for Document9)

A: The format is described in the README file of the LIBSVM distribution, basically it is
<categoryA> <feature1>:<value1> <feature2>:<value2> <feature3>:<value3> ...

one line per training instance. The feature indices should be in ascending order, too.
The test set looks exactly the same, except that the first column may contain some fixed number, e.g. 0, if you do not know the true labels for that set.
As for you data, I don't quite see how you can have all those different weight vectors for the same Document1 and the same set of terms. Could you clarify that?
EDIT:
The format is OK, if you remove the comments, LIBSVM runs just fine. Assuming you're running Windows and the file test.txt is as follows,
1 1:0.25 2:1.056 3:2.356
1 2:1.25 3:0.145 4:1.543
1 1:1.00 2:2.145 5:3.543
2 1:0.25 2:1.056 3:2.356
2 2:1.25 3:0.145 4:1.543
2 1:1.00 2:2.145 5:3.543
3 1:0.25 2:1.056 3:2.356
3 2:1.25 3:0.145 4:1.543
3 1:1.00 2:2.145 5:3.543

you can use ./libsvm-3.12/windows/svm-train.exe test.txt for training and ./libsvm-3.12/windows/svm-predict.exe test.txt test.txt.model test.txt.out for prediction. On other systems the CMD is similar.
Note that with this data the accuracy won't be higher than 1/3, since the same weight vectors are present in the dataset with each of the labels.


text:
Q: How to devide the same data in excel I'm doing an exercise with excel. The article requires me to read data from 2 files and combine it into a single file. Then, divide them into sheets (limited to 3 invoice codes for each sheet).
Visual Studio Code
import pandas as pd
from xlwt import Workbook
from pandas import ExcelWriter
import inspect, os
import numpy as np
from openpyxl import load_workbook
#import xlsxwriter

CurDir =
os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) # link

df_Input = pd.read_excel(CurDir+"\\input\\Input.xlsx",header = 1,
dtype='str')
df_Master= pd.read_excel(CurDir+"\\input\\Master.xlsx",dtype='str')

list_TEN = df_Master['Tên khách hàng (*)'].values
list_MST = df_Master['Mã số thuế'].values

list_New = []

for idx,row in df_Master.iterrows():
    for idx_MST,i_MST in enumerate(list_MST):
        if str(row['Mã số thuế']).strip() == str(i_MST):
            list_New.append(list_TEN[idx_MST])
            break
df = pd.DataFrame(df_Input)
new_df = pd.DataFrame({'Họ tên người mua hàng': list_New})
df.update(new_df)

writer = ExcelWriter(CurDir+"\\output\\RightInput.xlsx")
df.to_excel(writer, sheet_name='Sheet1', index=False)
writer.save()

df_Output = pd.read_excel(CurDir+"\\output\\RightInput.xlsx")
df_MergeInput = df_Output[0:0]

intcouter=0
intcoutsheet = 1
writer = ExcelWriter(CurDir+"\\output\\Output.xlsx")
for idx,row in df_Output.iterrows():

df_MergeInput = df_MergeInput.append(row)
if df_Output == c3:
    for row in df_Output:
        sheet=writer.active
        c3=sheet['C3']
        sheet.append(row)
else:
    if intcouter == 2:
    df_MergeInput.to_excel(writer, sheet_name='Sheet'+str(intcoutsheet), index=False)
    df_MergeInput = df_Output[0:0]
    intcoutsheet +=1
    intcouter=0
intcouter+=1

writer.save()


text:
Q: OpenVPN TLS HandShake Failed with Linux Server/Windows Client I recently bought a Odroid C2 with Ubuntu 16.04 operating system. I have installed OpenVPN to be able to have access from everywhere to my home network. I have Samba sharing folders...
I followed this tutorial: https://www.digitalocean.com/community/tutorials/how-to-set-up-an-openvpn-server-on-ubuntu-16-04
I have TLS problems when I try to connect my Windows 10 client to the server with the OpenVPN GUI for Windows.
TLS Error: TLS key negotiation failed to occur within 60 seconds (check your network connectivity)
TLS Error: TLS handshake failed

OpenVPN GUI Log:
Fri Jun 10 22:56:35 2016 OpenVPN 2.3.11 x86_64-w64-mingw32 [SSL (OpenSSL)] [LZO] [PKCS11] [IPv6] built on May 10 2016
Fri Jun 10 22:56:35 2016 Windows version 6.2 (Windows 8 or greater) 64bit
Fri Jun 10 22:56:35 2016 library versions: OpenSSL 1.0.1t  3 May 2016, LZO 2.09
Fri Jun 10 22:56:35 2016 MANAGEMENT: TCP Socket listening on [AF_INET]127.0.0.1:25340
Fri Jun 10 22:56:35 2016 Need hold release from management interface, waiting...
Fri Jun 10 22:56:36 2016 MANAGEMENT: Client connected from [AF_INET]127.0.0.1:25340
Fri Jun 10 22:56:36 2016 MANAGEMENT: CMD 'state on'
Fri Jun 10 22:56:36 2016 MANAGEMENT: CMD 'log all on'
Fri Jun 10 22:56:36 2016 MANAGEMENT: CMD 'hold off'
Fri Jun 10 22:56:36 2016 MANAGEMENT: CMD 'hold release'
Fri Jun 10 22:56:36 2016 Control Channel Authentication: tls-auth using INLINE static key file
Fri Jun 10 22:56:36 2016 Outgoing Control Channel Authentication: Using 160 bit message hash 'SHA1' for HMAC authentication
Fri Jun 10 22:56:36 2016 Incoming Control Channel Authentication: Using 160 bit message hash 'SHA1' for HMAC authentication
Fri Jun 10 22:56:36 2016 Socket Buffers: R=[65536->65536] S=[65536->65536]
Fri Jun 10 22:56:36 2016 UDPv4 link local: [undef]
Fri Jun 10 22:56:36 2016 UDPv4 link remote: [AF_INET](My address IP):1194
Fri Jun 10 22:56:36 2016 MANAGEMENT: >STATE:1465613796,WAIT,,,
Fri Jun 10 22:57:36 2016 TLS Error: TLS key negotiation failed to occur within 60 seconds (check your network connectivity)
Fri Jun 10 22:57:36 2016 TLS Error: TLS handshake failed
Fri Jun 10 22:57:36 2016 SIGUSR1[soft,tls-error] received, process restarting
Fri Jun 10 22:57:36 2016 MANAGEMENT: >STATE:1465613856,RECONNECTING,tls-error,,
Fri Jun 10 22:57:36 2016 Restart pause, 2 second(s)
Fri Jun 10 22:57:38 2016 Socket Buffers: R=[65536->65536] S=[65536->65536]
Fri Jun 10 22:57:38 2016 UDPv4 link local: [undef]
Fri Jun 10 22:57:38 2016 UDPv4 link remote: [AF_INET] (My address IP):1194
Fri Jun 10 22:57:38 2016 MANAGEMENT: >STATE:1465613858,WAIT,,,

My client configuration (.ovpn file) without the text in comment:
client
dev tun
proto udp
remote (My address IP) 1194
resolv-retry infinite
nobind
persist-tun
remote-cert-tls server
comp-lzo
verb 3
key-direction 1

(The ca.crt, the client.crt and the client.key files are include in the ovpn file)

My server configuration (server.conf) without the text in comment:
port 1194
proto udp
dev tun
ca ca.crt
cert server.crt
key server.key
dh dh2048.pem
server 10.8.0.0 255.255.255.0
ifconfig-pool-persist ipp.txt
push "redirect-gateway def1 bypass-dhcp"
push "dhcp-option DNS 208.67.222.222"
push "dhcp-option DNS 208.67.220.220"
keepalive 10 120
tls-auth ta.key 0
key-direction 0
comp-lzo
user nobody
group nogroup
persist-key
persist-tun
status openvpn-status.log
verb 3

On my router I set the Port Forwarding for the 1194 port with the Odroid IP address:
see the picture
I also try the TCP proto but it retry the connection every 5 seconds.
Can you help me please! :)

A: If you are sure that you are connecting to correct public IP address then Ubuntus firewall might be blocking the connection.
OpenVPN works for me with following rules:
iptables -A INPUT -i eth0 -p udp -m state --state NEW -m udp --dport 1194 -j ACCEPT
iptables -A INPUT -i tun+ -j ACCEPT
iptables -A OUTPUT -o tun+ -j ACCEPT

And ofcourse need to save the rules. Iptables-persistent is nice tool for this:
sudo apt-get install iptables-persistent

After it's installed, you can save/reload iptables rules anytime:
sudo /etc/init.d/iptables-persistent save
sudo /etc/init.d/iptables-persistent reload

For further troubleshooting you could monitor the traffic from server side to see if anything is reaching port 1194:
sudo apt-get-install ngrep
ngrep port 1194

Good luck


text:
Q: how to handle half open socket in middle of transfer? /*Basic Things has been done.*/
/*Like setting connection and receiving */
namespace bar = boost::asio::error;
void doWrite(char* buffer, size_t size_) {
    boost::asio::async_write_some(socket, boost::asio::buffer(buffer ,size), boost::bind(&Handler, this, bar::error, bar::bytes_transferred));
}

/*handler*/
void handler(/*parameters*/)
{
}

while my server is continuously transferring the data. sometimes client gets crash /*purposely */.
    errorCode.message() gives error of boost::asio::error::bad_descriptor and whole program crashes.
i have copied the program from boost chat server example.
if server is transmitting let say 1024 bytes and while writing client close in middle of writing of 1024 bytes. whole program crashes.
More Technical Wording:
how to handle half open socket in middle of transfer?

A: Be sure to do all operations either catching system_error or receiving (and checking) the error_code.
As you say, you already receive the boost::asio::error::bad_descriptor code, so I expect the program termination results because of a subsequent action on the same socket that throws.
Look for the overloads that take a boost::system::error_code& parameter (like e.g. http://www.boost.org/doc/libs/1_66_0/doc/html/boost_asio/reference/basic_stream_socket/close.html).


text:
Q: How to get action bar title as TextView in AppCompat? I'm trying this to get title as TextView but it's not working:
TextView title = (TextView) findViewById(R.id.action_bar_title);

And title is null. How to get title as TextView using AppCompat?

A: Typically when using the Toolbar in my cases, if I am doing something custom with the title, I will just inflate the title view manually, then set its attributes in XML. The point of Toolbar is to prevent things like this from happening, so you can have more control over what your toolbar looks like
<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/my_awesome_toolbar"
    android:layout_height="@dimen/standard_vertical_increment"
    android:layout_width="match_parent"
    android:minHeight="@dimen/standard_vertical_increment"
    android:background="@drawable/actionbar_background">

    <TextView
        style="@style/TextAppearance.AppCompat.Widget.ActionBar.Title"
        android:id="@+id/toolbar_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/Red" />

</android.support.v7.widget.Toolbar>

Then in code, you would do something like this:
Toolbar toolbar = findViewById(R.id.my_awesome_toolbar);
//Get rid of the title drawn by the toolbar automatically
toolbar.setTitle("");
TextView toolbarTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
toolbarTitle.setTextColor(Color.BLUE);

Taken from Getting ActionBar Title TextView with AppCompat v7 r21

A: Brute force seems to be one solution:
private void findTextViewTitle() {
    String title = "title";

    ActionBar ab = getSupportActionBar();
    ab.setTitle(title);

    Window window = getWindow();
    View decor = window.getDecorView();

    ArrayList<View> views = new ArrayList<View>();
    decor.findViewsWithText(views, title, View.FIND_VIEWS_WITH_TEXT);

    for (View view : views) {
        Log.d(TAG, "view " + view.toString());
    }

    TextView tvTitle = (TextView) decor.findViewById(views.get(0).getId());
    tvTitle.setBackgroundColor(Color.RED);

}

A: Here is how to get the TextView from the ActionBar. This method ensures that the TextView is selected even if the ActionBar orientation changes. It also allows you to get the icon if you ever want - just check for child instanceof ImageView.
//If you just want to set the text
ActionBar actBar = getSupportActionBar();
if(actBar != null) {
    actBar.setTitle(R.string.your_ab_title);
}

//If you want to customize more than the text
Toolbar ab = findViewById(R.id.action_bar);
if(ab != null){
    for (int i= 0; i < ab.getChildCount(); i++){
        if(ab.getChildAt(i) instanceof TextView) {
            TextView title = (TextView) ab.getChildAt(i);

            //You now have the title textView. Do something with it
            title.setText("Your Custom AB Title");
        }
     }
}

A: Hey thanks for the help everyone here, here's the implementation i ended up with.

// USAGE
Toolbar yourToolbar = (Toolbar) findViewById(R.id.your_toolbar);
TextView actionTitle = ActionBarTitle(toolbar);
    actionTitle.setTypeface(font("Snake"));

// IMPLEMENTATION
private TextView ActionBarTitle(Toolbar toolbarForRead)
{
    TextView title = null;
    if (toolbarForRead != null)
    {
        for (int i= 0; i < toolbarForRead.getChildCount(); i++)
        {
            if (toolbarForRead.getChildAt(i) instanceof
TextView)
            {
                title = (TextView)
toolbarForRead.getChildAt(i);
                return title;
            }
        }
    }
    return null;
}
private Typeface font(String fontName)
{
    return Typeface.createFromAsset(this.getAssets(), "fonts/"  + fontName + ".ttf");
}

A: im using AppCompatActivity , this works for me
val titleId :Int = resources.getIdentifier("title","id",BuildConfig.APPLICATION_ID )
        val title :TextView = findViewById(titleId)

A: The textView in Toolbar is added by code, so you cannot find it by view id.
Solution
With Kotlin, you can find the title textView by this way.
toolbar.forEachIndexed { _, v ->
    if (v is TextView && v.text == "Your title name") {
        v.setOnClickListener {
            // ...
        }
        return@forEachIndexed
    }
}


text:
Q: How to do multinomial regression when baseline choice percentage of one choice item is 0% I am trying to find a clever way to analyze the choice ratios between a baseline condition and a different condition.
Specifically, I have a baseline condition, where the choice ratio between two cells is let's say A/B.
In another condition, the choice ratio between the same two items is C/D.
Now, what I need to find out is whether (C/D)/(A/B) is significantly different from 1.
The problem I have is that B cell has a 0% choice rate.
In other words, the equation becomes (C/D)/(A/0), which leads to the conclusion that (C/D)/(A/0) is infinitely greater than 1.
I tried to analyze this with multinomial logistic regression, which is unable to take care of this problem.
Is there a clever way in which I can convert the choice ratios where the result is not "infinitely greater than 1", but a viable number?

A: A couple of thoughts come to mind.
First, I think Laplace Smoothing -- not to be confused with Laplacian Smoothing -- might be useful. Basically, you add a small value to every cell so there are no 0's.
Second, (C/D)/(A/0) is actually zero: (C/D) * (0/A). But that's probably not helpful in this case. Still, a rearrangement of your algebra/comparison might be helpful.
Third, if you can't do Laplace Smoothing and you want to do multinomial logistic regression, I wonder if a Bayesian multinomial logistic regression might help: you can set priors that keep coefficients from going to infinity. You may have to explain/understand/be comfortable with Bayesian methods, and the actual prior would take some thought, but it might be workable. (For example, in a straight-up binary logistic regression, you can keep the coefficients from blowing up if complete separation takes place. I'm not sure if this is good practice or helpful, but you can do it.)
Fourth, if you use a multinomial logistic regression, can you break it into two parts: the baseline (where B is never chosen) and the rest (where B is chosen? Use, say, A as your reference level for both and exclude B from the first part. The problem here is that you really can't compare A's across the two parts. So maybe it's a bad idea.


text:
Q: Orbital motion and likelihood of bodies colliding An asteroid is in a highly eccentric elliptical orbit around the sun. The period of the asteroid's orbit is $90$ days. Which of the following statements is true about the possibility between a collision between the asteroid and the Earth?
a.) There is no possibility of a collision
b.) There is a possibility of a collision
c.) There is not enough information provided to determine whether or not there is danger of a collision.
I feel like the answer is (a). Could anybody elaborate for me as to whether or not my assumption is correct and why?

A: It's an easy problem! Hint: From the information given you can calculate the semi-major axis $a$ in Astronomical Units (AU). Do it! Then, of course, at first sight, there is a problem. The eccentricity is not given, so one does not know the aphelion distance $Q$. Nevertheless, one can write down an upper bound on $Q$ in terms of $a$. Write it down! (Drawing an ellipsis may help you!) Finally, check whether this upper bound is good enough to answer the question.
This should definitely help you...
psm


text:
Q: Retrieving results by running a query based on condition in Django So i have following 2 tables which i am using to write a Book library in Django.
class Book(models.Model):
 """Model representing a book (but not a specific copy of a book)."""
    title = models.CharField(max_length=200)
    author = models.CharField(max_length=200,null=True)
    summary = models.TextField(max_length=1000, help_text="Enter a brief description of the book",null=True)
    genre = models.ManyToManyField(Genre, help_text="Select a genre for this book")
    shelflocation = models.CharField(max_length=10, null=True)
    pages = models.IntegerField(null=True)
    copies = models.IntegerField(null=True,default=1)

and another BookInstance model where i am maintaining both the status and number of copies
class BookInstance(models.Model):
    """Model representing a specific copy of a book (i.e. that can be borrowed from the library)."""
    id = models.UUIDField(primary_key=True, default=uuid.uuid4,
                          help_text="Unique ID for this particular book across whole library")
    book = models.ForeignKey('Book',on_delete=models.SET_NULL,null=True)
    due_back = models.DateField(null=True, blank=True)
    borrower = models.ForeignKey('MemberList',on_delete=models.SET_NULL,null=True)

    LOAN_STATUS = (
        ('d', 'Maintenance'),
        ('o', 'On loan'),
        ('a', 'Available'),
        ('r', 'Reserved'),
    )

So if a book is loaned then status will be set to 'o' in above table.
I would like to display all the Books of a specific author whose books has been loaned and copies are still available(which is maintained in copies in Book model)
I tried adding queryset to list but it failed. Is there a way to query based on the condition in the following query
if book_instance_count < book.copies or book_instance_count == 0:
    bookquery_res = Book.objects.filter(author__icontains=author_name)

    final_book_list = []
    for book in bookquery_res:
        book_instance_count = BookInstance.objects.filter(book_id=book.id).filter(status__exact='o').count()

        if book_instance_count < book.copies or book_instance_count == 0:
            final_book_list.append(list(book))

Edit 1
So if the number of copies of a particular Book is 3 and if the number of BookInstance for the same book is 2 then i should display the corresponding book.
Update
as a workaround i am calculating the count of each book that is loaned based on author name using following
num_books = Count('bookinstance',filter=Q(bookinstance__status__exact='o'))
result =Book.objects.filter(author__icontains=author_name).annotate(num_books=num_books)

and using the above result to filter further in HTML rendering  using condition

(result.copies > result.num_books)

A: You're making things too complicated. You can do this directly in a single query.
Book.objects.filter(
    author__icontains=author_name
).filter(
    bookinstance__status="o"
).filter(bookinstance__status="a")

which will find all books from that author with at least one available instance and at least one onloan instance.

A: One option would be an annotated query, displaying only books that have both available and loaned book instances:
from django.db import models

Book.objects\
    .annotate(
        on_loan=Coalesce(
            models.Sum(
                models.Case(
                    models.When(
                        bookinstance__status='o',
                        then=1))),
            0),
        available=Coalesce(
            models.Sum(
                models.Case(
                    models.When(
                        bookinstance__status='a',
                        then=1))),
            0))\
    .filter(author__icontains=author_name, on_loan__gt=0, available__gt=0)

You can read about .annotate(), Coalesce and others.


text:
Q: How to show multiple forms simultaneously I know this may have been answered, but I just can't find a suitable answer. Any idea how to show more than one Windows Form?
static void Main()
{
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     Application.Run(new Main());
     Application.Run(new MenuModule());
}

By declaring two Application.Run, the the Windows Form will show after I exit the first.

A: When you use that overload of Application.Run it will block until the form you passed has closed.
You could try:
new Main().Show();
new MenuModule().Show();
Application.Run();

This will run until you call Application.Exit even if both forms have been closed. So a better option might be:
new MenuModule().Show();
Application.Run( new Main() );

Which will cause the application to exit after the Main form has closed, regardless of the status of the MenuModule form.
As an option you could also have the Main form show the second one, that'll work too.

A: you can create an object in 'Main' class (form) contractor.
public main(){
     .
     .
     .
     new MenuModule().show();
     .
     .
     .
}


text:
Q: Convert a long dataframe to a wide dataframe on python (pandas) using stack/unstack or groupby I have a long data frame that looks like this, with two headers the first one with variables and the second with just the date in a wide format.

company
price
volume

date

1/1/11
TSLA
2
1

1/2/11
TSLA
2
1

1/1/11
MSFT
2
1

1/2/11
MSFT
2
1

I want to shift it to a long format:

price

volume

date
TSLA
MSFT
TSLA
MSFT

1/1/11
2
2
1
1

1/2/11
2
2
1
1

If possible i want to use stack or unstack/ groupby to do this. Assuming that I have the long dataframe saved as df - how would i convert it to a pandas dataframe named wide?

A: This is set_index with append=True to add company as the second level of the MultiIndex, then unstack company into columns:
df = df.set_index('company', append=True).unstack(level='company')

df:
        price      volume
company  MSFT TSLA   MSFT TSLA
date
1/1/11      2    2      1    1
1/2/11      2    2      1    1

DataFrame:
df = pd.DataFrame({'company': {'1/1/11': 'MSFT', '1/2/11': 'MSFT'},
                   'price': {'1/1/11': 2, '1/2/11': 2},
                   'volume': {'1/1/11': 1, '1/2/11': 1}})


text:
Q: $C^{1+\epsilon}$ conjugacy of expanding map on circle A continuously differentiable map $f:S^{1}\rightarrow S^{1}$ is called expanding if $|f^{'}(x)|>1$ for all $x\in S^{1}$.
We can define the degree of f, def(f) to be number of preimage $f^{-1}(x)$, for any $x\in S^{1}.$
Theorem Any expanding map $f:S^{1}\rightarrow S^{1}$ of degree $d\geq2$ is topologically conjugate to linear of degree d.
QuestionLet f be $C^{1+\epsilon}$. Does the theorem work for $C^{1+\epsilon}$ conjugacy?if No,Does anyone know under what assumption we have $C^{1+\epsilon} $conjugacy above theorem?
Remark We have following theorem:
Let $2\leq r\leq t$. If two orientation preserving expanding $C^r$ endomorphisms
f and g of $S^{l}$ are absolutely continuously conjugate, then they are conjugate by a $C^r$
diffeomorphism. But, i do not assume $C^{2}$. In fact, i was asking.  Does Shub and Sullivan's theorem work for $C^{1+\epsilon}?


text:
Q: How can I make the roadmap scroll effect in React? I'd love to make the effect like image.

When I scroll down the roadmap, the aircraft will move like image.
I tried to find the same and similar effect using react, but couldn't find it.
If you know about this and have reference links for this, could you gimme and guide me?
Thanks,