text:
Q: JAVA Program to find largest prime-factor, but the output is wrong? I have return the code(in Java) to Find the largest Prime-Factor of a given number.
I have found checked all the factors and then checked whether it is prime or not.... If so print the largest Prime Factor.
import java.util.Scanner;

public class Problem3 {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number");
        int n = Integer.parseInt(sc.next()); // Takes input from the user.
        int p=0,i,j,max=0,c=0;

        for(i=1;i<n;i++) {
            if(n%i != 0) { //Checks for factors and assigns that value to "c"
                c = i;
                for(j=1;j<c;j++) {
                    if(c%j==0) { //checks for prime number or not, if so... assign that value to "p"
                        p = j;
                    }

                    if(max<p) { // Checks for largest Prime factors, and assigns that value to "max"
                        max = p;
                    }
                }
            }

        }

        System.out.println(max); // prints the maximum prime-factor value.
        sc.close();
    }

}

I expect the output of 14 to be 7, but the actual output is 1

A: You prime check is wrong. c is prime only if c % j != 0 for all 1 < j < c.
int max=0,c=0;

for(int i=1;i<n;i++) {
    if(n%i == 0) { //Checks for factors and assigns that value to "c"
        c = i;
        for(int j=2;j<c;j++) {
            if(c%j==0) { // not prime
                c = 0;
                break;
            }
        }
        if(max < c) { // if c > max, it must be > 0, which means it must be prime
            max = c;
        }
    }
}

System.out.println(max); // prints the maximum prime-factor value.

A: Try this code
public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the number");
    int n = Integer.parseInt(sc.next()); // Takes input from the user.
    int p = 0, i, j, max = 0, c = 0;

    for (i = 1; i < n; i++) {
        if (n % i == 0) { //Checks for factors and assigns that value to "c"
            c = i;
            if (isPrime(c) && c > max) {
                max = c;
            }
        }
    }

    System.out.println(max); // prints the maximum prime-factor value.
    sc.close();
}

private static boolean isPrime(int num) {
    if (num == 0 || num == 1) {
        return false;
    }
    for (int i = 2; i < num / 2; i++) {
        if (num % i == 0) {
            return false;
        }
    }
    return true;
}

A: There seems to be an error in your for loop. I've created a method for this using java 8. try below code,
Java 8
public static void main(String[] args) {
    try (Scanner sc = new Scanner(System.in);) {
        System.out.println("Enter the number");
        int n = Integer.parseInt(sc.next()); // Takes input from the user.

        int max = IntStream.range(0, n).filter(q -> isFactor(n, q)).filter(q -> isPrimeNumber(q)).max().getAsInt();

        System.out.println(max); // prints the maximum prime-factor value.
    } catch (Exception e) {
        // TODO: handle exception
    }

}

public static boolean isPrimeNumber(int n) {
    int i, m = 0, flag = 0;
    m = n / 2;
    if (n == 0 || n == 1) {
        return false;
    } else {
        for (i = 2; i <= m; i++) {
            if (n % i == 0) {
                flag = 1;
                return false;
            }
        }
        if (flag == 0) {
            return true;
        }
    }
    return false;
}

public static boolean isFactor(int n1, int n2) {
    if(n2==0) {
        return false;
    }
    return n1 % n2 == 0;
}

Java 7
public static void main(String[] args) {
    try (Scanner sc = new Scanner(System.in);) {
        System.out.println("Enter the number");
        int n = Integer.parseInt(sc.next()); // Takes input from the user.

        int max = 0;

        for (int i = 0; i < n; i++) {
            if (isFactor(n, i)) { // checks for factor
                if (isPrimeNumber(i)) { // checks for prime
                    if (i >= max) { // checks for max number
                        max = i;
                    }
                }
            }
        }

        System.out.println(max); // prints the maximum prime-factor value.
    } catch (Exception e) {
        // TODO: handle exception
    }

}


text:
Q: ¿Como hago un puente de red en Ubuntu 18.04? llevo tiempo intentando conseguir interconexión entre host y guest [ubuntu18.04 - kvm qemu] porque estoy preconfigurando un webserver y quiero usar el invitado como banco de pruebas. Total, que no puedo avanzar mucho porque el guest si tiene acceso al host pero no al revés.
Buscando he leído que debo crear un puente, y para ello modificar /etc/networ/interfaces de la siguiente forma(Así es como lo he dejado):
# interfaces(5) file used by ifup(8) and ifdown(8)
auto lo
iface lo inet loopback
#a partir de aqui esta lo nuevo
auto br0
iface br0 inet static
address 192.168.1.37
network 192.168.1.0
netmask 255.255.255.0
broadcast 192.168.1.255
gateway 192.168.1.1
bridge_ports enp4s0
bridge_stp off
bridge_fd 0
bridge_maxwait 0

por supuesto en todos los tutoriales mencionan eth0, sin embargo en ubuntu no existe y en su lugar está enp4s0.
Curiosamente, después de reiniciar el servicio de red
/etc/init.d/network-manager restart

al comprobar los cambios con ifconfig -a... no aparece ningún cambio y se ve tal que así.
enp4s0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
    inet 192.168.1.37  netmask 255.255.255.0  broadcast 192.168.1.255
    inet6 fe80::dd0b:4362:2668:e119  prefixlen 64  scopeid 0x20<link>
    ether da:01:3a:03:c0:67  txqueuelen 1000  (Ethernet)
    RX packets 365643  bytes 484283142 (484.2 MB)
    RX errors 0  dropped 0  overruns 0  frame 0
    TX packets 177556  bytes 16509811 (16.5 MB)
    TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
    inet 127.0.0.1  netmask 255.0.0.0
    inet6 ::1  prefixlen 128  scopeid 0x10<host>
    loop  txqueuelen 1000  (Bucle local)
    RX packets 2566  bytes 247445 (247.4 KB)
    RX errors 0  dropped 0  overruns 0  frame 0
    TX packets 2566  bytes 247445 (247.4 KB)
    TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

virbr0: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
    inet 192.168.122.1  netmask 255.255.255.0  broadcast 192.168.122.255
    ether 52:54:00:7f:cc:c1  txqueuelen 1000  (Ethernet)
    RX packets 83  bytes 5750 (5.7 KB)
    RX errors 0  dropped 0  overruns 0  frame 0
    TX packets 57  bytes 5832 (5.8 KB)
    TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

virbr0-nic: flags=4098<BROADCAST,MULTICAST>  mtu 1500
    ether 52:54:00:7f:cc:c1  txqueuelen 1000  (Ethernet)
    RX packets 0  bytes 0 (0.0 B)
    RX errors 0  dropped 0  overruns 0  frame 0
    TX packets 0  bytes 0 (0.0 B)
    TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

Se suponía que enp4s0 debía perder su IP y aparece br0 con la IP de mi host, pero br0 ni aparece. Si abro virt-manager, en el apartado de red de cada maquina me reconoce un nuevo modo de puente br0 sobre enp4s0, sin embargo al arrancar la maquina me dice que no existe el dispositivo br0.
Llevo un semana y me estoy frustrando demasiado, no encuentro ningún tutorial sobre el tema(mencionando ubuntu 18.04) si quiera que sepa que en ubuntu no existe eth0. Y los pocos que quizá lo mencionan, siguiendo sus pasos da igual, porque br0 nunca llega a crearse. Os estaré muy agradecido si sabéis decirme donde me estoy perdiendo.
PD: tengo el paquete bridge-utils instalado y actualizado

A: Bueno finalmente encontré una pista y gracias a ella he resuelto el problema.
Resulta que ubuntu 18.04(creo de hecho que un par de versiones mas atrás tambien) gestiona las redes con netplan, por lo que los típicos dispositivos nombrados como eth0, etc los renombra de otro modo y el mismo se encarga de escribir sobre los archivos de configuración. Por eso mismo ningun tutorial terminaba de funcionar y terminaba por haber conflictos. No soy un experto en la materia(de serlo no hubiera tenido este problema) pero es lo que he sacado en claro.
Al lio:
hay que trabajar con un archivo yaml, netplan comprueba la sintaxis y ella se encarga de hacer los cambios en la configuracion de red. Los pasos serian así de sencillos:
Importante comprobar cuales son nuestros dispositivos. Con el comando ifconfig por ejemplo podremos ver cual seria el equivalente a eth0, en mi caso es enp4s0.
pasamos a modificar el fichero /etc/netplan/01-network-manager-all.yaml con algún editor tipo nano o vim. es posible que el fichero final se llame distinto en tu sistema.
vim /etc/netplan/01-network-manager-all.yaml

nos aparecerá algo así:
network:
  version: 2
  renderer: NetworkManager

Nosotros solo tendremos que añadir unas "pocas" lineas que definirán el puente y la conexión. Debe quedar de la siguiente forma:
network:
  version: 2
  renderer: NetworkManager

  ethernets:
          enp4s0:
                  dhcp4: no
                  dhcp6: no
  bridges:
          br0:
                  interfaces: [enp4s0]
                  dhcp4: no
                  dhcp6: no
                  addresses:
                          - 192.168.1.85/24
                  gateway4: 192.168.1.1
                  nameservers:
                        addresses: [1.1.1.1, 1.0.0.1, 8.8.8.8, 8.8.4.4]

(tened en cuenta de que en mi caso he decidido usar dirección estática, pero podéis ahorraros un par de lineas usando el modo dhcp)
Por ultimo nos quedan por conocer 3 comandos
sudo netplan try
sudo netplan generate
sudo netplan apply
Con el primero nos sobra, pues primero hace una comprobación de la sintaxis y después prueba la conexión dándote margen para probarla y guardar los cambios.
y...
fin(aleluya)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to pick photo from camera roll I do not have a working version or idea how to get photos from your albums via PHPhotoLibrary or ALAssetsLibrary and install them in uicollectionviewcell like in instagram. I'm new to objective c :)
not install - add

A: I'm not sure what you mean by 'install to uicollectionviewcell' but here's how you would get photos from your album.

*

*Ask for authorization

*Show a UIImagePickerController (which is the default image picker view apple created for us)

*Implement delegate methods to handle the picked image from the UIImagePickerController

Code would look as follows
Import statement:
#import <Photos/Photos.h>

Instantiate the image picker controller to show:
UIImagePickerController* imagePicker = [[UIImagePickerController alloc]init];
// Check if image access is authorized
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    // Use delegate methods to get result of photo library -- Look up UIImagePicker delegate methods
    imagePicker.delegate = self;
    [self presentViewController:imagePicker animated:true completion:nil];
}

