text:
Q: Control multiple servos using pic18f microcontroller? I want multiple servos to  be controlled through pic18f4550 microcontroller.
I know for a single servo I can use the following code.
unsigned int angle=0,i;
void cs_delay(unsigned int);
void main()
{
   TRISB.F0=0;
   while(1)
   {
      for(angle=0;angle<=180;angle+=45) // Loop to increase the angle by 45°
      {
         for(i=0;i<50;i++) // Loop to provide continuous train of pulse
         {
             LATB.F0=1; // Send high to control signal terninal
             cs_delay(angle); // Call delay function
             LATB.F0=0; // Send low to control signal terninal
             Delay_ms(18);
         }
      }
   }
}

void cs_delay(unsigned int count)
{
   int j=0;
   Delay_us(550); // Delay to move the servo at 0°
   for(j=0;j<count;j++) // Repeat the loop equal to as much as angle
   {
      Delay_us(6); // Delay to displace servo by 1°
   }
}

But I cannot figure out how it can be used for multiple servos..
BTW, using MikroC v8.2 for programming.
Any help?

A: Not easily.
You see, you have written there what is known as blocking code.  The PIC can't do anything else while it's processing your software PWM signal because you are using delays.
Instead you need to step away from that whole concept and instead to things based on time, not waiting.
For instance, when you get up in the morning, do you lie there awake all night staring at your clock until it's time to get up, or do you set the alarm for 7:30 then go to sleep, until the clock wakes you up?
Most PICs make it even easier, by allowing you to tie a timer to an output compare module, which will generate your PWM waveform purely in hardware.  The more output compare modules and timers you have the more servos you can drive with it.
Even without using output compare, there are ways of using a timer to trigger an alarm the next time an output is due to change state.  It's up to you to come up with how best to decide when that is, and change the timer's time accordingly.

A: If you want to use delays and control the servos you can see my code, which is written using mplab.
     PORTD=0b00000001;        //servo0
     Delay10TCYx(pul0);

     PORTD=0b00000110;  //servo 1,2
     Delay10TCYx(pul1);

     PORTD=0b00001000;  //servo 3
     Delay10TCYx(pul3);

     PORTD=0b00100000;  //servo 4
     Delay10TCYx(pul4);

     PORTD=0b00000000;  //pulse down
     Delay1KTCYx(15);

I have 5 servos connected to portD and servo 1 and 2 work on same pulse.
Ok here is how it works, the width of entire pulse cycle of servo is 20ms, but servo have tolerance of + or - 2ms.
out of 20ms the positive pulse is only 2ms and rest 18ms is zero.
I have cascaded all positive signals to servos, rest of the time all pins are set to zero.
My pic had 4MHz crystal and the below code worked to control 90 degree sweep of servo.


text:
Q: Script recorre URL's, recoge información y la guarda en archivo tengo un problema con un script que no soy capaz de hacer.
Hace mucho tiempo que no toco PHP (demasiado en realidad) y necesito hacer un script que recorra una serie de URL's, recoja unos datos de una tabla y los guarde en un documento.
El funcionamiento, básicamente, es:
Empieza el bucle, entra en la url https://www.ejemplo.com/000001/, carga los datos que esta contiene, recoge información de una tabla determinada (con id #tablaEjemplo), la pasa a una array (supongo), de este array selecciono otros datos (nombre, dirección y mail) y esta información la guarda en un fichero externo (txt/csv).
Una vez hecho esto pasa a la siguiente dirección https://www.ejemplo.com/000001/ y hace lo mismo... y así hasta un número determinado de veces.
El fichero resultante sería algo así como:
https://www.ejemplo.com/000001
Nombre
Direccion
Mail
https://www.ejemplo.com/000002
Nombre
Direccion
Mail
etc
<?php
  //Script recorre X URL (000001-000100), recoge determinados datos (nombre, direcion, mail) y los guarda en un archivo
  $userAgent = 'Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0';
  $valores = [];

  for ($idempresa = 000001; $idempresa < 000100; $idempresa++): //Bucle for para recorrer X paginas de una URL (891721-899999)
      $url = "https://www.ejemplo.com/".$idempresa."/";
      echo $url;
      //$url2 = $url." #tablaEjemplo > tbody > tr > td"; //URL con los parametros añadidos

  //function get_content_with_curl($html) //Definimos la función cURL
  //{
      $ch = curl_init(); //Inicia cURL
      $archivo = fopen("./datos.txt", "a") or die("ERROR: No ha sido posible abrir el archivo. Revisa su nombre y sus permisos."); //Abrimos el archivo
      curl_setopt($ch, CURLOPT_URL, "$url"); //Configura cURL con la URL deseada
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Configura cURL para devolver el resultado como cadena
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //Configura cURL para que no verifique el certificado
      curl_setopt($ch, CURLOPT_USERAGENT, $userAgent); //Configura el user-agent
      $info = curl_exec($ch); //Establece una sesión cURL y asigna la información a la variable $info
      curl_close($ch); //Cierra cURL

      //Recorremos el array y vamos guardando en un txt cada unos de los valores
      foreach ($valores as $datos) {
          fwrite($archivo, PHP_EOL ."$datos"); //Escribimos en el archivo los diferentes valores que se recogieron de la url
      }
      fclose($archivo); //Cerramos el archivo para evitar errores
  //}

  //Llamada a la función
  //Convierte la información de la URL en cadena
  //$html = get_content_with_curl($url);

  //Se imprime lo que obtuvimos en esa variable
  //echo $html;

      var_dump($info); //Devuelve la información

  endfor; //Cerramos bucle for para evitar problemas

Esto es todo lo que yo fui capaz de sacar, además de muchos pedazos de código que no sirven para nada y un buen dolor de cabeza.
Espero haberme explicado bien, si alguien me puede ayudar tendrá mi eterna gratitud!

A: No se cual es el error que te tira pero puedo notar que a la hora de crear el link con el $idEmpresa tienes una / de mas antes del id, deberia ser
$url = "https://www.ejemplo.com/".$idempresa."/";

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sorting a dynamic range based on cell value I want to sort these totals by client code (Row B) only for those under 200$. My code is not working, where is my mistake? (keep in mind the number of rows change all the time but columns stay the same)

Sub SortD()
    Dim TotalRows As Long
    Dim i As Integer
    Dim rng1 As Range
    Dim rng2 As Range

    TotalRows = Application.CountA(Range("F:F"))

    For i = 3 To TotalRows
        If Cells(i, 6).Value >= 200 Then

           Set rng1 = Range(Cells(2, 1), Cells(i - 1, 9))
           Set rng2 = Range(Cells(3, 2), Cells(i - 1, 2))

            Exit Sub
        End If
    Next i

    Application.Goto rng1
    ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=rng2, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets("Sheet1").Sort
        .SetRange rng1
        .Header = xlGuess
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
End Sub


text:
Q: How to navigate to another page without calling the page's constructor My first post here so hope somebody can help. I am pretty new to C# and Silverlight so please be gentle.
Here is my current issue/problem.
I have MainPage.xaml which has a Grid control to show pages. When my site loads up I would like to show a UserControl page for either logging in or registering.
I have created a UserControl page, lets call it ctrlLogon.xaml. ctrlLogon hosts a frame that will hold either the logon or register page. I am using the frame because I am using a custom transition between the logon and register page.
The logging in happens on the LoginPage.xaml which uses a wcf services to communicate with the database. That is fine, but I need an event handler to notify ctrlLogon if the user logs in successfully or fails to logon.
In ctrlLogon.xaml.cs:
public partial class ctrlLogon : UserControl
{
    pgLogonPage newLogonPage;

    public ctrlLogon()
    {
        InitializeComponent();
        newLogonPage = new pgLogonPage();
        newLogonPage.LoggedInOK += new EventHandler(newLogonPage_LoggedInOK);
        newLogonPage.LoginFailed += new EventHandler(newLogonPage_LoginFailed);
    }

    void newLogonPage_LoggedInOK(object sender, EventArgs e)
    {
        //throw new NotImplementedException();
    }

    void newLogonPage_LoginFailed(object sender, EventArgs e)
    {
        //throw new NotImplementedException();
    }

Then either through a button click or whichever means I use:
ContentFrame.Navigate(new Uri("/Views/pgLogonPage.xaml"), UriKind.Relative);
This works fine by navigating to pgLogonPage.
My problem comes in that the I create and instance of pgLogonPage in order to set up the event handler, but Navigate also creates an instance of pgLogonPage, so the following does not work:
public partial class pgLogonPage : Page
{
    ServiceClient smsClient;

    public pgLogonPage()
    {
        InitializeComponent();

        Client = new ServiceClient();
        Client.LoginCompleted += new EventHandler<LoginCompletedEventArgs (Client_LoginCompleted);
    }

public event EventHandler LoggedInOK;

    public void OnLoggedInOK()
    {
        if (LoggedInOK != null)
            LoggedInOK(this, new EventArgs());
    }

    public event EventHandler LoginFailed;
    public void OnLoginFailed()
    {
        if (LoginFailed != null)
            LoginFailed(this, new EventArgs());
    }

    void Client_LoginCompleted(object sender, LoginCompletedEventArgs e)
    {
        if (e.Result.Contains("Success"))
        {
            OnLoggedInOK();
        }

        else
        {
            OnLoginFailed();
        }
    }

}
LoggedInOK and LoginFailed event handlers are always null. I am thinking it is because the two instances of pgLogonPage are being created. I could be wrong so please any help to get this working is appreciated. If there is something not clear please let me know.
Kind regards
Neill

A: and welcome to StackOverflow.
The navigation framework will cause an instantiation of the target page so the page's constructor will be called whether you like it or not (the page object needs to be constructed at some point - right?).
Usually a default parameterless constructor is used - so the question is - how to notify the target control that a certain condition has occured? Simple, you can add public property like
public bool MyCondition {get; set;}

to the target control, and set it after an event in the navigation framework occurs and the target control/page is constructed.
Hope that helps a bit,
Best regards.


text:
Q: Amazon Lex fulfillmentActivity.codeHook I am following this tutorial provided in the Amazon Lex documentation:
http://docs.aws.amazon.com/lex/latest/dg/getting-started-ex2.html
and I am getting this error when I finally save my intent:
The value 'null' specified for 'fulfillmentActivity.codeHook.uri' is invalid. Member must not be null
If anyone can help me with this issue, I would greatly appreciate it :) Thank you!

A: You missed this step when creating the intent: Fulfillment – Leave Return parameters to client selected. We're not using a Lambda function in this example.

A: If you are using lambda functions with your bot then you must integrate it with your bot else just check the return parameters to client and that should work fine.


text:
Q: What does .where.get() return? i am new this website and to mobile programming.
My questions is:
In firebase i have a collection path with some documents.
.collection(maybe).doc(random)
Each doc has subcollection as well.
Also each doc has data such as:
roomName: randomName
roomPassword: randomPass.

So, now i would like to use the query with .where operator and .get like this:
const docRef=db.collection('maybe')
docRef.where('roomName' '==' 'randomName').get()

My question is what do i get back? As i understand i get the querySnapshot, but i do not fully get how to get the second field in data specifically i.e. how to get roomPass?

A: const docRef = db.collection('maybe');
const futureSnapshot = docRef.where('roomName','==','randomName').get();

