text:
Q: Putting ImageView on the bottom of the screen I am trying to put the ImageView on the bottom of the layout with following XML:
        <?xml version="1.0" encoding="utf-8"?>
        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical"
            tools:context=".MainActivity" >
            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:background="#EEEEEE"
                android:gravity="center"
                android:orientation="horizontal" >
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="bottom"
                    android:src="@drawable/photo" />
            </LinearLayout>
        </LinearLayout>

I am following the instructions found here http://sandipchitale.blogspot.co.uk/2010/05/linearlayout-gravity-and-layoutgravity.html
Only difference is that I use ImageView instead of Button as here:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center"
        android:orientation="horizontal" >
        <Button
            android:id="@+id/Button03"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:text="bottom" >
        </Button>
    </LinearLayout>
</LinearLayout>

Which puts the button on the expected place:

Unfortunately this isn't the case in my XML on the top of the post. The ImageView isn't placed on the bottom as the Button in reference XML is.

Any ideas why that happens ?

A: You should change a setting in ImageView itself, to be precise set android:scaleType="fitEnd" on your ImageView.
The other answers seem to be workarounds, including your own answer. This is not a problem with a layout, but with where inside the ImageView the image is loaded when the dimensions of the image and the screen aren't similar, (i.e. the width/height ratio is very different). By default it would load the image in the middle of the ImageView.

A: Try using RelativeLayout instead of LinearLayout and use parameter android:layout_alignParentBottom = "true".
EDIT: Try giving layout_height and layout_width as wrap_content for your LinearLayout that holds your ImageView.
Or it might be that the image you are using has extra space above and below it.
UPDATE:
The problem is with the size of the image. It is much larger than the screen size. I would suggest you to programmatically read the screen size of the device with below code:
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;

and set the height and width for imageView programmatically as below:
image_view.getLayoutParams().height = height - 50;
image_view.getLayoutParams().width = width - 50;

A: Try this inside relative layout
<ImageView
    android:id="@+id/imageView9"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:adjustViewBounds="?attr/isLightTheme"
    app:srcCompat="@drawable/client_app_footer" />

tested & working as expected

A: you did not include android:layout_gravity="bottom" line in your imageview.

A: I have resized photo size from width 2560 to width 270 and finally ImageView went to bottom.


text:
Q: Not finding Inherited annotations on Abstract Superclass I've created an inherited field type annotation that is placed on private properties in an abstract superclass.
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Lifecycle{
    Type type();
    String name() default "";

    public enum Type{
        DISCRIMINATOR,INITIAL,MUTABLE
    }
}

I'm calling a method from the subclass which seeks to gather all the annotations of this type (inherited or otherwise) and return them in a list.
public static <T extends Annotation> List<T> getAnnotation(final Class c, final Class<T> ann) {
    return getAnnotation(c, ann, new ArrayList<T>());
}

public static <T extends Annotation> List<T> getAnnotation(final Class c, final Class<T> ann, List<T> aList) {
    Field[] fields = c.getFields();
    for (int i = 0; i < fields.length; i++) {
        Field myField = fields[i];
        myField.setAccessible(true);
        T found = myField.getAnnotation(ann);
        if (found != null) {
            aList.add(found);
        }
    }
    if (!c.getSuperclass().equals(Object.class)) {
        return getAnnotation(c.getSuperclass(), ann, aList);
    } else {
        return aList;
    }
}