I believe this would usually prompt the user for access to the photo library, but it's always good practice to handle all cases of authorization prior to simply trying to show the imagepicker.
Ask for authorization:
PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if(status == PHAuthorizationStatusNotDetermined) {
        // Request photo authorization
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            // User code (show imagepicker)
    }];
    } else if (status == PHAuthorizationStatusAuthorized) {
        // User code
    } else if (status == PHAuthorizationStatusRestricted) {
        // User code
    } else if (status == PHAuthorizationStatusDenied) {
        // User code
    }

Finally implement delegate methods:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    // Do something with picked image
}

After you pick your image, you can add it to a newly instantiated UICollectionViewController. This is probably a whole other question and you would be better off reading documentation for this.
Note that this was introduced in IOS8(I think?), but the AL route code will be similar to the above.

Added
The photo library is just another database, but you still have to ask the user for authorization.
The steps would be as follows:

*

*Ask for authorization

*Retrieve photos from photo library

I haven't done #2 myself but there seems to be a way to do it.
Get all of the pictures from an iPhone photoLibrary in an array using AssetsLibrary framework?
From a cursory look, it seems like this is an asynchronous function so you should code accordingly (I would call the requestImage function inside each UICollectionViewCell if I were you).
Leave a comment if you run into any trouble.
Good Luck!