gives you a promise of snapshot.
You have to "await".
const docRef = db.collection('maybe');
const snapshot = await docRef.where('roomName','==','randomName').get();

after that you can get your data :
const room = snapshot.data(); // undefined if your query has no results

This link could help you
Happy coding !
EDIT
If your document looks like this :
{
  randomName: "a name",
  randomPassword: "a password"
}

Then you get your data like that :
const room = snapshot.data(); // undefined if your query has no results
const { randomPassword } = room;


text:
Q: Database Distances Cities Table I need a DB model, that can handle an exclusive PK with 2 values.
Lets say we have 3 cities and they are all connected.
The distances are:
    (1)->(2) = (2)->(1) = 5
    (1)->(3) = (3)->(1) = 3
    (2)->(3) = (3)->(2) = 4
The complex point is that i dont want duplicate entries!
Thx in advance

A: You need three columns. SourceID, DestID and Distance. Store in SourceID the smaller ID number and create a unique constraint on (SourceID, DestID);

A: Enforce the order to prevent duplicates. The same tactic works whether you're storing city names or city id numbers.
CREATE TABLE distances (
    start_city VARCHAR(35) NOT NULL CHECK (start_city < end_city),
    end_city   VARCHAR(35) NOT NULL,
    km_distant INTEGER     NOT NULL CHECK (km_distant > 0),
    PRIMARY KEY (start_city, end_city)
);

A: You can use latitude and longitude for calculate distances. See here


text:
Q: Is there a Java property to set the location of the CRL files instead of using CRL Distribution Point extension in X509 Certificate Is there a Java (JDK8) property that can be used to provide CRL support to point to a file or directory containing lists? I have looked into com.sun.net.checkRevocation and com.sun.security.enableCRLDP properties, and it appears that the certificates would need to have the CRL Distribution Point (CDP) extension to be able to use the second property. But our certificates are not guaranteed to have the CDP extension, and I am wondering if there is some other property in Java to specify the location of the CRL files, as in:
some.property.for.crl.location="/root/crl-dir".
Java has support to specify the OCSP responder URL in ocsp.responderURL property, it would be hard to image they don't have something similar for CRLs. But, all my searches on the net has only pointed me to CDP extension in the certificates, and I am turning to StackOverflow for some answers.
Any feedback is greatly appreciated!
Thanks,
Usha


text:
Q: Is there a way to read data into R or Python and split it by number of characters? Say I have a number of fields with their respective length of characters. The first field is the ID with length of 10, the second field is phone number with length 20, and so forth. Can I set the delimiter based on the length?
The data does not have any structure to it so in order to read it I have to find a way to construct the table when I read it in. It's a plain text file. I do, however, have the respective length of characters for each field. I have not done anything like this before so before I spend hours into it I wanted to see if this is even possible.

A: In python you can just slice the string.
msg = "ID12345678PHONE123456789012345BLOB"
_id = msg[:10]
phone = msg[10:30]
blob = msg[30:34]
print(_id, phone, blob)

Result
ID12345678 PHONE123456789012345 BLOB

Option 2: If you open the file in binary mode and get bytes strings, you can use the struct module to unpack them.
import struct

msg = b"ID12345678PHONE123456789012345BLOB"
_id, phone, blob = struct.unpack("10s20s4s", msg)
print(_id, phone, blob)

A: In python it should be quite simple indeed
In pandas you can use the simple function read_fwf()
Given for example something like this
myfile.txt
1name1surname1
2name2surname2

with columns of size [1, 5, 8]
you can read the file in this way
import pandas as pd
df = pd.read_fwf("myfile.txt", widths=[1, 5, 8])

Details here for this function
If you want to parse the file yourself instead, which is also quite simple:
import pandas as pd
# column name + size
meta_data = [('id',1),('name',5),('surname',8)]

def my_parser(line):
    curr_dict = {}
    start=0
    end=0
    for meta in meta_data:
        end = meta[1] + end
        curr_dict[meta[0]] = line[start:end]
        start = end
    return curr_dict

with open("myfile.txt", "r") as f_o:
    lines = f_o.readlines()
    dicts = []
    for line in lines:
         dicts.append(my_parser(line))

pd.Dataframe(dicts)


text:
Q: can't install Send2Trash python module been trying to install the Send2Trash module for python with pip, but so far with no success.
so i punched in pip install Send2Trash into the terminal and what i got was:
Collecting Send2Trash
  Using cached Send2Trash-1.3.0.tar.gz
Could not import setuptools which is required to install from a source distribution.
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/pip/req/req_install.py", line 377, in setup_py
    import setuptools  # noqa
  File "/usr/share/python-wheels/setuptools-20.7.0-py2.py3-none-any.whl/setuptools/__init__.py", line 11, in <module>
    from setuptools.extern.six.moves import filterfalse, map
  File "/usr/share/python-wheels/setuptools-20.7.0-py2.py3-none-any.whl/setuptools/extern/__init__.py", line 1, in <module>
    from pkg_resources.extern import VendorImporter
ImportError: No module named 'pkg_resources.extern'

You are using pip version 7.1.0, however version 9.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.

unrelated note, i also tried to update pip and it just installed 7.1.0 again.
this is the first time using pip, so it might be a real newbe mistake...

A: First upgrade pip with the command sudo pip install --upgrade pip.
If the upgrade is successful (a message will show), then install the send2trash package, again with the sudo command, as so sudo pip install send2trash. That should get the job done.

A: As mulanLA mentions, your error is likely because you should upgrade pip. However, you shouldn't be using sudo when upgrading pip.
Once you've upgraded pip you may still get a error: could not create '/usr/local/lib/python2.7/dist-packages/send2trash': Permission denied message when attempting to install Send2Trash. To get around this install with the --user flag:
pip install --upgrade pip
pip install Send2Trash --user


text:
Q: if else true condition to check in PHP i want a simple simply check if the json file contains latest  in the beganing than it should do some function, if the json file contains videos in the beganing than it should do some other functions.
This is my PHP code ---
$url = 'http://www.hello.se/3209406a5d0f95&limit=15';
$json = json_decode(file_get_contents($url), true);

if($json['latest']['videos']){ // how can i just put a condition where if it is true than
//do some function or if it is not true go to the next condition which is else if($json['videos']){ ...

        // do some functions
       }