For some reason unbeknownst to me this doesn't work. All fields both inherited and not are definitely found. Likewise all classes in the inheritance structure are traversed, but for some reason, myField.getAnnotation(ann); is always null.
I'm kind of at a loss - I don't understand why if I can properly retrieve the field (as well as get and set it's value, e.g. not a security thing) that I can't see it's annotation.

A: Instead of this one:
Field[] fields = c.getFields();

try this:
Field[] fields = c.getDeclaredFields();

If this doesn't work, try to iterate over declared annotations:
for(Annotation annotation : field[i].getDeclaredAnnotations()) {
 ...
 }

redpajama_set_name: RedPajamaStackExchange


text:
Q: DCC error : published field is not a class or interface type I keep getting this following DCC error, published field 'name' is not a class or interface type for the following class.
  TGroup = class
    name:string[32]; <<<========================
    rwFeatures:TFeatures;
    roFeatures:TFeatures;
    levels:TLevels;
  private

  public
    constructor Create;
    procedure Read(var f:file);
    procedure ReadOld(var f:file);
    procedure Write(var f:file);
  end;

What does it mean?

A: The class is compiled with the Emit runtime type information setting enabled. When the class is compiled with runtime type information, the default visibility is published. Which means that the short string field is published. And short string fields are not allowed to be published.
The documentation says:

Fields can be published only if they are of a class or interface type.

That's a pretty stringent requirement. It means that you can't publish integer or boolean fields, for example.
I suspect this limitation is because the primary use for published fields is for object references. Think of the components on a form.
Solve the problem using one of these options:

*

*Don't emit runtime type information for this class.

*Make the short string fields public rather than published.

*Use properties rather than fields.


text:
Q: Generate object coordinates in relation to neighbours I am making a game in which i have randomly spawned objects. I also have a table that has the data of which objects are close to one another, say within a range of 200px - lets call them neighbors. What i want is to generate and assign coordinates to all the available objects so that this relationship is reflected. I want to view the structure of how they are.
I have made a greedy algorithm. Which works very slowly. and gets stuck sometimes. Does anyone have a better approach to this? - the coordinates can be assigned dynamically through trial and error no problem.
Below is the current code classes.
    /**
     * biggest problem
     * */
    public void assignInitialCoords( MyObject[] objects )
    {
        objects[0].setxCoor(rand.nextInt(1000));
        objects[0].setyCoor(rand.nextInt(1000));

        for(int i=0; i<objects.length; i++ )
        {
            ArrayList<MyObject> neighs = objects[i].getNeighbours();
            System.out.println("Assigning " + objects[i].getId() + "'s coors");
            setNonNeighborCoords(objects, i);
            setNeighborCoordinates(objects, i, neighs);
            System.out.println(objects[i].getId() + "(" + objects[i].getxCoor() + ", " + objects[i].getyCoor() + ")\n");
        }
    }

The classes
import java.util.ArrayList;
import java.util.HashMap;

public class MyObject
{
    public ArrayList<MyObject> neighbours;
    public ArrayList<MyObject> nonNeighbours;
    public double fov = 360;
    public double sRange = 100, xCoor, yCoor;
    boolean isClustered = false;
    public String id;
    //Cluster[] clusters;

    public MyObject()
    {
        neighbours = new ArrayList<MyObject>();
        nonNeighbours = new ArrayList<MyObject>();
    }

    /**
     * Find neighbours for this Object given a relations table
     * example: if a MyObject has id A, and neighbor is B, then the key can be either: A_B or B_A
     * Both represent the same relation, so we only need to check it once
     * */
    public void findNeighbours(HashMap<String, Integer> table, MyObject[] objects)
    {
        for (int i = 0; i < objects.length; i++)
        {
            String key1 = getId() + "_" + objects[i].getId(), key2 = objects[i].getId() +"_" + getId(), key="";
            if(table.get(key1) != null)
            {
                key = key1;
                if(table.get(key) <= getsRange())
                    getNeighbours().add(objects[i]);
            }
            if(table.get(key2) != null)
            {
                key = key2;
                if(table.get(key) <= getsRange())
                    getNeighbours().add(objects[i]);
            }
        }
    }

    /**
     * Check whether a given Object is the neighbour ArrayList of this object
     * */
    public boolean isInNeighbours( MyObject n )
    {
        if(neighbours.equals(null)) { return false; }
        for(int i=0; i<getNeighbours().size(); i++)
            if(getNeighbours().get(i).getId().equals(n.getId())) { return true; }
        return false;
    }

    /**
     * Check whether a given Object is the noneighbour ArrayList of this object
     * */
    public boolean isInNonNeighbours( MyObject n )
    {
        if(nonNeighbours.equals(null)) { return false; }
        for(int i=0; i<getNonNeighbours().size(); i++)
            if(getNonNeighbours().get(i).getId().equals(n.getId())) { return true; }
        return false;
    }

    /**
     * Check if given MyObject Can be a neighbour to this Object - for rand coord generation
     * */
    public boolean canBeANeighbour(MyObject n)
    {
        return distanceTo(n) <= sRange;
    }

    // return Euclidean distance between this and p
   public double distanceTo(MyObject p) {
      double dx = this.xCoor - p.xCoor;
      double dy = this.yCoor - p.yCoor;
      return Math.sqrt(dx*dx + dy*dy);
   }

    //Setters And Getters
    public ArrayList<MyObject> getNeighbours(){ return neighbours; }

    public void setNeighbours(ArrayList<MyObject> neighbours)
    {
        this.neighbours = neighbours;
    }
    public double getFov()
    {
        return fov;
    }
    public void setFov(double fov)
    {
        this.fov = fov;
    }
    public double getsRange()
    {
        return sRange;
    }
    public void setsRange(double sRange)
    {
        this.sRange = sRange;
    }
    public double getxCoor()
    {
        return xCoor;
    }
    public void setxCoor(double xCoor)
    {
        this.xCoor = xCoor;
    }
    public double getyCoor()
    {
        return yCoor;
    }
    public void setyCoor(double yCoor)
    {
        this.yCoor = yCoor;
    }
    public boolean isClustered()
    {
        return isClustered;
    }
    public void setClustered(boolean isClustered)
    {
        this.isClustered = isClustered;
    }
    public String getId()
    {
        return id;
    }
    public void setId(String id)
    {
        this.id = id;
    }

    public ArrayList<MyObject> getNonNeighbours()
    {
        return nonNeighbours;
    }

    public void setNonNeighbours(ArrayList<MyObject> nonNeighbours)
    {
        this.nonNeighbours = nonNeighbours;
    }
}

//The sample test:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;

public class SampleField
{
    Random rand = new Random();
    public int range = 100;
    HashMap<String, Integer> table = new HashMap<String, Integer>();
    String[] nodeIds = {"A", "B", "C", "D", "E", "F"};
    public MyObject[] objects = new MyObject[nodeIds.length];

    public static void main(String[] args)
    {
        SampleField test = new SampleField();
        for(MyObject n: test.objects)
        {
            n.findNeighbours(test.table, test.objects);
        }
        test.populateNonNeighbours(test.objects);
        System.out.println(test.table);
        test.printRelationsTable(  test.objects );
        test.assignInitialCoords(test.objects);
        System.out.println(test.table);
        test.printRelationsTable(  test.objects );
    }

    public SampleField()
    {
        initialiseNodes();
        generateTestTable(objects);
    }

    /**
     * biggest problem
     * */
    public void assignInitialCoords( MyObject[] objects )
    {
        objects[0].setxCoor(rand.nextInt(1000));
        objects[0].setyCoor(rand.nextInt(1000));

        for(int i=0; i<objects.length; i++ )
        {
            ArrayList<MyObject> neighs = objects[i].getNeighbours();
            System.out.println("Assigning " + objects[i].getId() + "'s coors");
            setNonNeighborCoords(objects, i);
            setNeighborCoordinates(objects, i, neighs);
            System.out.println(objects[i].getId() + "(" + objects[i].getxCoor() + ", " + objects[i].getyCoor() + ")\n");
        }
    }

    /**
     * if this object has neighbours, try to set their coordinates so that they do not conflict
     *
     * @param objects
     * @param i
     * @param neighs
     */
    private void setNeighborCoordinates(MyObject[] objects, int i, ArrayList<MyObject> neighs)
    {
        //it should have at least one neighbour
        if(neighs != null )
            for( int j=0; j<neighs.size(); j++ )
            {
                //Initial assignment to the first neighbor
                neighs.get(j).setxCoor(rand.nextInt() + objects[i].getsRange() );
                neighs.get(j).setyCoor(rand.nextInt() + objects[i].getsRange() );
                //If not a neighbor keep generating coordinates until it keeps being a neighbor.
                while( !objects[i].canBeANeighbour(neighs.get(j))  )
                {
                    //go deeper? - later
                    neighs.get(j).setxCoor(rand.nextInt(1000) - shootRange() - 5 );
                    neighs.get(j).setyCoor(rand.nextInt(1000) - shootRange() - 5 );
                }
            }
    }

    /**
     * try to set the coordinates of each object here
     * @param objects
     * @param i
     */
    private void setNonNeighborCoords(MyObject[] objects, int i)
    {
        for(MyObject n : objects[i].getNonNeighbours())
        {
            n.setxCoor(rand.nextInt() + shootRange() - 5);
            n.setyCoor(rand.nextInt() + shootRange() - 5);
                //Make sure non neighbors remain non neighbors
                while(objects[i].canBeANeighbour(n))
                {
                    n.setxCoor(rand.nextInt() + shootRange() - 5 );
                    n.setyCoor(rand.nextInt() + shootRange() - 5 );
                }

        }
    }

    /* populate nonNeighbours */
    public void populateNonNeighbours(MyObject[] objects)
    {
        for(int i=0; i<objects.length; i++)
        {
            for(int j=0; j<objects.length; j++ )
            {
                if( (objects[i].getId() != objects[j].getId()) && !objects[i].isInNeighbours(objects[j]) )
                {
                    objects[i].getNonNeighbours().add(objects[j]);
                }
            }
        }
    }
    /* Show each object and its neighbors/nonneighbors - just for output */
    public void printRelationsTable( MyObject[] objects )
    {
        for(int i=0; i<objects.length; i++ )
        {
            System.out.print("MyObject " + objects[i].getId() + "'s neighbours: ");
            for(int j=0; j<objects[i].getNeighbours().size(); j++)
            {
                System.out.print(objects[i].getNeighbours().get(j).getId() + " ");
            }
            System.out.println();

            System.out.print("\t\t" +objects[i].getId()+ "' : ");
            for(int j=0; j<objects[i].getNonNeighbours().size(); j++)
            {
                System.out.print(objects[i].getNonNeighbours().get(j).getId() + " ");
            }
            System.out.println();
        }
    }
    /* Initialise Objects here - give basic information */
    public void initialiseNodes()
    {
        for(int i=0; i<nodeIds.length; i++)
        {
            MyObject n = new MyObject();
            n.setId(nodeIds[i]);
            n.setsRange(shootRange());
            objects[i] = n;
        }
    }

    /* Generate a list of neighbors for testing */
    public void generateTestTable(MyObject[] objects)
    {
        for(int i=0; i<objects.length; i++)
        {
            /* Get two objects' ids and make them neighbors - ids must be unique */
            String firstId = objects[rand.nextInt(objects.length)].getId();
            String secondId = objects[rand.nextInt(objects.length)].getId();
            while( firstId.equals(secondId) || table.containsKey(firstId + "_" + secondId) || table.containsKey(secondId + "_" + firstId) )
            {
                firstId = objects[rand.nextInt(objects.length)].getId();
                secondId = objects[rand.nextInt(objects.length)].getId();
            }
            table.put(firstId + "_" + secondId, shootRange());
        }
    }

    /* Range within which they are neighbors */
    public int shootRange()
    {
        return range;
    }

    public void setRange(int range)
    {
        this.range = range;
    }
}

A: If you only compare distances (and if you are talking about neighbours, it seems so), then you don't need to count them at all. Instead of
range = sqrt(sqr(a.x-b.x)+sqr(a.y-b.y))
if (range >d)...

use
sqrange(a,b) = sqr(a.x-b.x)+sqr(a.y-b.y)
if (range> d_sqr) ...

That means, you don't use ranges, but their squares. That quickens the comparisons about 50 times (for double). So, you can use much more easy structures.


text:
Q: Difference between two products Let $q$ be a square free natural number. Can the difference
$$
\prod_{p \mid q} (p^2+1) - \prod_{p \mid q} (p-1)^2
$$
be estimated in terms of $q$? What would be the correct order of the difference in terms of $q$? Is the difference $\asymp q^2$? Can something be said about
$$
\prod_{p \mid q} \frac{p^2+1}{p+1} - \prod_{p \mid q} \frac{(p-1)^2}{p+1},
$$
in the same spirit?

A: Such difference equals
$$ q^2\left[\prod_{p\mid q}\left(1+\frac{1}{p^2}\right)-\prod_{p\mid q}\left(1-\frac{1}{p}\right)^2\right]\tag{1} $$
and by Euler's product
$$ \prod_{p\in\mathcal{P}}\left(1+\frac{1}{p^2}\right)=\frac{\zeta(2)}{\zeta(4)}=\frac{15}{\pi^2}\tag{2}$$
while
$$ \prod_{p\leq x}\left(1-\frac{1}{p}\right)^2\approx\frac{C}{\log(x)^2}\tag{3}$$
hence your difference is by $\frac{15}{\pi^2}q^2$, but can be as small as $2q$ if $q$ is a prime.


text:
Q: SeriLog Formatter: how to pass formatter parameters in the json configuration file Is it possible to pass constructor parameters for Formatter in json config file?
    "WriteTo": [
        {
            "Name": "Console"
            "Args": { "formatter": "Serilog.Formatting.Elasticsearch.ElasticsearchJsonFormatter, Serilog.Formatting.Elasticsearch" }
        }
     ]

As you can see here ElasticsearchJsonFormatter ctor accepts some parameters. I would like to configure them in the config file above.
Thanks.

A: You need to expand the formatter, and explicitly specify type and all the parameters that need to be passed to the constructor:
"WriteTo": [
  {
    "Name": "Console",
    "Args": {
      "formatter": {
        "type" : "Serilog.Formatting.Elasticsearch.ElasticsearchJsonFormatter,Serilog.Formatting.Elasticsearch",
        "formatStackTraceAsArray" : true
      }
    }
  }
]


text:
Q: Creating Form with accepts_nested_attributes_for I have 2 models, a User and Patient. A User HAS_ONE Patient and a Patient BELONGS_TO a User.
class Patient < ActiveRecord::Base
  belongs_to :user
  accepts_nested_attributes_for :user
  attr_accessible :user_id, :user_attributes
end

# == Schema Information
#
# Table name: patients
#
#  id         :integer         not null, primary key
#  user_id    :integer
#  insurance  :string(255)
#  created_at :datetime
#  updated_at :datetime
#

class User < ActiveRecord::Base
  has_one :patient

  attr_accessible :username, :password, :active, :disabled, :first_name, :last_name,
  :address_1, :address_2, :city, :state, :postcode, :phone, :cell, :email
  attr_accessor :password
end

# == Schema Information
#
# Table name: users
#
#  id                 :integer         not null, primary key
#  username           :string(255)
#  encrypted_password :string(255)
#  salt               :string(255)
#  active             :boolean
#  disabled           :boolean
#  last_login         :time
#  first_name         :string(255)
#  last_name          :string(255)
#  address_1          :string(255)
#  address_2          :string(255)
#  city               :string(255)
#  state              :string(255)
#  postcode           :string(255)
#  phone              :string(255)
#  cell               :string(255)
#  email              :string(255)
#  created_at         :datetime
#  updated_at         :datetime
#

In my patients controller I am trying to create a new Patient form.
class PatientsController < ApplicationController
  def new
    @patient = Patient.new
  end
end

In My View (new.html.erb)
<%= form_for @patient do |patient_form| %>
<% patient_form.fields_for :user do |user_fields| %>

            <%= user_fields.label :username %> *:

            <%= user_fields.text_field :username, :class=>"TextField" %>

...
<%end%>
<%end%>

The form shows up blank with a submit button with no generated markup for the user_fields
I have been told I am doing this wrong because of the patient having the accepts_nested_attributes_for :user and it should be the user nesting the attributes BUT in my system I want to use the resources model so a patient and other user types are treated separately.
Example Database table:
USERS:     id|first_name|last_name...etc
PATIENTS:  id|user_id|insurance

A: Unless I'm mistaken, you have no user when you are calling fields_for. Before you can do the fields_for, you will need to have an instance of a user that can be used to build the form, kind of like how you have @patient for your patient_form.
Your best bet would be to build a User in your controller, based off of your @patient, and then you will have access to that in the view.

A: try <%= patient_form.fields_for with the equals sign in there?  I know there was a warning message for awhile about "block style helpers are deprecated".

A: The answers from Jeff Casimir and theIV are correct, but you need to do them both. I.e., fix the patient_form.fields_for block to user <%=, and build a User object for the Patient in the controller, something like:
def new
  @patient = Patient.new
  @patient.user = User.new
end


text:
Q: 12.10 Black screen on boot after unplugging external monitor Here is my story:
1. I plugged an external VGA monitor to my laptor (Dell Vostro 3550) and configured dual display using System Settings/Displays. Everything worked well
2. I unplugged the external monitor, switched off my laptop and left my office
3. Being at home, when I turn on my laptop I get a blank screen on my LCD display. Ctrl+Alt+F1...F7 doesn't work. I assume that my primary display is still set to the external monitor, but I don't have any external monitor at home. How can I switch back to LCD?

A: A quick and dirty method

*

*Boot into recovery

*Select 'root'

*Remount root partition as writable

*

*mount -o remount,rw /

*Backup, but remove your xorg.conf

*

*mv /etc/X11/xorg.conf /etc/X11/xorg.conf.bak

*Reboot

Plan ahead
Do some research on Disper and see if it can ease your monitor woes once you've gotten back on your system.  You might find this post informative.

A: I use Ubuntu 16. Before disconnecting the external monitor, you could go to display settings and manually turn off the external one. Then try to disconnect. Works for me.


text:
Q: Dynamic size styling in paperclip I have searched for this, I got the some idea from Resize missing.png depending upon style in paperclip but not the exact solution of the following scenario.
I have a form where user choose image size from dropdown, which is to upload and Then user upload the particular image.(I have validations for the same. used Paperclip::Geometry.from_file(image.queued_for_write[:original].path) for the same) .
I want to reduce the quality of original Image using convert option like (-strip -quality 90). Is there any way to create a style for original image which will be based on the selected value from the dropdown.
For eg. I have following Image sizes in dropdown
['1230 X 615'],['1230 X 390'],['1230 X 180'],['1230 X 240'],['1230 X 30'],['1020 X 180'],['1020 X 240'],['180 X 180'],['180 X 240'],['610 X 180'],['610 X 240'],['810 X 180']
Then how to create style if user select ['1020 X 240'] size from dropdown while uploading image?
Any suggestions?
Thanks in advance

A: As my thought you want to set image size whenever you are creating and updating object. You can try this one or this one .

A: Thanks for help.
Following approach I used and it is working fine without proc,
The ' ' in {:large=>' '} are taking dropdown selected size  by default.
has_attached_file :image, { :styles => {:large => ''},
                                          :convert_options => { :large => '-strip -quality 80'}}.merge(SECTION_PATH).merge(BUCKET_PATH)


text:
Q: How linux handles when a function containing infinte loop is queued in the work queue? I tried searching the net but couldn't find a perfect answer for this? What is the name of the procedure which is followed to avoid this situation where the other worker function will wait forever for this infinte loop to get over

A: if talking about processes infinite loop or no infinite loop linux does not care. the keyword you are looking for is 'preemption' and that can be looked up in any respectable os book
if there is an infinite loop not giving up the cpu in the kernel itself, that's a programming error. this is spotted with 'watchdog'.

A: Linux allows each thread of execution to run only for a specified quantum, before it is subject to being swapped out for another. It does not matter whether the process is in an infinite loop, the kernel has the power here.
As an aside (and I assume this is still the case with current kernels), threads which relinquish the CPU before their quantum is fully used can be given temporary priority boosts by the kernel as a reward for behaving nicely.


text:
Q: using window.location.href to pass variables in react I am trying to make a page which when refreshed it passes a variable back to itself.
the npm package for the toasts(messages) I am using would not allow me to display these before the redirect as the redirect would happen to fast and erase the toast.
I solved this initially by saving these to localstorage but any fellow web dev would hiss at the sound of that.
so essentially.this is my code.
pageRelocator(mssg) {

    if (mssg.length < 35) {

        window.location.href = "http://localhost:3000/completed-assessment";
    } else if (mssg.length > 35) {

     this.setState({redoToken : "yes"})

        window.location.href = `http://localhost:3000/user-questions`;
    }
  }

Would I be able to pass a variable through one of these such as
 window.location.href = `http://localhost:3000/user-questions:${MY CUSTOM VARIABLE}`;

and if so how would i retrieve it?
I am using react router dom so was thinking about just setting a boolean for each one and putting something like this in the render

{this.state.redoToken === "yes" && <Redirect to={{pathname :"/user-questions",
state: {id: " "}}} />}
 {this.state.redoToken === "no" && <Redirect to="/completed-assessment" />}

but once again seems to hacky for my liking.
Thanks in advance.

A: What version of react-router are you using? As of v5.1 you can use useParams() to get your url parameters.
Like so,
import { useParams } from 'react-router-dom'

const { slug } = useParams()

And your route for the page would have the path /user-questions/:slug


text:
Q: 2 sample Z test for non normally distributed data I'm trying to analyse the impact of a marketing campaign and I'm looking to identify the most appropriate statistical test. I have one group of customers who received the campaign (approx 100,000 people) and a random control (approx 50,000 customers) who received nothing. I want to measure whether there is any difference in the average spend from both groups in the period following the campaign launch.
The vast majority of customers in both groups will spend nothing after the campaign. Only approximately 2% of the customers in the groups will spend anything. So the average spend variable in both groups is not normally distributed - it will have a huge tail at 0, corresponding to the large number of people who will spend nothing.
As the population sizes are very large (100,000 and 50,000) can I just use a 2 sample z test as normal due to the central limit theorem? Or will the fact that the variable being tested is highly skewed mean that a 2 sample z test is invalid?

A: As noted in a comment, z-test is not appropriate in this case, since it requires a normal distribution and your data is obviously not normally distributed.
EDIT: When can you use z-test? It is true that many test statistics may approach normality with large number of samples. Now the question is whether your mean amount spent will approach a normal distribution given the large number of your samples. The way you have described (with majority, 98% of individuals spending nothing), it might be contested. I am at heart an experimentalist, so here is what I'd do: draw samples of 10,000 from your data and see whether the means are normally distributed on a q-q plot. If your data is good enough at 10K samples, it will be even better at 50K.
One possibility is, of course, a non-parametric alternative such as a U-test. With these numbers, you could also safely use a randomization approach.
However, it might be that whatever the obtained p-value, your results will not be very meaningful – precisely because of the large sample size, which will allow to detect even very small effects. If the amount spent is, say, in \$10-20 range, would an average difference of \$0.05 make any difference?
In other words, your statistical test may be overpowered.
Rather than focusing on the test, you could focus on the effect size – or actual difference (and estimate its confidence intervals).
Another problem with your approach is that very often the amount spent is not a continuous variable; for example, we are talking about a price list which contains a finite number of prices (e.g., \$9.99, \$19.99 and \$29.99, and no-one ever spends \$12.75). If that is the case, maybe comparing the frequencies of individuals who choose a particular option (or none at all) using a χ² test or something similar might be a better choice.


text:
Q: PHP: Issues with querying multiple tables My search function works well when it queries just a single table. But when I query more than one table in the same database (using 'UNION'), am faced with 2 issues:
1. $query (specifically the line: if ( ! $query->num_rows )) gives
    the error: Notice: Trying to get property of non-object in function.php line 18.
I think this has to do with how the array is to be accessed now that
it holds rows from multiple tables?
2.  Once I do get these values, am unsure how to extract the field information from the different tables. As long as there was one table, this foreach loop was fine:
foreach($_SESSION['search_output']['results'] as $value){
echo $value->title;
echo"
";
}

However how would one access the differently named fields when there are multiple tables. I was thinking of switch-case, but how to I get the table name using the procedural approach?
Would appreciate any help in understanding how to approach this.
Following are the files
function.php
<?php
function search($conn, $search_term) {
    $sanitized =  $conn->real_escape_string($search_term);

    $query = $conn->query("(SELECT * FROM news WHERE title LIKE '%{$sanitized}%' OR body LIKE '%{$sanitized}%' OR sources LIKE '%{$sanitized}%'
      OR date LIKE '%{$sanitized}%')
      UNION
      (SELECT * FROM events WHERE eventname LIKE '%{$sanitized}%' OR eventsumm LIKE '%{$sanitized}%' OR eventdate LIKE '%{$sanitized}%')
      UNION
      (SELECT * FROM recipes WHERE rectitle LIKE '%{$sanitized}%' OR recsummary LIKE '%{$sanitized}%')
      UNION
      (SELECT * FROM reviews WHERE bookname LIKE '%{$sanitized}%' OR revbody LIKE '%{$sanitized}%' OR revsource LIKE '%{$sanitized}%')
      UNION
      (SELECT * FROM foodiq WHERE iqitem LIKE '%{$sanitized}%' OR iqbody LIKE '%{$sanitized}%')");

    if ( ! $query->num_rows ) {
      return false;
    }

 $rows = array(); // ADD THIS
    while( $row = $query->fetch_object() ) {
      $rows[] = $row;
    }

    $search_results = array(
      'count' => $query->num_rows,
      'results' => $rows
    );

    return $search_results;
  }
  ?>

index.php
<?php require_once  ('setup.php');
require_once  ('function.php');
    if (session_id() === "") { session_start(); }
?>

<!DOCTYPE html>

<?php
if ( isset( $_GET['s'] ) ) {
  $search_results='';
  $search_term = htmlspecialchars($_GET['s'], ENT_QUOTES);
  $search_results = search($conn, $search_term);
  }
?>

<form role="search" method="get" class="search-form" action="">

                <input type="search" class="search-field" placeholder="Search" value="searchitem" name="s">

                <input type="submit" class="search-submit" value="Search">
</form>

  <?php if (isset($search_results)) :
  print_r($search_results); exit;
        $_SESSION['search_output'] = $search_results;
        header("Location: final.php");
        exit;
   endif; ?>

final.php
<?php
session_start();
?>

<!DOCTYPE html>

<?php
if(isset($_SESSION['search_output']) && is_array($_SESSION['search_output']))
{
echo $_SESSION['search_output']['count']. " result(s) found
";
foreach($_SESSION['search_output']['results'] as $value){
echo $value->title;
echo"
";
}

}
else
echo "Sorry, no results found";

?>

setup.php
    <?php
    $hn = 'localhost';
    $db = 'kkh';
    $un = 'water';
    $pw = 'water';

    #DB Connection:
     $conn = new mysqli($hn, $un, $pw, $db);
     if ($conn->connect_error) die($conn->connect_error);
    ?>

A: *

*YOU SHOULD check if there any connection errors like right after ->query:
/* check error */
if ($conn->error) {
    printf("Query failed: %s\n", $conn->error);
    exit();
}

Please not it's not the same as $conn->connect_error.

*You may access your fields using field names of your 1st table in union statement.
Let's assume the table news has these fields: id, title, author, date_created. Then simply use $row->id, $row->title, etc.
To know which table is related with a relevant row you may want to use something like:
SELECT *, 'news' AS source FROM news ....
    UNION
SELECT *, 'events' AS source FROM events ...

and then $row->source will contain your table.

*Please note that when you use UNION statement all fields in every SELECT must have the same number of columns! Read more.


text:
Q: OOP: Object Inheritance and Composition Relationships in Simple Game Design I'm currently learning Java for several reasons, but one of the main ones being that it's a very OOP orientated language, and writing code in Java is really helping me understand the core concepts behind OOP programming.
I am, however, having difficulty in defining the relationships between my classes. I understand the difference between inheritance and composition, but I'm having some difficulty seeing the whole picture, and how all of my classes should work together as a whole.
An example of how I would write a simple game of Tic-Tac Toe using OOP;

*

*Create a Game class - creates an instance of the gameBoard class,
decides who starts first, keeps track of games won and lost, starts
and ends the game.

*Create a gameBoard class - updates the tic-tac-toe board,
determines the next player's turn, if a move is legal, and
determines when there is a winner

*Create an abstract Player class - holds the player's tile (X or O), and
contains a method that takes a gameBoard instance as an argument and
passes the move made by the player to the instance reference

*Create a Human class that extends the Player class. Contains
methods dealing with player input from the keyboard

*Create a Computer class that extends the Player class. Has a
method that takes a gameBoard instance as an argument and analyses
the gameboard for a winning move, a blocking move, or any other
move, then makes a move
This is the approach I would take. However, I'm having a little trouble relating all of the classes together. The line seems a little blurred in some cases as to where some methods and fields should belong.
Edit: Revised question:
What would be a good methodology in determining clear, defined roles for my classes, without getting too caught up in trying to define and ecapsulate every aspect of my program? A lot of my objects could be called from other classes to perform the specific functions that each class has, i.e Player updates gameBoard, gameBoard updates Game, but I do not know if this is good practice, or will make for rigid and hard to maintain code by passing around too many object references.

A: Martyn, try to classify every relationship in your problem as either "is-a" or "has-a". This will make it easier to work out the class relationships.
For example,
Game has-a Gameboard
Human is-a Player
Computer is-a Player

and then
Game has-a Player1
Game has-a Player2

etc.
See how you go with that, you'll answer many of your own questions. Good luck!
edit: you wrote: Player updates gameBoard, gameBoard updates Game
Could you do it like this, making 'Game' more central to the control of the game?
Game asks player to select next move from GameBoard
Player looks on Gameboard to see possible legal moves
Player selects a legal move and returns it to Game
Game plays the move on the GameBoard
Game checks the Gameboard to see if any player has won
if not, Game ends the turn and goes to the next player
...

A: A Game has two Players and a Board. Until the board says the game is up, it should interrogate each player in turn to discover what their desired move is. It should then pass that move to the board. If the board accepts it, because it's valid, then it is the next players turn. If the board rejects the move, because it is invalid, then it asks the same player to make a move again.
This in mind, some pseudo code might take the form of;
class Game {
    Player p1, p2, current;
    Board board;

    public Game() {
        Board = new TicTacToeBoard();
        p1 = new Human('X');
        p2 = new Compooterwooter('O');

        current = p1;
    }
}

abstract class Player {
   char label;
   Move getMove(Board);
}

abstract class Board {
   boolean makeMove(Move);
   Position getPosition();
   boolean gameIsUp(); /* has the game finished? */
}

class Move {
   int x, y;
}

class Position {
    boolean isVacant(int x, int y);
    char whoHasPlayed(int x, int y);
}

class Human extends Player {
    Move getMove(Board b) { /* ask user for move */ }
}

class Compooterwooter extends Player {
    Move getMove(Board b) { /* compute move */
}

class TicTacToeBoard extends Board {
   boolean makeMove(int x, int y) { /* check valid move */
}

It's not the most useful answer, but I'm just speculating, and it seemed at least a slightly speculative question. Hopefully it will help get your mind going in the right direction.

A: start with something like the code below.
then make it work so you can play both sides manually from the command line.
then refactor your code into some player classes and whatever else is needed.
enum State {
    x('x'),o('o'),vacant(' ');
    State(char c) {
        this.c=c;
    }
    char c;
}
class Game {
    Game() {
        for(int i=0;i<3;i++)
            for(int j=0;j<3;j++)
                board[i][j]=State.vacant;
    }
    void makeMove(int i,int j,State state) {
        if(board[i][j]!=State.vacant)
            throw new RuntimeException("bad move!");
        board[i][j]=state;
    }
    boolean isGameOver() {
        // ...
        return false;
    }
    public String toString() {
        String s="";
        for(int i=0;i<3;i++) {
            s+='|';
            for(int j=0;j<3;j++)
                s+=""+board[i][j].c+'|';
            s+='\n';
        }
        return s;
    }
    final State[][] board=new State[3][3];
}
public class So15013410 {
    public static void main(String[] args) {
        Game game=new Game();
        System.out.println(game);
        game.makeMove(0,0,State.x);
        System.out.println(game);
        game.makeMove(0,1,State.o);
        System.out.println(game);
    }
}


text:
Q: my transaction is not rollback when something goes wrong in C# with mysql? I am connecting mysql 5.1 from C# by using mysql connector6.2.3.0(.net).I want to insert 3 tables at a time.So, i am using transaction for that.Suppose, when some errors encountered while inserting data into my 3rd table, then the transaction is not rollback.The data is inserted into first two tables.
This is my code...
MySqlDataAdapter da = new MySqlDataAdapter();
 DBUtil cUtil = new DBUtil();
 MySqlConnection mysqlCon=null;
 MySqlTransaction txn = null;

try
{
    mysqlCon = cUtil.getDbConnection();
    txn = mysqlCon.BeginTransaction();

    //1
    sql = "insert into test_details()";
    da.InsertCommand = new MySqlCommand(sql, mysqlCon,txn);
    da.InsertCommand.ExecuteNonQuery();

    //2
    sql = "insert into task_details()";
    da.InsertCommand = new MySqlCommand(sql, mysqlCon,txn);
    da.InsertCommand.ExecuteNonQuery();

    sql = "select task_id from task_details where test_id='" + testId + "'";
    da.SelectCommand = new MySqlCommand(sql, mysqlCon,txn);
    dt1 = new System.Data.DataTable();
    da.Fill(dt1);
    string task_id = dt1.Rows[0]["task_id"].ToString();

    //3
    sql = "insert into test_evaluators()";
    da.InsertCommand = new MySqlCommand(sql, mysqlCon,txn);
    da.InsertCommand.ExecuteNonQuery();

    txn.Commit();
    mysqlCon.Close();
    da.Dispose();
}
catch (Exception e)
{
    txn.Rollback();
    mysqlCon.Close();
}

i think, initially, i want to disable autocommit... but i dont know where i have to set this...
please suggest me what's going wrong with this...

A: As we found out that it is DB engine problem, you can use
ALTER TABLE tablename ENGINE = innodb

refer Documentation


text:
Q: strchrnul on visual studio c++? I recently received an old source code from a port scanner program that worked in the old Visual Studio, but this source does not work in Visual Studio 2019.
p = strchrnul(h, ',');

The strchrnul function is not inside the string.h header file.
Can any of you help replace this function ? I have no knowledge of text in cpp

A: You can write your own strchnul() implementation easily enough:
char * strchnul(const char * s, int c)
{
   while(*s)
   {
      if (c == *s) break;
      s++;
   }
   return const_cast<char *>(s);
}


text:
Q: How can I do automatic memory management in C? In C memory allocation/deallocation done by malloc and free.
In C++ memory allocation/deallocation done by new and delete.
There are some solutions in C++ for automatic memory management like:

*

*Smart Pointers.

*RAII (Resource Acquisition Is Initialization)

*Reference counting and cyclic references

*...

But how can I do automatic memory management in C?
Is there any solutions for AUTOMATIC memory management in C?
Is there any guidelines or something like that for C?
I want when I foget free a block of memory:

*

*My code doesn't compile

-- or --

*

*Memory automatically deallocated

And then I say: Oh, C is better than C++, Java and C#. :-)

A: As answered by Juraj Blaho, you can use a garbage collection library, such as the Boehm conservative garbage collector, but there are other ones : Ravenbrook's memory pool system, my (unmaintained) Qish GC, Matthew Plant's GC, etc...
And often, you can write your own garbage collector specialized for your use case. You could use in C the techniques mentioned in your question (smart pointers, reference counting), but you can also implement a mark & sweep GC, or a copying GC.
An important issue when coding your GC is to keep track of local pointer variables (to garbage collected data). You could keep them in local struct and chain them together.
I strongly suggest to read more about GC, e.g. the GC handbook. The algorithms there are useful in many situations.
You could even customize your GCC compiler (e.g. using MELT) to add checks or to generate code (e.g. code to scan local variables) for your particular GC implementation. Or you could use some pre-processor (e.g. GPP) for that
In practice, Boehm's GC is often good enough.
Notice that liveness of some data is a whole-program property. So it better to think about GC very early in the design phase of your software development.
Notice also that detecting reliably memory leaks by static source code analysis is in general impossible (undecidable), since it can be proven equivalent to the halting problem.

A: You may use a Boehm garbage collector library.

A: For linux, I use valgrind. Sure, the original reason for why valgrind was build was to debug your code, but it does a lot more.  It will even tell you where potentially erroneous code could be in a non-invasive way. My own command line of choice is as follows.
# Install valgrind. Remove this line of code if you already have it installed
apt install valgrind
# Now, compile and valgrind the C
gcc main.c -Werror -fshort-enums -std=gnu11 -Og -g3 -dg -gdwarf-2 -rdynamic -o main
valgrind --quiet --leak-check=yes --tool=memcheck -Wall  ./main

Hope this helps. ~ Happy Coding!


text:
Q: eclipse(oxygen-latest) brings error after connecting ADT After Connecting ADT eclipse brings window like thisFirst Window
After clicking Open SDK Manager
It is starting to load SDK
But nothing happpen
And eclipse brings errorError
Please help me I have probles with eclipse approximatley 4 mounth


text:
Q: wix installer / Create web-site and assign the new or exisiting web app pool i try create a new web-site using wix installation. it's ok there is no problem but i cannot assign a new or existing web app pool to new web-site. iis:website tag does not contains WebAppPool attribute. How can i assign web app pool to web-site. You can see my code bellow.
thanks for helping.
        <Component Id="WEB_SITE_CONFIGURE_COMPONENT" Guid="{35087032-D049-48C8-BCAD-1FEFD0C06A25}" NeverOverwrite="yes" Shared="yes" Permanent="yes" Transitive="yes">
          <Condition><![CDATA[WEBSITE_INSTALLTYPE<>2]]></Condition>
          <CreateFolder Directory="WEBSITE_FOLDER"/>
          <iis:WebSite Id="WEB_SITE" Description="[WEBSITE_NAME]" SiteId="*" Directory="WEBSITE_FOLDER" ConfigureIfExists="yes" AutoStart="yes" StartOnInstall="yes">
            <iis:WebAddress Id="AllUnassigned" Port="[WEBSITE_PORT]" />
          </iis:WebSite>
          <RegistryValue Root="HKLM" Key="$(var.DefaultRegistryKey)" Name="ConfigSite" Value="1" Type="string"></RegistryValue>
        </Component>

        <Component Id="WEBAPP_POOL_CONFIGURE_COMPONENT" Guid="{316738A6-26A2-4C14-9AB9-B2066E3FA288}" KeyPath="yes" Permanent="yes" Transitive="yes">
          <Condition><![CDATA[(WEBSITE_INSTALLTYPE=0) OR (USE_CUSTOM_WEBSITE_FOLDER=1)]]></Condition>
          <iis:WebAppPool Id="APP_POOL" Name="[WEBAPP_POOL_NAME]" ManagedPipelineMode="Classic" ManagedRuntimeVersion="v4.0"/>
          <RegistryValue Root="HKLM" Key="$(var.DefaultRegistryKey)" Name="ConfigPool" Value="1" Type="string"></RegistryValue>
        </Component>

        <Component Id="WEPAPP_CONFIGURE_COMPONENT" Guid="{F95B024E-B6B6-4E6C-AC35-9B1086FC3521}" Transitive="yes">
          <Condition><![CDATA[(WEBSITE_INSTALLTYPE<>2) AND ((WEBSITE_INSTALLTYPE=0) OR (USE_CUSTOM_WEBSITE_FOLDER=1))]]></Condition>
          <iis:WebVirtualDir Id="VIRTUAL_DIR" Alias="[WEB_APP_NAME]" Directory="WWW_FOLDER" WebSite="WEB_SITE">
            <iis:WebApplication Id="WEB_APP" Name="[WEB_APP_NAME]" WebAppPool="APP_POOL"/>
          </iis:WebVirtualDir>
          <RegistryValue Root="HKLM" Key="$(var.DefaultRegistryKey)" Name="ConfigVirtualDir" Value="1" Type="string"></RegistryValue>
        </Component>

A: With the help of the following articles I have come up with a working installer in which a new AppPool can be created or an existing AppPool can be selected.

*

*Creating a Web Application Installer with WIX 3.5 and Visual Studio 2010–Part 1

*Web Application Installer in WiX

*WiX and DTF: Using a Custom Action to list available web sites on IIS

*Installing a Web Application to an Existing IIS Website using Wix3
In short:
Create a Website element in your Product element:
<Product>
    <iis:WebSite Id="SelectedWebSite" Description="[WEBSITE_DESCRIPTION]" Directory="INSTALLFOLDER" SiteId="[WEBSITE_ID]">
      <iis:WebAddress Id="AllUnassigned" Port="80" />
    </iis:WebSite>
</Product>

Create an Include WebSites.wxi with the following content:
<?xml version="1.0" encoding="utf-8"?>
<Include>
  <Property Id="WEBSITE_DESCRIPTION">
    <RegistrySearch Id="WebSiteDescription" Name="WebSiteDescription" Root="HKLM" Key="SOFTWARE\!(loc.CompanyName)\[ProductName]\Install" Type="raw" />
  </Property>
  <Property Id="WEBSITE_ID">
    <RegistrySearch Id="WebSiteID" Name="WebSiteID" Root="HKLM" Key="SOFTWARE\!(loc.CompanyName)\[ProductName]\Install" Type="raw" />
  </Property>
  <Property Id="WEBSITE_PATH">
    <RegistrySearch Id="WebSitePath" Name="WebSitePath" Root="HKLM" Key="SOFTWARE\!(loc.CompanyName)\[ProductName]\Install" Type="raw" />
  </Property>
  <Property Id="WEBSITE_VD">
    <RegistrySearch Id="WebSiteVD" Name="WebSiteVD" Root="HKLM" Key="SOFTWARE\!(loc.CompanyName)\[ProductName]\Install" Type="raw" />
  </Property>
  <CustomTable Id="AvailableWebSites">
    <Column Id="WebSiteID" Category="Identifier" PrimaryKey="yes" Type="int" Width="4"/>
    <Column Id="WebSiteDescription" Category="Text" Type="string" PrimaryKey="no"/>
    <Column Id="WebSitePath" Category="Text" Type="string" PrimaryKey="no" Nullable="yes"/>
    <Row>
      <Data Column="WebSiteID">0</Data>
      <Data Column="WebSiteDescription">Dummy</Data>
      <Data Column="WebSitePath"></Data>
    </Row>
  </CustomTable>
</Include>

Create the CustomAction described here.
Create a wxs file with your AppPool:
<?xml version="1.0" encoding="UTF-8"?>
<Wix
  xmlns="http://schemas.microsoft.com/wix/2006/wi"
  xmlns:util="http://schemas.microsoft.com/wix/UtilExtension"
  xmlns:iis="http://schemas.microsoft.com/wix/IIsExtension">
    <Fragment>
    <Component Id="WebVirtualDirComponent" Guid="PUT-GUID-HERE" Directory="INSTALLFOLDER" KeyPath="yes">
      <iis:WebAppPool
        Id="YourAppPoolName"
        Name="[VD][WEBSITE_ID]"
        ManagedRuntimeVersion="v4.0"
        IdleTimeout="0"
        RecycleMinutes="0"
        ManagedPipelineMode="integrated"/>
      <iis:WebVirtualDir Id="VDir" Alias="[VD]" Directory="INSTALLFOLDER" WebSite="SelectedWebSite">
        <iis:WebApplication Id="NotizBrowserWebApp" WebAppPool="YourAppPoolName" Name="[VD][WEBSITE_ID]" />
        <iis:WebDirProperties Id="NotizBrowserProps" AnonymousAccess="no" WindowsAuthentication="yes" DefaultDocuments="-" Execute="yes" Script="yes" Read="yes"/>
      </iis:WebVirtualDir>
    </Component>
    </Fragment>
</Wix>

A: Late answer, but hopefully someone will be benefited with this.
You don't need a CustomAction to make this work.
It is simple like this:
<Component Id="WebSite" Guid="PUT-YOUR-GUID-HERE">
    <CreateFolder/>
    <iis:WebSite Id="WebSite" Directory="WebSiteRoot" Description="[WEBSITEDESCRIPTION]" >
        <iis:WebApplication Id="WebSiteApplication" Name="[WEBSITEDESCRIPTION]" WebAppPool="MyAppPool" />
    </iis:WebSite>
    <iis:WebAppPool Id="MyAppPool" Name="[APPPOOLNAME]" ManagedRuntimeVersion="v4.0"/>
</Component>

You need to update the "Internal" WebApplication of the WebSite.
You don't need to have the "WebSite Description" and "WebApplication Name" equal, but that will help you to understand what is going on.


text:
Q: Remap "Get Help" fn (F1 key) to open specific app The fn "?" (icon on the F1 key) on my laptop is useless to me, and I keep accidentally pressing it. So I want to remap it, not just disable it like here: https://www.winhelponline.com/blog/disable-f1-key-help-windows-10/
How can I remap it to open an app, using Registry (Sharpkey affects my Start key)? Or at least remap it to other key (Caps lock, Shift, Sleep fn will be awesome...)
My Laptop: HP Envy 13
https://images.app.goo.gl/BcGMs8egzdDQD9X99

A: The "Function" key can be turned off with a few simple steps.

*Steps for Turning off the Function Key

*Step 1
Look on your keyboard for the "Fn" key and hold it down. This is usually located on the bottom left corner of your
keyboard, next to the "Alt" key, depending on which model of computer you are using.

*Step 2
Locate the "Num Lock" or "Num Lk" key, whichever way it may appear on your keyboard.
Press the "Num Lock" key at the same time as you are pressing the "Fn" key.
This should turn off the "Function" key.

*Step 3
Hold down and press the "Fn" + "Shift" + "Num Lk" keys all at the same time to turn off the "Function" key, if the
above step didn't work. You may need to use the "Shift" key based on which model of computer you have.

https://www.techwalla.com/articles/how-can-i-turn-off-the-function-key


text:
Q: Mac OS - swift - CABasicAnimation current value I have a CABasicAnimation moving a NSHostingView (it's a scrolling marquee text). When the user get his mouse cursor over the view, the animation must stops and it can interact with the view.
I tried the following approaches:
Method 1:
As recommended by Apple documentation (https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CoreAnimation_guide/AdvancedAnimationTricks/AdvancedAnimationTricks.html#//apple_ref/doc/uid/TP40004514-CH8-SW14), I tried to implement the pause/resume method using the convertTime / speed = 0.
It works, the animation is paused and resumed, but while the animation is paused, the coordinates of the user clic inside the view are the one of the model layer and not the one of the presentation layer. So the click respond to where the user would have click if their was no animation.
Method 2:
I tried the various animation flags on my CABasicAnimation as follow :
let animation = CABasicAnimation(keyPath: "position");
animation.duration = 10
animation.fromValue = [0, self.frame.origin.y]
animation.toValue = [-500, self.frame.origin.y]
animation.isCumulative = true
animation.isRemovedOnCompletion = false
animation.fillMode = .forwards

Not matter what I use, when the animation is removed, the view get back to it's original position (it jumps back to it's original position).
Method 3:
I tried to save the current animation value before removing by reading the presentation layer position as follow:
print("before")
let currentPosition = layer.presentation()?.position
print("after")

But this method never returns! (ie. "after" is never printed). Could it be a bug or something?
I'm out of idea now. If anyone has a suggestion, it would help a lot. Thanks!

A: Accessing layer?.presentation()?.position doesn't work because animation.fromValue and animation.toValue should be CGPoint values:
animation.fromValue = CGPoint(x: 0, y: self.frame.origin.y)
animation.toValue = CGPoint(x: -500, y: self.frame.origin.y)

Then Method 3 works just fine.


text:
Q: Redirect 12,000 pages from SPIP to Wordpress I'd like to switch from SPIP to Wordpress and redirect all SPIP's URLs to Wordpress ones.
The format for an SPIP URL is: example.com/spip.php?article{ID}, for example: example.com/spip.php?article123
The format for a Wordpress URL is: example.com/?p={ID}, for example: example.com/?p=123
If I transfer all data to Wordpress under the same IDs it would mean example.com/spip.php?article123 is exactly example.com/?p=123
My question is: how so I actually do this? I've searched many forums and how just found ways to transfer a page with specific pattern (without question mark) to a new pattern, with question mark.

A: You have not specified the web server - which is important.  I am assuming you are using Apache as it is probably the most common server for this kind of hosting.
To do this you need to add a rewriteRule in your apache config (in a Directory container) or .htaccess file.  Something like:
RewriteEngine On
RewriteCond %{QUERY_STRING} ^article(.*)$
RewriteRule ^spip.php?$ /index.php?p=%1 [R=301,L]

A: To switch from SPIP to WordPress and redirect automatically the URLs, you can use the plugin FG SPIP to WordPress.


text:
Q: Java: Find .txt files in specified folder Is there a built in Java code that will parse a given folder and search it for .txt files?

A: It's really useful, I used it with a slight change:
filename=directory.list(new FilenameFilter() {
    public boolean accept(File dir, String filename) {
        return filename.startsWith(ipro);
    }
});

A: I made my solution based on the posts I found here with Google. And I thought there is no harm to post mine as well even if it is an old thread.
The only plus this code gives is that it can iterate through sub-directories as well.
import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.WildcardFileFilter;

Method is as follows:
List <File> exploreThis(String dirPath){

    File topDir = new File(dirPath);

    List<File> directories = new ArrayList<>();
    directories.add(topDir);

    List<File> textFiles = new ArrayList<>();

    List<String> filterWildcards = new ArrayList<>();
    filterWildcards.add("*.txt");
    filterWildcards.add("*.doc");

    FileFilter typeFilter = new WildcardFileFilter(filterWildcards);

    while (directories.isEmpty() == false)
    {
        List<File> subDirectories = new ArrayList();

        for(File f : directories)
        {
            subDirectories.addAll(Arrays.asList(f.listFiles((FileFilter)DirectoryFileFilter.INSTANCE)));
            textFiles.addAll(Arrays.asList(f.listFiles(typeFilter)));
        }

        directories.clear();
        directories.addAll(subDirectories);
    }

    return textFiles;
}

A: Try:
List<String> textFiles(String directory) {
  List<String> textFiles = new ArrayList<String>();
  File dir = new File(directory);
  for (File file : dir.listFiles()) {
    if (file.getName().endsWith((".txt"))) {
      textFiles.add(file.getName());
    }
  }
  return textFiles;
}

You want to do a case insensitive search in which case:
    if (file.getName().toLowerCase().endsWith((".txt"))) {

If you want to recursively search for through a directory tree for text files, you should be able to adapt the above as either a recursive function or an iterative function using a stack.

A: import org.apache.commons.io.filefilter.WildcardFileFilter;

.........
.........

File dir = new File(fileDir);
FileFilter fileFilter = new WildcardFileFilter("*.txt");
File[] files = dir.listFiles(fileFilter);

The code above works great for me

A: import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;

public class FileFinder extends SimpleFileVisitor<Path> {
    private PathMatcher matcher;
    public ArrayList<Path> foundPaths = new ArrayList<>();

    public FileFinder(String pattern) {
        matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);
    }

    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
        Path name = file.getFileName();

        if (matcher.matches(name)) {
            foundPaths.add(file);
        }

        return FileVisitResult.CONTINUE;
    }
}

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) throws IOException {
        Path fileDir = Paths.get("files");
        FileFinder finder = new FileFinder("*.txt");
        Files.walkFileTree(fileDir, finder);

        ArrayList<Path> foundFiles = finder.foundPaths;

        if (foundFiles.size() > 0) {
            for (Path path : foundFiles) {
                System.out.println(path.toRealPath(LinkOption.NOFOLLOW_LINKS));
            }
        } else {
            System.out.println("No files were founds!");
        }
    }
}

A: You can use the listFiles() method provided by the java.io.File class.
import java.io.File;
import java.io.FilenameFilter;

public class Filter {

    public File[] finder( String dirName){
        File dir = new File(dirName);

        return dir.listFiles(new FilenameFilter() {
                 public boolean accept(File dir, String filename)
                      { return filename.endsWith(".txt"); }
        } );

    }

}

A: import org.apache.commons.io.FileUtils;

List<File> htmFileList = new ArrayList<File>();

for (File file : (List<File>) FileUtils.listFiles(new File(srcDir), new String[]{"txt", "TXT"}, true)) {
    htmFileList.add(file);
}

This is my latest code to add all text files from a directory

A: Here is my platform specific code(unix)
public static List<File> findFiles(String dir, String... names)
    {
        LinkedList<String> command = new LinkedList<String>();
        command.add("/usr/bin/find");
        command.add(dir);
        List<File> result = new LinkedList<File>();
        if (names.length > 1)
            {
                List<String> newNames = new LinkedList<String>(Arrays.asList(names));
                String first = newNames.remove(0);
                command.add("-name");
                command.add(first);
                for (String newName : newNames)
                    {
                        command.add("-or");
                        command.add("-name");
                        command.add(newName);
                    }
            }
        else if (names.length > 0)
            {
                command.add("-name");
                command.add(names[0]);
            }
        try
            {
                ProcessBuilder pb = new ProcessBuilder(command);
                Process p = pb.start();
                p.waitFor();
                InputStream is = p.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String line;
                while ((line = br.readLine()) != null)
                    {
                        // System.err.println(line);
                        result.add(new File(line));
                    }
                p.destroy();
            }
        catch (Exception e)
            {
                e.printStackTrace();
            }
        return result;
    }


text:
Q: F# Charting on Mac OSX issues When trying to load the fsx "Fsharp.Charing.Gtk.fsx" I get the error "The assembly reference FSharp.Compiler.Interactive.Settings.dll was not found or is invalid". When I #r the dll the error goes away but when I try to use Chart.Line I'm given the error, "The type referenced through 'OxyPlot.OxyColor' is defined in an assembly that is not referenced. You must add a reference to assembly 'OxyPlot'" So then I referenced the OxyPlot dll as well, trying with Oxyplot.Core and OxyPlot.GtkSharp. With both the same error remains.
edit: I'm using mac osx, which is why I'm using the Gtk.

A: Are you able to to run .fs files? It sounds like you might not have F# installed on your machine, also there is a typo in your first reference
Fsharp.Charing.Gtk.fsx"

Ought to be
Fsharp.Charting.Gtk.fsx"

And unless that fsx is in the same directory as your fsharp file, you will need to specify the path as well.


text:
Q: Trying to use variable into command prompt using python and adb import os
import random
xpixel = random.randint(359,402)
ypixel = random.randint(256,368)
trest = random.randint(10,16)
print(trest)
time.sleep(trest)
print(xpixel)
print(ypixel)
os.system('cmd /k adb.exe shell input tap xpixel ypixel') <----I know this part is absolutly wrong but the concept is to be able to input those two numbers into command prompt some how.

I'm trying to click on a point in a screen using python/ adb.
I know how to generate the random number, and also the adb command. I just don't know how to transfer those variables and make them useful in command prompt.

A: While you can include variable values using f-strings
f'cmd /k adb.exe shell input tap {xpixel} {ypixel}'

it might be better if instead of using adb and input you use a more specific library like AndroidViewClient/culebra or any other, to be able to do something. like this
#! /usr/bin/env python3

import time
import random

from com.dtmilano.android.viewclient import ViewClient

device, serialno = ViewClient.connectToDeviceOrExit()
xpixel = random.randint(359,402)
ypixel = random.randint(256,368)
trest = random.randint(10,16)
print(trest)
time.sleep(trest)
print(xpixel)
print(ypixel)
device.touch(xpixel, ypixel)


text:
Q: animation for video slider works once, then fails I have a video slider, and the videos are supposed to fade in when you click on the corresponding thumbnail. It works when I preview it in chrome, but when I try it on an iPad (iOS5) it stops working after one time. If I remove the fade(it's actually an animation), it works, and when it's in use, the video still plays, but the div which has it it black. The function is

$(window).load(function(){
$('li', '.thumbs').on('click', function() {
    var numb = $(this).index(),
        videos = ['images/intro01.m4v', 'images/clip2.m4v', 'images/intro01.m4v', 'images/clip2.m4v', 'images/intro01.m4v', 'images/clip2.m4v'],
        myVideo = document.getElementById('myVid');
        myVideo.src = videos[numb];
        $('#myVid').hide();

    $(myVideo).animate({
        'opacity': '0'
        }, 000, function() {

        myVideo.load();
        $('#myVid').show();
        myVideo.play();

        $(myVideo).animate({
            'opacity': '1'
        }, 1000);

    });
  });
});

Do I need to reset it or something? If you can help at all, that would be greatly appreciated as I'm on a deadline and this is the final part.Basically, instead of fading in it fades to black.


text:
Q: (#803) Some of the aliases you requested do not exist: {education-experience-id} Android I am trying to get education detail and work description of user from facebook. I login successfully and get Access token. But I am unable to get details I want
Code I am using for it :-
    public void getUserExpandEducation() {

    new GraphRequest(
            AccessToken.getCurrentAccessToken(),
        "/{education-experience-id}",  //"/{user_education_history}",//
            null,
            HttpMethod.GET,
            new GraphRequest.Callback() {
                public void onCompleted(GraphResponse response) {
                    Log.d("fb response",response.toString());
                }
            }
    ).executeAsync();
}

can anyone please reply

I am getting error (#803) Some of the aliases you requested do not exist: {education-experience-id}

A: Finally I got full work and education detail by this code:
GraphRequest request = GraphRequest.newMeRequest(
            accessToken,
            new GraphRequest.GraphJSONObjectCallback() {
                @Override
                public void onCompleted(
                        JSONObject object,
                        GraphResponse response) {

                    FirstNameSocial = object.optString("first_name");
                    LastNameSocial = object.optString("last_name");
                    GenderSocial = object.optString("gender");
                    EmailSocial = object.optString("email", "");
                    id = object.optString("id");

                    if (!EmailSocial.equals("")) {
                        login_type = Config.Login_Type_facebook;
                        callAPI(EmailSocial, id, "");

                    } else {
                        Toast.makeText(getApplicationContext(), "Permision Denied", Toast.LENGTH_LONG)
                                .show();
                    }

                }
            });

    Bundle parameters = new Bundle();
    parameters.putString("fields", "id,name,email,birthday,gender,first_name,last_name,picture,education,work");
    request.setParameters(parameters);
    request.executeAsync();

Might help someone !
Happy coding :)

A: Make sure you authorized with that permission: user_education_history
API call to get a list of education IDs: https://developers.facebook.com/tools/explorer/?method=GET&path=me%3Ffields%3Deducation
In your code, you need to replace the following string with one of the resulting education IDs: {education-experience-id}
For example:
new GraphRequest(
    AccessToken.getCurrentAccessToken(),
    "/12345",
        null,
        HttpMethod.GET,
        new GraphRequest.Callback() {
            public void onCompleted(GraphResponse response) {
                Log.d("fb response",response.toString());
            }
        }
).executeAsync();


text:
Q: Internationalised labels in JSF/Facelets Does Facelets have any features for neater or more readable internationalised user interface text labels that what you can otherwise do using JSF?
For example, with plain JSF, using h:outputFormat is a very verbose way to interpolate variables in messages.
Clarification: I know that I can add a message file entry that looks like:
label.widget.count = You have a total of {0} widgets.

and display this (if I'm using Seam) with:
<h:outputFormat value="#{messages['label.widget.count']}">
   <f:param value="#{widgetCount}"/>
</h:outputFormat>

but that's a lot of clutter to output one sentence - just the sort of thing that gives JSF a bad name.

A: Since you're using Seam, you can use EL in the messages file.
Property:
label.widget.count = You have a total of #{widgetCount} widgets.

XHTML:
<h:outputFormat value="#{messages['label.widget.count']}" />

This still uses outputFormat, but is less verbose.

A: I've never come across another way of doing it other than outputFormat. It is unfortunately quite verbose.
The only other thing I can suggest is creating the message in a backing bean and then outputting that rather than messageFormat.
In my case I have Spring's MessageSource integrated with JSF (using MessageSourcePropertyResolver). Then, it's fairly easy in your backing beans to get parameterised messages - you just need to know which Locale your user is in (again, I've got the Locale bound to a backing bean property so it's accessible via JSF or Java).
I think parameters - particular in messages - are one thing JSF could really do better!

A: I have been thinking about this more, and it occurs to me that I could probably write my own JSTL function that takes a message key and a variable number of parameters:
<h:outputText value="#{my:message('label.widget.count', widgetCount)}"/>

and if my message function HTML-encodes the result before output, I wouldn't even need to use the h:outputText
#{my:message('label.widget.count', widgetCount)}

A: You could create your own faces tag library to make it less verbose, something like:
<ph:i18n key="label.widget.count" p0="#{widgetCount}"/>

Then create the taglib in your view dir: /components/ph.taglib.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE facelet-taglib PUBLIC "-//Sun Microsystems, Inc.//DTD Facelet Taglib 1.0//EN" "https://facelets.dev.java.net/source/browse/*checkout*/facelets/src/etc/facelet-taglib_1_0.dtd">

<facelet-taglib xmlns="http://java.sun.com/JSF/Facelet">
    <namespace>http://peterhilton.com/core</namespace>

    <tag>
        <tag-name>i18n</tag-name>
        <source>i18n.xhtml</source>
    </tag>

</facelet-taglib>

create /components/i18n.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets"
        xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core">

    <h:outputFormat value="#{messages[key]}">
            <!-- crude but it works -->
        <f:param value="#{p0}" />
        <f:param value="#{p1}" />
        <f:param value="#{p2}" />
        <f:param value="#{p3}" />
    </h:outputFormat>

</ui:composition>

You can probably find an elegant way of passing the arguments with a little research.
Now register your new taglib in web.xml
<context-param>
<param-name>facelets.LIBRARIES</param-name>
<param-value>
        /components/ph.taglib.xml
    </param-value>
</context-param>

Just add xmlns:ph="http://peterhilton.com/core" to your views and you're all set!

A: You can use the Seam Interpolator:
<h:outputText value="#{interpolator.interpolate(messages['label.widget.count'], widgetCount)}"/>

It has @BypassInterceptors on it so the performance should be ok.

A: You can use the Bean directly if you interpolate the messages.
label.widget.count = You have a total of #{widgetCount} widgets.
label.welcome.message = Welcome to #{request.contextPath}!
label.welcome.url = Your path is ${pageContext.servletContext}.

${messages['label.widget.count']} is enougth.
This one works great using Spring:
package foo;

import javax.el.ELContext;
import javax.el.ELException;
import javax.el.ExpressionFactory;
import javax.el.ResourceBundleELResolver;
import javax.faces.context.FacesContext;

import org.springframework.web.jsf.el.SpringBeanFacesELResolver;

public class ELResolver extends SpringBeanFacesELResolver {
    private static final ExpressionFactory FACTORY = FacesContext
            .getCurrentInstance().getApplication().getExpressionFactory();
    private static final ResourceBundleELResolver RESOLVER = new ResourceBundleELResolver();

    @Override
    public Object getValue(ELContext elContext, Object base, Object property)
            throws ELException {
        Object result = super.getValue(elContext, base, property);
        if (result == null) {
            result = RESOLVER.getValue(elContext, base, property);
            if (result instanceof String) {
                String el = (String) result;
                if (el.contains("${") | el.contains("#{")) {
                    result = FACTORY.createValueExpression(elContext, el,
                            String.class).getValue(elContext);
                }
            }
        }
        return result;
    }
}

And...
You need to change the EL-Resolver in faces-config.xml from org.springframework.web.jsf.el.SpringBeanFacesELResolver to
Regards
<el-resolver>foo.ELResolver</el-resolver>

A: Use ResourceBundle and property files.


text:
Q: WPF - Set propeties of child controls of custom style I have a custom style for a SearchTextBox. I have multiple Bindings in this control.
<Style TargetType="{x:Type controls:SearchTextBox}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type controls:SearchTextBox}">
                <Grid>
                    <TextBox Text="{Binding SearchText, UpdateSourceTrigger=PropertyChanged}">
                        <TextBox.InputBindings>
                            <KeyBinding Command="{Binding Path=SearchCommand}" Key="Enter" />
                            <KeyBinding Command="{Binding Path=DeleteSearchCommand}" Key="Esc" />
                        </TextBox.InputBindings>
                    </TextBox>
                    <Button Style="{StaticResource WatermarkButtonCancelStyle}" HorizontalAlignment="Right" Command="{Binding DeleteSearchCommand}" Margin="0,0,22,0"/>
                    <Button Style="{StaticResource WatermarkButtonSearchStyle}" HorizontalAlignment="Right" Command="{Binding SearchCommand}"/>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

I am using the TextBox in my view right here:
<controls:SearchTextBox Width="300" HorizontalAlignment="Left" Margin="0,0,0,6" />

How can I set the bindings in my view, not in the definition of the style. So that I can use the control in multiple Views with different bindings?

A: Style for the custom TextBox:
        <Style TargetType="{x:Type local:SearchTextBox}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:SearchTextBox}">
                    <DockPanel DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:SearchTextBox}}}">
                        <Button DockPanel.Dock="Right"
                                Style="{StaticResource WatermarkButtonCancelStyle}"
                                Command="{Binding DeleteSearchCommand}"/>
                        <Button DockPanel.Dock="Right"
                                Style="{StaticResource WatermarkButtonSearchStyle}"
                                Command="{Binding SearchCommand}"
                                CommandParameter="{Binding Text}"/>
                        <TextBox x:Name="InnerTextBox"
                                 Text="{Binding Path=Text}">
                            <TextBox.InputBindings>
                                <KeyBinding Command="{Binding SearchCommand}"
                                            CommandParameter="{Binding Text}"
                                            Key="Enter" />
                                <KeyBinding Command="{Binding DeleteSearchCommand}"
                                            Key="Escape" />
                            </TextBox.InputBindings>
                        </TextBox>
                    </DockPanel>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

Code of the SearchTextBox.cs:
public class SearchTextBox : TextBox
{
    public static readonly DependencyProperty SearchCommandProperty = DependencyProperty.Register(
        "SearchCommand", typeof(ICommand), typeof(SearchTextBox), new PropertyMetadata(default(ICommand)));

    public SearchTextBox()
    {
        DeleteSearchCommand = new Command
        {
            ExecuteHandler = o => Clear()
        };
    }

    public ICommand SearchCommand
    {
        get { return (ICommand) GetValue(SearchCommandProperty); }
        set { SetValue(SearchCommandProperty, value); }
    }

    public Command DeleteSearchCommand { get; private set; }
}

Because the Command for clearing the TextBox is always the same, the SearchTextBox contains the Command for clearing it.
Now it is possible to use the SearchTextBox in a View and just set the SearchCommand property.
<local:SearchTextBox Height="30" Width="200" SearchCommand="{Binding DoTheSearch}"/>

As you can see in the style for the SearchTextBox, the Text is set as the parameter for the SearchCommand, so you can use it, where the command is specified.


text:
Q: My string breaks into multiple line in my console.log but does not in my html I have an array, which I have converted into a string. I have added a line break which is picked up by the console, I would like to have this printed into my html using document.getElementByID but the html picks up the literal string rather than the line break. The code:
data = ["name 1: Bob", "name 2: Steve"]
var dataLined = data.toString().replace(',','
')
console.log(dataLined)

document.getElementByID('Content').append("Data\n" + dataLined)

The console returns exactly what I want:
name 1: Steve
name 2: Bob

however, in my html I get
name 1: Steve
name 2: Bob

As it appears to printing the literal string (as I've replace the comma with
).
There may be a better way to print this to multiple lines, but this is what I've seen from similar queries on here. Does anyone know if there is a way I can print to the html without the
 there? Many thanks.

A: I just figured this out by editing the CSS to:
white-space: pre-wrap
this allows \n to be picked up by the html.
So I changed my code to:
data = ["name 1: Bob", "name 2: Steve"]
var dataLined = data.toString().replace(',','\n')
console.log(dataLined)

document.getElementByID('Content').append("Data\n" + dataLined)

Thanks to those that are maybe in progress of helping!

A: It didn't work because you are adding  into string. You need to do something like this:
data = ["name 1: Bob", "name 2: Steve"];
let list = document.querySelector("ul");
data.forEach(item => {
  let parts = item.split(": ");
  let elm = document.createElement("li");
  let text = document.createTextNode(`${parts[0]}: ${parts[1]}`);
  elm.appendChild(text);
  list.appendChild(elm);
})


text:
Q: MySQL FORCE INDEX got unexpected time cost Table:
CREATE TABLE `hosts` (
  `id` int NOT NULL AUTO_INCREMENT,
  `host_name` varchar(255) DEFAULT NULL,
  `ip` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `unq_ip_host` (`ip`,`host_name`),
  KEY `idx_host` (`host_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

MySQL version: mysql:5.7.36.
Here's the situation, in my project, the IP can match several hosts, I wanna get the result that matches (ip_a,host_a),(ip_b,host_b), so I use following sql:
select * from hosts h
     where (h.ip,h.host_name) in (("198.168.214.166","la-worker-01")... ...)

Actually the target set is so large, around 3000 rows, this sql will scan the complete table, and it costs 24s, I tried to use FORCE INDEX (unq_ip_host), but it still cost a lot of time, almost equals scanning the whole table. Explain result:
type: range, key: unq_ip_host, key_len: 768,rows: 8952, filtered: 50.0, extra: Using where
Then I tried to use FORCE INDEX (idx_host), and this is the result of sql explain:
type: ALL, key: null, key_len: null,rows: 284000, filtered: 50.0, extra: Using where
type is ALL which means it won't use the index, this is weird, when I executed the sql, FORCE INDEX (idx_host) costs about 4.1s, but FORCE INDEX (idx_ip_host) costs 24s, this is weird.

select count(distinct(ip)) from hosts; // result: 900000
select count(distinct(host_name)) from hosts; // result: 890000

I can improve the sql but I'm puzzled as to why the two applications of FORCE INDEX provide different results.
Question:

*

*Why doesn't MySQL use the index, when I use FORCE INDEX (idx_host)?

*Why is scanning the entire table(FORCE INDEX (idx_host)) faster than using index(FORCE INDEX (idx_ip_host))?

A: As per MySQL's docs when using FORCE INDEX a table scan is used if there is no way to use one of the named indexes to find rows in the table.
In this case when you use FORCE INDEX (idx_host) it can not find all the required information using this index and defaults to a FULL TABLE SCAN, the table scan query needs 4 seconds in your case.
When you use FORCE INDEX (idx_ip_host) it is able to get all it's required information (indexes have information regarding their PK), however due to the way your data/query is structured, using this index is inefficient hence the 24 seconds execution time.
You already mentioned that you wish to not touch the query, but it will probably be better to make a join/temporary table for this.

A: Do you use id for anything?  Some queries will run faster with PRIMARY KEY(IP, host_name)
One way to get more insight into what is going on is:
FLUSH STATUS;
SELECT ...;
SHOW SESSION STATUS LIKE 'Handler%';

That should show numbers like 3000.  But it sounds like it may be giving numbers like 1M.
Also, please provide EXPLAIN FORMAT=JSON SELECT ...


text:
Q: Many crash reports with android lite sdk from here api last version with the new lite android api library I get the following crash report data from Google Play Console on many customers using my application (last library version 4.1.5) :
java.lang.RuntimeException:
  at android.os.Parcel.readByteArray (Parcel.java:2249)
  at com.here.sdk.mapviewlite.MapViewLite$SavedState.<init> (Unknown Source:10)
  at com.here.sdk.mapviewlite.MapViewLite$SavedState.<init> (Unknown Source)
  at com.here.sdk.mapviewlite.MapViewLite$SavedState$1.createFromParcel (Unknown Source:3)
  at com.here.sdk.mapviewlite.MapViewLite$SavedState$1.createFromParcel (Unknown Source)
  at android.os.Parcel.readParcelable (Parcel.java:2790)
  at android.os.Parcel.readValue (Parcel.java:2684)
  at android.os.Parcel.readSparseArrayInternal (Parcel.java:3134)
  at android.os.Parcel.readSparseArray (Parcel.java:2367)
  at android.os.Parcel.readValue (Parcel.java:2741)
  at android.os.Parcel.readArrayMapInternal (Parcel.java:3053)
  at android.os.BaseBundle.initializeFromParcelLocked (BaseBundle.java:288)
  at android.os.BaseBundle.unparcel (BaseBundle.java:232)
  at android.os.Bundle.getSparseParcelableArray (Bundle.java:1010)
  at com.android.internal.policy.PhoneWindow.restoreHierarchyState (PhoneWindow.java:2182)
  at android.app.Activity.onRestoreInstanceState (Activity.java:1195)
  at android.app.Activity.performRestoreInstanceState (Activity.java:1150)
  at android.app.Instrumentation.callActivityOnRestoreInstanceState (Instrumentation.java:1317)
  at android.app.ActivityThread.handleStartActivity (ActivityThread.java:3153)
  at android.app.servertransaction.TransactionExecutor.performLifecycleSequence (TransactionExecutor.java:180)
  at android.app.servertransaction.TransactionExecutor.cycleToPath (TransactionExecutor.java:165)
  at android.app.servertransaction.TransactionExecutor.executeLifecycleState (TransactionExecutor.java:142)
  at android.app.servertransaction.TransactionExecutor.execute (TransactionExecutor.java:70)
  at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1947)
  at android.os.Handler.dispatchMessage (Handler.java:106)
  at android.os.Looper.loop (Looper.java:214)
  at android.app.ActivityThread.main (ActivityThread.java:7037)
  at java.lang.reflect.Method.invoke (Native Method)
  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:494)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:965)

Also got this report data :
java.lang.NullPointerException:
  at com.here.sdk.mapviewlite.MapViewLite.getMapScene (Unknown Source:2)
  at mediacominteractive.com.jelocaliseviewer.ViewMap.CreateMap (ViewMap.java:982)
  at mediacominteractive.com.jelocaliseviewer.ViewMap.lambda$getDataMap$7$ViewMap (ViewMap.java:661)
  at mediacominteractive.com.jelocaliseviewer.-$$Lambda$ViewMap$v0swVppxULx4N4KfETgPrMrUUd8.run (Unknown Source:2)
  at android.os.Handler.handleCallback (Handler.java:888)
  at android.os.Handler.dispatchMessage (Handler.java:100)
  at android.os.Looper.loop (Looper.java:213)
  at android.app.ActivityThread.main (ActivityThread.java:8147)
  at java.lang.reflect.Method.invoke (Native Method)
  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:513)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1101)


text:
Q: Constructing Distribution By Coin Flipping I am interested in any example of construction distribution by coin flipping.
Actually I want to show the process of construction a random variable $X$ with distribution $(p_1,...,p_n)$ by coin flipping  and to prove expectation of the number of coin flipping is at least entropy $H(X)$.
So far I have no idea where to start from. Will appreciate for examples and hits.

A: I'm not sure exactly what you're trying to ask here.  You'll probably be able to find this answer in a textbook somewhere.  If you were asking something else it would be helpful if you gave a little more detail in your question.
Suppose $p_i< 2^{-k}$.  If I toss a coin $k$ times I have $2^k$ possible events each of probability $2^{-k}$.  So I cannot generate an event of probability $p_i$ with $k$ coin flips.
Therefore if my generator returns $X=i$ it must have flipped the coin at least $-\log_2(p_i)$ times.
So if $K$ is the number of coin flips before my algorithm returns a value we must have
$$\mathbb E(K|X=i) \geq \log_2(p_i).$$
Now we just add these up
$$\begin{array}{rcl}\mathbb E(K) &=& \sum_{i=1}^n \mathbb E(K|X=i)\mathbb P(X = i) \\ &\geq& \sum_{i=1}^n -\log_2(p_i)p_i \\ &=&\mathcal H(X).\end{array}$$
In reality it can take much longer.  If I have a random variable with $p_1 = 0.50001$ $p_2 = 0.49999$ I need a very large number of coin flips to simulate that exactly, even though the entropy is pretty much one.
The easiest way to generate your random number is to think of an infinite string of coin flips as a random number.
If you replace every Head with a $1$ and every Tail with a $0$, Then a sequence of coinflips
$THTHHT\dots$ would represent a binary number $0.010110\dots\equiv 0.17187$.
Let's make this rigorous.
Set $$\begin{array}{rcl}
d_k &=& \left\{\begin{array}{rl} 2^{-k} &\text{if the $k$th toss is a head} \\0 &\text{if the $k$th toss is a tail}\end{array}\right. \\
X_i &=& \sum_{k=1}^i d_i \\
X &=& \sum_{k=1}^\infty d_i \\
q_i&=& \sum_{k=1}^i p_i \\
&=& \mathbb P(M\leq i).
\end{array}$$
Now we want to set $m=i$ whenever $p_{i-1} < X < p_{i}$
So if we toss the coin $k$ times we know that $X_k < X < X_k + 2^{-k}$ so we stop tossing the coin the first time $k$ such that $p_{i-1} <X_k <  X_k + 2^{-k} < p_{i}$ for some $i$.


text:
Q: Restrict attribute on update, but not creation, but fail when update can't update I read this post on
In Rails, how do I limit which attributes can be updated, without preventing them from being created?
They problem is that the u.save returns true, so it give the impression that all the values got updated. When they did not.
Is there a way to use attr-readonly, but on save return false if an attribute is read only?
class User < ActiveRecord::Base
  attr_accessible :name
  attr_readonly :name
end

> User.create(name: "lorem")
> u = User.first
=> #<User id: 1, name: "lorem">
> u.name = "ipsum"
=> "ipsum"
> u.save
=> true
> User.first.name
=> "lorem

A: You can use a validator method to write an error on changes detected to your read only field
Class User
  validate :name_not_changed

  private

  def name_not_changed
    return unless name_changed?

    errors.add(:name, 'Cannot change name of User')
  end
end

Is this really necessary though? If you're making your attribute read-only, why are you still leaving the possibility for it to be changed and additionally need validation errors for that operation? Ideally, you shouldn't permit the name to ever be used when updating models and the story ends there, no validation errors needed.


text:
Q: Assign name to seat and display in array I'm having a problem assigning users to an array and then displaying the array. Typical 'flight seat-assign' program. Any help would be fantastic, as I am seriously stuck.
I haven't been getting any errors when compiling so I'm assuming I'm not too far off? code as follows.
Note, classes in separate header files.
// Flight Class - Scotia 2
// Contains information on seating (array), space available and return to menu option.
#include <iostream>
#include <string>
#include "booking.h"

using namespace std;

class Flight
{

public:

    public:
    struct Seat
        {
            int Available;
            string fullName;
        };// End of struct

// Structure for seat plan (24 spaces available)
    struct Seat seatArray[4][6];

    void seatPlan()
    {   //------
        cout << "Scotia Airlines Seating Plan\n";
        cout << "------------------------\n";
        cout << " 1D  2D  3D  4D  5D  6D\n";
        cout << " 1C  2C  3C  4C  5C  6C\n";
        cout << "                       \n";
        cout << " 1B  2B  3B  4B  5B  6B\n";
        cout << " 1A  2A  3A  4A  5A  6A\n";
        cout << "------------------------\n\n\n";
        //------
        for (int i=0;i<4;i++)
        {
            for (int j=0;j<6;j++)
                {
                if (seatArray[i][j].Available == 0)
                cout << seatArray[i][j].fullName << "=" << i+1;

                else
                cout << "Seating Plan is unavailable";
                break;
                }
        }// End of for loop
    }// End of seatPlan function

};// End of Flight class

Here is my booking class also, as I'm sure it'll help identify a problem...
//Booking class - Scotia Airlines
//This class will reserve a seat for passenger

#include <iostream>
#include <string>

using namespace std;

class Booking{

public:
    struct Seat
        {
            int Available;
            string fullName;
        };// End of struct

// Structure for seat plan (24 spaces available)
    struct Seat seatArray[4][6];

//variables for taking in customer details, calculating ticket cost (inc discounts) and adding details to system
    public:
    string fName, sName, busName, fullName;
    int age, livesAt;
    float discount, tickPrice, tCost;

    void addBooking()

    {
    cout << "\tBooking Menu \n\n";
    cout << "Please select ticket type: \n";
    cout << "1- Business \n";
    cout << "2- Western Isles \n";
    cout << "3- Ordinary \n";
    cin >> livesAt;

    // This will be used to calc total cost for each passenger dependant on ticket type
                    if(livesAt == 1)
                        {
                            discount = 0.75;
                            cout << "Please enter your business name\n";
                            cin >> busName;
                        }

                        else if (livesAt == 2)
                            {
                            discount = 0.90;
                            }

                        else
                            {
                            discount = 1.0;
                            };

    // Calculation - Standard ticket price is 60 Beans
                tickPrice = 60.0;
                tCost = (tickPrice * discount);

            bool booked = false;
                for(int i = 0; i < 4 && !booked; i++)
                    {
                        for(int j = 0; j < 6 && !booked; j++)
                        {
                            if(seatArray[i][j].Available == 1)
                            {
                                cout << "Please enter your first name \n";
                                cin >> fName;
                                cout << "Please enter your second name \n";
                                cin >> sName;
                                fullName == fName + " " + sName;
                                seatArray[i][j].fullName = fullName;
                                booked = true;
                                    // Message on screen for customer displaying cost of flight
                                cout << "*******************************\n";
                                cout << "\tBooking for " << fName + " " + sName << " confirmed.\n";
                                cout << "\tTotal cost = " << tCost << " GBP.\n";
                            }//end of if
                        }//end of for2
                    }//end of for1

    }// End of addBooking function
};// End of Booking class

Any help would be greatly appreciated!

A: Here are some errors I have spotted:

*

*First of all you never mark a seat as not available. Add this to your add booing function.

*Second the else in the second for in seatPlan should be in the else I believe.

*You don't need a semi-column after an else statement(in the else when setting discount to 1.0)

As you never mention what are the errors you are getting this is as good as I can get. Hope this answer helps.


text:
Q: Ant regexp. Read value of matched expression I need to replace all occurrence of some regular expression in xml file with proper values loaded from property file. As example

*

*in xml file I have < port=${jnpPort}/>

*in property file I have port=3333
I want to have xml file with entries like < port=3333/>
Now using
<replaceregexp match="\$\{(.*)\}" replace="${\1}" flags="g" byline="true">
        <fileset dir="." includes="file.xml"/>
</replaceregexp>

I get pretty much the same <port=${jnpPort} />. I would like value of ${jnpPort} were read from property file.

A: You just use copy with a filterset
<filterset id="version.properties.filterset" begintoken="$" endtoken="$">
<filter token="jnpPort" value="${port}" />
</filterset>
<copy file="file.xml.template" tofile="file.xml" overwrite="true" >
<filterset refid="version.properties.filterset" />
</copy>
Okay, not quite copy in place, but pretty good.

A: Try:
<replaceregexp match="@< port=\${jnpPort}/>@" replace="@< port=$(port)/>@" flags="g" byline="true">
        <fileset dir="." includes="file.xml"/>
</replaceregexp>