A: You need to declare delegate UIImagePickerControllerDelegate
like this..
hope its helps you a lot...
- (IBAction)captureImagehandler:(id)sender
{
    if (! [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {

    UIAlertView *deviceNotFoundAlert = [[UIAlertView alloc] initWithTitle:@"No Device" message:@"Camera is not available"
                                                             delegate:nil
                                                    cancelButtonTitle:@"exit"
                                                        otherButtonTitles:nil];
    [deviceNotFoundAlert show];

}
else
{

    UIImagePickerController *cameraPicker = [[UIImagePickerController alloc] init];
    cameraPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    cameraPicker.delegate =self;
    // Show image picker
    [self presentViewController:cameraPicker animated:YES completion:nil];
}
}


text:
Q: can you reference a task from an issue in a commit? I have an issue on gitlab, #1. This issue when it was created it contained two tasks.
Is there a way to mention/reference/close one of the two tasks in a git commit ?

A: Not yet, but at least you can define tasks in an issue now.
This comes with GitLab 15.3 (Aug. 2022)

Create tasks in issues
Tasks provide a robust way to refine an issue into smaller, discrete work units.
Previously in GitLab, you could break down an issue into smaller parts using markdown checklists within the description.
However, these checklist items could not be easily assigned, labeled, or managed anywhere outside of the description field.
You can now create tasks within issues from the Child Items widget.
Then, you can open the task directly within the issue to quickly update the title, set the weight, or add a description.
Tasks break down work within projects for GitLab Free and increase the planning hierarchy for our GitLab Premium customers to three levels (epic, issue, and task).
In our next iteration, you will be able to add labels, milestones, and iterations to each task.
Tasks represent our first step toward evolving issues, epics, incidents, requirements, and test cases to work items.
If you have feedback or suggestions about tasks, please comment on this issue.

See Documentation and Epic.


text:
Q: Como criar uma coluna em uma tabela a partir de um Select Tenho a tabela users e a tabela posts, preciso copiar as mesmas informações de uma coluna da tabela users para uma coluna da tabela posts, Por exemplo, eu tenho esse código:
SELECT posts.*, users.username
FROM posts
  inner join users on (posts.user_id = users.id )

que me trás uma consulta de exatamente o que eu preciso, mas no meu projeto em php preciso que essa coluna seja criada, para conseguir visualiza-la pelo meu html.
Mais um exemplo para ajudar no entendimento da minha pergunta, se eu executar o código:
ALTER TABLE articles ADD COLUMN user_id INT(11);

ele consegue criar exatamente o que eu preciso, mas com o campo "id" que esta na tabela users, mas somente com o "id", se eu fizer o mesmo código com o campo que eu preciso, que é o username: "user_username", me retorna nulo.


text:
Q: null validation failed when attribute supplied rom-rb I'm trying to get to grips with the rom-rb persistence library, using sqlite3.
I ran the following migration, which includes a NOT NULL constraint:
ROM::SQL.migration do
  change do
    create_table :users do
      primary_key :id
      column :name, String, null: false
      column :age, Integer
      column :is_admin, TrueClass
    end
  end
end

Here's my simple app.rb:
require 'rom'

rom = ROM.container(:sql, 'sqlite://db/my-db-file.db') do |config|
  class Users < ROM::Relation[:sql]
    schema(infer: true)
  end

  config.relation(:users)
end

users = rom.relations[:users]
puts users.to_a.inspect # => []

create_user = users.command(:create)
create_user.call( name: 'Rob', age: 30, is_admin: true )
puts users.to_a.inspect # never reached

Trying to run this script produced the following output:
Roberts-MacBook-Pro:my-rom-demo Rob$ ruby app.rb
[]
/Rob.rvm/gems/ruby-2.4.0@learn-rails/gems/sqlite3-1.3.13/lib/sqlite3/statement.rb:108:in `step': SQLite3::ConstraintException: NOT NULL constraint failed: users.name (ROM::SQL::NotNullConstraintError)
    from /Rob.rvm/gems/ruby-2.4.0@learn-rails/gems/sqlite3-1.3.13/lib/sqlite3/statement.rb:108:in `block in each'
    from /Rob.rvm/gems/ruby-2.4.0@learn-rails/gems/sqlite3-1.3.13/lib/sqlite3/statement.rb:107:in `loop'
    from /Rob.rvm/gems/ruby-2.4.0@learn-rails/gems/sqlite3-1.3.13/lib/sqlite3/statement.rb:107:in `each'
    from /Rob.rvm/gems/ruby-2.4.0@learn-rails/gems/sqlite3-1.3.13/lib/sqlite3/database.rb:156:in `to_a'
    from /Rob.rvm/gems/ruby-2.4.0@learn-rails/gems/sqlite3-1.3.13/lib/sqlite3/database.rb:156:in `block in execute'
    from /Rob.rvm/gems/ruby-2.4.0@learn-rails/gems/sqlite3-1.3.13/lib/sqlite3/database.rb:95:in `prepare'
    from /Rob.rvm/gems/ruby-2.4.0@learn-rails/gems/sqlite3-1.3.13/lib/sqlite3/database.rb:137:in `execute'
    from /Rob.rvm/gems/ruby-2.4.0@learn-rails/gems/sequel-5.11.0/lib/sequel/adapters/sqlite.rb:189:in `block (2 levels) in _execute'
    from /Rob.rvm/gems/ruby-2.4.0@learn-rails/gems/sequel-5.11.0/lib/sequel/database/logging.rb:38:in `log_connection_yield'
    from /Rob.rvm/gems/ruby-2.4.0@learn-rails/gems/sequel-5.11.0/lib/sequel/adapters/sqlite.rb:189:in `block in _execute'
    from /Rob.rvm/gems/ruby-2.4.0@learn-rails/gems/sequel-5.11.0/lib/sequel/database/connecting.rb:253:in `block in synchronize'
    from /Rob.rvm/gems/ruby-2.4.0@learn-rails/gems/sequel-5.11.0/lib/sequel/connection_pool/threaded.rb:91:in `hold'
    from /Rob.rvm/gems/ruby-2.4.0@learn-rails/gems/sequel-5.11.0/lib/sequel/database/connecting.rb:253:in `synchronize'
    from /Rob.rvm/gems/ruby-2.4.0@learn-rails/gems/sequel-5.11.0/lib/sequel/adapters/sqlite.rb:180:in `_execute'
    from /Rob.rvm/gems/ruby-2.4.0@learn-rails/gems/sequel-5.11.0/lib/sequel/adapters/sqlite.rb:146:in `execute_insert'
    from /Rob.rvm/gems/ruby-2.4.0@learn-rails/gems/sequel-5.11.0/lib/sequel/dataset/actions.rb:1099:in `execute_insert'
    from /Rob.rvm/gems/ruby-2.4.0@learn-rails/gems/sequel-5.11.0/lib/sequel/dataset/actions.rb:399:in `insert'
    from /Rob.rvm/gems/ruby-2.4.0@learn-rails/gems/rom-sql-2.5.0/lib/rom/sql/relation/writing.rb:39:in `insert'
    from /Rob.rvm/gems/ruby-2.4.0@learn-rails/gems/rom-sql-2.5.0/lib/rom/sql/commands/create.rb:46:in `block in insert'
    from /Rob.rvm/gems/ruby-2.4.0@learn-rails/gems/rom-sql-2.5.0/lib/rom/sql/commands/create.rb:46:in `map'
    from /Rob.rvm/gems/ruby-2.4.0@learn-rails/gems/rom-sql-2.5.0/lib/rom/sql/commands/create.rb:46:in `insert'
    from /Rob.rvm/gems/ruby-2.4.0@learn-rails/gems/rom-sql-2.5.0/lib/rom/sql/commands/create.rb:31:in `execute'
    from /Rob.rvm/gems/ruby-2.4.0@learn-rails/gems/rom-core-4.2.1/lib/rom/command.rb:280:in `call'
    from /Rob.rvm/gems/ruby-2.4.0@learn-rails/gems/rom-sql-2.5.0/lib/rom/sql/commands/error_wrapper.rb:16:in `call'
    from /Rob.rvm/gems/ruby-2.4.0@learn-rails/gems/rom-core-4.2.1/lib/rom/commands/composite.rb:17:in `call'
    from app.rb:15:in `<main>'

Why does it think my name attribute is null when I'm providing it?

A: NOTE: I revised my answer after some testing and learning about ops gem versions
The reason you're getting a NULL CONSTRAINT error is because ROM does not
have a schema loaded for the the users table.
When you defined the container below
rom = ROM.container(:sql, 'sqlite://db/my-db-file.db') do |config|
  class Users < ROM::Relation[:sql]
    schema(infer: true)
  end

  config.relation(:users)
end

you defined two things, a relation class bound to a constant called Users and an auto generated relation with the same name but is actually registered inside the ROM container. Effectively the Users constant relation is being ignored. The reason this is important is because the auto generated relation isn't automatically inferring the schema from the database so when you go to write data out, the schema forces all of the unknown keys to be removed causing the error. All you're sending to the db is {}.
To fix the error just tell the relation to infer the schema - an example can be seen below.
require 'rom'
require 'rom/sql'
require 'sqlite3'

puts "ROM Version #{ROM::Core::VERSION}" # 4.2.1
puts "ROM Version #{ROM::SQL::VERSION}" # 2.5.0
puts "Sequel Version #{Sequel::VERSION}" # 5.11.0
puts "SQLite3 Gem Version #{SQLite3::VERSION}" # 1.3.13

opts = {
  adapter: :sqlite,
  database: 'c:/mydb.db'
}

rom = ROM.container(:sql, opts) do |c|
  # Just another way to write the same users table
  # c.gateways[:default].create_table(:users) do
  #   column :id,   :integer, primary_key: true
  #   column :name, :string, null: false
  #   column :age,  :integer
  #   column :is_admin, :bool
  # end

  c.gateways[:default].create_table :users do
    primary_key :id
    column :name, String, null: false
    column :age, Integer
    column :is_admin, TrueClass
  end

  c.relation(:users) do
    schema(infer: true)
  end
end

users = rom.relations[:users]
puts users.to_a.inspect # => []

create_user = users.command(:create)
create_user.call(name: 'Rob', age: 30, is_admin: true)
puts users.to_a.inspect # never reached

# Uncomment if you want to see the users schema
# puts users.dataset.db.schema(:users)

If you want to use standalone relation classes instead of the container config dsl then I suggest reading up on the Auto Registration system.
DATABASE CREATION ISSUE
There is a whole host of things that could be going on which could prevent a sqlite database from being created.

*

*It could be a permissions issue

*The directory structure might not exist

*Sqlite might not be compiled to handle URI's (only matters if you are using file:// in your paths) [see sqlite docs]
My advice here is when working with sqlite and ROM, use the opts hash example from the script above and try and use a relative path from the current working directory. That seems to always work.


text:
Q: Parse-Swift: unable to find the appropriate type to save data in an Object type field of a Parse Object Using Parse-Swift 4.7.0 on MacOS, Xcode 14.0ß7
One of my table is made of Parse Objects containing a field of type Object (as it appears in Sashido/Parse Server). This field contains a dictionary of type [String: Any] representing a JSON dictionary.
With the Parse Objc SDK this dictionary was saved successfully as is with the PFObject.
With the Parse-Swift framework, I tried:

*

*To define the variable type as ParseBytes, containing the json object as Data. Saving failed blaming to get an Object iso ParseBytes.

*To define the variable type as Data, without success

*To define the variable type as a [String: Any] dictionary. But as Any is not Equatable, the merge(:) func doesn't accept it.

What's the way to save this [String: Any] dictionary in the Object field?

A: Finally solved by creating an Equatable Struct!


text:
Q: Configuring Ninject in App_start folder specifically ninjectwebcommon.cs file I have a simple query, i am following the tutorial on this link:
http://www.prideparrot.com/blog/archive/2012/12/how_to_create_a_simple_blog_part1#book-unique-identifier
My problem is the author on this tutorial configure ninject in the global.asax file and deleted the ninjectwebcommon.cs file. i am trying to integrate the justblog into my existing asp.netMVC5 application that is using the ninjectwebcommon.cs file.
Any help would be much appreciated.

A: Did you use Nuget to add Ninject? You'll need a reference to WebActivatorEx for the bootstrapper to work (obviously along with the other required Ninject references). Add a NinjectWebCommon.cs class in your App_Start folder in your project, looking like this:
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(YourMvcApp.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(YourMvcApp.App_Start.NinjectWebCommon), "Stop")]

namespace YourMvcApp.App_Start
{
    using System;
    using System.Web;

    using Microsoft.Web.Infrastructure.DynamicModuleHelper;

    using Ninject;
    using Ninject.Web.Common;

    public static class NinjectWebCommon
    {
        private static readonly Bootstrapper bootstrapper = new Bootstrapper();

        /// <summary>
        /// Starts the application
        /// </summary>
        public static void Start()
        {
            DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
            DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
            bootstrapper.Initialize(CreateKernel);
        }

        /// <summary>
        /// Stops the application.
        /// </summary>
        public static void Stop()
        {
            bootstrapper.ShutDown();
        }

        /// <summary>
        /// Creates the kernel that will manage your application.
        /// </summary>
        /// <returns>The created kernel.</returns>
        private static IKernel CreateKernel()
        {
            var kernel = new StandardKernel(); // you'll add modules to the parameter list here
            try
            {
                kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
                kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

                //RegisterServices(kernel);
                return kernel;
            }
            catch
            {
                kernel.Dispose();
                throw;
            }
        }

        ///// <summary>
        ///// Load your modules or register your services here!
        ///// </summary>
        ///// <param name="kernel">The kernel.</param>
        //private static void RegisterServices(IKernel kernel)
        //{
        //}
    }
}


text:
Q: QWebEngine - how to catch execution of any javascripts from C++? I know how to communicate between C++ and Javascript in Qt WebEngine from this tutorial:
https://myprogrammingnotes.com/communication-c-javascript-qt-webengine.html
But that is a case when I'm the author of loaded page so C++ and HTML parts are programmed by me. But is it possible to catch any javascript executed on any page loaded (like google.com etc)? Some kind of signal emitted when JS is executed so I could investigate function name and input args.QWebEnginePage->QWebEngineScriptCollection->scripts() return only my own injected scripts, it doesn't contain page scripts
Regards


text:
Q: Date Formatting - Dataweave I two date functions that I'm useing to convert Date/Times into another format.
Input_1: 02/01/21 11:00:00 AM
Input_2: 02/01/21  3:00:00 PM

Desired Output 1: 2021-02-01T11:00:00.000
Desired Output 2: 2021-02-01T15:00:00.000

fun date_time_format(d: LocalDateTime {format: "M/d/yy  h:mm:ss a"}) = d as String {format: "yyyy-MM-dd'T'HH:mm:ss.SSS"}

fun date_time_format2(d: LocalDateTime {format: "M/d/yyyy h:mm:ss a"}) = d as String {format: "yyyy-MM-dd'T'HH:mm:ss.SSS"}

concert_time:
          try(() -> date_time_format(Input_1) )
          orElseTry(() -> date_time_format2(Input_1) )
          orElse null

My resoult is null when using Input_1 but when using Input_2 it's 2021-02-01T15:00:00.000

A: The problem is the spacing between the date and the time is not fixed in the input, but it is fixed in the pattern. Instead use the padding format character to fix the issue.
I don't like the way the functions seems to be doing an implicit type conversion with formatting. You are not really passing a LocalDateTime but a String. That makes the intention very obscure. I suspect it is not a good practice. I changed my example to use explicit conversions. You could convert the parameter to LocalDateTime explicitly before invoking the function if you prefer it.
fun date_time_format(d: String) =
    (d as LocalDateTime {format: "M/d/yy pph:mm:ss a"})
        as String {format: "yyyy-MM-dd'T'HH:mm:ss.SSS"}

Output:
{
  "concert_time1": "2021-02-01T11:00:00.000",
  "concert_time2": "2021-02-01T15:00:00.000"
}


text:
Q: Modifying an existing Calendar Event from HtmlService input I'm trying to add a "Sign Up" link to a Google Calendar Event where upon clicking the user is prompted via HtmlService to submit their email address. Their email address is then added to the event.
Here's a similar example. What I'd like to do differently is use HtmlService to have the user input their email address, which then is passed back to GAS to be added to the Calendar Event in question. That way they can choose the email they want (instead of whatever Session.getActiveUser().getEmail() returns) to sign up with. (and by sign up, I mean get added to the guest list - they still have to accept the invite, but that's fine).
Is this possible? I'm not seeing any examples of this so maybe there's a better way?
I am starting to tear out what little hair I have. I've included my latest sample code, where I pass the event object into the HTML template. It's not throwing an error, but it's not working either. Thank you in advance!!
Code.gs:
function doGet(event) {
  //    // shorten the event parameter path;
 var param = event.parameter;
//    // get the calendar event id passed in the query parameter
 var eventId = param.eId;
 var calId = param.calId;
 var cal = CalendarApp.getCalendarById(calId);
 var t = HtmlService.createTemplateFromFile('Index');
 t.eObj = cal.getEventById(eventId);
 return t.evaluate();
}

function addEmail(emObj,myForm){
  var guestEmail = myForm.user;
  emObj.addGuest(guestEmail)
}

and Index.html:
<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <script>
      function update() {
        alert("Success!");
      }

    </script>
  </head>
  <body>
    <form id="myForm">
      <input id="userEmail" name="user" type="text" />
      <input type="button" value="Submit" onClick="google.script.run.withSuccessHandler(update).addEmail(eObj,this.form)" />
    </form>
 </body>
</html>

A: You don't have scriptlets in your html file, so you don't need to evaluate a template.  I've added another 2 input fields for the calId and eventId.  They get replaced in the HTML before being served.  Then the event ID and Cal ID are passed back in the form object.
<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <script>
      function update() {
        alert("Success!");
      }

    </script>
  </head>
  <body>
    <form id="myForm">

      <input id="userEmail" name="user" type="text" />

      <input name="calId" type="text" style="display:none"
        value="zzz_calID_zzz"/>
      <input name="eventId" type="text" style="display:none"
        value="zzz_eventID_zzz"/>

      <input type="button" value="Submit" onClick="google.script.run
            .withSuccessHandler(update)
            .addEmail(this.form)" />
    </form>
 </body>
</html>

doGet:
function doGet(event) {
  //    // shorten the event parameter path;
 var param = event.parameter;
//    // get the calendar event id passed in the query parameter
 var eventId = param.eId;
 var calId = param.calId;

 var t = HtmlService.createHtmlOutputFromFile('Index').getContent();

 t = t.replace('zzz_calID_zzz',calId);
 t = t.replace('zzz_eventID_zzz',eventID);

 return HtmlService.createHtmlOutput(t);
}

Server code:
function addEmail(myForm){

  var cal = CalendarApp.getCalendarById(myForm.calId);
  var event = cal.getEventById(myForm.eventId);
  var guestEmail = myForm.user;

  event.addGuest(guestEmail)
}


text:
Q: Display and post comments on facebook photo from webpage We would like to use the Facebook Comment plugin (or something similar) on a website. The photos are being pulled in from Facebook to our site (built in PHP). We would like to enable commenting on a particular photo and post the comment back to Facebook. Addtionally, if a comment is made on Facebook, we would also like for the comment to display on the webpage.
From the website, we have only been able to get the comment to apply to the webpage, but not to the photo itself. Thus the comment posts on facebook with a link to the webpage, but does not display the individual photo.
Does anyone know how to successfully post comments on a particular photo from a webpage?

A: Using the Graph API, just do an HTTP POST to https://graph.facebook.com/PHOTOID/comments?access_token=ValidUserAccessToken with the correct parameters specified (such as message) as well as a user access token with the correct permissions specified.
See the comments connection of photo at https://developers.facebook.com/docs/reference/api/photo/


text:
Q: C: questions about function prototype in header file
*

*Normally we declare a function prototype in header file like:
void function();
Can this function take any argument?

*If the function takes integer as argument, we write:
void function(int);
But sometimes I see people write: void function(int*);
What is the * doing here?

*If the function can a single argument of several types, like integer or
double, what should we do?

A: *

*
Normally we declare a function prototype in header file like:
void function();

Can this function take any argument?

It is unspecified what arguments this function will take.

*
If the function takes integer as argument, we write:
void function(int);
But sometimes I see people write: void function(int*);
What is the * doing here?

This is a pointer to an int.

*
If the function can take several types of argument, like integer and double, what should we do?

int and double are incompatible types. You can't take one function that takes either one, or the other. You can't define two different functions with two different types, but that share the same name, either.

A: *

*The question itself is worded incorrectly. This is not a prototype at all. This is a non-prototype function declaration.
It does not say anything about function arguments, which is exactly what makes it different from prototype. The function declared in this way can be called with any set of arguments.
However, if the arguments used in the call (after usual arithmetic conversions) do not match the parameters used the actual definition (in number and type), the behavior is undefined. If the actual function is defined as variadic (has ... in the parameter list), the behavior is undefined.

*These are prototypes. The first one says that the function has a single int parameter. The second one says that it has a single int * parameter (a pointer to int). There's nothing special about it if you know what pointers are.

*It is not clear what is being asked. "What should we do?" I don't know... Fly to Hawaii and spend five days dancing naked in the rain.
This function is declared as taking several arguments of different types
void foo(int, double, char, short *);

There's nothing special about it. If you meant something else - clarify the question.


text:
Q: Favoriting in the Android app Since yesterday I cannot favorite any question from the Android app any more. I always get

As has been shown (nicael's comment), this issue may be one with my own system - any ideas about how to find the cause?
Favoriting in the Web UI works as always.


text:
Q: Java Concurrent Iteration: Divide and Conquer vs Runnable for each item When I have hundreds of items to iterate through, and I have to do a computation-heavy operation to each one, I would take a "divide and conquer" approach. Essentially, I would take the processor count + 1, and divide those items into the same number of batches. And then I would execute each batch on a runnable in a cached thread pool. It seems to work well. My GUI task went from 20 seconds to 2 seconds, which is a much better experience for the user.
However, I was reading Brian Goetz' fine book on concurrency, and I noticed that for iterating through a list of items, he would take a totally different approach. He would kick off a Runnable for each item! Before, I always speculated this would be bad, especially on a cached thread pool which could create tons of threads. However each runnable would probably finish very quickly in the larger scope, and I understand the cached thread pool is very optimal for short tasks.
So which is the more accepted paradigm to iterate through computation-heavy items? Dividing into a fixed number of batches and giving each batch a runnable? Or kicking each item off in its own runnable? If the latter approach is optimal, is it okay to use a cached thread pool or is it better to use a bounded thread pool?

A: With batches you will always have to wait for the longest running batch (you are as fast as the slowest batch). "Divide and conquer" implies management overhead: doing administration for the dividing and monitoring the conquering.
Creating a task for each item is relative straightforward (no management), but you are right in that it may start hundreds of threads (unlikely, but it could happen) which will only slow things down (context switching) if the task does no/very few I/O and is mostly CPU intensive.
If the cached thread pool does not start hundreds of threads (see getLargestPoolSize), then by all means, use the cached thread pool. If too many threads are started then one alternative is to use a bounded thread pool. But a bounded thread pool needs some tuning/decisions: do you use an unbounded task queue or a bounded task queue with a CallerRunsPolicy for example?
On a side note: there is also the ForkJoinPool which is suitable for tasks that start sub-tasks.


text:
Q: How can i get the number of bytes allocated by mmap? I'm building a custom implementation of malloc using mmap.
If the user wants to allocate 500 bytes of memory, i call mmap(0, 500, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0). mmap returns a pointer to a block with size 4096 (if that is the page size).
In my linked list I want to have one block set to 500 bytes marked as taken, and one block set to 4096-500=3596 bytes marked as free. It is not clear, however how much memory mmap really allocates. How can I get that information?

A: The prototype of mmap() is:
void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset);`

Technically you are guaranteed only that it will allocate length bytes. However, in practice it allocates whole pages (i.e. multiples of PAGE_SIZE) though you are not guaranteed you can use anything beyond length. Indeed per the man page:

offset must be a multiple of the page size as returned by sysconf(_SC_PAGE_SIZE).

Note that there is no restriction on length being a multiple of PAGE_SIZE but you might as well round up length to a multiple of PAGE_SIZE (as that's what's going to be allocated anyway), in which case the amount of memory allocated is exactly length. If you don't do that, it will allocate the minimum number of whole pages that contain length bytes.


text:
Q: Undefined not a function issue I have a Backbone.js application that has a js file that looks like:
var ProductView = Backbone.View.extend({
    initialize: function() {
        _.bindAll(this, 'render','createProduct');

        this.render();
    },

    events: {
        "click #createProduct": "createProduct"
    },

    render: function() {
        var source = $('#product-template').html();
        var template = Handlebars.compile(source);
        var html = template(this.model.toJSON());
        this.$el.html(html);
    },

    createProduct: function(){
        var product_title = this.$(".title").val();
        var product_description = this.$(".description").val();

        var data = [];

        $(".product").each( function(){
            var type = $( this ).data("type");

            var wd = new Object();

            if (this.$(".adInput").val())           { wd.ad      = this.$(".adInput").val();            }
            if (this.$(".citeInput").val())             { wd.cite        = this.$(".citeInput").val();          }
            if (this.$(".addressInput").val())      { wd.address     = this.$(".addressInput").val();       }

            alert(wd);
        });

    }

I'm getting the error:
 Uncaught TypeError: undefined is not a function main.js?body=1:61
 (anonymous function) main.js?body=1:61
 jQuery.extend.each jquery.js?body=1:385
 jQuery.fn.jQuery.each jquery.js?body=1:138
 Backbone.View.extend.createProduct main.js?body=1:56
 jQuery.event.dispatch jquery.js?body=1:4625
 elemData.handle

Also, my html looks like:
<div class='item ad' data-type="ad">
  <textarea class='adInput' placeholder='Ad'></textarea>
  <input class='citeInput' type='text'/>
</div>

Thanks for all help!

A: Issue is in this statement :
if (this.$(".adInput").val())
    wd.ad = this.$(".adInput").val();

Try replacing it with :
if ($(this).find(".adInput").val())
    wd.ad = $(this).find(".adInput").val();

this.$(selector) is a Backbone method defined in a View. You can see it here.
In the anonymous function invoked by each iterator, the context of this gets changed. It no more refers to the View. You can use $(this) to get the element being currently processed by the each iterator and use find on it to select elements which belong to it's hierarchy. This is exactly what Backbone's view $ method does.
$: function(selector) {
   return this.$el.find(selector);
}

Similarly correct the other 2 if blocks.

A: Change  this
 var wd = new Object();

to this
var wd = {ad: '', cite: '', address: ''};

And (".addressInput") is invalid because i cant find any DOM element in your HTML with this class


text:
Q: PyGreSQL - Unable to Insert Data I am using CentOS-6 with Python 3.8, PostgreSQL 12 and PyGreSQL 5.2.2.  This is the error I get trying to insert data into my database.
>>> db.insert('settings', None, **data)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.8/site-packages/pg.py", line 2322, in insert
    adapt = params.add
  File "/usr/local/lib/python3.8/site-packages/pg.py", line 1667, in __getattr__
    if self.db:
AttributeError: 'pg.Connection' object has no attribute 'escape_identifier'

Can anyone point me towards what is wrong?

A: The method escape_identifier on the connection corresponds to the function PQescapeIdentifier in libpq. It exists since PostgreSQL 9 which is required by PyGreSQL 5.2. PyGreSQL does not compile support for these functions if it is installed with the no-escaping-funcs option or if it thinks PostgreSQL is older than version 9.
Since you say that you have PostgreSQL 12 installed, a possible explanation could be that you still have the client library (libpq) of an old PostgreSQL version installed as well, and the pg_config tool reports that old version. You should check this with pg_config --version. The pg_config tool is in libpq-devel, so make sure you have libpq and libpq-devel installed for PostgreSQL 12.
You can also try to explicitly enable the escaping functions by installing PyGreSQL with python setup.py build_ext --escaping-funcs install, but you will still need the latest libpq, and there will be other functions disabled as well when PyGreSQL thinks that libpq is too old. So the proper solution is to make sure libpq is up to date and pg_config --version reports the corresponding PostgreSQL version.


text:
Q: Inclusion of Lp into L1 on bounded domains using Holder inequal On bounded domains, $L^p \subset L^1, p>1$ because on such domains a function isn't integrable if the function is too large. Exponentiating the function makes it larger.
Is it possible to show that $L^1(a,b)$ space is a more general space than $L^p(a,b),p>1$ using Holder inequality (below)?
$$\int_{a}^{b}|f(x)g(x)|dx \leq \Big(\int_{a}^{b}|f(x)|^pdx\Big)^{1/p} \Big(\int_{a}^{b}|g(x)|^qdx\Big)^{1/q}$$

A: If $f\in L^p(a,b)$ with $p>1$, then using Holder's inequality with $f$ and $1$ we get
$$ \int_a^b|f(x)|\;dx\leq\Big(\int_a^b|f(x)|^p\;dx\Big)^{\frac{1}{p}}\Big(\int_a^b\;dx\Big)^{\frac{1}{q}}=(b-a)^{\frac{1}{q}}||f||_p $$
Therefore $f\in L^1(a,b)$, and in fact
$$ ||f||_1\leq (b-a)^{\frac{1}{q}}||f||_p$$


text:
Q: How to initialize an int array member of a structure? struct node {int n; int k; int arr[n]};

The size of the array n is not known before compilation. It is taken from the user during the execution.

A: you can take reference from this code,I am not sure whether it will work or not but you can take reference from this.
my_struct_t *myStruct;
size_t noOfElements;
size_t completeSize;
int index;

/* ...code which sets the number of elements at runtime... */

completeSize = sizeof(my_struct_t) * noOfElements;

myStruct = malloc(completeSize);
memset(myStruct, 0, completeSize);

/* ...and then access it as if it were an array...*/

myStruct[index].someInt = 10; // index < noOfElements

A: The memory cannot be allocated in the structure itself, but you can define a pointer to the array in your structure and then later you can allocate the memory using malloc or new() with the size of 'n'.
Here is the way you can define your structure.
struct node {int n; int k; int *arr};

To allocate memory you can do it using the object of the structure as follows,
1) using malloc:
fun() {
    node obj;
    obj.arr = (int*)malloc(sizeof(int)*obj.n);
}

2) using new()
fun() {
    node obj;
    obj.arr = new int(obj.n);
}


text:
Q: Identity UserManager CreateAsync does not write to database It doesn't give any errors or warnings but it doesn't insert in the database. Seems like it's only in memory.
Also UserManager's FindByNameAsync can't check users already created in the database, probably for the same reason.
Here is my Controller:
public class AccountController : Controller
    {
        private readonly UserManager<User> _userManager;
        private readonly SignInManager<User> _signInManager;

        public AccountController(UserManager<User> userManager, SignInManager<User> signInManager)
        {
            _userManager = userManager;
            _signInManager = signInManager;
        }

        public IActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Login(User user)
        {
            if (ModelState.IsValid)
            {
                var result = await _userManager.CreateAsync(user, user.Password);

                if (result.Succeeded)
                {
                    Console.WriteLine("OK");
                }

                var username = await _userManager.FindByNameAsync(user.UserName);

                if (username != null)
                {
                    //sign in
                    var signInResult = await _signInManager.PasswordSignInAsync(user.UserName, user.Password, false, false);

                    if (signInResult.Succeeded)
                    {
                        return RedirectToAction("Index", "ProjectCampaign");
                    }
                }
            }
            return View();
        }

        public async Task<IActionResult> Logout()
        {
            await _signInManager.SignOutAsync();

            return RedirectToAction("Login", "Account");
        }
    }

Startup.cs
public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<RandomContext>(config =>
            {
                config.UseInMemoryDatabase("Memory");
            });

            services.AddIdentity<User, Role>(config => {
                config.Password.RequireDigit = false;
                config.Password.RequiredLength = 4;
                config.Password.RequireNonAlphanumeric = false;
                config.Password.RequireUppercase = false;
            })
                .AddEntityFrameworkStores<RandomContext>()
                .AddDefaultTokenProviders();

            services.ConfigureApplicationCookie(config =>
            {
                config.Cookie.Name = "AuthCookie";
                config.LoginPath = "/Account/Login";
                config.ExpireTimeSpan = TimeSpan.FromMinutes(1);
            });

            services.AddScoped<RandomContext>();

            services.AddControllersWithViews().AddRazorRuntimeCompilation();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }

User.cs

   public partial class User : IdentityUser<int>
    {
        public int ID { get; set; }
        [Required(ErrorMessage = "Username is required")]
        public override string UserName { get; set; }
        [Required(ErrorMessage = "Password is required")]
        public string Password { get; set; }
    }

RandomContext.cs

public partial class RandomContext : IdentityDbContext<User, Role, int>
    {
        public RandomContext()
        {
        }

        public RandomContext(DbContextOptions<RandomContext> options)
            : base(options)
        {
        }

        public virtual DbSet<ProjectCampaign> ProjectCampaigns { get; set; }
        public virtual DbSet<Role> Roles { get; set; }
        public virtual DbSet<User> Users { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.
                optionsBuilder.UseSqlServer("Server=.;Database=Random;Trusted_Connection=True;");
            }
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<ProjectCampaign>(entity =>
            {
                entity.ToTable("ProjectCampaign");

                entity.Property(e => e.Id).HasColumnName("ID");

                entity.Property(e => e.Campaign)
                    .HasMaxLength(50)
                    .IsUnicode(false);

                entity.Property(e => e.CreateDate)
                    .HasColumnType("datetime")
                    .HasDefaultValueSql("(getdate())")
                    .HasAnnotation("Relational:ColumnType", "datetime");

                entity.Property(e => e.Project)
                    .HasMaxLength(50)
                    .IsUnicode(false);
            });

            modelBuilder.Entity<Role>(entity =>
            {
                entity.Property(e => e.Id).HasColumnName("ID");

                entity.Property(e => e.CreateDate)
                    .HasColumnType("datetime")
                    .HasDefaultValueSql("(getdate())")
                    .HasAnnotation("Relational:ColumnType", "datetime");

                entity.Property(e => e.Description)
                    .IsRequired()
                    .HasMaxLength(50)
                    .IsUnicode(false);
            });

            modelBuilder.Entity<User>(entity =>
            {
                entity.Property(e => e.Id).HasColumnName("ID");

                entity.Property(e => e.Password).IsRequired();

                entity.Property(e => e.UserName)
                    .IsRequired()
                    .HasMaxLength(50)
                    .IsUnicode(false);
            });

            OnModelCreatingPartial(modelBuilder);
        }

        partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
    }