else if($json['videos']){
// do some functions

i have also tried like so ----
$url = 'http://www.hello.se/3209406a5d0f95&limit=15';
$json = json_decode(file_get_contents($url), true);

if($json['latest']['videos'] === true){

        // do some functions
       }
else if($json['videos'] === true){
// do some functions

which is not working for me, can anyone help me to fix this issue.
Any advice will be really appreciate, thanks in advanced.

A: use isset() : http://php.net/manual/en/function.isset.php
if(isset($json['latest']['videos'])){ // how can i just put a condition where if it is true than
//do some function or if it is not true go to the next condition which is else if($json['videos']){ ...

        // do some functions
       }
else if(isset($json['videos'])){
// do some functions


text:
Q: TypeError [ERR_INVALID_URL]: Invalid URL using Next-auth only in Production The app fails on trying to sign in using next-auth in my Next.js app in production mode when using the following command in the terminal on my local machine:
`yarn build && yarn start`
The error message observed in the terminal is as follows:
TypeError [ERR_INVALID_URL]: Invalid URL
    at new NodeError (node:internal/errors:372:5)
    at URL.onParseError (node:internal/url:553:9)
    at new URL (node:internal/url:629:5)
    at Object.redirect (/Users/name/Documents/GitHub/app/node_modules/next-auth/core/lib/default-callbacks.js:16:65)
    at createCallbackUrl (/Users/name/Documents/GitHub/app/node_modules/next-auth/core/lib/callback-url.js:20:35)
    at init (/Users/name/Documents/GitHub/app/node_modules/next-auth/core/init.js:132:48)
    at AuthHandlerInternal (/Users/name/Documents/GitHub/app/node_modules/next-auth/core/index.js:98:28)
    at AuthHandler (/Users/name/Documents/GitHub/app/node_modules/next-auth/core/index.js:335:34)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async NextAuthHandler (/Users/name/Documents/GitHub/app/node_modules/next-auth/next/index.js:38:20) {
  input: 'undefined/home',
  code: 'ERR_INVALID_URL'
}

If I run in development mode with the following command in the terminal, the issue does not occur:
`yarn dev`
This is my [...nextauth].ts file:
import NextAuth from "next-auth";
import type { NextAuthOptions } from "next-auth";

import GoogleProvider from "next-auth/providers/google";
import FacebookProvider from "next-auth/providers/facebook";
import EmailProvider from "next-auth/providers/email";

import { PrismaAdapter } from "@next-auth/prisma-adapter";
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

export const authOptions: NextAuthOptions = {
  adapter: PrismaAdapter(prisma),
  providers: [
    GoogleProvider({
      // @ts-ignore
      clientId: process.env.GOOGLE_CLIENT_ID,
      // @ts-ignore
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
    FacebookProvider({
      // @ts-ignore
      clientId: process.env.FACEBOOK_CLIENT_ID,
      // @ts-ignore
      clientSecret: process.env.FACEBOOK_CLIENT_SECRET,
    }),
    EmailProvider({
      server: {
        host: process.env.SMTP_HOST,
        port: Number(process.env.SMTP_PORT),
        auth: {
          user: process.env.SMTP_USER,
          pass: process.env.SMTP_PASSWORD,
        },
      },
      from: process.env.SMTP_FROM,
    }),
  ],

  secret: process.env.NEXTAUTH_SECRET,

  callbacks: {
    session: async ({ session, token }) => {
      if (session?.user) {
        // @ts-ignore
        session.user.id = token.uid;
      }
      return session;
    },
    jwt: async ({ user, token }) => {
      if (user) {
        token.uid = user.id;
      }
      return token;
    },
  },
  session: {
    strategy: "jwt",

    maxAge: 30 * 24 * 60 * 60, // 30 days

    // updateAge: 24 * 60 * 60, // 24 hours
  },

  jwt: {
    secret: process.env.NEXTAUTH_SECRET,
  },
};

export default NextAuth(authOptions);

I tried figuring out what is different in production regarding the error message TypeError [ERR_INVALID_URL]: Invalid URL but could not figure it out. I haven't changed any environmental variables, and I have set the following variables in .env.local:
NEXTAUTH_SECRET="SomeLongString"

NEXTAUTH_URL="http://localhost:3000"

Adding package.json on request:
{
  "name": "app",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@headlessui/react": "^1.7.4",
    "@heroicons/react": "^2.0.13",
    "@next-auth/prisma-adapter": "^1.0.5",
    "@prisma/client": "^4.7.1",
    "@tailwindcss/aspect-ratio": "^0.4.2",
    "@tailwindcss/typography": "^0.5.8",
    "@types/node": "18.11.9",
    "@types/react": "18.0.25",
    "@types/react-datepicker": "^4.8.0",
    "@types/react-dom": "18.0.9",
    "autoprefixer": "^10.4.13",
    "classnames": "^2.3.2",
    "clsx": "^1.2.1",
    "date-fns": "^2.29.3",
    "eslint": "8.28.0",
    "eslint-config-next": "13.0.4",
    "framer-motion": "^7.6.7",
    "graphql-request": "^5.0.0",
    "next": "13.0.4",
    "next-auth": "^4.18.6",
    "next-seo": "^5.14.1",
    "nodemailer": "^6.8.0",
    "postcss": "^8.4.19",
    "react": "18.2.0",
    "react-datepicker": "^4.8.0",
    "react-dom": "18.2.0",
    "react-hook-form": "^7.40.0",
    "react-hot-toast": "^2.4.0",
    "react-icons": "^4.6.0",
    "sass": "^1.56.1",
    "swr": "^1.3.0",
    "tailwindcss": "^3.2.4",
    "typescript": "4.9.3"
  },
  "devDependencies": {
    "prettier-plugin-prisma": "^4.4.0",
    "prisma": "^4.7.1"
  }
}

What am I missing?

A: You are using development NEXTAUTH_URL for release. You need to define NEXTAUTH_URL in your .env file with your production link.

A: NEXTAUTH_URL is undefined. You need to define NEXTAUTH_URL in your .env file.
NextJs has built in ways to allow you to use different environment variables whether you are testing, developing or in production. Though usually in production you'd just have a single .env as you don't want to commit your secrets to git.

A: NextJS has two policies about looking for environment files, what you have to know though is that:

*

*For localhost and whatever scenario where NODE_ENV is not production, nextjs will be looking for the .env.local file.

*For production scenarios (where NODE_ENV is production), it will look for .env.production.
Moreover, these rules also applies:

*

*All the variables defined in the env file (either .env.local, either .env.production) are available server-side.

*Variables starting with NEXT_PUBLIC are available client side.
Also, you need to consider that:

*

*Environment variables are evaluated at BUILD TIME, so you must ensure that the correct .env.[local|production] file exists and has the relevant data at BUILD TIME. Taking from the documentation:

Note: In order to keep server-only secrets safe, environment variables are evaluated at build time, so only environment variables actually used will be included. This means that process.env is not a standard JavaScript object, so you're not able to use object destructuring. Environment variables must be referenced as e.g. process.env.PUBLISHABLE_KEY, not const { PUBLISHABLE_KEY } = process.env.

As a final side note, I suggest you to also consider this chapter where it basically mentions that those .env files should be under version control, other than the env*.local ones in case you have multiple .env.local files. Another important side note is that the command you are running to start the next server must be next start and not next dev, where the environment in case of next dev is specifically development.
Summarized, either of the above are your problem, although I think that the problem is that you probably are missing the .env.production at build time.

A: I think it's because you're using the development link NEXTAUTH_URL="http://localhost:3000" in production. Instead, use the live link NEXTAUTH_URL="yourwebsite.com" in production.
Also, instead of doing an if-statement to check whether you're in development or in production, have 2 .env files - one locally with the localhost url, and the one on live with the live url. This can help you better diagnose issues.
More so, check to confirm that your env variables are actually accessible in your app.


text:
Q: The mode about geometric distribution. A random variable, X, is defined as X ~ Geo(p). I know the mode is 1 as it is the value of X with highest probability.
How do i show this? As this is a discrete R.V, can i be allowed to use Calculus? I can proceed if i knew that. Thanks

A: The probability distribution, as you've set it out, is
$$
P(X = k) = (1-p)^{k-1}p \qquad k \in \mathbb{N}
$$
It should then be simple to show that for any integer $k > 1$,
\begin{align}
P(X = 1) & = p \\
         & > (1-p)^{k-1}p \\
         & = P(X = k)
\end{align}
provided $0 < p < 1$, so that $0 < 1-p < 1$ and $0 < (1-p)^{k-1} < 1$.


text:
Q: pass ng-value data to ng-model this is a field that filters ng-value and the input field has ng-model. When the the ng-value data is printed, the value is undefined.
snippet below:
<input ng-model="schoolWordsCaption"
              class="ng-untouched ng-pristine ng-valid" ng-value="schoolWords | words" readonly>

alert($scope.schoolWordsCaption) //prints undefined

at the moment, words is a directive coming from the controller but the fact is the data gotten from ng-value is not reachable to ng-model as seen from the alert.


text:
Q: Python - create wordlist from given characters of that contain 4-5 letters and 5-6 numbers ONLY I'm looking to preform a dictionary attack and want to know how to create a wordlist that has every 10 letter permutation of the letters a-f and 2-9 (which I can do) WHEN every word contains 5 letters (a-f) and 5 numbers (2-9) OR 6 letters (a-f) and 4 numbers (2-9) ONLY (what I can't do).
Here's what I have so far (from here):
import itertools

chrs = 'abcdef23456789'
n = 2

min_length, max_length = 10, 10

for n in range(min_length, max_length+1):
    for xs in itertools.product(chrs, repeat=n):
        print ''.join(xs)

Thanks

A: Just write a function that returns the number of valid letters and numbers in a string and test the return value.
nums = '23456789'
chars = 'abcdef'

def letter_number_count(word):
    l,n = 0,0
    if len(word) == 10:
        for c in word:
            if c in nums:
                n += 1
            elif c in chars:
                l += 1
    return l,n

Test output
>>> s = 'abcdef2345'
>>> (l,n) = letter_number_count(s)
>>> if (l,n) == (6,4) or (l,n) == (5,5):
...     print "Do something"
...
Do something
>>>

A: You could just individually check each permutation, and if it satisfies the condition, add it to an array.
just write a simple boolean function that counts the numbers and letters in each function, and checks the condition.

A: This will print you 20 such permutations from total number n! where n = 10 (10! = 3,628,800)
import itertools as it
print(list(map(''.join,it.islice(it.permutations('abcdef23456'), 20))))

['abcdef2345', 'abcdef2346', 'abcdef2354', 'abcdef2356', 'abcdef2364', 'abcdef2365', 'abcdef2435', 'abcdef2436', 'abcdef2453', 'abcdef2456', 'abcdef2463', 'abcdef2465', 'abcdef2534', 'abcdef2536', 'abcdef2543', 'abcdef2546', 'abcdef2563', 'abcdef2564', 'abcdef2634', 'abcdef2635']


text:
Q: Google Sheet API - sheet creation with specific app scripts I need to be able to create Google sheets on the fly and link them to some app scripts code (some gs and html files). For the sheets creation, using the API is fine but I couldn't figure out how to then attach app scripts code to it.
I have my app script code in a central project that I update through a CI process. I need all the google sheets to be fed by the app script code from this central project so that when I update this code, all the google sheets will get the update.
Thank you.

A: There are 3 ways to bind an Apps Script project to a Google Sheet.

*

*Tools Menu - Script Editor menu item

*Copy an existing Sheets file with a project bound to it - If the original Sheets file has an Apps Script project bound to it, the the Sheets file copy will also have a project bound to it.

*Publish an add-on, and have the user install the add-on.

There are library's, but a library can not be directly bound to the Sheets document.  A library is simply one Apps Script project bound to another Apps Script project.  So, even with a library you still need a second Apps Script project bound to the document.  (The document being the Sheets file in this case)
There is no way to bind an Apps Script file to a Google Sheets file using code.
If you want to keep your code from being seen by the users, then your only option is an add-on.  Library code can be seen by the public.  And add-on can be published as Public, unlisted, or private to a G Suite domain.  So, you have two choices for keeping it from being seen by the public.
If your main goal is to have users always be using the latest version of your code, then your only real option is an Add-on.  You could have users add a library that uses the "head" version, but if users were using the "head" version, then you wouldn't want to do any development and testing on the library file itself.
Copying Google Sheets template files, in order to create a new Sheets file with a project bound to it has a problem, because each bound project would need to be updated individually, unless the bound project had a library installed in it.  I'm not sure if a bound script file with a library installed will also have a library installed when a copy of the Sheets file is made.
The Apps Script API can modify an Apps Script projects manifest file, which can be used to automate the updating of projects to a new library version.  Otherwise the user would need to manually change the version number.  But you'd need to keep track of every project file ID so that your code could access every user's Apps Script project file.  An add-on doesn't have that problem, the user is always using the latest published version of the add-on, and you don't need to know or keep track of who every user is.


text:
Q: php site much slower after moving to https I have developed a large PHP tool for a client, running on a server that recently moved to HTTPS. On the same server, several other tools run (like wordpress and joomla) which aren't impacted speedwise by the move to HTTPS, but my script is.
As it is a pretty large script that I've developed, I am not sure what to look into first. What are likely things that may affect the speed of the pages?

A: For a script the main problem link to https is the number of consecutive connections you made. Make sure to set the options to reuse https connetions to avoid the handshake time.


text:
Q: What is the difference between MDA and LDA and how is it applied in SciKit-learn? According to this paper, Canonical Discriminant Analysis (CDA) is basically Principal Component Analysis (PCA) followed by Multiple Discriminant Analysis (MDA). I am assuming that MDA is just Multiclass LDA.
My work uses SciKit-Learn's LDA extensively. According to its description, it is

A classifier with a linear decision boundary, generated by fitting class conditional densities to the data and using Bayes' rule.

It applies pretty well to cases with multiple classes; can this implementation be also called as MDA?
So to do CDA in Scikit-Learn, should one just apply PCA followed by LDA?


text:
Q: A combinatoric solution (closed expression) for $\sum_{k=i}^n \binom{n}{k}p^k(1-p)^{n-k}$ I am trying to find a combinatoric solution for $\sum_{k=i}^n \binom{n}{k}p^k(1-p)^{n-k}$.
i.e. write it as a closed function (and not as a sum).
I know that in generating functions one can for example multiply the relevant function  by $\frac{1}{1-x}$. But this is relevant for combinatoric problems like identical k balls in n cells.
Is there something like that for the formula above?

A: As mentioned in the comment by Jair Taylor there doesn't appear to be a closed form. The hypergeometric representation is
$$
Q(i,n,p)=\sum_{k=i}^n \binom{n}{k}p^k(1-p)^{n-k} = (1-p)^{n-i}p^i \binom{n}{i}\; _2F_1 \left(1,i-n;i+1;\frac{p}{p-1}\right)
$$
and the generating function is very similar
$$
\sum_{k=i}^n \binom{n}{k}p^k(1-p)^{n-k}x^{k} = (1-p)^{n-i}p^i x^i \binom{n}{i} \;_2F_1 \left(1,i-n;i+1;\frac{p x}{p-1}\right)
$$
if you want the generating function over all possible values of $i$, Mathematica claims there is a recursion relation for
$$
F(x)=\sum_{i=0}^n Q(i,n,p)x^i
$$
then if we define a function $y_k(x,p,n)$ where
$$
y_0 = 0 \\
y_1 = \left(\frac{1}{1-p}\right)^n \\
y_2 = y_1 + \left(y_1-1\right)x
%(n-k)p x^2 y_k - x(1+k-p-2kp+np-kpx+npx)y_{k+1} + (1 + k -p-kp + x + kx-px-2kpx+npx)y_{k+2}+(1+k)(p-1)y_{k+3}=0
$$
and in general
$$
y_{k+3} = a(k) y_{k+2} + b(k) y_{k+1} + c(k) y_{k}
$$
with
$$
a(k) = -\frac{(1 + k -p-kp + x + kx-px-2kpx+npx)}{(1+k)(p-1)}\\
b(k) = \frac{x(1+k-p-2kp+np-kpx+npx)}{(1+k)(p-1)} \\
c(k) = -\frac{(n-k)p x^2}{(1+k)(p-1)}
$$
then
$$
F(x) = (1-p)^ny_{n+1}
$$


text:
Q: Who can undownvote besides me? I downvoted a post yesterday and it got undownvoted today. Can the privileged users access my account and make these changes? Who else can make this change?

A:
I downvoted a post yesterday and it got undownvoted today.

If you have downvoted a post then it will appear like this

was the color still orange when you check the post again?
Or is the post like this now?

If it's not orange then you probably has double clicked on it (undownvoted it) like
animuson' comment says.

Can the privileged users access my account and make these changes?

Surely Not.

A: Jason as far as I know, you can upvote and downvote on any post and it shall not rollback,  unless you have a serial upvote or downvote on a particular account.  Technically, anyone with access to the database (which would be the SE developers) could change the vote, however this is only done when the voting is found to violate the rules (serial voting and using a sockpuppet to vote for your own posts).
Another thing might be that your vote was not reversed, but that someone else upvoted that post .


text:
Q: Laravel 5.1 - Testing a multiple selectbox I'm experiencing trouble when I write my tests for a multiple select box with the Laravel 5.1 testing helpers.
I've tried both storeInput and select which is kinda much an alias for storeInput. When I'm working with a multiple select and I want the input to be formatted as an array I've created a <select name="roles[]"> but this is not testable, I can't write something like this $this->storeInput( 'roles[]', [ 1, 2 ] ). The errors I get then are:

Symfony\Component\CssSelector\Exception\SyntaxErrorException: Expected
  identifier or "*", but  found.`

How is this possible to go around? I've also tested with an ID but
then I get the error `Unreachable field "THE_ID".

A: The way I did this is to create an override of storeInput as follows (I put this in my base TestCase so I could reach it from all my tests):
public function storeInput($element, $text, $force = false)
{
    if ($force) {
        $this->inputs[$element] = $text;
        return $this;
    }
    else {
        return parent::storeInput($element, $text);
    }
}

and then when testing a multiselect, strip off the trailing braces for the identifier you pass to this method:
$this->storeInput('roles', [1, 2], true);


text:
Q: how to make static factory method for not static instance? I have few tests with explicit waits for selenium tests.
I use waiting too much. And I want to move it to base class and cut every time create new object:

new WebDriverWait(...)

Now it looks next:
public void logOutUser() {
    new WebDriverWait(driver, 30).until(presenceOfElementLocated(By.xpath("//span[@class='gb_W gbii']")));
    userOptionsMenu.click();
    new WebDriverWait(driver, 30).until(presenceOfElementLocated(By.xpath("//div/a[@id='gb_71']")));
    signOutLink.click();
}

I want to move it to Base class, and circumvent redundant object creation.
Base class:
public class AndroidBasePage implements IPage {

    protected WebDriver driver = null;

    private WebDriverWait driverWait;

    public AndroidBasePage() {
        driver = SeleniumManager.activeBrowser();
    }

    @Override
    public WebDriver getDriver() {
        return driver;
    }

    public WebDriverWait getWait() {
        if (driverWait == null) {
            driverWait = new WebDriverWait(driver, 30);
        }
        return driverWait;
    }
    protected void driverWaitPresenceOfElement(String xpath) {
        getWait().until(presenceOfElementLocated(By.xpath(xpath)));
    }
}

It works now:
public void logOutUser() {
    driverWaitPresenceOfElement("//span[@class='gb_W gbii']");
    userOptionsMenu.click();
    driverWaitPresenceOfElement("//div/a[@id='gb_71']");
    signOutLink.click();
}

But I not sure about it efficiency. Any suggestions.
Does exist some way to make getWait() static?

A: We did something similar in our Selenium webdriver based project(non Android) years back. using an abstract super class. One of the functionalities was  getElement(String id/Xpath/name etc), which would provide wait implicitly.
for your case I would like to know why you need a factory method? rather make it part of your object instantiation (wait needs your exact driver instance). slightly modifying your class:
public class AndroidBasePage implements IPage {

    protected WebDriver driver;

    private WebDriverWait driverWait;

    public AndroidBasePage() {
        driver = SeleniumManager.activeBrowser();
         //only one driverwait for a page instance
        driverWait = new WebDriverWait(driver, 30);//time should be configurable
    }

    @Override
    public WebDriver getDriver() {
        return driver;
    }

    protected void driverWaitPresenceOfElement(String xpath) {
       driverWait.until(presenceOfElementLocated(By.xpath(xpath)));
    }
}

A: I see that you have a fixed wait time of 30 seconds. Is'nt it better to use implicit wait after you call the web driver initialization?
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);


text:
Q: Making random rectangles on Processing I want to make random rectangles on Processing. So far, I used for loops for making window size rectangle but I can't figure out how to make only 10 rectangle randomly. Here is my sample code for you:
void setup()
{
  size(400, 400);
}

void draw()
{
  background(0); // Black Background

  stroke(255); // White lines

  for (int j = 0; j <= height; j += 40)
  {
    for (int i = 0; i < width; i += 40)
    {
      fill(0);
      rect(i, j, 40, 40);
    }
  }
}

It shows 100 black rectangles but I want to see only 10 black rectangles. For example: The first line will get random 1 rectangle, second line will get 2 , third line will get 1 and it goes till the 10.

A: There are multiple ways to solve this fun homework/exercise.
First thing is drawing the right number of boxes per column:
void setup()
{
  size(400, 400);

  background(0); // Black Background
  fill(0);
  stroke(255); // White lines

  int boxSize = 40;
  int maxBoxes = 1;

  for (int j = 0; j <= height; j += boxSize)
  {
    // box count per row
    int boxCount = 0;

    for (int i = 0; i < width; i += boxSize)
    {
      // only draw the max number of boxes
      if(boxCount < maxBoxes){

        rect(i, j, 40, 40);
        // increment per row box count
        boxCount++;
      }
    }
    // increment max boxes per box
    maxBoxes++;
  }
}

Secondly the positions for the drawn boxes per column need to be randomized, but ideally not overlap. One option is to split the full solution space to sections: each section having it's own range of positions so it won't overlap the next.
void setup()
{
  size(400, 400);

  background(0); // Black Background
  fill(0);
  stroke(255); // White lines

  int boxSize = 40;
  int maxBoxes = 1;
  int totalBoxes = width / boxSize;

  for (int j = 0; j <= height; j += boxSize)
  {
    // box count per row
    int boxCount = 0;
    // a list of box indices of where to draw a box (as opposed
    int[] randomXIndices = new int[maxBoxes];
    // how many index ranges to span per row
    int indexRangePerBox = totalBoxes / maxBoxes;
    // for each random index
    for(int k = 0 ; k < maxBoxes; k++)
    {
      // pre-calculate which random index to select
      // using separate ranges per box to avoid overlaps
      randomXIndices[k] = (int)random(indexRangePerBox * k, indexRangePerBox * (k + 1));
    }

    for (int i = 0; i < width; i += boxSize)
    {
      // only draw the max number of boxes
      if(boxCount < maxBoxes)
      {

        int randomX = randomXIndices[boxCount] * boxSize;

        rect(randomX, j, 40, 40);
        // increment per row box count
        boxCount++;
      }

    }
    // increment max boxes per box
    maxBoxes++;
  }
}

void draw(){
}

void mousePressed(){
  setup();
}

Click to reset. Notice that the bottom rows almost always look the same:

*

*there is less wiggle room to pick a random position

*random() is a rough pseudo-random number generator, but there are better ones out there like randomGaussian(), noise(), etc.

*overall there are other strategies to explore picking random positions and avoiding overlaps

Live demo bellow:

function setup()
{
  createCanvas(400, 400);
  reset();
  // reset once per second
  setInterval(reset, 1000);
}

function reset(){
  background(0); // Black Background
  fill(0);
  stroke(255); // White lines

  var boxSize = 40;
  var maxBoxes = 1;
  var totalBoxes = width / boxSize;

  for (var j = 0; j <= height; j += boxSize)
  {
    // box count per row
    var boxCount = 0;
    // a list of box indices of where to draw a box (as opposed
    var randomXIndices = new Array(maxBoxes);
    // how many index ranges to span per row
    var indexRangePerBox = totalBoxes / maxBoxes;
    // for each random index
    for(var k = 0 ; k < maxBoxes; k++)
    {
      // pre-calculate which random index to select
      // using separate ranges per box to avoid overlaps
      randomXIndices[k] = floor(random(indexRangePerBox * k, indexRangePerBox * (k + 1)));
    }

    for (var i = 0; i < width; i += boxSize)
    {
      // only draw the max number of boxes
      if(boxCount < maxBoxes)
      {

        var randomX = randomXIndices[boxCount] * boxSize;

        rect(randomX, j, 40, 40);
        // increment per row box count
        boxCount++;
      }

    }
    // increment max boxes per box
    maxBoxes++;
  }
}

function draw(){
}

function mousePressed(){
  reset();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>


text:
Q: Very weird PreparedStatement in java? I found a very odd PreparedStatement in a program today do to an error that I received.  I tracked it down and found some perplexing SQL.  Now, I am no master of SQL or PreparedStatements, but this seems very wrong.  I should also mention that this works on a coworker's computer but not mine.
static final String SELECT_UNCOMPLETE_TASKS_FOR_UPGRADE =
"SELECT i.employeeid, i.taskid, i.itptaskarchivecd, i.itptaskstartdt, i.itptaskcompletiondt,t.taskobsoletecd, "
+ "t.taskknowledgetx, t.taskProductid, t.taskrfrncid, t.taskcorecd, t.taskwartimecd, t.parentheaderid, "
    + "t.taskparentindcd, i.itptaskstatuscd, i.itptaskarchivedt, t.certified "
    + "FROM itptask i,task t "
    + "WHERE (i.itptaskcompletiondt is NULL "
        + "AND i.employeeid = ?1 "
        + "AND i.taskid = t.taskid "
        + "AND i.itptaskarchivecd = ?2 "
        + "AND t.taskproductcd = ?3 "
        + "AND t.taskobsoletecd = ?4 "
        + "AND t.taskcorecd = ?5) "
    + "OR (i.employeeid = ?6 "
        + "AND i.taskid = t.taskid "
        + "AND 'T' = t.taskparentindcd "
        + "AND t.taskproductcd = ?7)";

My question is simple, what are the numbers after the parameter placeholders (Question marks) for? If this is completely incorrect syntax, what would allow it to work in another workspace/environment?  Any and all help would be greatly appreciated.  Thanks.

A: That particular syntax looks to be specific to JPA syntax.  In JPA, you could specify ?# to specify the parameter index via a Query object.
Query myQuery = entityManager.createNativeQuery("select * from my_table where foo = ?1 and bar = ?2");

q.setParameter(1,myFoo);
q.setParameter(2,myBar);


text:
Q: output comes out to an integer when I want a string import java.util.Scanner;

public class QuestionTwo{

    public static void main(String[] args) {
        Integer number;
        Character first, middle, last;
        Scanner keyboard = new Scanner(System.in);
        System.out.print("First name: ");
        first = keyboard.next().charAt(0);
        System.out.print("Middle name: ");
        middle = keyboard.next().charAt(0);
        System.out.print("Last name: ");
        last = keyboard.next().charAt(0);
        System.out.print("Which type of sort order would you like (1 for ascending and 2 for descending)? ");
        number = keyboard.nextInt();

        if (number == 1) {

            System.out.println("Sort order: 1");

            if ((first) < (middle) && (first) < (last)) {

                if ((middle) < (last)) {

                    System.out.println(first + middle + last);
                }

                if ((last) < (middle)) {
                    System.out.println(first + last + middle);
                }
            }

            if ((middle) < (first) && (middle) < (last)) {

                if ((first) < (last)) {
                    System.out.println(middle + first + last);
                }
                if ((last) < (first)) {

                    System.out.println(middle + last + first);
                }
            }

            if ((last) < (middle) && (last) < (first)) {

                if ((middle) < (first)) {
                    System.out.println(last + middle + first);
                }
                if ((first) < (middle)) {
                    System.out.println(last + first + middle);
                }
            }
        }

        if (number == 2) {
            System.out.println("Sort order: 2");
            if ((first) > (middle) && (first) > (last)) {
                if ((middle) > (last)) {
                    System.out.println(first + middle + last);
                }

                if ((last) > (middle)) {
                    System.out.println(first + last + middle);
                }
            }

            if ((middle) > (first) && (middle) > (last)) {
                if ((first) > (last)) {
                    System.out.println(middle + first + last);
                }

                if ((last) > (first)) {
                    System.out.println(middle + last + first);
                }
            }

            if ((last) > (middle) && (last) > (first)) {
                if ((middle) > (first)) {
                    System.out.println(last + middle + first);
                }

                if ((first) > (middle)) {
                    System.out.println(last + first + middle);
                }
            }
        }
    }
}

The output that I get from this is a large integer value, whereas what the program should do is ask for a first name, then middle name, then last name. It should then ask for which sort order, 1 being ascending and 2 being descending. What this means is that once it gets the name it looks through the names and counts the number of letters per name. It will then give the answer as the name sorted in the order that the user selected.
For example:
if I tell it my name is David H. Anderson, and click 1 for ascending order, my result should be "H. David Anderson", as H. is 2 symbols, David is 5 and Anderson is 8.
What it currently does is all of the above except for giving me the last line int he format I want (I end up just getting a number).

A: I would change a few things to get you started.
Firstly, your input should probably be a String
Secondly, remove .charAt(0)
Then compare the String lengths before printing them.

A: Try this:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class Main2 {

    private static ArrayList<String> splitAndSortFullName(String fullName, int sortOrder) {
        String[] names = fullName.split(" "); //Split names by space character.

        //Create a list with only non-empty names:
        ArrayList<String> namesList = new ArrayList();
        for (int i=0; i<names.length; ++i)
            if (!names[i].isEmpty())
                namesList.add(names[i]);

        switch (sortOrder) {
            case 1: Collections.sort(namesList); break;
            case 2: Collections.sort(namesList, (a, b) -> { return b.compareTo(a); }); break;
        }

        return namesList;
    }

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);

        System.out.print("Enter full name: ");

        String fullName = keyboard.nextLine(); //Read the full name. For example "John D. Doe".

        System.out.print("Which type of sort order would you like (1 for ascending and 2 for descending)? ");

        int number = keyboard.nextInt();

        System.out.println(splitAndSortFullName(fullName, number));

        //For use with many full names, just re-call the method splitAndSortFullName(...). For examples:
        System.out.println("Full examples:");
        System.out.println(splitAndSortFullName("John D. Doe", 1));
        System.out.println(splitAndSortFullName("Alice K. Example", 2));
        System.out.println(splitAndSortFullName("Martin T. Anderson", 1));
    }
}

In this code, the user enters his complete name fully.

A: import java.util.Scanner;

public class QuestionTwo

{

  public static void main(String[] args)
  {
    Integer number;

    String first, middle, last;

    Scanner keyboard = new Scanner (System.in);

    System.out.print("First name: ");

    first = keyboard.next();

    System.out.print("Middle name: ");

    middle = keyboard.next();

    System.out.print("Last name: ");

    last = keyboard.next();

    System.out.print("Which type of sort order would you like (1 for ascending and 2 for descending)? ");

    number = keyboard.nextInt();

    int firstLength = first.length();
    int middleLength = middle.length();
    int lastLength = last.length();

    if(number == 1)
    {
      System.out.println("Sort order: 1");

  if(firstLength < middleLength && firstLength < lastLength)
  {

    if(middleLength < lastLength)
    {

      System.out.println (first + " " + middle + " " + last);
    }

    if(lastLength < middleLength)
    {

      System.out.println (first + " " + last + " " + middle);
   }
  }

  if(middleLength < firstLength && middleLength < lastLength)
  {

    if(firstLength < lastLength)
    {

      System.out.println (middle + " " + first + " " + last);
    }

    if(lastLength < firstLength)
    {

      System.out.println (middle + " " + last + " " + first);
    }
  }

  if(lastLength < middleLength && lastLength < firstLength)
  {

    if(middleLength < firstLength)
    {

      System.out.println(last + " " + middle + " " + first);
    }

    if(firstLength < middleLength)
   {

     System.out.println(last + " " + first + " " + middle);
    }
  }
}

if(number == 2)
{

  System.out.println("Sort order: 2");

   if(firstLength > middleLength && firstLength > lastLength)
  {

    if(middleLength > lastLength)
    {

      System.out.println (first + " " + middle + " " + last);
    }

    if(lastLength > middleLength)
    {

      System.out.println (first + " " + last + " " + middle);
    }
  }

  if(middleLength > firstLength && middleLength > lastLength)
  {

    if(firstLength > lastLength)
    {

     System.out.println (middle + " " + first + " " + last);
    }

    if(lastLength > firstLength)
    {

      System.out.println (middle + " " + last + " " + first);
    }
  }

  if(lastLength > middleLength && lastLength > firstLength)
 {

    if(middleLength > firstLength)
    {

      System.out.println(last + " " + middle + " " + first);
    }

    if(firstLength > middleLength)
    {

      System.out.println(last + " " + first + " " + middle);
    }
  }
}
}
}

Listening to the comments and with help from thanopi57, I was able to get the proper answer. The first thing I did was to remove the ".AtChar(0)" and define the variables as Strings, not Characters. I then defined the variables as variable length, with variable xxxx becoming int xxxxLength=xxxx.Length();, doing this for all three variables (which converted them from String to Int). I then replaced the subsequent concatenation operands with my newly defined variables, I also added " " for spaces inbetween operands in the println lines.


text:
Q: Google Sheets return value based on multiple conditions I have a google sheet that looks like this
Empty sheet
In the same sheet, I have this source data:
Source data
The name column is the exact same names that are arranged horizontally in the sheet
The status column is a text
My goal is to add either an "X" or "O" in the cells under each name and next to the appropriate date column based on the status of each person on a specific day.
If status = "On site" then put "X", if status is "Off site" then put "O"
The output should look something like this:
Goal
So 3 things should match: name, status, and date
I tried using IF() functions with AND() but it's not giving me the desired output.
I tried the following:
=IF(AND(T15="Person 1", U15="On site", V15=A2), "X", "O")

V15 is the cell containing the source date and A2 is the cell containing the destination date
Why is this not working? What am I doing wrong? any help is greatly appreciated!

A: try in C2:
=INDEX(IFNA(SUBSTITUTE(SUBSTITUTE(VLOOKUP(A2:A,
 QUERY({T15:V22; SPLIT(FLATTEN(C1:M1)&"×!×1", "×")},
 "select Col3,max(Col2) where Col2 is not null group by Col3 pivot Col1"),
 MATCH(C1:M1, TRANSPOSE(SORT(FLATTEN(C1:M1))), 0)+1, 0),
 "On site", "X"), "Off site", "O")))

update
optimized formula:
=INDEX(IFNA(IF(A2:A="",,SUBSTITUTE(SUBSTITUTE(VLOOKUP(TO_TEXT(A2:A),QUERY({QUERY(TEXT(
 IMPORTRANGE("1IANXcVXKRMj591vs_jLkHAQp-ZCoZFpbf7xOSm2srJA", "Form Responses 1!A2:C"),
 {"m/d/yyyy", "@", "@"}), "where Col2 <> '0'");
 SPLIT("!×"&FLATTEN(C1:M1)&"×!", "×")},
 "select Col1,max(Col3) where Col2 is not null group by Col1 pivot Col2"),
 MATCH(C1:M1, TRANSPOSE(SORT(FLATTEN(C1:M1))), )+1, ),
 "Working alone", "X"), "Not working alone/Not working", "O"))))


text:
Q: UICollectionViewCell with Binding Variable for SwiftUI? So I'm building a project based on SwiftUI and on one of my struct Views I have a UIViewRepresentable that produces a UICollectionView. Also on this View, I have a @State variable called 'showNextSheet' that presents a new sheet when toggled.
I've implemented the UICollectionView successfully, but now I'm trying to present a new sheet when a user clicks on a cell in the UICollectionView. I have access to the 'didSelectItemAt' method, but I can't figure out how to pass the Binding variable (showNextSheet) into the cell. Is this possible?


text:
Q: How to use classes like RegistryRoot correctly in custom actions? I have to implement a custom action to search the windows registry for the installed version of the dotnet framework. Therefore I thought to extend the ReadRegistryValueAction to integrate my individual search algorithm. But the custom action will not be found at the IDE. So I extends the action from the AbstractInstallAction and included the RegistryRoot class to configure the action inside the IDE the same way as with provided registry actions of install4j framework.
public class CheckDotNetInstallationAction extends AbstractInstallAction {

    private RegistryRoot registryRoot;

    public RegistryRoot getRegistryRoot() {
        return registryRoot;
    }

    public void setRegistryRoot(RegistryRoot registryRoot) {
        this.registryRoot = registryRoot;
    }

    @Override
    public boolean install(InstallerContext paramInstallerContext)
            throws UserCanceledException {
        // do custom search
        return false;
    }
}

But instead to get a dropdown list, there is only a blank field. I expected also a dropdown list the same way as in the present registry action. Now there are two questions:

*

*Is it possible to extends existing actions/screens/forms and to use and configure it in the IDE or is it necessary to extends from the AbstractInstallAction?

*How can I use classes like RegistryRoot for my custom components the same way as they are used in the actions provided by the install4j framework? Specifically the way to configure these components inside the IDE.

A: You have to add add a BeanInfo class and set an enumeration mapper. See the source file
samples/customCode/SampleActionBeanInfo.java
in your install4j install4j Installation and and look for the the call to setEnumerationMappers.


text:
Q: Exact difference between "keep doing" and "keep on doing"? I often come across sentences like these

He kept on chasing the thief even it's deep into the night.
  Shall we keep practicing in the next few days?

But as far as I'm concerned, both of the following sounds fairly OK.

He kept chasing the thief ...
  Shall we keep on practicing ...?

I can barely remember that they have a monir difference in meaning but I Googled (and searched ELL.SE) around and found only usage differences. Can anyone tell the exact difference in meaning?

A: When you say keep doing X, it means twothings: A) you expect X to be finished soon or at a definite time, and B) you were already doing X