If you need more detail please let me know.

A: I had similar problem - AspNetCore.Identity.UserManager did not throw any errors but did not write entry to database on CreateAsync(user, password).  However, when I debugged the UserManager I could see there was a single entry in the PasswordValidators array.
Basically, the entered password was not complex enough.  Changed the password and everything worked.


text:
Q: Normal distribution with mean coming from normal distribution this is my first time writing here. I have been looking the whole day in this page and others and I couldn't find the answer, even if it seems trivial to me.
Given a normal distribution $N(m,s_1^2)$, what is the distribution of $N(N(m,s_1),s_2^2)$?
I know by simulation that it will follow $N(m,s_1^2+s_2^2)$. This property has a name? Where can I find a demonstration for this?
Thank you in advance.
By the way, I found this other post in which is explained:
Density of a Normal RV whose mean is drawn from a Normal Distribution (Compound Distribution)
The explanation is the following:
You will find that if $X∼N(μ,σ^2)$ and $Y∼N(X,τ^2)$ then $Y∼N(μ,σ^2+τ^2)$. Consider $Z=Y−X∼N(0,τ^2)$ independent of X, and then consider Y=X+Z.
However I find unclear the step $Z=Y−X∼N(0,τ^2)$

A: Suppose $X = x$, fixed. Then $Y \sim N(x,\tau^2)$, so $Y - x \sim N(0,\tau^2)$. Basically what is said is that $Z\mid X = x \sim N(0,\tau^2)$ for every possible value of $x$, hence $Z \sim N(0,\tau^2)$, i.e. conditioning doesn't change the distribution.