Keep looking at this report.

When you say keep on doing X, it means two things: A) you're talking about making X part of a routine or background activity, and B) you were already doing it.

Keep on looking at these reports everyday.

It can also mean to progress further with a path or course.  In these cases you can omit the -ing word if it will be understood from context.

Keep on walking down the path until you get to the house.  ("Keep on down the path until you get to the house" also works.)
Keep on driving until you are past 5th street.  ("Keep on until you are past 5th street" also works.)

A: To the idea of "persistence" that comes from "keep" + {verb}ing, the word on adds a vague sense of forward motion (onward in space|time) and so it serves to make the abstract idea of "persistence" more concrete, which makes the statement more emphatic.


text:
Q: Lifetimes of stable particles What are possible lifetimes of up/down quarks, electronic/muonic/tau neutrinos, photon, gluon?
I understand they are said to be stable, but, as I saw on wikipedia, the lower bound for the "stable" electron's mean lifetime is $4.6×10^{26}$years. Are there any bounds for the mentioned particles?

A: Here is the elementary particle table of the Standard Model

Stability for these building blocks of matter is an experimental observation, with  limits for the ones never seen to decay. Columns II and III have measured lifetimes, excepting the neutrinos.Z and W also have measured lifetimes.
The neutrinos have a very small mass and there is nothing with smaller mass they could decay into except each other, and that is called neutrino oscillations and have been measured.
The photon and gluon have 0 mass and cannot decay.
The u and d are bounded in lifetime by the order of 10^34years  of the proton decay.
The theory of the Standard Model describes all the existing data very successfully. New theories will have to embed it and predict/give these experimental bounds.


text:
Q: show a windows form from a window service i am creating a window service. my requirement is to display window form from window NT service on particular interval. For testing purpose , i just want to display the form on service start:
 protected override void OnStart(string[] args)
        {
            eventLog1.WriteEntry("In OnStart -before form show");

            Messager_Form obj = new Messager_Form();
            obj.Show();
           // System.Diagnostics.Process.Start("calc.exe");
            eventLog1.WriteEntry("In OnStart -after form show");
           // timer1.Start();
        }

it not working. Neither form is showing nor calc process is running.  i have found some links
showing pop up  , but most of them suggesting WCF. isn't it possible without wcf. can anybody show me the way to achieve this.

A: Cant be done*. In later Operating Systems that won't work as Windows Services are disallowed from interacting with the Desktop - instead UI presented by Windows Services is shown in Session 0, a special logon session which is not normally visible to the end user.
What you should instead do is write a separate Windows Forms application which is always running, but not always visible (possibly have that application run at startup and have an icon in the notification area) and communicates with the Windows Service using some form of IPC
When the Windows Service wishes to display some UI to the user it sends a message to the application, which in turns shows the desired UI to the end user.
*or at least it definitely shouldn't be done

A: I am just referring to the answer given in another link in StackOverflow
How to communicate with a windows service from an application that interacts with the desktop?
Answer is :
Be aware that if you are planning to eventually deploy on Windows Vista or Windows Server 2008, many ways that this can be done today will not work. This is because of the introduction of a new security feature called "Session 0 Isolation".
Most windows services have been moved to run in Session 0 now in order to properly isolate them from the rest of the system. An extension of this is that the first user to login to the system no longer is placed in Session #0, they are placed in Session 1. And hence, the isolation will break code that does certain types of communication between services and desktop applications.
The best way to write code today that will work on Vista and Server 2008 going forward when doing communication between services and applications is to use a proper cross-process API like RPC, Named Pipes, etc. Do not use SendMessage/PostMessage as that will fail under Session 0 Isolation.
http://www.microsoft.com/whdc/system/vista/services.mspx
Now, given your requirements, you are going to be in a bit of a pickle. For the cross-platform concerns, I'm not sure if Remoting would be supported. You may have to drop down and go all the way back to sockets: http://msdn.microsoft.com/en-us/library/system.net.sockets.aspx