text:
Q: Python PyDictionary Import error from futures So I run python -m pip install PyDictionary and I get this output:
Collecting PyDictionary
  Using cached PyDictionary-2.0.1-py3-none-any.whl (6.1 kB)
Requirement already satisfied: requests in d:\python\lib\site-packages (from PyDictionary) (2.27.1)
Collecting goslate
  Using cached goslate-1.5.2.tar.gz (16 kB)
  Preparing metadata (setup.py) ... done
Requirement already satisfied: click in d:\python\lib\site-packages (from PyDictionary) (8.1.3)
Collecting bs4
  Using cached bs4-0.0.1.tar.gz (1.1 kB)
  Preparing metadata (setup.py) ... done
Collecting beautifulsoup4
  Using cached beautifulsoup4-4.11.1-py3-none-any.whl (128 kB)
Requirement already satisfied: colorama in d:\python\lib\site-packages (from click->PyDictionary) (0.4.4)
Collecting futures
  Using cached futures-3.0.5.tar.gz (25 kB)
  Preparing metadata (setup.py) ... error
  error: subprocess-exited-with-error

  × python setup.py egg_info did not run successfully.
  │ exit code: 1
  ╰─> [27 lines of output]
      Traceback (most recent call last):
        File "<string>", line 2, in <module>
        File "<pip-setuptools-caller>", line 14, in <module>
        File "D:\Python\lib\site-packages\setuptools\__init__.py", line 189, in <module>
          monkey.patch_all()
        File "D:\Python\lib\site-packages\setuptools\monkey.py", line 99, in patch_all
          patch_for_msvc_specialized_compiler()
        File "D:\Python\lib\site-packages\setuptools\monkey.py", line 169, in patch_for_msvc_specialized_compiler
          patch_func(*msvc14('_get_vc_env'))
        File "D:\Python\lib\site-packages\setuptools\monkey.py", line 149, in patch_params
          mod = import_module(mod_name)
        File "D:\Python\lib\importlib\__init__.py", line 126, in import_module
          return _bootstrap._gcd_import(name[level:], package, level)
        File "D:\Python\lib\site-packages\setuptools\_distutils\_msvccompiler.py", line 20, in <module>
          import unittest.mock
        File "D:\Python\lib\unittest\mock.py", line 26, in <module>
          import asyncio
        File "D:\Python\lib\asyncio\__init__.py", line 8, in <module>
          from .base_events import *
        File "D:\Python\lib\asyncio\base_events.py", line 18, in <module>
          import concurrent.futures
        File "C:\Users\localuser\AppData\Local\Temp\pip-install-vsl457j6\futures_9b56e18f578949cd955c2218e6840e1e\concurrent\futures\__init__.py", line 8, in <module>
          from concurrent.futures._base import (FIRST_COMPLETED,
        File "C:\Users\localuser\AppData\Local\Temp\pip-install-vsl457j6\futures_9b56e18f578949cd955c2218e6840e1e\concurrent\futures\_base.py", line 357
          raise type(self._exception), self._exception, self._traceback
                                     ^
      SyntaxError: invalid syntax
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

How do I fix it so I can download PyDictionary.
I am using python 3.10.4.
I have saved Python onto a hard drive D: but it causes no other problems for pip.
The main problem I can see is that there is a problem importing Futures but from my research I have found that Futures is already downloaded for python 3  but when I try to uninstall it is says skipping as futures in not installed so maybe that is the problem but I don`t know how to solve it.
Anyone have any ideas?

A: This seems to be a known issue with this package. When issues like this occur, it is always best to go and check the official GitHub repository of the project and look through the open issues.
https://github.com/geekpradd/PyDictionary/issues/52#issuecomment-1105459595

I don't have any privileges on this repo. But I did some debugging I think the actual issue here is that goslate depends on futures, and futures >=3.0.0 isn't installable on python3 at all. The pypi page calls this out saying It does not work on Python 3 due to Python 2 syntax being used in the codebase. Python 3 users should not attempt to install it, since the package is already included in the standard library. -- https://pypi.org/project/futures/
I am able to work around the issue by installing futures <3.0.0 before installing PyDictionary:

A: Try this method but it is giving few results only. This library uses dictionary.com
pip install Py-Dictionary
from pydictionary import Dictionary
dict = Dictionary("lastname")

To store it somewhere in a variable
meanings_list = dict.meanings()

synonyms_list = dict.synonyms()

antonyms_list = dict.antonyms()

To print this
dict.print_meanings()

dict.print_synonyms()

dict.print_antonyms()


text:
Q: Zoom calculation with image rotation I am trying to make the zoom work in all 4 directions. However it is only working in the opposite directions, which are 180 and 360 degrees. In the 90 and 270 degrees the zoom behaves strangely and does not fit with the image.
Can anyone help me with the calculation for the zoom to work in all directions? I have tried everything and I can't get it.

var statusRotate = 4;
rotateImage();

function rotateImage() {
    if (statusRotate == 1) {
        imageLen('90', '90');
        statusRotate = 2
    } else if (statusRotate == 2){
        imageLen('180', '-180')
        statusRotate = 3
    } else if (statusRotate == 3){
        imageLen('270', '270')
        statusRotate = 4
    } else if (statusRotate == 4){
        imageLen('360', '360')
        statusRotate = 1
    }
}

function imageLen(x, y){
    var degrees_image = x;
    var degrees_image_native = y;

    var $element = $('#target');
    $element.css({
        'transform': 'rotate('+ degrees_image +'deg)'
    }); // rotate imagem in html

    // Constants
    var $IMAGE_URL    = $element.attr("src");
    var NATIVE_IMG    = new Image();
    NATIVE_IMG.src    = $element.attr("src");

    var lens = document.createElement("div");
    lens.id = "BlowupLens";
    $("body").append(lens);
    $blowupLens = $("#BlowupLens");

    $blowupLens.css({
        "position"          : "absolute",
        "display"           : "none",
        "pointer-events"    : "none",
        "zIndex"            : 999999,
        "width"             : 200,
        "height"            : 200,
        "border"            : "6px solid #FFF",
        "background"        : "#FFF",
        "border-radius"     : "50%",
        "box-shadow"        : "0 8px 17px 0 rgba(0, 0, 0, 0.2)",
        "background-repeat" : "no-repeat",
    });

    // Show magnification lens
    $element.mouseenter(function () {
        $blowupLens.css("display", "block");
    });

    // Mouse motion on image
    $element.mousemove(function (e) {

    // Lens position coordinates
    var lensX = e.pageX - (200 / 2);
    var lensY = e.pageY - (200 / 2);

    var width = $element.width();
    var height = $element.height();

    var left = $('#target').offset().left;
    var top = $('#target').offset().top;

    // Relative coordinates of image
    var relX = e.pageX - left;
    var relY = e.pageY - top;

    var nativeImageWidth = NATIVE_IMG.width;
    var nativeImageHeight = NATIVE_IMG.height;

    // Zoomed image coordinates
    var zoomX = -Math.floor(relX / width * (NATIVE_IMG.width) - 200 / 2);
    var zoomY = -Math.floor(relY / height * (NATIVE_IMG.height) - 200 / 2);

    if(degrees_image == '90') {
        var backPos = "calc(100% - " + zoomY + "px) calc(100% - " + zoomX + "px)";
        //var backPos = zoomY + "px " + zoomX + "px";
        var backgroundSize = NATIVE_IMG.width + "px " + NATIVE_IMG.height + "px";

        //
    } else if(degrees_image == '180') {
        var backPos = "calc(100% - " + zoomX + "px) calc(100% - " + zoomY + "px)";
        var backgroundSize = NATIVE_IMG.width + "px " + NATIVE_IMG.height + "px";

    } else if(degrees_image == '270') {
        var backPos = zoomY + "px " + zoomX + "px";
        var backgroundSize = NATIVE_IMG.width + "px " + NATIVE_IMG.height + "px";

    } else if(degrees_image == '360') {
        var backPos = zoomX + "px " + zoomY + "px";
        var backgroundSize = NATIVE_IMG.width + "px " + NATIVE_IMG.height + "px";
    }

    // Apply styles to lens
    $blowupLens.css({
        left                  : lensX,
        top                   : lensY,
        "background-image"    : "url(" + encodeURI($IMAGE_URL) + ")",
        "background-size"     : backgroundSize,
        "background-position" : backPos,
        "transform"           : 'rotate('+ degrees_image_native +'deg)' //rotate the image original
        });
    })

    // Hide magnification lens
    $element.mouseleave(function () {
        $blowupLens.css("display", "none");
    });
}

<button onclick="rotateImage()">Rotate</button>

A: I have slightly corrected your example:

var statusRotate = 4;
rotateImage();

function rotateImage() {
  if (statusRotate == 1) {
    imageLen('90', '90');
    statusRotate = 2
  } else if (statusRotate == 2) {
    imageLen('180', '-180')
    statusRotate = 3
  } else if (statusRotate == 3) {
    imageLen('270', '270')
    statusRotate = 4
  } else if (statusRotate == 4) {
    imageLen('360', '360')
    statusRotate = 1
  }
}

function imageLen(x, y) {
  var degrees_image = Number(x);
  var degrees_image_native = Number(y);

  var $element = $('#target');
  $element.css({
    'transform': 'rotate(' + degrees_image + 'deg)'
  }); // rotate imagem in html

  // Constants
  var $IMAGE_URL = $element.attr("src");
  var NATIVE_IMG = new Image();
  NATIVE_IMG.src = $element.attr("src");

  if (!$("#BlowupLens").length) { // if not exists
    var lens = document.createElement("div");
    lens.id = "BlowupLens";
    $("body").append(lens);
  }
  $blowupLens = $("#BlowupLens");

  $blowupLens.css({
    "position": "absolute",
    "display": "none",
    "pointer-events": "none",
    "zIndex": 999999,
    "width": 200,
    "height": 200,
    "border": "6px solid #FFF",
    "background": "#FFF",
    "border-radius": "50%",
    "box-shadow": "0 8px 17px 0 rgba(0, 0, 0, 0.2)",
    "background-repeat": "no-repeat",
  });

  $element.off('mouseenter'); // remove previous event
  // Show magnification lens
  $element.mouseenter(function() {
    $blowupLens.css("display", "block");
  });

  $element.off('mousemove'); // remove previous event
  // Mouse motion on image
  $element.mousemove(function(e) {

    // Lens position coordinates
    var lensX = e.pageX - (200 / 2);
    var lensY = e.pageY - (200 / 2);

    var width = $element.width();
    var height = $element.height();

    var left = $('#target').offset().left;
    var top = $('#target').offset().top;

    // Relative coordinates of image
    var relX = e.pageX - left;
    var relY = e.pageY - top;
    var nativeImageWidth = NATIVE_IMG.width;
    var nativeImageHeight = NATIVE_IMG.height;

    // Zoomed image coordinates
    var zoomX = -Math.floor(relX / width * (NATIVE_IMG.width) - 200 / 2);
    var zoomY = -Math.floor(relY / height * (NATIVE_IMG.height) - 200 / 2);

    if (degrees_image === 90) {
      var backPos = `${zoomY}px calc(100% - ${zoomX}px)`;
      var backgroundSize = NATIVE_IMG.width + "px " + NATIVE_IMG.height + "px";
    } else if (degrees_image === 180) {
      var backPos = `calc(100% - ${zoomX}px) calc(100% - ${zoomY}px)`;
      var backgroundSize = NATIVE_IMG.width + "px " + NATIVE_IMG.height + "px";
    } else if (degrees_image === 270) {
      var backPos = `calc(100% - ${zoomY}px) ${zoomX}px`;
      var backgroundSize = NATIVE_IMG.width + "px " + NATIVE_IMG.height + "px";
    } else if (degrees_image === 360) {
      var backPos = `${zoomX}px ${zoomY}px`;
      var backgroundSize = NATIVE_IMG.width + "px " + NATIVE_IMG.height + "px";
    }

    // Apply styles to lens
    $blowupLens.css({
      left: lensX,
      top: lensY,
      "background-image": "url(" + encodeURI($IMAGE_URL) + ")",
      "background-size": backgroundSize,
      "background-position": backPos,
      "transform": 'rotate(' + degrees_image_native + 'deg)' //rotate the image original
    });
  })
  $element.off("mouseleave"); // remove previous event
  // Hide magnification lens
  $element.mouseleave(function() {
    $blowupLens.css("display", "none");
  });
}

<button onclick="rotateImage()">Rotate</button>

However, I recommend refactoring your example, because it can be simplified and make the code cleaner.


text:
Q: Schedule mysql event to run every chosen day of the week i want to read my table logs after rotating my logs using an event and i want my event to run in any day of the week i choose.
After doing some research,i have come up with this
CREATE EVENT read_rotated_logs
ON SCHEDULE
  EVERY 1 WEEK
  STARTS CURRENT_DATE + INTERVAL 7 - WEEKDAY(CURRENT_DATE) DAY
    DO BEGIN

    END */$$
DELIMITER ;

Its not clear how i might arrive at a specific day of the week for example monday.How may i structure my code to make the event run on any speific day of the week (mon or tuesday or wednesday or thursday or friday or saturday or sunday)

A: Here is how you do it for the other days of the week
Monday
STARTS CURRENT_DATE + INTERVAL 0 - WEEKDAY(CURRENT_DATE) DAY

Tuesday
STARTS CURRENT_DATE + INTERVAL 1 - WEEKDAY(CURRENT_DATE) DAY

and so on


text:
Q: C++\cli Check if file can be created here, FolderBrowseDialog I'm using a folderBrowseDialog to give the user the ability to choose where the program is going to save some files. there is a problem that the user can choose path that the application can not manipulate, for instance "c:\" (the program is launched by user not admin)
I've seen some program that propose me change my path to "my documents" whenever I try to choose a path that USER cannot manipulate, however I could not figure out how to do it.
note that I'm using folderBrowseDialog not savefiledialog.
So I thought that maybe I'll pop a warning, using the FileIOPermission. but for some reasone it doesn't work. here is a quick code I wrote, but the exception is never thrown.
FileIOPremission on MSDN
using namespace System::Security::Permissions;

FileIOPermission^ f2 = gcnew FileIOPermission( FileIOPermissionAccess::Write,"C:\\");

try {
    f2->Demand();
}
catch (System::Security::SecurityException^ s){
    MessageBox::Show(s->Message);
}

A: You are on the wrong track with this.  Yes, a FileIOPermission doesn't do what you hope it does, that's a security related class that allows you to write code that runs in a sandbox.  Like code that runs in a browser, stopping it from splattering files all over the user's disk.  Or reading sensitive files.  That doesn't work in a vanilla C++/CLI app, it runs in full trust, giving the user access to all the directories and files she normally has access to without adding further restrictions.  You have no reason to add extra ones.
Writing files to a disk is in general a perilous operation.  Lots of things can go wrong.  You are running your code on an operating system that has many other processes that are accessing files.  Trying to overwrite a file that's being read by some other process is going to cause an exception.  The disk might fill up.  The user might have entered the name of directory that she doesn't have access to, that's just one more failure mode.  Just catch the IOException and tell the user about it.
And sure, start the journey in the dialog from a directory that a restricted user is well familiar with.  Her Documents folder is her "home" directory.  If it isn't obvious that you're going to dump a whole bunch of files in the selected directory then display a gentle reminder if you see any other files in the directory.  Avoids the "Eek, what did you DO!" response when she finds out that here Documents directory suddenly has a lot more files.  The first few times.  Also don't hesitate to create your own sub-folder when you can give it a descriptive name so this doesn't happen.  Some name that has the date/time in it usually works.


text:
Q: Accssess to repository from .net core library I need to wrap some function in repository class in .net core library. But I get a mistake that my constructor doesn't have properly constructor. What am I doing wrong?
Here is my DBcontext code
 public class effMercContext : DbContext
{
    public DbSet<Department> Departments { get; set; }
    public DbSet<Employee> Employees { get; set; }
    public DbSet<Project> Projects { get; set; }
    public effMercContext(DbContextOptions<effMercContext> options)
        : base(options)
    {
    }
}
     public class EffMercDbContextFactory : IDbContextFactory<effMercContext>
{
    public effMercContext Create(DbContextFactoryOptions options)
    {
        var builder = new DbContextOptionsBuilder<effMercContext>();
        builder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=pinchdb;Trusted_Connection=True;MultipleActiveResultSets=true");
        return new effMercContext(builder.Options);
    }
}

My repository class so far
public class EmployeeRepository
{
    public Employee GetByID(int id)
    {
        using (effMercContext db = new effMercContext())
        {

        }
    }
}

A: That's because you call the constructor without parameters here:
public Employee GetByID(int id) {
    using (effMercContext db = new effMercContext())
    {

    }
}

But in your DbContext class you only have a constructor with one parameter:
public class effMercContext : DbContext {
    public effMercContext(DbContextOptions<effMercContext> options)
        : base(options) {
    }
}

Look at this article to find out how to use DbContextOptions: https://docs.efproject.net/en/latest/miscellaneous/configuring-dbcontext.html

A: You can modify your EmployeeRepository as following...
public class EmployeeRepository
{
    var optionsBuilder = new DbContextOptionsBuilder<effMercContext>();
    // add necessary options
    public Employee GetByID(int id)
    {
        using (effMercContext db = new effMercContext(optionsBuilder.Options))
        {

        }
    }
}

To learn more you can follow this


text:
Q: How to enable Arabic support in GNOME terminal? I'm trying to write Arabic in the terminal app but it does not recognize right-to-left text and does not bind the Arabic letters together as it should.
I tried this solution https://bugs.launchpad.net/ubuntu/+source/vte/+bug/263822 but it did not work.
Are there any plans to implement Arabic support in the gnome terminal? KDE Konsole terminal works without any problems.
This is what is needed in a terminal to support Arabic:

*

*Arabic letters need to be displayed correctly with a font that supports Arabic, from right to left, with the letters taking the correct forms (letters in the same word are joined together, usually, we want to see على not ع ل ى)

*It needs to support diacritic marks (known as shakl شَكْل in Arabic)

*There needs to be a way to enable right-to-left mode for the entire line. For example, the word على followed by a . should be displayed with the dot on the left, not the right.

*There needs to be a way to align the text of the line to the right, not to the left.

Here is an example of four properties being met in Gedit:

However, GNOME Terminal in Ubuntu 21.10 only supports properties 1 and 2 of the previous list of requirements:

(The letters are displayed correctly right to left, however, the dot is on right when it should be on the left, and the text is left-aligned rather than right-aligned.)

A: try this: sudo apt-get install libfribidi0 libfribidi-dev, install THIS package, then vim /usr/share/applications/gnome-terminal.desktop and add this code to the document:
Terminal=true
Exec=/usr/bin/bicon.bin

A: GNOME Terminal 3.34 supports right to left scripts such as Arabic.
The work actually went into VTE version 0.58, so any other terminal emulator using VTE (e.g. Tilix, Terminator, Xfce Terminal, Guake...) will automatically receive it.
It's going to debut in Ubuntu 19.10 Eoan Ermine.

A: Update
As egmont mentioned in his comment below, a BiDi implementation is coming to vte terminal emulator. Check his answer which is the last updated concerning this topic.
Here is a reference if looking for details: https://terminal-wg.pages.freedesktop.org/bidi/

Original answer
No, there is no plans to implement RTL support in gnome-terminal or any terminal depends on vte as the case of synaptic installation terminal.

*

*You may proxy your command through fribidi command to make bidi & basic shaping of Arabic.

*You may also use konsole (KDE) or mlterm that had implemented a partial support for Unicode bidi and shaping.

Currently, there is no correct way to implement those Unicode algorithms for the consoles. (Those implementions in konsole & mlterm are kind of workaround)
Here is a portion from a Behdad Esfahbod's post, he is the main developer of  HarfBuzz (hb for short, an OpenType text shaping engine)

Terminal emulators with support for complex text are very weird
  hybrids. On the one hand terminal emulators have to lay text out in a
  predefined grid in a predefined way, which is in conflict with many
  aspects and requirements of complex text, on the other hand users
  demand support for complex text in their terminals. It gets uglier
  when you think about bidirectional text, say, inside a console text
  editor. Nonetheless, it is fair to say that such hybrids do not put
  any new demands on the shaping engine. gnome-terminal currently has no
  support for complex text other than combining marks. Konsole has
  bidirectional text support. Apple's Terminal App has at least bidi
  support as well as Arabic shaping support, not sure about other
  complex text. Update (Jan 18, 2010): The terminal mode (term and
  ansi-term) in recent versions of Emacs can render complex text,
  including Indic.

Source: State of Text Rendering
Here is the corresponding bug report in Launchpad bug #263822: RTL (right to left) support in terminal (BiDi).

A: There are three more solutions:

*

*use tabby (an electron app - web based):

*use Konsole (the default emulator for KDE distros):
sudo apt install konsole

*use butterfly (a pure web based terminal):

thank you @singrium

A: For Ubuntu 64 bit, you would need to download BiCon, the Bidirectional Console. To add the PPA and install:
sudo add-apt-repository ppa:behnam/ppa
sudo apt-get update
sudo apt-get install bicon

I guess you were having a dependency problem.
You would need also to install the apps stated above with this command:
sudo apt-get install libfribidi0 libfribidi-dev

Hope that this could help

A: Use Mlterm, It's has great support for Arabic and other non-latin characters. You can download it from Ubuntu repositories:
sudo apt install mlterm


text:
Q: Multiple backslashes in string java regex So I have a string X1X2X3\\\\. I only want to capture the AlphaNumerics values. My regex is ([A-z0-9]*).*. But it will return X1X2X3\\. My code looks like this:
Pattern pattern = Pattern.compile("([A-z0-9]*).*");
Matcher matcher = pattern.matcher(str);
matcher.matches();
return matcher.group(1);

Would like to find regex Answer. Not String.replaceAll() or replace() :)

A: The problem is with A-z in [A-z0-9], which can match non-alpha characters as well, namely the code points between Z and a.
The correct expression to use is [A-Za-z0-9] for alphanumeric characters, or the predefined character class \\w.
(credit goes to all those who pointed out the mistake in comments)


text:
Q: Is it possible to calculate the height and width of the following labyrinth without using list functions or list synthax My goal is to write a function that calculates the width and height of a labyrinth by using following code. So far i only found approaches that include using list functions or list syntax, but i want to find a alternative solution without using list syntax. I am a Haskell beginner and very new to programming in general.
showLabyrinth labyrinth =
   putStrLn $ unlines $ [[labyrinth j i | i <- [1..dimH]] | j <- [1..dimV]]
 where
   dimH = length . takeWhile (/='O') $ [labyrinth 1 i | i <- [1..]]
   dimV = length . takeWhile (/='O') $ [labyrinth i 1 | i <- [1..]]

labyrinthA 9 _  = 'O'
labyrinthA _ 16 = 'X'
labyrinthA _ 17 = 'O'
labyrinthA 1 _  = 'X'
labyrinthA 2 1  = 'X'
labyrinthA 2 8  = 'X'
labyrinthA 2 12 = 'X'
labyrinthA 2 _  = ' '
labyrinthA 3 1  = 'X'
labyrinthA 3 3  = 'X'
labyrinthA 3 5  = 'X'
labyrinthA 3 6  = 'X'
labyrinthA 3 8  = 'X'
labyrinthA 3 9  = 'X'
labyrinthA 3 10 = 'X'
labyrinthA 3 12 = 'X'
labyrinthA 3 14 = 'M'
labyrinthA 3 _  = ' '
labyrinthA 4 1  = 'X'
labyrinthA 4 2  = 'X'
labyrinthA 4 3  = 'X'
labyrinthA 4 5  = 'X'
labyrinthA 4 6  = 'X'
labyrinthA 4 12 = 'X'
labyrinthA 4 _  = ' '
labyrinthA 5 1  = 'X'
labyrinthA 5 5  = 'X'
labyrinthA 5 8  = 'X'
labyrinthA 5 9  = 'X'
labyrinthA 5 10 = 'X'
labyrinthA 5 12 = 'X'
labyrinthA 5 13 = 'X'
labyrinthA 5 15 = 'X'
labyrinthA 5 _  = ' '
labyrinthA 6 1  = 'X'
labyrinthA 6 3  = 'X'
labyrinthA 6 4  = 'X'
labyrinthA 6 5  = 'X'
labyrinthA 6 7  = 'X'
labyrinthA 6 8  = 'X'
labyrinthA 6 10 = 'X'
labyrinthA 6 _  = ' '
labyrinthA 7 1  = 'X'
labyrinthA 7 6  = 'T'
labyrinthA 7 9  = 'X'
labyrinthA 7 10 = 'X'
labyrinthA 7 11 = 'X'
labyrinthA 7 12 = 'X'
labyrinthA 7 13 = 'X'
labyrinthA 7 14 = 'X'
labyrinthA 7 15 = 'X'
labyrinthA 7 _  = ' '
labyrinthA 8 6  = 'E'
labyrinthA 8 _  = 'X'

labyrinthB 7 6  = '.'
labyrinthB 6 6  = '.'
labyrinthB 5 6  = '.'
labyrinthB 5 7  = '.'
labyrinthB 4 7  = '.'
labyrinthB 4 8  = '.'
labyrinthB 4 9  = '.'
labyrinthB 4 10 = '.'
labyrinthB 4 11 = '.'
labyrinthB 5 11 = '.'
labyrinthB 6 11 = '.'
labyrinthB 6 12 = '.'
labyrinthB 6 13 = '.'
labyrinthB 6 14 = '.'
labyrinthB 5 14 = '.'
labyrinthB 4 14 = 'T'
labyrinthB x y  = labyrinthA x y

labyrinthC 3 14 = ' '
labyrinthC 4 14 = ' '
labyrinthC x y  = labyrinthB x y

A: You can do it using a recursive function:
type Labyrinth = Int -> Int -> Char
width :: Labyrinth -> Int
width l = width' 1
  where width' n | l 1 n == 'O' = n-1
                 | otherwise    = width' (n+1)

This is a relatively standard recursive technique.  The function width uses a helper function width' which takes the current column index (starting with 1 when first called by width).  It checks if the labyrinth function returns 'O' at that column with a "pattern guard".  If it does, it returns the index of the column just before the 'O'.  If it doesn't, it recursively calls itself to check the next column.


text:
Q: How to use Overcommit inside of Xcode I have installed "Overcommit" globally using:
sudo gem install overcommit

It works inside of terminal, but when I try to commit code from within Xcode, I get the following error:

This repository contains hooks installed by Overcommit, but the overcommit gem is not installed.
  Install it with gem install overcommit.

My overcommit.yml file looks like this:
PreCommit:
  SwiftLint:
    enabled: true
    command: ["Pods/SwiftLint/swiftlint", "lint", "--strict"]

It is also worth noting that I installed Ruby using rbenv and set the newest version as my global version.
Is there any way to make it work from inside Xcode?


text:
Q: use jsp as both view and controller I have the following class
A JAVA FILE(data)
 package p1;

 class data
 {
private String pro;
private String sta;

   public void set1(String a)
   {
   pro=a;
   }

   public void set2(String b)
   {
   sta=b;
   }

   }

A class file to retrive data from db
A JAVA FILE(conb)
  package p1;
  import java.sql.*;
  import java.sql.Connection;
  import java.sql.DriverManager;
  import java.sql.SQLException;
  import java.util.*;
  import p1.*;
  public class conb
  {
  public static List<data> datadb() throws SQLException
   {
  List<data> n1=new ArrayList<data>();
 Connection conn = null;
 Statement st = null;
       try
       {
           String userName = "frank";
           String password = "asdf";
           String url = "jdbc:mysql://localhost:8080/work";
           Class.forName ("com.mysql.jdbc.Driver").newInstance ();
           conn = DriverManager.getConnection (url, userName, password);

       }
       catch (Exception e)
       {
    e.printStackTrace();

       }

        try {

            st = conn.createStatement();
            st.execute("select * from work1");
            ResultSet rs = st.getResultSet();
            while(rs.next())
                {
                    data d1=new data();
                    d1.set1(rs.getString("pron"));
                    d1.set2(rs.getString("sdata"));
                    n1.add(d1);
                }
            rs.close();
            }

        catch (SQLException e)
            {
            e.printStackTrace();

            }
       finally
       {
           if (conn != null)
           {
               try
               {
                   conn.close ();
               }
               catch (Exception e)
       {
        e.printStackTrace();
       }
           }
       }
return n1;
   }
 }

This files are in WEB-INF/Classes/p1
And i want to display the data in a jsp file (using jsp as controller and view)
I am using tomcat 6.0 in windows.
I have written jsp page also for this
 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
 <%@ import "java.util.*" %>
 <%@ import "p1.conb" %>
 <!doctype HTML public "-//W3C//DTD HTML 4.0 Frameset//EN">

        Name
        Start time

 <%
 List<data> da1 = new List<data>();
 da1=p1.conb.datadb();
 %>
 <c:forEach items="${da1}" >
 <c:out value="{$da1.pro}" />
 <c:out value="{$da1.sta}" />

 </c:forEach>

I am getting errors
how can i retrive the data from database using only jsp.
I dont want to use a servlet as a controller.
The errors are:
org.apache.jasper.JasperException: org.apache.jasper.JasperException: Unable to load class for JSP org.apache.jasper.servlet.JspServletWrapper.getServlet(JspServletWrapper.java:161) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:340) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260) javax.servlet.http.HttpServlet.service(HttpServlet.java:717)

A: I must admint that I do not feel comfortable with this answer, but if you simply want to get it running remove the <c:forEach [...] loop.
Replace this
<%
List<data> da1 = new List<data>();
da1=p1.conb.datadb();
%>
<c:forEach items="${da1}" >
    <c:out value="{$da1.pro}" />
    <c:out value="{$da1.sta}" />

</c:forEach>

with something like this (you have to create the getter methods in your data class:
<%
List<data> da1 = new List<data>();
da1=p1.conb.datadb();

for (data da : da1) {
%>

    <%=da.getPro()%>
    <%=da.getSta()%>

<%
}
%>

Just for info - there is a huge number of issues with your code, to name a few:

*

*scriptlets in JSP are a bad idea

*classes do not conform to Java naming conventions at all

*HTML tags are inconsistent, e.g.  at the end of the document,  not well formatted

*database connection initialization on each call to JSP (this will not scale)

A: I realize that I'm late to the party, but I've come across this type of problem many times as I've refactored JSPs to stop using scriptlets. In the intermediate stages, there are a lot of times where I have scriptlets that load data, but I want to use that data with some JSTL tags/EL expressions. This is my usual, temporary solution:
<%
List<data> da1 = new List<data>();
da1=p1.conb.datadb();

pageContext.setAttribute("da1", da1);
%>
<c:forEach items="${da1}" >
    <c:out value="{$da1.pro}" />
    <c:out value="{$da1.sta}" />

</c:forEach>

You could just as easily add your data as an attribute in the request scope instead, but I start as local as possible and move to broader contexts as I need it.


text:
Q: For any $n$, $G^\dot{n}$ is a subgroup of $G$. Is $G$ abelian? Let $G$ be a group such that for each $n$:
$$G^\dot{n}=\{a^n|a\in G\}$$
is a subgroup of $G$. Is $G$ abelian?

A: Here it is a large family of those groups. A a finite  $p$-group is said to be powerful if $p$ is odd and $[G,G]\leq G^p$ or if $p=2$ and $[G,G]\leq G^4$. If $G$ is a powerful $p$-group then for any integer $n$ we have $G^n=\{g^n:n\in G\}$. This is Theorem 2.7 in the book Analytic pro-$p$ group: http://books.google.com.ar/books?id=7yxplSjMWtkC&printsec=frontcover&hl=es&source=gbs_ge_summary_r&cad=0#v=onepage&q&f=false

A: Look at the quaternion group...

A: Let $Q = \{1, -1, i, -i, j, -j, k, -k\}$ be the quaternion group of order 8.  Then
$$Q^2 = \{1, -1\}$$
$$Q^3 = Q$$
$$Q^4 = 1$$
So $Q^k$ is a subgroup for all $k$ (because $Q^5 = Q$, $Q^6 = Q^2$, etc.).  But $Q$ is not abelian.
I've found that whenever you conjecture that some property implies a group is abelian, it's always useful to check if $Q$ is a counterexample.  It's the standard counterexample to show that "every subgroup is normal" does not imply abelian.


text:
Q: Bash/PHP/Javascript: How to run a php file that outputs javascript, and execute that javascript? Currently i'm trying to send a webhook request to discord, so i can send updates to my repository to a channel in my discord server.
If I load the page in my browser, it will run this code just fine, and the message will appear in my discord:
      <script>
      $(document).ready(function(){
        setTimeout(send(), 300);
      });
      function send(){
        var link = "discordwebhooklink";
        var hookurl = link + "/slack";
        var msgJson
        msgJson = {
         "username": "",
         "icon_url": "",
         "text": "Hey! I've got a new project [here](http://repo.mydomain.ca/<?php echo $link; ?>/)!",
         "attachments":[{
           "author_icon": "",
           "author_name": "",
           "color": "#ff9900",
           "fields": [{
            "title": "Repo Project Created!",
            "value": "\n----------------------------------------------------------------------------\n```json\nProject Information\n\nTitle:\n \"<?php echo $title; ?>\"\nDescription:\n \"<?php echo $description; ?>\"\nVersion: <?php echo $version; ?>\n```",
           }]
          }]
        };
        post(hookurl, msgJson);
      }
      </script>

      <script>
      function post(url, jsonmsg){
        xhr = new XMLHttpRequest();
        xhr.open("POST", url, true);
        xhr.setRequestHeader("Content-type", "application/json");
        var data = JSON.stringify(jsonmsg);
        console.log(jsonmsg);
        console.log(data);
        xhr.send(data);
        xhr.onreadystatechange = function() {
            if(this.status != 200){
                alert(this.responseText);
            }
        }
      }
      </script>