A: Checking the "Interact with desktop" box will work on Windows NT, 2000, XP and 2003 but thanks to Session 0 Isolation that setting no longer works as you may expect in Windows Vista and beyond. You want to think very carefully before developing an interactive service...


text:
Q: Force an unchecked call Sometimes, when using Java reflection or some special storing operation into Object, you end up with unchecked warnings. I got used to it and when I can't do anything about it, I document why one call is unchecked and why it should be considered as safe.
But, for the first time, I've got an error about a unchecked call. This function :
public <K,V extends SomeClass & SomeOtherClass<K>> void doSomethingWithSomeMap (Map<K,V> map, V data);

I thought that calling it this way :
Map someMap = ...;
SomeClass someData = ...;
doSomethingWithSomeMap(someMap, someData);

would give me an unchecked call warning. Jikes does a warning, but javac gives me an error :
Error: <K,V>doSomethingWithSomeMap(java.util.Map<K,V>,V) in SomeClass cannot be applied to (java.util.Map,SomeClass)
Any way to force it to compile with a warning?
Thanks.

A: In what voodoo have you got yourself into :) ? From the question and comments I assumed that you are sure that you have objects that extend abstract class SomeClass and also implement interface SomeOtherClass. If this is the case I suggest an intermediate abstract class in the hierarchy that share these properties.
public abstract class Foo<K> extends SomeClass implements SomeOtherClass<K> {
  ...
}

That way you could simplify the static method signature to:
public <K,V extends Foo<K>> void doSomethingWithSomeMap (Map<K,V> map, V data);

If you do not want to change your current object hierarchy you can fool the compiler using another level of indirection with the adapter pattern.

"All problems in computer science can
  be solved by another level of
  indirection." -- David Wheeler

public abstract class SomeClass {
  public abstract void method1();
}

public interface SomeOtherClass<K> {
  void method2(K value);
}

public class MyClass extends SomeClass implements SomeOtherClass<Integer> {
  @Override
  public void method1() {
    System.out.println("MyClass.method1");
  }

  @Override
  public void method2(Integer value) {
    System.out.println("MyClass.method2(" + value + ")");
  }
}

public class Indirection<K> extends SomeClass implements SomeOtherClass<K> {
  private final Object objectValue;

  public Indirection(final Object value) {
    this.objectValue = value;
  }

  @Override
  public void method1() {
    ((SomeClass) objectValue).method1();
  }

  @Override
  public void method2(K value) {
    @SuppressWarnings("unchecked")
    SomeOtherClass<K> delegate = ((SomeOtherClass<K>) objectValue);

    delegate.method2(value);
  }
}

public static void main(String[] args) {
  Map someMap = new HashMap<Integer, MyClass>();
  SomeClass someData = new MyClass();
  Indirection a = new Indirection(someData);
  doSomethingWithSomeMap(someMap, a, 12);
}

public static <K,V extends SomeClass & SomeOtherClass<K>>
void doSomethingWithSomeMap (Map<K,V> map, V data, K value) {
  data.method1();
  data.method2(value);
}

This would print:

MyClass.method1
  MyClass.method2(12)

A: You already know that the problem is the type of someData. Unfortunately Java does not currently allow you to use the intersection type SomeClass & SomeOtherClass as the type for declaring a variable, nor as a cat target.
But there is a not-so-perfect way to do just this, by introducing an spurious type variable X extends SomeClass & SomeOtherClass and then declaring X someData.
This should be done on the method that reflectively produces values to be assigned to someData. An unchecked cast (X) will be necessary which is provably safe.
Overall, something like this:
public <X extends SomeClass & SomeOtherClass>
void doReflectionMagic() {
    Map someMap = ...;
    X someData = (X) ...;
    doSomethingWithSomeMap(someMap, someData);
}

A: Try to specify it explicitely:
//Type2 is subclass of (or implements) SomeClass
Map<Type1, Type2> someMap = ...;
SomeClass someData = ...;
<Type1, Type2>doSomethingWithSomeMap(someMap, someData);

A: You specify the second bound for V to extend SomeOtherClass. But I assume SomeClass does not implement SomeOtherClass (if it did, you wouldn't need multiple bounds). So someData does not conform to this bound, and hence compiler error. The variable someData needs to belong to a class which both extends SomeClass and implements SomeOtherClass.


text:
Q: How does an electric dipole lose its energy while aligning with a uniform electric field? How does an electric dipole lose its energy while aligning with a uniform electric field: through heat or light?

A: The potential energy a molecular dipole loses when aligning to an electric field is either converted to rotational kinetic energy in the free dipole which eventuallt converts back to potential energy (oscillation) or it converts into heat when friction with other molecules occurs. The latter is responsible for the microwave heating of water. Some energy might also be converted to emitted EM radiation due to the rotational dipole oscillaton.

A: You are asking what happens to the work that is done when a dipole rotates into alignment with an applied electric field. In particular whether it emerges in the form of light (more precisely, electromagnetic radiation) or heat (random movement of other molecules).
The answer (as @freecharly says) is that it could be a bit of both; but most commonly we would assume it's lost through EM radiation. Or to be more precise, the energy lost by the dipole takes the form of an oscillating electric and magnetic field disturbance that propagates outwards into the universe.
Alternately you could say that "the dipole emits a photon of the corresponding energy".

A: In an electric field ($\vec{E}$), the electric dipole ($\vec{P}$) experience a torque approximated by $\vec{\tau}=\vec{P}\times \vec{E}$. Due to this torque, the dipole gains angular momentum, which is what the potential energy is converted to when the dipole aligns with the field.
When the dipole is finally aligned with the fields, instead of stopping it starts oscillating due to the angular velocity it has gained. But there is also a simultaneous loss of energy through radiation, which is because the charges are accelerating while rotating. Thus, the oscillation completely stops after a finite time, because all the energy has been lost through radiation.
To conclude, the energy is lost in  2 ways:

*

*Rotational Energy

*Radiation

A: Electric dipole has different potential energy in different direction in electric field . It has lowest energy in direction of constant electric field because it is most stable there as net force is zero. So if electric dipole aligned in any direction ( having some energy) is aligned in direction of electric field its final potential energy decreases.

A: Isolated dipole
If we talk about an isolated dipole then it will not lose its energy - rather its potential energy would convert into rotational energy, which will then be converted back to the potential energy when the dipole passes the position of its potential minimum. The total energy thus can be written as
$$
E=\frac{I\dot{\theta}^2}{2} - dE\cos\theta,
$$
where $\theta$ is the angle between the dipole moment, $\mathbf{d}$ and the electric field, $\mathbf{E}$; $V(\theta)=-\mathbf{d}\cdot\mathbf{E}=dE\cos\theta$ is the potential energy of the dipole, and $\frac{I\dot{\theta}^2}{2}$ is its rotational kinetic energy. The motion of the dipole is then that of a non-linear oscillator, described by the sine-Gordon-like equation equation
$$
I\ddot{\theta}+dE\sin\theta=0,
$$
which can be analyzed using Floquet theory or linearized for small oscillations (it is identical to the equation of a pendulum).
Dipole in a real world
In most real life situations the oscillations of the dipole will be damped. As a minimum that can be described by introducing the damping term in the oscillator equation above:
$$
I\ddot{\theta}+\gamma I\dot{\theta}+dE\sin\theta=0.
$$
In terms of the more general Bloch equations, which describe magnetic and electric dipoles, the damping coefficient corresponds to the relaxation time $T_1=\gamma^{-1}$.
Energy loss mechanisms
The machanisms leading to the damping depend on the concrete physical situation:

*

*interaction with other dipoles (as, e.g. in Ferroelectric materials)

*radiating photons

*interaction with other surrounding environment: crystal lattice, free electrons in a metal, etc.

Light or heat?
In elementary mechanics one often speaks of heat as anything but the mechanical energy (potential and kinetic terms in my first equation). However, in statistical physics heat is a more specific term, referring to the average energy of microscopic motion. Thus, whether the energy is converted to heat or not does not depend on depend on the specific energy transfer mechanism, but whether the energy becomes diffused between many microscopic degrees of freedom or not. That is conversion to light may be as well conversion to heat - in the form of the black body radiation.
(The OP opposes heat and light: How does an electric dipole lose its energy while aligning with a uniform electric field--through heat or light?)
When discussing ferroelectric or similar phenomena, one usually ignores the specific loss mechanism, assuming that the dipoles, after losing their energy, become oriented along the field. In this case we talk about the energy converted to heat, regardless of what is the transfer mechanism.


text:
Q: Looping off of MySQL result and building custom array The following code is building the proper structure of array that I want, but it's only doing it for one result even though the MYSQL result is about 65 items.
I need the 'type' and 'features' levels to be static, and then start the loop within the features level (so every mysql result would build an item in within the features level)
The following is only loading the last result from the query:
$db->setQuery($query);
$item=$db->loadObjectList();
echo $db->getErrorMsg();
//dump($item);

$stores = [
    'type' => 'FeatureCollection',
    'features' => [
      foreach ($item as $i) {
        [
            'type' => 'Feature',
            'geometry' => [
                'type' => 'Point',
                'coordinates' => [
                    $i->lat,
                    $i->lng
                ]
            ],
            'properties' => [
                'storeImage' => $i->logo, // you need to convert this into an actual URL
                'storeName' => $i->name,
                'phoneFormatted' => $i->phone, // this needs formatting aswell
                'address' => $i->address,
                'city' => $i->city,
                'country' => $i->country,
                'postalCode' => $i->zip,
                'state' => $i->state
            ]
        ]
      }
    ]
];

How can I properly loop the mysql query to build my array in the correct way?

A: Use array_map() to generate a new array from another array.
$item=$db->loadObjectList();

$stores = [
    'type' => 'FeatureCollection',
    'features' => array_map(function($i) {
        return [
            'type' => 'Feature',
            'geometry' => [
                'type' => 'Point',
                'coordinates' => [
                    $i->lat,
                    $i->lng
                ]
            ],
            'properties' => [
                'storeImage' => $i->logo, // you need to convert this into an actual URL
                'storeName' => $i->name,
                'phoneFormatted' => $i->phone, // this needs formatting aswell
                'address' => $i->address,
                'city' => $i->city,
                'country' => $i->country,
                'postalCode' => $i->zip,
                'state' => $i->state
            ]
        ];
    }, $item)
];


text:
Q: Delete only those records from Master when 'sku' and 'link' match with the child table I want to delete only those records from Master when sku and link match with the child table
DECLARE @MASTER TABLE
(
SKU VARCHAR (50),
LINK VARCHAR (100)
)

INSERT @MASTER

SELECT 'A7061B',    'IMG_A7061S_A7061B.jpg' UNION ALL
SELECT 'A7063B',    'IMG_A7063S_A7063B.jpg' UNION ALL
SELECT 'A7065B',    'IMG_A7065S_A7065B.jpg'

SELECT * FROM @MASTER

DECLARE @CHILD TABLE

(
SKU VARCHAR (50),
LINK VARCHAR (100)
)

INSERT @CHILD

SELECT 'A7061B',    'IMG_A7061S_A7061B.jpg' UNION ALL
SELECT 'A7063B',    'IMG_A7063S_A7063B.jpg'

SELECT * FROM @CHILD

Expected Output
only below records should be deleted.
SKU,    LINK
A7061B, IMG_A7061S_A7061B.jpg
A7063B, IMG_A7063S_A7063B.jpg

A: In SQL Server you need a query like the following:
DELETE m
FROM @MASTER AS m
INNER JOIN @CHILD AS c ON m.LINK = c.LINK AND m.SKU = c.SKU


text:
Q: Simple C# server to stream video over HTTP I am trying to create a simple console application in C #. I need to make a streaming video and it must be accessible directly from the browser.
I was reviewing the link Streaming large video files .net, but it seems that this code is for asp.net
Another thing that i was trying, is TCPCliente, but I have problems when sending large files.
var fs = File.Open("../../video.mp4", FileMode.Open);

outHeaders.Add("Content-Type", "video/mp4");
outHeaders.Add("Accept-Ranges", "0-" + fs.Length);

long size = fs.Length;
long length = size;
long startBytes = 0;
long endBytes = size - 1;

if (headers["Range"] != null)
{
    var msg = System.Text.Encoding.ASCII.GetBytes("HTTP/1.0 206 Partial Content" + "\n");
    stream.Write(msg, 0, msg.Length);

    var range = ParseRange(size, headers["Range"].ToString());

    startBytes = range.Start;
    endBytes = range.End;

    fs.Seek(startBytes, SeekOrigin.Begin);
    length = endBytes - startBytes + 1;
}
else
{
    var msg = System.Text.Encoding.ASCII.GetBytes("HTTP/1.0 200 OK" + "\n");
    stream.Write(msg, 0, msg.Length);
}

outHeaders.Add("Content-Length", length);
outHeaders.Add("Content-Range", string.Format("bytes {0}-{1}/{2}", startBytes, endBytes, size));

SendHeader(stream, outHeaders);

int bytesRead = 0;
byte[] buf = new byte[client.SendBufferSize];
while (fs.Position <= endBytes &&
    (bytesRead = fs.Read(buf, 0, buf.Length)) > 0)
{
    stream.Write(buf, 0, bytesRead);
    stream.Flush();
}

fs.Close();

the problem is in:
while (fs.Position <= endBytes &&
    (bytesRead = fs.Read(buf, 0, buf.Length)) > 0)
{
    stream.Write(buf, 0, bytesRead);
    stream.Flush();
}

when fs.Position = 425984 I get the error:
No se controló System.IO.IOException
  HResult=-2146232800
  Message=No se pueden leer los datos de la conexión de transporte: Se ha forzado la interrupción de una conexión existente por el host remoto.
  Source=System
  StackTrace:
       en System.Net.Sockets.NetworkStream.Write(Byte[] buffer, Int32 offset, Int32 size)
       en HttpServer.Program.Main(String[] args) en j:\HttpServer\HttpServer\Program.cs:línea 85
       en System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       en System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       en Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       en System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       en System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       en System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       en System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       en System.Threading.ThreadHelper.ThreadStart()
  InnerException: System.Net.Sockets.SocketException
       HResult=-2147467259
       Message=Se ha forzado la interrupción de una conexión existente por el host remoto
       Source=System
       ErrorCode=10054
       NativeErrorCode=10054
       StackTrace:
            en System.Net.Sockets.Socket.Send(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
            en System.Net.Sockets.NetworkStream.Write(Byte[] buffer, Int32 offset, Int32 size)
       InnerException:

in line stream.Write(buf, 0, bytesRead);
What can i do?
thx


text:
Q: Create multiple copies of xlsx file with different file names on Mac Excel
*

*I have a .xlsx file that contains 4 sheets filled with data and
formulas etc.

*I need to duplicate that .xlsx file 1000 times and save each file
with a different name.

*I have another .xlsx file containing the list of 1000 names that I
would like these duplicates to be named when saved.

*Is it possible for me to do this without manually copying the file 1000 times and renaming every one?

*I am using excel on a Mac, not sure if this limits my options....


text:
Q: Leer fichero TXT y convertir ciertos valores en variables Tengo que comparar los tamaños de unas carpetas para poder hacer un % de diferencia entre ellas y en función del resultado enviar un mail. Quiero hacer el for por cada carpeta SITE, las carpetas SITE se encuentran todas a partir de un directorio, .../backup/SITE1..2..3. Mi intención es cuando termine el SITE1 utilice las mismas variables para el SITE2.

La parte de coger tamaños de carpeta y sacar el % y el envío de mail por separado por cada carpeta ya lo tengo resuelto, pero me gustaría simplificar el código y por ejemplo tener un fichero txt con las rutas de las carpetas, que lo leyera hasta un carácter y usara las variables, cuando terminara que siguiera con el siguiente SITE etc
    :SITE1
    Carpeta1
    Carpeta1.bkp
    Carpeta2
    Carpeta2.bkp

    :SITE2
    Carpeta1
    Carpeta1.bkp
    Carpeta2
    Carpeta2.bkp

Quiero asignar los valores de Carpeta1,... a variables hasta que encuentre ":", en ese momento ejecutar un comando y cuando termine continuar la lectura de SITE2 y volver a asignar sus variables
Gracias!

A: Escribí el siguiente script, creo que puede ayudarte, solo necitas adaptarlo a lo que necesitas. Saludos.
comando=0
for linea in $(cat prueba.txt)
do
    if [[ $linea == :* ]]
    then
        comando=$((comando+1));
        echo    "EJECUTAR COMANDO"
        if [ $comando -eq 1 ]
        then
            echo "GUARDAR VARIABLES"
        fi
    fi

done

A: No te explicas muy bien o soy yo el que no te entiende. He entendido que quieres:

*

*Leer de un tirón de sitio a sitio todas las carpetas.

*Aplicarles a todas las carpetas una función.

Entiendo, además, que el formato del fichero donde tienes apuntadas las carpetas es arbitrario y tú fijas el que quieres. Así que yo eliminaría los dos puntos y simplemente, separaría un sitio de otro con una línea en blanco (si deseas mantener los dos puntos tampoco hay problema.
Yo lo resolvería así::
awk -F '\n' -v RS='\n\n' '{for(i=1;i<=NF;i++) $i="\""$i"\""; print}' listado.txt | \
while read -r sitio; do
    eval set -- $sitio
    manipulacion "$@"
done

Y ya está: "manipulacion" es la función que ya tienes preparada según cuentas y que recibe como primer argumento el sitio (SITE1) y como resto de argumentos las carpetas. He complicado un poco el código para permitir que las carpetas (y el sitio) puedan tener espacios. Si quisieras mantener los dos puntos en el fichero no tendrías más que modificar un poco el bucle después del "set"::
sitio=${1#:}
shift
manipulacion "$sitio" "$@"


text:
Q: taking string input from user in java I am new to java and practicing java  programs. My code is as below:
String i;
    String[] people={"Ronald","Donald"};

System.out.println("Whose information do you want?"+Arrays.toString(people));
Scanner s =new Scanner(System.in);
**i=s.nextLine();**

          if(i=="Ronald")
     {
         System.out.println("Ronald is CEO and is in Room No 20");
     }
          if(i=="Donald")
     {
         System.out.println("Donald is postman and is in Room No 10");
     }

     }
    }

This is actually a simple program. What I wanted to know is whenever user inputs Ronald, its print statement should be printed in console. But the user should be asked whose information it wants to see. I wanted to know how to take string values from user.
Thank you in advance :)

A: Use the equals method when comparing Strings in java
if ( i.equals("Ronald") ){

}

A: check string equality this way
  if(i.equals("Ronald"))

not using ==
OUTPUT
Whose information do you want?[Ronald, Donald]
Ronald
Ronald is CEO and is in Room No 20

Use this class it fully works:
    import java.util.Arrays;
import java.util.Scanner;
class ronald {
    public static void main(String[] args) {
     String i;
     String[] people={"Ronald","Donald"};
     System.out.println("Whose information do you want?"+Arrays.toString(people));
     Scanner s =new Scanner(System.in);
     i=s.nextLine();
         if(i.equals("Ronald")) {
         System.out.println("Ronald is CEO and is in Room No 20");
         }
         if(i.equals("Donald")) {
         System.out.println("Donald is postman and is in Room No 10");
         }
     }
    }

output for Donald
Whose information do you want?[Ronald, Donald]
Donald
Donald is postman and is in Room No 10


text:
Q: Is there a way to simply resemble a truth table? Is there any simple way to resemble a truth table in code? It has 2 inputs and 4 outcomes, as shown below:

My current code is:
private void myMethod(bool param1, bool param2)
{
    Func<int, int, bool> myFunc;
    if (param1)
    {
        if (param2)
            myFunc = (x, y) => x >= y;
        else
            myFunc = (x, y) => x <= y;
    }
    else
    {
        if (param2)
            myFunc = (x, y) => x < y;
        else
            myFunc = (x, y) => x > y;
    }
    //do more stuff
}

A: I suggest using an array, i.e.
  // XOR truth table
  bool[][] truthTable = new bool[][] {
    new bool[] {false, true},
    new bool[] {true, false},
  };

...
  private void myMethod(bool param1, bool param2, bool[][] table) {
    return table[param1 ? 0 : 1][param2 ? 0 : 1];
  }

A: public int myTest(bool a, bool b)
{
  if(!b)
    return 3;
  return a ? 1 : 2;
}

A: To simplify your code you could use param1 and param2 as bits of a value indexing in a predefined array:
private void myMethod(bool param1, bool param2)
{
    Func<int, int, bool>[] myFuncs = {
        (x, y) => x > y,
        (x, y) => x < y,
        (x, y) => x <= y,
        (x, y) => x >= y
    };

    int index = (param1 ? 2 : 0) + (param2 ? 1 : 0);
    Func<int, int, bool> myFunc = myFuncs[index];
    //do more stuff
}

But of course simplicity and readability is in the eye of the reader.
If both paramX are false, index will be 0. If both are true, index will be 3 etc...


text:
Q: Bind RichTextBox.Selection in MVVM I have a RichTextBox in my MVVM program.
I would like to bind the RichTextBox.Selection property to my model.
To achieve this task, I've created a custom UserControl which contains a RichTextBox:
<UserControl x:Class="MyProject.Resources.Controls.CustomRichTextBox"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300">
    <RichTextBox x:Name="RichTextBox" SelectionChanged="RichTextBox_SelectionChanged"/>
</UserControl>

In my UserControl class:
// Selection property
public static readonly DependencyProperty TextSelectionProperty =
    DependencyProperty.Register("TextSelection", typeof(TextSelection),
    typeof(CustomRichTextBox));

[Browsable(true)]
[Category("TextSelection")]
[Description("TextSelection")]
[DefaultValue("null")]
public TextSelection TextSelection
{
    get { return (TextSelection)GetValue(TextSelectionProperty); }
    set { SetValue(TextSelectionProperty, value); }
}

The usage is:
<ResourcesControls:CustomRichTextBox TextSelection="{Binding ModelTextSelection}"/>

And I have this property on my model:
private TextSelection _TextSelection;
public TextSelection TextSelection
{
    get { return _TextSelection; }
    set { _TextSelection = value; }
}

I would like to get the RichTextBox.Selection property in my model, but TextSelection is always null.
I know I'm missing the binding between the RichTextBox.Selection property and his model but I don't know how to do it.
I think I'm missing something but I can't find what.

A: RichTextBox.Selection is not a DependancyProperty so you cannot bind to that.
But for your setup you just need to set the BindingMode as TwoWay on your UserControl  (ssuming your model property name is ModelTextSelection)
   <ResourcesControls:CustomRichTextBox TextSelection="{Binding ModelTextSelection, Mode=TwoWay}"/>

and in SelectionChanged method your need to update your TextSelection DependancyProperty with RichTextBox.Selection
    private void RichTextBox_SelectionChanged(object sender, RoutedEventArgs e)
    {

       TextSelection = richTextBox.Selection;

    }


text:
Q: Multi variable integral with probability density function of random variable I'm not good at multi variable integration. So, I am stuck at this part of research paper.
How the $p_{ij} - p_{ji}$ can be like the form of $rX(i)X(j)E[p_j-p_i]$?


text:
Q: Calculate the mean of groups of an unordered vector in R My question may be very simple!
I have an unordered variable.
I would like to cut this variable in k groups of equal size and then calculate the mean of each of these groups of values.
vec = c(1:10,1:5,2:6)
mean(vec[1:4])
mean(vec[5:8])
mean(vec[9:12])
mean(vec[13:16])
mean(vec[17:20])

Thanks in advance for your help!

A: Split into 5:
lapply(split(vec, sort(vec%%5)), mean)
$`0`
[1] 2.5

$`1`
[1] 6.5

$`2`
[1] 5.5

$`3`
[1] 3.5

$`4`
[1] 4.5

A: Another way would be to use aggregate
vec <- c(1:10,1:5,2:6)

mystep <- 4

bins <- rep(1:ceiling(length(vec)/mystep), each = mystep)
bins <- bins[1:length(vec)]  # removes any "overflow" values due to ceiling
xy <- data.frame(vec, bins)

aggregate(vec ~ bins, data = xy, FUN = mean)

  bins vec
1    1 2.5
2    2 6.5
3    3 5.5
4    4 3.5
5    5 4.5

A: vec = c(1:10,1:5,2:6)

# get quartiles, quantiles, or any prob
q <- quantile(vec, c(0.25,.5,.75, 1) )

# get the means
lapply(q, function(x){mean(vec[vec<=x])})

    $`25%`
[1] 1.6

$`50%`
[1] 2.636364

$`75%`
[1] 3.5

$`100%`
[1] 4.5

A: Thanks to this answer, I found a solution
vec = c(1:10,1:5,2:6)
aa= split(vec, floor(5 * seq.int(0, length(vec) - 1) / length(vec)))
lapply(aa, mean)
 # To be compared:
mean(vec[1:4])
mean(vec[5:8])
mean(vec[9:12])
mean(vec[13:16])
mean(vec[17:20])


text:
Q: Alternative to python atexit module that works when called from other scripts Using atexit.register(function) to register a function to be called when your python script exits is a common practice.
The problem is that I identified a case when this fails in an ugly way: if your script it executed from another python script using the execfile().
In this case you will discover that Python will not be able to locate your function when it does exits, and this makes sense.
My question is how to keep this functionality in a way that does not presents this issue.

A: I think the problem you're having is with the location of the current working directory. You could ensure that you're specifying the correct location doing something like this:
import os

target = os.path.join(os.path.dirname(__file__), "mytarget.py")

A: This works for me. I created a file to be executed by another file, a.py:
$ cat a.py
import atexit

@atexit.register
def myexit():
    print 'myexit in a.py'

And then b.py to call execfile:
$ cat b.py
import atexit

@atexit.register
def b_myexit():
    print 'b_myexit in b.py'

execfile('a.py')

When I run b.py, both registered functions get called:
$ python b.py
myexit in a.py
b_myexit in b.py

Note that both of these scripts are in the same directory when I ran them. If your a.py is in a separate directory as Ryan Ginstrom mentioned in his answer, you will need to use the full path to it, like:
execfile('/path/to/a.py')


text:
Q: Apache POI autoColumnWidth java.lang.OutOfMemoryError: GC overhead limit exceeded Am getting the OutOfMemoryError when the autoColumnWidth function is called on all the columns in my excel containing 1,28,237 rows and 20 columns. Am using SXSSF api and allocating -Xms2048m -Xmx4096m -XX:PermSize=1024m -XX:MaxPermSize=2048m to JVM but still no success.
CPU utilization goes upto 100% , my system RAM is 6gb which is used upto 5.8gb during the process and then i get OutOfMemoryError. Any solution to it ?
With this, I can think of one solution i.e. taking a variable for each column, finding the max length and in the end after all data is entered set the column to respective variable.
Any other solution?
My Code To Create Excel
public static void createVideodataExcelFile(String excelPath, int maxRiskArea){

    FileOutputStream fileOut = null;
    XSSFWorkbook workbook = new XSSFWorkbook();

    CellStyle style = workbook.createCellStyle();
    XSSFFont font = workbook.createFont();
    font.setColor(HSSFColor.BLACK.index);
    font.setBold(true);
    style.setFont(font);
    int cellCount = 0;

    try {
        File file = new File(excelPath);

        if(file.createNewFile()){
            SXSSFWorkbook wb = new SXSSFWorkbook(workbook);
            wb.setCompressTempFiles(true);
            Sheet sheet = wb.createSheet("GLE Video Data");
            int rowCount = sheet.getPhysicalNumberOfRows();
            //System.out.println("Row Count ="+rowCount);
            Row row = sheet.createRow(rowCount);

            Cell cell1 = row.createCell(cellCount);
            createCell(cell1, row, "CourseContent name", style, cellCount);
            createCell(cell1, row, "lang", style, ++cellCount);
            createCell(cell1, row, "CourseTitle", style, ++cellCount);
            createCell(cell1, row, "Audience", style, ++cellCount);
            createCell(cell1, row, "ContentRegion", style, ++cellCount);
            createCell(cell1, row, "CourseTitle", style, ++cellCount);
            createCell(cell1, row, "DeprecatedId", style, ++cellCount);
            createCell(cell1, row, "GleCode", style, ++cellCount);
            createCell(cell1, row, "Guid", style, ++cellCount);
            createCell(cell1, row, "LearningFormat", style, ++cellCount);

            for(int i = 0 ; i < maxRiskArea ; ++i){
                createCell(cell1, row, "RiskArea", style, ++cellCount);
            }

            createCell(cell1, row, "SalesforceId", style, ++cellCount);
            createCell(cell1, row, "Setting", style, ++cellCount);
            createCell(cell1, row, "SmsCode", style, ++cellCount);
            createCell(cell1, row, "pageID", style, ++cellCount);
            createCell(cell1, row, "title", style, ++cellCount);
            createCell(cell1, row, "ID", style, ++cellCount);
            createCell(cell1, row, "media_src", style, ++cellCount);
            createCell(cell1, row, "cuePoint", style, ++cellCount);
            createCell(cell1, row, "character", style, ++cellCount);
            createCell(cell1, row, "line", style, ++cellCount);

            fileOut = new FileOutputStream(excelPath);
            wb.write(fileOut);
            System.out.println("Excel Of GLE Data Created.");
        }

    } catch (IOException e) {
        errorLog.error("Excel Read/Write Error ="+e.getMessage());
        throw new GLEException(e);
    }
    finally{
        try {
            if(fileOut!=null)
            fileOut.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            errorLog.error("Excel Read/Write Error ="+e.getMessage());
            throw new GLEException(e);

        }
    }
}

private static void createCell(Cell cell , Row row, String name, CellStyle style, int cellCount ){
    cell = row.createCell(cellCount);
    cell.setCellStyle(style);
    cell.setCellValue(name);
}

A: Try to call trackAllColumnsForAutoSizing() on the SXSSFSheet object before calling autoSizeColumn(columnIndex) and it will be fixed