But if i run the page from crontab with php /path/to/file.php then it doesn't show up in the channel. I've figured out that the cause is that it won't execute javascript, so I'm here asking, how can I run the PHP code, and Javascript code, from bash. (Note: jQuery is included in the outputted html from the php script)
I also tried doing a pure PHP solution, but couldn't get the messages to appear in my channel either. I tried a few PHP solutions that used CURL, stream_context_create, and include, but I don't understand any of the solutions given, so it could be a fault on my part.
TL;DR: How do I use crontab to execute a .php file that outputs javascript, and have the outputted javascript be executed, not just printed.
Edit: Flagged as duplicate, but i said i couldn't figure out cURL solutions.


text:
Q: https not workking AWS ELB(ssl cert) + FLASK + NGNIX I have a AWS Load balancer with SSL which is pointing to a ec2(windows) on 80, i.e on LB,
https 443 http 80
However the app i'm running is on another port 9100 which is configured in ngnix, now i'm unable to access the server via https
Please help me out on this
here is my nginx config,
server {
        listen 80;
        server_name mydomain.com;

        location / {
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto https;
            proxy_pass http://127.0.0.1:9100;
            proxy_connect_timeout 150;
            proxy_send_timeout 100;
            proxy_read_timeout 100;
            proxy_buffers 4 32k;
            client_max_body_size 8m;
            client_body_buffer_size 128k;
        }
}

A: There  are many examples of Nginx with https around. Merging the Nginx HTTPS documentation with your sample configuration gives something like:
server {
    listen 80;
    listen 443 ssl;

    server_name mydomain.com;

    ssl_certificate     www.example.com.crt;
    ssl_certificate_key www.example.com.key;
    ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;

    location / {
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto https;
        proxy_pass http://127.0.0.1:9100;
        proxy_connect_timeout 150;
        proxy_send_timeout 100;
        proxy_read_timeout 100;
        proxy_buffers 4 32k;
        client_max_body_size 8m;
        client_body_buffer_size 128k;
    }
}

This will get Nginx to serve traffic as HTTPS on port 443. You would need to update the ELB to send HTTPS traffic to port 443 if it's coming via that device.
You would also need to update the Nginx ssl_certificate & ssl_certificate_key options to point to somewhere on the EC2 instance that contains those files.