How to create recyclerview where the view input is dynamic

Question: I have a system where I get a custom view from a library. I do not have access to the view itself but I have an api call to return the view. I want to use this view in a recyclerview. Since I do not have access to the class, I cannot create a < customview > type object in my listItem xml class. Is there any way to implement this?
Answer: You can implement a custom RecyclerView.ViewHolder and whenever you're required to return the view use such API call to instantiate the new view from your RecyclerView.Adapter

class Adapter: RecyclerView.Adapter<RecyclerView.ViewHolder> {
    override fun getItemViewType(position: Int): Int = dataSet[position].viewType

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder  {
        val inflater = LayoutInflater.from(parent.context)
       return when(viewType) {
            // I suggest to assign this to a constant variable CUSTOM_VIEW for more readability
            1 -> CustomViewHolder.create(…)
            else -> OtherStuff from your collection

       }
    }
}

And as long as all views extend the RecyclerView.ViewHolder you should be good to go.
Comment: This view extends the exoplayer PlayerView so I guess that should work? Let me try it out tho.
Comment: Yes you have to wrap it into your own ViewHolder. You can just create a layout file with just a `FrameLayout`and programatically add the ExoPlayer view inside of it


No way to make it work with Slim framework

Question: I have a raspberry with Apache2.
In /var/www/ I have these files :
/myprojet
     /public_html
         index.php
         .htaccess
     /lib
         Slim

In index.php I have :
<?php

$app = new \Slim\Slim();

$app->get('/alertes.json', 'getalertes');

$app->run();

function getalertes() {
    $sql = "select * FROM T_ALERT ORDER BY name";
    try {
        $db = getConnection();
        $stmt = $db->query($sql);
        $alertes = $stmt->fetchAll(PDO::FETCH_OBJ);
        $db = null;
        echo '{"alerte": ' . json_encode($alertes) . '}';
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}';
    }
}

function getConnection() {
    $dbhost="127.0.0.1";
    $dbuser="root";
    $dbpass="root";
    $dbname="db";
    $dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    return $dbh;
}

?>

In .htaccess I have :
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]

In /etc/apache2/sites-enabled/000-default I have :
<VirtualHost *:80>
        ServerAdmin webmaster@localhost
        DocumentRoot "/var/www/myproject/public_html"

        ErrorLog "/var/www/logs/error.log"

        <Directory "/var/www/myproject/public_html">
                Options Indexes FollowSymLinks MultiViews
                AllowOverride All
                Order allow,deny
                Allow from all
        </Directory>

        ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
        <Directory "/usr/lib/cgi-bin">
                AllowOverride None
                Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
                Order allow,deny
                Allow from all
        </Directory>

        # Possible values include: debug, info, notice, warn, error, crit,
        # alert, emerg.
        LogLevel debug

        CustomLog /var/www/logs/access.log combined
</VirtualHost>

When I go on the url :
http://192.168.1.99/myproject/alertes.json

I've got nothing, a blank page.
Did I miss something ?
Thanks
Comment: Have you enabled error reporting? Checked your logs? I suspect your documentroot is wrong.
Comment: the documentroot is good (i just changed it in my post ;) ), in the error.log I have : [Tue May 27 12:50:26 2014] [error] [client 192.168.1.10] PHP Fatal error:  Class 'Slim\\Slim' not found in /var/www/myproject/public_html/index.php on line 3
[Tue May 27 12:50:26 2014] [debug] mod_deflate.c(615): [client 192.168.1.10] Zlib: Compressed 0 to 2 : URL /index.php
Comment: Have you included the Slim files?
Comment: What do you mean ? I put the files in : /var/www/myproject/lib/Slim/
For example I have Slim.php, View.php, Route.php...etc
Comment: By putting "require '../lib/Slim/Slim.php';" in the beginning of the file, I have now a Slim 404 error when I call : http://192.168.1.99/myproject/alertes.json
Comment: Try 192.168.1.99/alertes.json
Comment: I've posted it as an answer for you.
Answer: You have two errors. You need to require or include the Slim files and you need to use the URL 192.168.1.99/alertes.json.
Comment: Could you explain me why ? How could I configure htaccess to have access only with /watchit/alertes.json ?
Comment: In that case you would have to define the route in Slim `$app->get('/watchit/alertes.json' 'function');`
Comment: In fact, I think there is some wrong configuration in htaccess...
For example, if I have other projects in /var/www, none of them works now...


Associate Core Data Objects based on matching Dates

Question: I've designed my first database using Core Data. Consider the flow chart on the right of the attached image. It describes an algorithm to connect EntryType objects (light blue) with Day objects. Trouble is I don't know how to implement it.
What I would like to do is create a new Core Data Entity "Day" and associate it TrainingEntries, WaterEntries, MealEntries, etc when they are being created by the user in realtime through the UI. If there is already a "Day" object with a calendar date matching the new Entries date property associate the two together via core data relationships. Then I can just pass "Day" objects to my TableView and detailViews and use CoreData to traverse the graph as needed.

Is there a way to execute some code when an EntryType object is created in Core Data at the database level?
How do I then associate "Days" with "Entries" based on their date property?
How do I tell "Day" to recalculate it's properties after a "Entry" is added?

Thanks in Advance. It's easiest to save the image and open it in Preview.
=)
Answer: Addressing each question individually:

Yes you can.  Checkout the awakeFromInsert method on NSManagedObject
Since you have a day entity and an entry entity, it's simply a 1 to many relationship days->entries.  Though I have not used it CoreData supports abstract entities which you might try.  That way MealEntry, TrainingEntry, etc can all extend the base entry entity.  If you're thinking about CoreData as an object graph the entries are a relationship on "day"
What you're probably looking for is a transient property, one that's not a stored field but is computed based on other values.


How do I get rid of these briar hearts?

Question: I have 13 briar hearts in my inventory and I can't get rid of them because it says they're quest items.  What's up with that?
Answer: It's a bug with the White Phial questline. Use them all up in alchemy and further Briar Hearts will not be quest items. Use one to complete Repairing the White Phial if you haven't already.
Answer: You can eat all of them except for I think 5, then try using the rest in Alchemy after you completed the quest the white phial

How do I get rid of these briar hearts?


How to apply transformation matrices from multiple primitives on a mesh

Question: I'm working on some code to convert a 3d geometry from IFC to gltf/glb. One of the challenges I'm facing with this is that - IFC provides transformations for each primitive separately i.e., if I have a mesh (MeshA) which has 4 primitives, i'm getting a transformation matrix for each of the primitive. And once I construct MeshA using all these primitives, I would like to re-use this mesh in all other nodes where this mesh is referenced and apply a new transformation which I can retrieve from the respective mesh in IFC file.
Below is the available structure of Geometry from IFC File:

IFC (Available)

Mesh 1
primitive A -   TransformationA-1  primitive B - TransformationB-1

Mesh 2
primitive A -   TransformationA-2  primitive B - TransformationB-2

Below is the expected structure of geometry:

Gltf/Glb (Expected)

Mesh 1
Primitive A + Primitive B

Node 1
Mesh 1
TransformationA-1 + TransformationB-1

Node 2
Mesh 1
TransformationA-2 + TransformationB-2

What I have currently tried is to

apply the transformations of each primitive on each of its respective Vertex & Normal arrays to get a new set of arrays with the actual location after applying the transformation.
Then I add each primitive to a mesh and then add the mesh into a node

But I'm having to do this to each mesh and create new mesh - instead of referencing the existing mesh (because I don't know the transformation of the entire mesh) - which is increasing the output size significantly.
Can someone help me in understanding how to combine transformations of multiple primitives and apply it to a mesh?
Answer: In the glTF format, "primitives" are just a way to specify separate draw calls (and hence, separate materials or shader programs) for a single mesh.  There is no transform, as you've discovered, applied to a glTF primitive separately from its parent mesh.
I think your best bet here may be to take each IFC "mesh" and make it an empty parent node in glTF, and then take each IFC "primitive" and make it into a glTF child node + mesh + primitive with its transforms applied to the node.
This would mean that each time an IFC mesh is reused, you would possibly need to place multiple child nodes and meshes in glTF.  But the raw vertex data wouldn't change per instance, so could be easily reused without duplication.
If you have a substantial number of mesh instances, consider using EXT_mesh_gpu_instancing.


Traverse to matching parens in Lispworks

Question: Is this possible?  I haven't been able to find out how in the help or manuals.
Comment: Editor User Guide.  Editing Lisp Programs. Forms.
http://www.lispworks.com/documentation/lw70/EDUG-M/html/eduser-m-57.htm#pgfId-884090
Comment: @HenriqueJung: The LispWorks IDE provides an editor, which belongs to the class of Emacs editors. There are many editors like that, who share principles like UI with meta/control commands, modes, buffers, command layouts, movement, etc etc. If the general tag emacs is used to mean a specific editor, say GNU Emacs, then this would be wrong...
Comment: @HenriqueJung: tags might mean something slightly different based on context. Some communities occupy generic tags for their specialized meanings. In this case Emacs means a class of editor with a specific idea about commands/keymaps/modifiers and movements. Even though the keyboard commands are not fully the same, they share ideas. c-f, m-f, etc. for moving forward over various quantities (character, word, sentence, Lisp expressions, ...).
Comment: @RainerJoswig I don't think this question is related with emacs. I suggest revert the edit.
Comment: @RainerJoswig Thanks for the clarification. But the description of the tag refers to GNU Emacs. Anyway I don't see a problem since LispWorks is emacs-like and I don't think we have a tag for that.
Answer: C-M-Left and C-M-Right should jump the cursor to the previous and next SEXP in the LispWorks editor which really is an old version of emacs.


How to make drawers close softly?

Question: I've bought a MALM drawer system that comes without any soft close-mechanism on the drawers. Is it possible to make or buy external silencers that i can attach to the drawers so they don't make so much noise when closing them?
And example on dampening for kitchen doors: http://www.ikea.com/us/en/catalog/products/80126213/
Comment: do they pull themselves shut the last inch or so? if so then you just need an attachment point
Comment: No, i don't think so. Really basic shutting on those drawers
Answer: You can either replace the slides with a soft closing model, or you could possibly shoe horn in a damper piston like this one made by Blum.

They work in the same way as the ones in your link (those are made to attach to a hinge) but it can be recessed into a block or, in theory, drilled into a drawer side. The process would be to attach the piston in whatever fashion works with the pin pointed to the back of the cabinet. When you close the drawer the weight and momentum compresses the piston before it contacts the end of the slides travel, effectively softening the landing. You may have to apply a block on the back of the cabinet to give the piston a place to contact at the correct depth relative to the position of the drawer when it's fully closed.
Comment: Replacing slides, you you think these will work? http://www.amazon.com/SoftClose-Drawers-Retrofit-measuring-required/dp/B00JH81K6Y/ref=sr_1_fkmr0_1?s=hi&ie=UTF8&qid=1415553198&sr=1-1-fkmr0&keywords=soft+close+slides+malm
Comment: @Haaakon Those might work if your slides are on the side of your drawer.  What type of slides does yours use?  What's the clearance on each side of the drawer?
Comment: It looks like those are appropriate for your application but I haven't worked with (or heard of) them personally so I can't guarantee their efficacy or if they'll work with your particular drawer configuration. It looks like if they do work, it will require a bit less dinking around to implement than the pistons, but they are considerably more expensive so....your call:)
Answer: MALM drawers soft close available now in IKEA as an ad-on. Easy to install and very efficient.
Part No. MARKHUS  Soft closing device   604.265.71
https://www.ikea.com/gb/en/products/storage-furniture/chest-of-drawers/markhus-soft-closing-device-art-60426571/
https://www.ikea.com/gb/en/images/products/markhus-soft-closing-device__0677782_pe719070_s4.jpg

How to make drawers close softly?


run the startUp method at the deploy a web service

Question: I try to execute the startUp method when i deploy my web services, but doesn`t work.
I'm using:

windows 7
tomcat 8.0.30
axis2 1.7.0

I've tryed to deploy my service as a pojo service also i try generating the *.aar and placing it in:

apache-tomcat-8.0.30\webapps\axis2\WEB-INF\services
  but when i run the tomcat, and deploy this and other services, the startUp method dont launch.
  this is my code:

import java.io.*;
import java.util.*;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.description.AxisService;
import org.apache.axis2.engine.ServiceLifeCycle;

public class Login implements ServiceLifeCycle{

    static String IPprop = "";
    static String rutaDB = "C:/resources/users_DB.txt";
    static String rutaUddiXml = "C:/resources/uddi.xml";
    static String rutaIP = "C:/resources/ip.txt";
    static boolean registrado=false;
    static String comp ="";

    public static void main(String[] args) {

        IP();
        String nombreServicio = "Login";
        String rutaServicio = "http://"+ IPprop +":8080/axis2/services/Login";
        SimplePublishPortable spp = new SimplePublishPortable(rutaUddiXml);
        spp.publish(nombreServicio, rutaServicio);
        System.out.println("te registraste");
    }

    public static void createUser(String user, String pass) {
        interacFich("crea", user, pass);
    }

    public static String loginAccess(String user, String pass) {
        return interacFich("login", user, pass);
    }

    public static String runComprobation(){
        return "deployed service" + comp;
    }

    public static String regComprobation(){
        if(registrado==true){
            return "registered";
        }
        else{
            return "failed";
        }
    }

    private static String getToken() {
        String cadenaAleatoria = "";

        int i = 0;
        while (i < 10) {
            char c = (char) ((int) (Math.random() * 255 + 1));
            if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z')) {
                cadenaAleatoria += c;
                i++;
            }
        }
        return cadenaAleatoria;
    }

    private static String interacFich(String accion, String user, String pass) {
        String usuario = "";
        LinkedHashMap<String, String> usuarios = new LinkedHashMap<String, String>();

        File archivo = new File(rutaDB);

        // leer fichero y meterlo en el mapa
        if (archivo.exists() == false) {
            try {
                archivo.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            try (BufferedReader br = new BufferedReader(new FileReader(archivo))) {
                while (br.ready()) {
                    usuario = br.readLine();
                    String[] param = usuario.split("\\*");
                    usuarios.put(param[0], param[1]);

                }
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        switch (accion) {
        case "crea":
            usuarios.put(user + "-" + pass, getToken());

            try (BufferedWriter bw = new BufferedWriter(new FileWriter(archivo))) {
                Set<String> keysUsuarios = usuarios.keySet();
                for (String k : keysUsuarios) {
                    bw.write(k + "*" + usuarios.get(k).toString());
                    bw.write("\n");

                }
                System.out.println("todo escrito");
                bw.close();

                return "el fichero se crea";
            } catch (IOException e) {
                e.printStackTrace();
            }
            break;
        case "login":
            if (usuarios.containsKey(user + "-" + pass)) {
                return usuarios.get(user + "-" + pass);
            }
            return "User o pass erroneos";
        default:
            break;

        }

        return null;
    }

    private static void IP() {
        File archivo = new File(rutaIP);
        try (BufferedReader br = new BufferedReader(new FileReader(archivo))) {
            br.readLine();
            IPprop = br.readLine();

    br.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return;

}
@Override
public void startUp(ConfigurationContext arg0, AxisService arg1) {
    ///////////////
    //registrarse//
    ///////////////
    comp="entramos";
    IP();
    String nombreServicio = "Login";
    String rutaServicio = "http://"+ IPprop +":8080/axis2/services/Login";
    SimplePublishPortable spp = new SimplePublishPortable(rutaUddiXml);
    spp.publish(nombreServicio, rutaServicio);
    registrado=true;
}

@Override
public void shutDown(ConfigurationContext arg0, AxisService arg1) {
    // TODO Auto-generated method stub

}

}

Answer: Have you created the Service Definition (services.xml) file, on which you describe your services?
I am referring to a file similar to the example in Code Listing 3: The Service Definition File in the following link (axis2 quick start):
https://axis.apache.org/axis2/java/core/docs/quickstartguide.html#services
Comment: yes, the services.xml is automatically generated when i do:

"wsdl2java -uri serviceName.wsdl" ->
"ant jar.server -ss -sp"

to generate the *.aar


Function conv_units() not working inside an ifelse() statement

Question: I want to convert geographic coordinates in a table. I have some measurement in decimal degrees (dec_deg) and some in decimal minutes (deg_dec_min). I want to convert those in decimal minutes to decimal degrees. Using the function conv_unit() within a mutate() and ifelse() statement, I get a Warning message and an incorrect value.
Here's a reproducible example:
library(dplyr)
library(measurements)

data_latlon <- tibble(latitude = c(8.726088, -16.365242, -19.888074,
                                   '1 40.232', '0 2.308', '2 2.356'),
                      longitude = c(-83.180764, -62.015502, -40.549983,
                                    '75 54.301', '70 56.693', '72 41.143'),
                      unit = c('dec_deg', 'dec_deg', 'dec_deg',
                               'deg_dec_min', 'deg_dec_min','deg_dec_min'))

Case 1: using ifelse()
data_latlon %>%
  mutate(latitude = ifelse(unit=='deg_dec_min',
                           conv_unit(latitude, from = 'deg_dec_min', to = 'dec_deg'),
                           latitude))

# A tibble: 6 × 3
  latitude         longitude  unit
  <chr>            <chr>      <chr>
1 8.726088         -83.180764 dec_deg
2 -16.365242       -62.015502 dec_deg
3 -19.888074       -40.549983 dec_deg
4 2.34133333333333 75 54.301  deg_dec_min
5 2.356            70 56.693  deg_dec_min
6 0                72 41.143  deg_dec_min
Warning messages:
1: Problem while computing `latitude = ifelse(...)`.
ℹ longer object length is not a multiple of shorter object length
2: Problem while computing `latitude = ifelse(...)`.
ℹ data length is not a multiple of split variable

Case 2: doing it separately
data_latlon %>%
  filter(unit=='deg_dec_min') %>%
  mutate(latitude = ifelse(unit=='deg_dec_min',
                           conv_unit(latitude, from = 'deg_dec_min', to = 'dec_deg'),
                           latitude))

# A tibble: 3 × 3
  latitude           longitude unit
  <chr>              <chr>     <chr>
1 1.67053333333333   75 54.301 deg_dec_min
2 0.0384666666666667 70 56.693 deg_dec_min
3 2.03926666666667   72 41.143 deg_dec_min

Answer: I believe the issue is measurments::conv_unit is intended to receive numeric vector. However, some of your values in latitude column is character. This would be an issue if you run the entire column simultaneously.
For example, running conv_unit will return warnings and incorrect results:
conv_unit(data_latlon$latitude, from = 'deg_dec_min', to = 'dec_deg')

[1] "8.99884203333333"  "-19.9047406666667" "-40.232"
[4] "2.34133333333333"  "2.356"             "0"
Warning messages:
1: In as.numeric(unlist(strsplit(x_na_free, " "))) * c(3600, 60) :
  longer object length is not a multiple of shorter object length
2: In split.default(as.numeric(unlist(strsplit(x_na_free, " "))) *  :
  data length is not a multiple of split variable

Solution:
The easiest solutions are to vectorize the function or use rowwise():
conv_unit_vec<-Vectorize(conv_unit)

data_latlon %>%
  mutate(latitude = ifelse(unit=='deg_dec_min',
                           conv_unit_vec(latitude, from = 'deg_dec_min', to = 'dec_deg'),
                           latitude))

# A tibble: 6 x 3
  latitude           longitude  unit
  <chr>              <chr>      <chr>
1 8.726088           -83.180764 dec_deg
2 -16.365242         -62.015502 dec_deg
3 -19.888074         -40.549983 dec_deg
4 1.67053333333333   75 54.301  deg_dec_min
5 0.0384666666666667 70 56.693  deg_dec_min
6 2.03926666666667   72 41.143  deg_dec_min

or:
data_latlon %>%
  rowwise()%>%
  mutate(latitude = ifelse(unit=='deg_dec_min',
                           conv_unit_vec(latitude, from = 'deg_dec_min', to = 'dec_deg'),
                           latitude)) %>%
  ungroup()

# A tibble: 6 x 3
  latitude           longitude  unit
  <chr>              <chr>      <chr>
1 8.726088           -83.180764 dec_deg
2 -16.365242         -62.015502 dec_deg
3 -19.888074         -40.549983 dec_deg
4 1.67053333333333   75 54.301  deg_dec_min
5 0.0384666666666667 70 56.693  deg_dec_min
6 2.03926666666667   72 41.143  deg_dec_min

Comment: Thanks a lot, @peter861222 ! I think `conv_unit()` can deal with strings else I wouldn't be able to convert a value like `1 40.232` (but they must be numbers). If you see my second case, it works. However, apparently, it cannot deal with mixed char and num. I like the row-wise solution :)
Answer: Few things to note here:

from ?ifelse : "yes will be evaluated if and only if any element of test is true, and analogously for no"; so both yes and no are fully evaluated here.

conv_unit() does not really check if values in x arg make sense.
Snippet from function source:

    if (from == "deg_dec_min")
      secs = lapply(split(as.numeric(unlist(strsplit(x_na_free,
        " "))) * c(3600, 60), f = rep(1:length(x_na_free),
        each = 2)), sum)

Note how it uses unlist(), c(3600, 60) and rep(..., each = 2), it relies on an assumption that each element in input vector x will be split into exactly 2 numbers, no more no less.
If you take your input vector, c("8.726088", "-16.365242", "-19.888074", "1 40.232", "0 2.308", "2 2.356"), split strings by " ", and unlist, you will get 9 instead of 12 numbers. This is the reason for the warning and messed up result.
Besides rowwise() you could also handle this by e.g. split() and map_at() to only process rows where deg_dec_min is set:
library(measurements)
library(dplyr, warn.conflicts = FALSE)
library(purrr)

# split to list of tibbles by "unit" column,
# apply mutate only on "deg_dec_min" part,
# rbind both parts back together
data_latlon %>%
  split(~ unit) %>%
  map_at("deg_dec_min",
         \(x) x %>% mutate(across(ends_with("itude"),
                                  \(coord_col) conv_unit(coord_col,
                                                         from = 'deg_dec_min',
                                                         to = 'dec_deg')))) %>%
  list_rbind()
#> # A tibble: 6 × 3
#>   latitude           longitude        unit
#>   <chr>              <chr>            <chr>
#> 1 8.726088           -83.180764       dec_deg
#> 2 -16.365242         -62.015502       dec_deg
#> 3 -19.888074         -40.549983       dec_deg
#> 4 1.67053333333333   75.9050166666667 deg_dec_min
#> 5 0.0384666666666667 70.9448833333333 deg_dec_min
#> 6 2.03926666666667   72.6857166666667 deg_dec_min

Input:

data_latlon <- tibble(latitude = c(8.726088, -16.365242, -19.888074,
                                   '1 40.232', '0 2.308', '2 2.356'),
                      longitude = c(-83.180764, -62.015502, -40.549983,
                                    '75 54.301', '70 56.693', '72 41.143'),
                      unit = c('dec_deg', 'dec_deg', 'dec_deg',
                               'deg_dec_min', 'deg_dec_min','deg_dec_min'))

Created on 2023-05-10 with reprex v2.0.2
Comment: Thanks for the details @margusl! Now I understand why it's messing it up :)


Topological Definition of Continuity

Question: I am having some trouble understanding the mechanics of the topological definition of continuity.
It has been defined as follows:
A function $ f: \mathbb{R^n} \to \mathbb{R^m}$ is continuous if for every open set $V \subseteq \mathbb{R^m}$, the inverse image $f^{-1}(V) = \{x \in \mathbb{R^n} | f(x) \in V \subset \mathbb{R^m}\}$ is an open subset of $\mathbb{R^n}$.
Why, specifically, under the context of topology do we define continuty in terms of the inverse? Is there an equivalent definition of this that goes "the other way around"?
Furthermore, this is not an iff implication. That is, an open subset of $\mathbb{R^n}$ does not imply $V \subseteq \mathbb{R^m}$ is closed. Or am I incorrect?
Comment: Are you comfortable with the $\epsilon-\delta$ definition for continuity?
Comment: If you understand the closure, it is equivalent to say $f(\overline A) \subset \overline{f(A)}$ for any subset $A$.
Comment: Yeah I'm aware of the $ϵ−δ$ definition of continuity.
Comment: @JustinYoung Is A the subset of X (the "input space")? Your statement does make sense though. But what if I am not talking about the closure?
Comment: @MH1993 In the last part of the question, are you asking whether $V \subseteq \mathbb R^m$ is **open** if and only if $f^{-1}(V) \subseteq \mathbb R^n$ is open?
Comment: Possibly useful are these two old sci.math posts of mine: [Characterizations of continuity](http://mathforum.org/kb/message.jspa?messageID=5144243) (18 September 2006) and [Characterizations of continuity](http://mathforum.org/kb/message.jspa?messageID=5422934) (9 December 2006)
Comment: Yes, I assumed it was implied since I plugged it into $f$, but yes, $A$ is a subset of $\mathbb R^n$ in your example.
Answer: Continuous functions have many important properties. One crucial one in $\mathbb{R}^n$ is that they preserve convergent sequences. In other words, if I have a sequence $x_{n}$ converging to $x$, then $f(x_{n})$ converges to $f(x)$. What does it mean for $f(x_{n})$ to converge to $f(x)$? From the topological perspective, it means that the sequence $f(x_{n})$ eventually enters (and stays in) every open set $V$ containing $f(x_{n})$. If $f^{-1}(V)$ is open, then since it contains $x$ the sequence $x_{n}$ must eventually enter and remain in it, since we have assumed $x_{n} \to x$. From this we can conclude that $f(x_{n})$ eventually enter and remain in $V$.
The key point of this proof is that we are using information in the domain to prove stuff in the range/codomain, so we need to be able to "pull back" objects from the former to the latter. If $f^{-1}(V)$ is open for every open $V$, then all the open sets in the codomain ``come from" open sets in the domain. But if we insist instead that $f(V)$ is open for $V$ open, then the codomain may have many extra open sets that are not of the form $f(V)$, and we would be at a loss to prove anything about them.
Answer: The topological notion of continuity (which is stated for any topological space - even not metric, not only the $\mathbb{R}^n$) is a generalisation of the intuitions you may have from the real analysis (with $\delta$s and $\epsilon$s). Think of a function $f:\mathbb{R} \to \mathbb{R}$.  If it is not continuous at some point you may choose the neighbourhood violating the definition.
Let's analyse a simple example: $\operatorname{signum} : \mathbb{R} \to \mathbb{R}$  - equal 1 for positive numbers and 0 otherwise. If we take an open set $X = (-1/2, 1/2)$, its counter image $\operatorname{signum}^{-1}(X) = (-\infty, 0]$ is not open (because the function is "broken" in 0).
The definition is "iff" in the sense that functions $f:\mathbb{R}^n \to \mathbb{R}^m$ are continuous in the $\delta - \epsilon$ sense iff they have this property. However, there are more interesting topologies than the one on $\mathbb{R}$, where the $\epsilon - \delta$ definition does not make sense, but this one allows us to define what does it mean for the function to be continuous.
I think drawing it could help you to get more intuitions if this is not enough ; )
Comment: This was extremely helpful. Yeah, I think I need to draw out a few examples.
Comment: Actually, just to add on, how did you come up with the open set X = (-1/2, 1/2)? And why is the inverse of this (-oo, 0]?
Comment: Well, to unfold the definition of an inverse image of $X$: it is just a set of all points, which are mapped to $X$, so in this case - in fact just points, which are mapped to 0 (as the function value is either equal to 1 0r 0). So which points are mapped to 0 by $signum$? All non-positive, which means: $(-oo, 0]$ ;)
Comment: I am a bit confused because you've defined X as being a subset of the domain, so the function is mapped to (-oo,0] makes sense, but I don't see why we used the inverse here. (Even if it is by definition). Wouldn't it be the case that $signum^{-1}((-oo,0]) = (-1/2, 1/2)$ instead? And not the way you've defined it? Or am I wrong? :o I might be getting confused. Time for a quick coffee break.
Comment: Though just to be more precise, we are saying X $\subseteq\ \mathbb{R^n}$
Comment: $signum ((-oo, 0]) = \{0\} \subseteq (-1/2, 1/2)$, so for sure $(-oo, 0] \subseteq signum^{-1} ((-1/2, 1/2)) $. In fact, tey are just $equal$, as other points are mapped to $1 \notin (-1/2, 1/2)$. The example uses just $\mathbb{R}$ to make it more simple.
Comment: And what we actually do here is not random: we have chosen a point $x$ where function f is not continuous and some open neighbourhood $X$ (a "padding") of x s.t. the the value $f(x) \in X$, but the value "close to" $x$ where the function jumps is not in $X$. If you think a moment you'll see that it can be done iff the function is "broken" (that is: not continuous). And the $f^{-1}(X)$ will not be open.
Answer: There are several equivalent def'ns of continuity. Some of them are more suitable for certain problems than others.
1.The inverse of an open set of the range is open in the domain.
2.The inverse of a closed set of the range is closed in the domain.

For a given $p$ in the domain of $f:$ Suppose that whenever $f(p)\in V$ with $V$  open in the range, there is an open $U$ in the domain, with $p\in U,$ such that $\forall x'\in U\;(f(x')\in V).$ Then we say that  $f$ is continuous  at $p.$ And $f$ is continuous iff $f$ is continuous at every point $p$ of its domain. This is the topological generalization of the "$\delta, \epsilon$" criterion for continuity of a real function.
For a function $f:X\to Y$ : Whenever $S\subset X$ and $p\in Cl_X(S)$ then $$f(p)\in Cl_Y\{f(p'):p'\in S\}.$$ This is the topological generalization of a criterion for continuity of $f$ when $(X,d), (Y,e)$ are metric spaces: Whenever $(p_n)_n$ is a sequence in $X$ with $\lim_{n\to \infty}d(p,p_n)=0$ then $\lim_{n\to \infty}e(f(p),f(p_n))=0.$
Local continuity: $f$ is continuous iff every $p$ in the domain of $f$ belongs to an open set $U_p$ in the domain such that the restriction of $f$ to the domain $U_p$ is continuous. This is useful in some constructions. E,g. where we have $X=\cup_{n\in N}U_n$ where each $U_n$ is open in $X, $ and $U_n\subset U_{n+1},$ and we have continuous $f_n:U_n\to Y$ with $f_{n+1}|U_n=f_n.$ Then $\cup_{n\in N}f_n$ is continuous.
Comment: 1.The inverse of an open set of the range is open in the domain.

2.The inverse of a closed set of the range is closed in the domain.

How do these imply continuity?
Comment: Nevermind. Got it. :)
Answer: Let $X, Y$ be two topological spaces.  A function $f : X \rightarrow Y$ is said to be continuous at a point $x_{0} \in X$ if into every neighborhood of $y_{0} = f(x_{0}) \in Y$ this function maps some neighborhood of $x_{0}$.
(See also the definitions of continuity and equivalent conditions in: (a) Komogorov and Fomin's book on real analysis, (b) Vulikh's Brief Course of Functions of a Real Variable.)

Topological Definition of Continuity


Arranging factors in increasing order

Question: I am trying to create two plots which should display frequency in a decreasing order.
#preparing the data to resemble actual data
test <- data.frame(HairEyeColor) %>%
  mutate(combi = paste(Hair,Eye)) %>%
  group_by(Sex) %>%
  mutate(prop = Freq / sum(Freq))  %>%
  ungroup()
test$combi <- factor(test$combi)
freq_test_count <- test %>%
  setorder(Freq)

#creating the plot
freq_test_plot <- freq_test_count %>%
  ggplot(aes(x = reorder(combi,prop),y = prop, label = Freq)) +
  geom_col(show.legend = FALSE) +
  geom_text(check_overlap = TRUE, nudge_y = 0.005, size = 3) +
  facet_wrap(~Sex, scales = "free") +
  labs(y = "Proportion",
       x = NULL) +
  coord_flip()

When i plot freq_test_plot, it shows the plot but the output is not in decreasing order
I am not sure what should I do so that I can see terms in decreasing order of frequency.
Comment: Looks to be in overall decreasing order. Do you mean that you want the scales in different orders for males and females? That sounds potentially misleading as it will take a careful observer to realize the labels are in different orders.
Comment: The idea is to show that the labels are in different orders for males and females.

I am not sure how the order is being decided here. I cant figure out why "Blond Blue" 30 is before "Brown Blue" 50.
Comment: Your ordering ignored sex. Blond Blue has a total of 30 + 64 = 94, so it is ahead of Brown Blue which is 50 + 34 = 84. I think this chart is useful because it orders by the overall population, and where the bars for a particular sex are not in order it highlights the differences between the sexes. The chart you are asking for makes it much harder to compare the sex differences because you have to switch back and forth reading and comparing the labels.
Comment: For example, this version makes it obvious that the Blond Blue combination is far more common for women than for men - it jumps out as soon as you look at the chart. The charts in the answers, however, hide that insight unless you read them carefully. Similarly, the chart in your question shows that Brown Blue is more common than for women, but if you glanced at the charts in the answers I would assume the labels are in the same order and since the distributions look about the same I would conclude there is no real difference between male and female distributions.
Answer: A workaround is to create two different plots and arrange them in grid. But you should be cautious because, like Gregor mentioned, it could definitely be misleading.
library(grid)
p1 = freq_test_count[freq_test_count$Sex == "Male",] %>%
    ggplot(aes(x = reorder(combi,prop),y = prop, label = Freq)) +
    geom_col(show.legend = FALSE) +
    geom_text(check_overlap = TRUE, nudge_y = 0.005, size = 3) +
    facet_wrap(~Sex, scales = "free") +
    labs(y = "Proportion",
         x = NULL) +
    coord_flip()

p2 = freq_test_count[freq_test_count$Sex == "Female",] %>%
    ggplot(aes(x = reorder(combi,prop),y = prop, label = Freq)) +
    geom_col(show.legend = FALSE) +
    geom_text(check_overlap = TRUE, nudge_y = 0.005, size = 3) +
    facet_wrap(~Sex, scales = "free") +
    labs(y = "Proportion",
         x = NULL) +
    coord_flip()

graphics.off()
grid.newpage()
grid.draw(ggarrange(p1, p2, ncol = 2))

Comment: Thank you. I hoped I wont have to add another library as the code might be shared with others. But seems this is the only way. I will accept this as answer if nothing better comes up.
Answer: Another work-around is to make male and female specific levels for the factor. Here I add a space " " to the front of the Male Hair/Eye labels. This lets you define an ordering that takes sex into account:
test <- data.frame(HairEyeColor) %>%
  mutate(combi = paste(Hair,Eye)) %>%
  group_by(Sex) %>%
  mutate(prop = Freq / sum(Freq))  %>%
  ungroup() %>%
  mutate(combi = factor(test$combi),
         sex_combi = factor(paste(ifelse(Sex == "Male", " ", ""), Hair, Eye)),
         sex_combi = reorder(sex_combi, prop))

#creating the plot

ggplot(test, aes(x = sex_combi,y = prop, label = Freq)) +
  geom_col(show.legend = FALSE) +
  geom_text(check_overlap = TRUE, nudge_y = 0.005, size = 3) +
  facet_wrap(~Sex, scales = "free") +
  labs(y = "Proportion",
       x = NULL) +
  coord_flip()

But as I mentioned in the comments, I think this is a misleading plot.
Comment: Thanks. I will check if introducing a leading character in my actual data would be acceptable.
Answer: Are you wanting the values to be sorted on male or female?
library(tidyverse)

#preparing the data to resemble actual data
test <- data.frame(HairEyeColor) %>%
  mutate(combi = paste(Hair,Eye)) %>%
  group_by(Sex) %>%
  mutate(prop = Freq / sum(Freq))  %>%
  ungroup()
test$combi <- factor(test$combi)

test$combi<- factor(test$combi, levels = unique(test$combi)[order(test$Freq)],)

#creating the plot

  ggplot(test,aes(x = combi,y = prop, label = Freq))+
  geom_col(show.legend = FALSE)+
  geom_text(check_overlap = TRUE, nudge_y = 0.005, size = 3) +
  facet_wrap(~Sex, scales = "free")+
  labs(y = "Proportion",
   x = NULL) +
  coord_flip()

updated to include full code from question.
Comment: This doesn't produce a sorted bar chart for me.
Comment: Agree with @Gregor. This code doesn't produce a sorted bar chart for me.
Comment: The point of the chart is to show sorting by male or female, not both male and female. Running the code will show male sorted in descending order.

Arranging factors in increasing order


c# - ASP.NET MVC4 HtmlHelper Not rendering html

Question: Im trying to create an Html Helper that renders blog posts from a database, but for some reason the HtmlHelper doesn't render the code..
This is what my helper looks like:
@helper Render(System.Web.Mvc.HtmlHelper html, T2L.Models.Post post, bool isAdmin, bool isMember)
{

dsfds

                    @post.time.ToString("MMM").ToUpper()

                @post.time.ToString("dd")

@post.title

@post.body

                    Read More

By@post.author

10 Comments

Tags: Design,Creative,wordpress theme

Share

}

and this is how I call it:
   @if (Model.Count() == 0)
                {

No posts available..

                }
                else
                {
                    foreach (Post post in Model)
                    {
                        PostGenerator.Render(Html, post, isAdmin, isMember);
                    }
                }

I don't see what I'm doing wrong exactly..
Can someone please help??
Comment: that's not usually how you make an HtmlHelper.  Usually it's an extension method off an `HtmlHelper` object.  It looks like what you're trying to do is define a _Section_ or perhaps a _Partial View_
Comment: That's a View Helper indeed.
Comment: Yeah its a view helper, but it wont render.. i had it working a while ago but idk am i doing something wrong??
Comment: You're missing the `@` as @Floremin already answered.
Answer: Try adding @ in front of your call:
@PostGenerator.Render(Html, post, isAdmin, isMember)

Comment: Sweeet! That did the trick! lol thw power of the "At" Symbol!


What Stats and Equipment increase damage from Hexes?

Question: I current have INT 16, FTH 26, and am using Resonant Soul with an Idol's Chime +1.
What do I need to level up, in order to increase the damage from Resonant Soul? Do I Level Up Intelligence, or Faith, or does reinforcing the Chime increase the damage.
Answer: Your dark damage scaling is determined by the lower of your Faith and Intelligence stats. So, you would have to increase your intelligence first to increase your dark scaling.
As for the Chime, reinforcing it would also increase the dark damage it does.
Source: http://darksouls.wikia.com/wiki/Dark
Comment: Post note: if both your Faith and Int stats are equal, you can effectively double the damage output.


Custom Validator does not fire

Question: I have the following code. When I press my save button, three requiredfieldvalidators run fine and work properly. However my custom validator does not work. It does not fire the event at all. I have standard text boxes and a validationsummary control. Is there any reason why it might not be working?
<code><asp:RequiredFieldValidator runat="server" ControlToValidate="txtForename" Display="None" ErrorMessage="Must enter a valid first name." />
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtSurname" Display="None" ErrorMessage="Must enter a valid last name." />
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtEmail" Display="None" ErrorMessage="Must enter a valid e-mail address." />

<asp:CustomValidator runat="server" OnServerValidate="CheckAtLeastOnePhoneNumber"
        ErrorMessage="Must enter at least one phone number." Display="None"
        ValidateEmptyText="True" />

<script runat="server">
    void CheckAtLeastOnePhoneNumber(Object s, ServerValidateEventArgs e)
    {
        if (txtMobileNumber.Text.Equals("") &&
            txtWorkNumber.Text.Equals("") &&
            txtHomeNumber.Text.Equals(""))
        {
            e.IsValid = false;
        }
    }
</script>
</code>
Answer: I fixed it.
The custom validator control is a server-side check, and so the other validators (which are client side) execute first. This is a little bit misleading as the validationsummary control usually displays all validator errors.
Assuming the name, email etc. were valid, only then would it submit to the server and come up with the validation error.
Comment: You could do this check client side as well with a custom validator so it would fit right in with your client side checks.
Answer: That's right.  That's the way it works.  If you want a custom validator to also work in the browser, you need to implement your custom validation in JavaScript and define the method in the control's ClientValidationFunction property.  Then it will show up with the client-side errors in the validation summary.

Custom Validator does not fire


ANTLR: How to get rid of 'missing NEWLINE at '''?

Question: I'm having trouble recognising 'end of file' correctly with ANTLR. As soon there's no new line but just 'end of file' after the last character I get
line 37:1 missing NEWLINE at ''
Any ideas on how to deal correctly with end of file?
This is my grammer (for GCode):
grammar GCode;

gcode :
    start_end NEWLINE
    line (NEWLINE line)*
    start_end ( NEWLINE | EOF);

line : (
        comment |
        command WHITESPACE* COMMENT?
);

start_end : PERCENT;
comment : COMMENT;

command : (
    g00 |
    g01 |
    g02 |
    g03 |
    g21 |
    m2  |
    m3  |
    m5)  ;

g00 : G '00' WHITESPACE coordinates ;
g01 : G '01' WHITESPACE coordinates (speed)?;
g02 : G '02' WHITESPACE coordinates arc (speed)?;
g03 : G '03' WHITESPACE coordinates arc (speed)?;

g21 : G '21';

m2 : M '2';
m3 : M '3' (WHITESPACE 'S' DIGITS+)?;
m5 : M '5';

coordinates : (x | y | z)+; // jeder nur einmal, min 1, max 3
arc : i j;
speed : f;

f : F FLOAT (WHITESPACE)?;
i : I FLOAT (WHITESPACE)?;
j : J FLOAT (WHITESPACE)?;
x : X FLOAT (WHITESPACE)?;
y : Y FLOAT (WHITESPACE)?;
z : Z FLOAT (WHITESPACE)?;

fragment LOWERCASE  : [a-z] ;
fragment UPPERCASE  : [A-Z] ;
fragment DIGIT : [0-9];

NEWLINE : ('\r'? '\n' | '\r')+ ;
WHITESPACE : (' ' | '\t') ;
SPECIAL : [."':];
COMMENT : '(' .*? ')';
PERCENT : '%';
DIGITS : DIGIT+;
F : 'F';
G : 'G';
I : 'I';
J : 'J';
M : 'M';
X : 'X';
Y : 'Y';
Z : 'Z';
FLOAT: ('+'|'-')? DIGITS '.' DIGITS;

And this is the testfile:
%
(Header)
(Generated by gcodetools from Inkscape.)
(Using default header. To add your own header create file "header" in the output dir.)
M3
(Header end.)
G21 (All units in mm)

(Start cutting path id: path4827)
(Change tool to Cone cutter)

G00 Z5.000000
G00 X85.340320 Y22.949391

G01 Z-1.000000 F100.0(Penetrate)
G02 X82.451429 Y10.393260 Z-1.000000 I-28.731155 J0.000010 F400.000000
G02 X77.835955 Y7.504376 Z-1.000000 I-4.615471 J2.242548
G02 X73.220483 Y10.393262 Z-1.000000 I0.000001 J5.131434
G02 X70.331593 Y22.949391 Z-1.000000 I25.842269 J12.556139
G02 X73.220481 Y35.505528 Z-1.000000 I28.731173 J-0.000000
G02 X77.835955 Y38.394417 Z-1.000000 I4.615476 J-2.242547
G02 X80.361909 Y37.463849 Z-1.000000 I0.000002 J-3.893531
G02 X83.142342 Y33.870675 Z-1.000000 I-7.195292 J-8.440138
G02 X84.717221 Y29.203570 Z-1.000000 I-17.511307 J-8.508321
G02 X85.340320 Y22.949391 Z-1.000000 I-31.075686 J-6.254179
G01 X85.340320 Y22.949391 Z-1.000000
G00 Z5.000000

(End cutting path id: path4827)

(Footer)
M5
G00 X0.0000 Y0.0000
M2
(Using default footer. To add your own footer create file "footer" in the output dir.)
(end)
%

Comment: Can you try to use `start_end ( NEWLINE)? EOF` instead?
Answer: Your grammar always requires a newline at the end, that's why you get the syntax error. Instead use:
gcode :
    start_end NEWLINE
    line (NEWLINE line)*
    start_end NEWLINE? EOF;

Btw. I find it odd that you handle whitespaces manually, instead of just skipping them. Is this really a requirement of the language?
Comment: This changes the error message to `line 37:0 mismatched input '%' expecting {COMMENT, 'G', 'M'}`
Comment: `line (NEWLINE line)*` should be `line (NEWLINE line)* NEWLINE`
Comment: Oh right, I didn't realize there's another mistake.


Basic HTML operations in Emacs

Question: I am working with HTML in Emacs and I am looking for ways to make basics operations as:

convert list of string to HTML-list
one
two
three

to

one

two

three

add class to list of elements

to

Is there any extensions which can helps me?
Answer: I would do this with a macro:

Move to the first line, and type C-x (
Type the
, move to the end
, and move to the next line
End and repeat the macro on the remaining lines with C-x e e e e e...

This can easily be generalized to add classes to your  tags, and many other things.
Answer: You should take a look at zencoding , it's pretty useful. Here's a youtube video showing it with yasnippet, showing some functionality like what you want.
Answer: You can add class to list of elements using command M-x replace-string.
Answer: Here is an Emacs Lisp function which performs the first task (operates on selected text):
(defun my-make-list (start end)
  (interactive "r")
  (insert "
\n")
  (mapcar '(lambda (line) (insert (concat "
" line "
\n")))
          (split-string (buffer-substring start end) "\n"))
  (insert "
")
  (delete-region start end))

In the second case I would just use search/replace.

Basic HTML operations in Emacs


Angular rxjs to rxjs 6 and rxjs-compat

Question: I've tried issuing the following command:
npm install --save rxjs-compat

but I can't find the rxjs-compat folder. Anyway, here's the real problem:
import { Subject } from 'rxjs';
import { startWith, DebounceTime } from 'rxjs/Operator';
...
ngOnInit() {
    this.products$ = this.searchSubject
    .pipe(startWith(this.searchTerm), debounceTime(300));
}

This should be proper rxjs v6 code.  The error is "Property 'startWith' does not exist on type 'Subject'.ts
Can you advise?  I'm in a bit of a jam.  Thank you - Dale
Answer: There are mistakes in the import: import { startWith, DebounceTime } from 'rxjs/Operator'; should be import { startWith, debounceTime } from 'rxjs/operators'; (case sensitive and operators with a "s")

Angular rxjs to rxjs 6 and rxjs-compat


"Add to favorites" option in a soundboard app

Question: I have this code for my soundboard,
public class soundboardActivity extends Activity {
<code>View lastClickedView;

    public static void setIntArrayPref(Context context, String key, ArrayList<Integer>       values) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor = prefs.edit();
    JSONArray a = new JSONArray();
    for (int i = 0; i < values.size(); i++) {
        a.put(values.get(i));
    }
    if (!values.isEmpty()) {

        editor.putString(key, a.toString());
    } else {
        editor.putString(key, null);
    }
    editor.commit();
}

   public boolean onCreateOptionsMenu(Menu menu) {
       MenuInflater inflater = getMenuInflater();
       inflater.inflate(R.menu.menu, menu);
       return true;
   }
   // Contextual Menu
    public void onCreateContextMenu(ContextMenu menu, View v,  ContextMenuInfo menuInfo)
    {
        super.onCreateContextMenu(menu, v, menuInfo);

            menu.setHeaderTitle("OPTIONS");
            MenuInflater inflater = getMenuInflater();
                inflater.inflate(R.menu.menu_contex_apm, menu);

                lastClickedView = v;
    }
    public boolean onContextItemSelected(MenuItem item) {

            switch (item.getItemId()) {
                case R.id.ctxtapm_opcio1:
                    //favorites

                    switch (lastClickedView.getId()){
                                 case R.id.a1: favorites.add(R.raw.sound1);
                                return true;
                                    }
                                 case R.id.a2: favorites.add(R.raw.sound2);
                                return true;
                                    }
                                 case R.id.a3: favorites.add(R.raw.sound3);
                                return true;
                                    }
                  setIntArrayPref(this, "favoritos", favorites);

                    return true;
                case R.id.ctxtapm_opcio2:
                   //share

                    return true;

                default:
                    return super.onContextItemSelected(item);
            }
        }

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.apm);

    Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    map.put(R.id.a1, R.raw.sound1);
    map.put(R.id.a2, R.raw.sound2);
    map.put(R.id.a3, R.raw.sound3);

    for (Map.Entry<Integer, Integer> entry : map.entrySet()) {

        final MediaPlayer sound = MediaPlayer.create(this,entry.getValue());
        Button button = (Button) findViewById(entry.getKey());

        registerForContextMenu(button);

        button.setOnClickListener(new View.OnClickListener() {

           public void onClick(View v) {
                sound.start();
            }

        });

    }
</code>
FavoritesActivity code:
<code>   public class FavoritosActivity extends Activity {

ArrayList<Integer> favorites=new ArrayList<Integer>();

public View getView (int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater = this.getLayoutInflater();
        View item = inflater.inflate(R.layout.buttonsample, null);

    return item;
}

public static ArrayList<Integer> getIntArrayPref(Context context, String key) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    String json = prefs.getString(key, null);
    ArrayList<Integer> favoritos = new ArrayList<Integer>();
    if (json != null) {
        try {
            JSONArray a = new JSONArray(json);
            for (int i = 0; i < a.length(); i++) {
                int musicaid = a.optInt(i);
                favoritos.add(musicaid);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    return favoritos;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu, menu);
    return true;
}

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.proba);

    favorites = getIntArrayPref(this, "favoritos");

    ListView lv = (ListView) findViewById(R.id.listView1);

    ArrayAdapter<Integer> arrayAdapter =  new ArrayAdapter<Integer>(this,android.R.layout.simple_list_item_1, favorites);
    lv.setAdapter(arrayAdapter);

}
</code>
}
question is, how can I implement an "add to favorites" option ( favorites are in another activity)  for the contextual menu?
thanks a lot!
Answer: Over ride onCreateOptionsMenu with in that create one more ArrayList for favorites .
Store the song id in arraylist for each time.
Store this array list in SharedPreferences object
When user select favourites play navigate to next activity get SharedPreferences.
According to position from the list of favourites play the song.
I hope the above solution is clear for you
Comment: Thanks for your answer! my question now is, how can I create a new button in the favorites activity table row, every time the user clicks in the " add to favorites" option?
Thanks again.
Comment: i didnt get actual flow how "add to favorites" and main screen links.If you have any screen please refer it here
Comment: In the main screen I have two buttons, the one that gets you into the soundboard activity, and the other one that gets you in your "favorites" activity. Every time user clicks "add to favorites" at the soundboard activity, a new button in "favorites" must be created.

I don't know if that's what you ask.
Comment: Instead of Using TableLayout if you use ListView to hold favorites then you can use one single xml file to inflate listitem view(for one favorite) with in that layout you can use one button which will be used for n number of favorites.But be careful you have to write onclick event for that button within getView function of adapter
Comment: Hi again! I'm still trying to get the arrayList on the favorites activity. I've edited the code in the main question with a test i've done to see it works, only with one button and one audio file, but is not working. LogCat in favorites Activity says IndexOutofBoundException: Invalid index 0, size is 0. What am I doing wrong?
Comment: One thing im not understanding why you took JSONArray to hold the arraylist 2.you are already having favourites arraylist why cant you store that array list in Sharedpreferences if that is not possible you can send array list through bundle object.Its all about just storing the name of song in arraylist to identify in next activity still if you have doubt paste the full code i will edit that
Comment: I've edited with the code I have at the moment, but only for 3 buttons. I can't find a way to make it work.


Need to add html input values which are part of a mysqli array

Question: I am an extreme newbie when it comes to coding but here it goes anyway. I have a table which has the first two columns populated from MySQL database and each row gets a text box for user input. This is then written back to the database. This works fine, i need to get the total from the user input of each text box as they are inputting it and subtract that from another text box earlier on the page. I need to get the sum of the budgetamount input field.
Here is my table code:
    0
    <?php
        $result = mysqli_query($con,"SELECT envelopename, envelopebudget FROM envelopes");
        echo "

        Envelope
        Budget
        Amount

";
        while($row = mysqli_fetch_array($result)) {
        echo "<input type='hidden' value='$row[envelopename]' name='envelopename[]'/>";
        echo "
";
        echo "" . $row['envelopename'] . "	";
        echo "" . $row['envelopebudget'] . "	";
        ?><input type="text" name="budgetamount[]" class="textboxone">	<?php;
        echo "
";
        }
        echo "
";
        mysqli_close($con);
    ?>

Here is the jquery script i tried but it does not work:


Input not supported!

Question: I'm new to the whole Ubuntu forum but I've seen this topic many times before - thing is, all of the answers I've come across have not worked (e.g nomodeset, console commands, GRUB stuff ect.) and most of the posts seem to be from more than a year ago. The problem I'm having is actually getting onto the media itself, I can get onto the Ubuntu loading dots, then after that there's usually a message that says "can't find usb interrupt point" which is normal for my Corsair keyboard and mouse, but then after that is where I have the problem; this is usually where it would start up but lately all it says is "Input not support" (obvious Chinese mistranslated on my AOC screen but it's all the same) This has only started happening since I got my GTX1060 graphics card; I used to own a 660 and it had worked fine, but since getting this graphics card I can't seem to even get to the "try ubuntu" or "install ubuntu" screen. I suspect it's something to do with default drivers since I am able to boot into the arch-linux based Antergos live USB? Strange... Any answers would be appreciated.
Comment: Yes, you need nomodeset until you install proper Nvidia drivers. How exactly did you add the parameter and what happened?
Comment: I added it using the "shift" at startup and setting it via the F6 menu, although the same thing occurred when I did.; I will post an answer as I have found the cause and a solution.
Answer: So I seem to have found the reason for this annoying bug, it seems whenever I had tried to start the installer, it would some reason go from 1920x1080 60Hz down to 1920x1080 30Hz and then the smallest resolution possible while at 30Hz, because my monitor isn't able to display 30Hz, it just told me that it wasn't supported, which is the reason I was just seeing this message.
The way I got around this and was able to discover the issue is because my graphics card has an HDMI port in the back, I used this in order to plug it into my TV, and it booted straight up after that, I was able to see the hertz difference as my TV notifies me whenever the image changes size or Hz, and when my screen would have gone black with my normal monitor, it notified me that it had gone from 60Hz to 30Hz... In order to solve this I had to go through the whole install process with the smallest screen size (which I wasn't able to change), then boot it up still with the same screen size, then install the proprietary drivers from NVIDIA for my graphics card and some microcode for my AMD CPU, after all of that and a restart, it's working perfectly, and is what I'm using right now to write this!
Hope this helps if anyone else gets stuck in future! :-)
-Adam

Input not supported!


Bootstrap modal not shown on first call

Question: I'm trying to use a bootstrap 3.0 modal to load external html file into a modal using jQuery Ajax loader, however it's not shown on first call but works on subsequent calls.
Department

                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                </button>

Comment: Try remove `id="myModal"` from the `` tag? You assigned the same id `myModal` to two different elements
Comment: i tried remove and also change id="myModalss" like this..  still i had same error..
Comment: i tried inspect element on browser shown this error: "event.returnValue is deprecated. Please use the standard event.preventDefault() instead."
Comment: still had same error..... plzzzzzz
Comment: while my first call "" shown still this
Answer: Just add:
success: function(data){
        $('.modal-body').html(data);
        $('#myModal').modal("show");
    }

Comment: datt-target="#myModal" to data-target="#myModal"
Comment: i rewrite my answer) check it please

Bootstrap modal not shown on first call


How to resume from suspend or hibernate only by the power button?

Question: My motherboard's bios/uefi don't provide an option for disabling wake up from keyboard or mouse. So I tried to disable all others devices than PWRB in /proc/acpi/wakeup, but my system ignores that and still wakes up on mouse clicks or keyboard.

System: ubuntu 20.04
Motherboard: H97-D3H-CF
my   /proc/acpi/wakeup
Comment: If all else fails you instruct the system to power off (unbind) all the USB buses on suspend and power on (bind) to same address on resume. I wrote a script to do that but don't have it handy.
Answer: This seems to be even better (as integrates with systemd) :

For a USB mouse or keyboard, you can use a udev rule to make the
setting permanent. First, look up the PCI vendor ID of your
mouse/keyboard using lsusb. For my mouse, it's 046d:
Bus 001 Device 006: ID 046d:c52b Logitech, Inc. Unifying Receiver
Then create a "rules" file like my /etc/udev/rules.d/logitech.rules,
only replace "046d" with the vendor ID of your own device:
ACTION=="add", SUBSYSTEM=="usb", DRIVERS=="usb", ATTRS{idVendor}=="046d", ATTR{power/wakeup}="disabled"

Source: https://unix.stackexchange.com/a/532839/439288
Tested. Works fine with Ubuntu 20.04 and MS Sculpt keyboard


Why is this operator essentially self-adjoint?

Question: Let $T^{*}$ be the adjoint of a densely defined, symmetric operator $T$. Suppose that the operator $T^{*}$ is a symmetric operator. Why does it follow that $T$ is essentially self-adjoint?
Thanks in advance!
Comment: Are you assuming that $T$ is symmetric and densely defined as well?
Comment: Yes, I correct that now.
Answer: Here is a proof using the definitions.
First check that if $T$ is symmetric and densely defined, that then $D(T^*)\supseteq D(T)$ and $T^*\lvert_{D(T)}= T$. For if $x \in D(T)$ then:
$$|\langle x, Ty\rangle| = |\langle Tx,y\rangle| ≤ \|Tx\| \ \|y\|$$
for all $y\in D(T)$ and $x\in D(T^*)$ follows. Further $T^*(x)$ is defined via:
$$\langle T^* x, y\rangle := \langle x, Ty\rangle = \langle Tx,y\rangle$$
holding for all $y\in D(T)$ (which is dense). It follows that $T^*x=Tx$ for all $x\in D(T)$.
Now if $T^*$ is also symmetric this very same step gives you $D(T^{**})\supseteq D(T^*)$ and $T^{**}\lvert_{D(T^*)}=T^*$. The only thing we are still interested in proving is that $D(T^*)\supseteq D(T^{**})$. So let $x\in D(T^{**})$. This means that
$$|\langle x,T^*y\rangle| ≤ C_x\|y\|$$
for all $y\in D(T^*)$. In particular since $D(T^*)\supseteq D(T)$ it holds for all $y\in D(T)$ and you get the desired $x\in D(T^{*})$.
Comment: I had some of the things mixed up: The general statement is that if $T$ is symmetric then $T^{**}$ is the closure of $T$. This is always true and a calculation can be found in the appendix of these [notes](http://www-users.math.umn.edu/~garrett/m/fun/adjointness_crit.pdf) for example. What is done here shows that $T^*$ is self-adjoint, hence $T^{**}=T^*$ is self-adjoint giving that the closure of $T$ is self-adjoint.
Comment: What definition of essential-self-adjointness are you using?
Comment: Thank you very much!


how do I get into the didSelectAnnotationView method?

Question: Im tryin to make a mapview where I can get a location and its coordinates then send it to another view.
I tried to use didSelectAnnotationView to send the information.
But for some reason I'm not getting into the didSelectAnnotationView method.
Can someone tell me?
Or if I am doing something wrong. What method should I use?
thanks in advance
Comment: Did you set the delegate (a MKMapViewDelegate) on your MKMapView ?
Comment: yes I did, but I have used another method which does workL=) - (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
Comment: hi does you get any solution for the problem??
Answer: Make sure you add the delegate on the interface, and the method header names are correct.
Example:
<code>@interface MapperViewController : UIViewController <MKMapViewDelegate>
{
    IBOutlet MKMapView *mapView;
}
@property (nonatomic, retain) IBOutlet MKMapView *mapView;

- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view;

@end
</code>
This code should fire when user taps on pin head:
<code>- (void)mapView:(MKMapView *)mapView1 didSelectAnnotationView:(MKAnnotationView *)mapView2
{
    MapAnnotation *annotation = mapView2.annotation;
    NSString *temp = annotation.title;
}
</code>
Comment: hi what is this `MapAnnotaion`?


Regression with statsmodels having index disaligned Series

Question: I have done some research to use regression in python and I found some problem this is my code i Hope you Can help me guys

I Have 2 variable when I use my code :
X = sm.add_constant(X)
result = sm.OLS(Y,X).fit()

I got this error : ValueError: The indices for endog and exog are not aligned
And len of X and Y are the sam 5486 if someone can help me it will be very kindfull thank u
Comment: *I can't do regression* is not a question.
Comment: Yes, that's a too generic request for help. I suggest you change it to something such as "regression with statsmodels having index disaligned Series"
Comment: Thank you @LucaMassaron
Answer: Your code doesn't seem to have any problem. The problem is with your variables and their indices which are not aligned (they are somehow different in some way).
Since you are working with two Pandas Series that you are expecting being aligned, you can just extract their values and ignore about the indices.
Please try:
X = sm.add_constant(X.values)
result = sm.OLS(Y.values, X).fit()

Comment: Thank u for your answer , and If i want use regression and I have 2 dataframe I can do the same code that you share or should I do something else?Sh
Comment: Yes, definitevely. Have a look at: https://www.statsmodels.org/dev/generated/statsmodels.regression.linear_model.OLS.html OLS takes array like inputs for dependent and independent variables. Also in a Pandas dataframe, if you use the .values method, this will turn the input into a Numpy array, and you won't suffer from any index disallineagment.


Extract date type data in NiFi 1.9.2

Question: The data is convert other type automatically?How can i get raw data?TIA
Source Table:

DF:

Result:
Answer: That is just a unix timestamp. If you want to get the human-readable timestamp, you should update the record by UpdateRecord processor or something with the following way.

Reader and writer to JSON
Add the attribute as follows:

/STARTTIME    ${field.value:toNumber():toDate("yyyy/MM/dd HH:mm:ss", "GMT"):format("yyyy/MM/dd HH:mm:ss", "GMT")}

Then, it will be the timestamp in such a format.
1900/10/20 11:24:32

Comment: ```.IllegalAttributeException: Cannot parse attribute value as a date; date format: yyyy/MM/dd HH:mm:ss; attribute value: -2183728164000.```in UpdateAttribute
Comment: Yeap, that is just an example. Updated my answer.
Comment: Can i set the JsonRecordSetWriter properties in UpdateAttribute Processor which i need?
Comment: I am not sure. Can you post a Json example file then I will test it.
Comment: Sorry,my wrong.i want to extract data of the right format in dataflow:GenerateTableFetch->ExecuteSQLRecord(JsonRecordSetWriter)->UpdateAttribute->``````But format of date type data is -2183728164000,is it possible to obtain this format "1900-10-20 08:52:48" by JsonRecordSetWriter?
Comment: Well, I guess you can change the type of the record when you do the query. Not the json writer part.
Comment: '''will route to failure: Cannot parse attribute value as a date; date format: yyyy/MM/dd HH:mm:ss; attribute value: -2183728164000'''in UpdateRecord.Any other suggestions?thanks
Comment: Oh, sorry. Not toDate function but it would be a format function.
Comment: Thanks.you way is right but the date is less than 1970,it would fail.https://stackoverflow.com/questions/59062398/the-date-type-data-has-changed-by-jsonrecordsetwriter
Comment: Can you try my answer again? Updated.
Comment: @Lamnus the way is right until today,the time has changed.Do u know why?Thanks!

Extract date type data in NiFi 1.9.2


Trouble with Transmission

Question: I have a 30gb root setup, and when i download anything from Transmission, it takes up the whole 30 gb. The save to location is Downloads. I tried changing the location to /media/.../Downloads, which has >200gb size, but it says I don't have permission, which i know I don't btw. How can I give only Transmission the permission to make this change. I am using it on another user profile, and therefore the permission issues.
It's an Ubuntu 15.10 machine.
Thanks in advance!
Answer: Run transmission with sudo privileges by.
Opening a new terminal by pressing
Ctrl + Alt + T

In that new window type
sudo transmission

Press enter
It will ask for your password type that in and press enter
Now transmission will be running with elevated privileges so it can access the downloads folder.
Hope this helps, if it did mark this post as answered
Zimbinskers

Trouble with Transmission


Facebook Messenger Sender Actions

Question: I am trying to use Sender Actions as described in the messenger Send API docs. However when I send a typing_on POST I do no see anything happen in messenger. I have tried on chrome desktop and the messenger android app.
I am able to send a mark_seen POST and this does update the chat with an icon indicating my message has been seen.
The request body looks as follows:-
<code>{
  "recipient":{
    "id":"<PSID>"
  },
  "sender_action":"typing_on"
}
</code>
When sending mark_seen, typing_on or typing_off I always get the following response body.
<code>{
    "recipient_id": "<PSID>"
}
</code>
Are there additional steps needed to get the typing indicator to display? Does it only work on a specific platform? I cannot find any more documentation, and I am not getting any error messages, the POST status comes back OK identically when sending mark_seen or typing_on, I just can't see any effect after typing_on.
Comment: I think you are doing everything correctly. It may be something Facebook has done lately. Our bot was setting this action
on as soon as message was delivered to server (after marking it seen). I noticed today it doesn't work anymore. Just stopped.
Comment: Thanks! Good to know someone else has the same issue, I'd not be surprised if it was an issue on Facebook's end, I'll try again tomorrow.
Answer: Okay I got reply from Facebook developer team on Facebook Developers group
Quote:
"This changed recently for mobile and is currently assigned to an internal team". Looks like something internal.
Comment: Started working at last for me today, with no code changes. So can only assume that they fixed the issue on Facebook's end.
Comment: looks like issue is user and/or page and/or app specific. I saw typing icon with our qa page linked to qa app. now I see it on the page linked to production app but another user doesn't. They must be working on it.
Comment: I also got the same issue for typing_on. Does anyone know if this has been fixed?

Facebook Messenger Sender Actions


(hibernate) table altered after failed commit

Question: I'm new to hibernate. I have a transaction that fails with a HibernateException, yet the table is altered after the commit. Here is the code:
<code>public StoreResult store(Entry entry)
{
    Session session = HibernateUtility.getSessionFactory().openSession();
    Transaction transaction = session.beginTransaction();

    try
    {
        String id;

        if (entry.getStatus() == Entry.Status.PUBLISHED)
        {
            id = TitleToURLConverter.convert(entry.getTitle());
        }
        else
        {
            id = "temp_";
        }

        if (entry.getId() == null)
        {
            entry.setId(id);
            session.save(entry);
        }
        else
        {
            session.update(entry);

            session.createQuery("update Entry set id = :newId where id = :oldId")
            .setString("newId", id)
            .setString("oldId", entry.getId())
            .executeUpdate();

            session.refresh(entry);
        }

        transaction.commit();

        return StoreResult.SUCCESS;
    }
    catch (RuntimeException e)
    {
        transaction.rollback();
        if (e instanceof ConstraintViolationException) return StoreResult.DUPLICATE_ID;

        throw e;
    }
    finally
    {
        session.close();
    }
}
</code>
EDIT: Apparently InnoDB does not rollback the transaction on a duplicate key error but only the statement. I would like the transaction to be always rolled back on ANY error.
EDIT2: Disregard this. I was using MyIsam.
Comment: What are the details of the exception you are getting?
Comment: It is a ConstraintViolationException, because of a duplicate id in the table. It means that an entry with the same id exists. I want to handle it and display such a message to the user. Thanks for your response! transaction.wasCommited() returns false.
Comment: Now that you have it working, consider putting the session and transaction instance creation in using statements to dispose properly.
Comment: Doesn't the finally block do this? Does java have a using keyword? I thought it was in C#. Thanks
Answer: Switching from MyIsam to InnoDB fixed this.


How to fix drawer runners

Question: I have a set of drawers (custom made) that have draw runners which are attached to the bottom of each drawer on both sides. Unfortunately, the small plastic wheels on part that attaches to the housing has cracked on two of the three drawers (and on the same side, bizarrely). Neither drawer is overloaded nor even very heavy--a few kilos of weight max.
I can't see a way to replace just the wheels as they the part they fit onto wouldn't allow such a thing to be replaced and the only way to remove them would be to break them anyway! I was wondering if there was any way to repair these plastic wheels without replacing the entire mechanism, as this would be time consuming.
If the only way to repair the sliders is to completely replace them, are there any you can recommend that should be able to handle weight and daily usage?
Each drawer is approximately 20cm high, 1m wide and 50cm deep.
Update:
I can only upload one photo, so here's the plastic wheel which had snapped in half. I've tried repairing it with super glue, but this is all that's left of it!

Update (solution):
I have now replaced the runners with new ones that can take a load of up to 45Kg and they feel much smoother than the old ones ever did. Although I tried to re-use the old screws, I had to use the new screws provided to ensure that they were flush. Turns out that some of the old screws were not flush with the runners and this caused some rubbing on the wheels at the back of the drawers. They were pretty weak when I replaced them, but I was able to hear where the rubbing was happening and have rectified that problem. I also had to adjust the position as I think the first set of drawers that broke ended up resting on the next one which caused that one to break. I now have an even gap between the drawers and with a bit more care, hopefully they will last a lot longer!
Comment: Some pictures would probably help get your question answered.
Comment: As suggested, a photo has been uploaded.
Answer: I'm guessing these shattered because of shock or perhaps from being fully extended more than normal since the front wheel takes a lot of the weight when drawer is fully extended. The rail is acting as a lever where 10kg in the front of the drawer could easily be the equivalent of 100kg on that wheel when the drawer is fully open. The other thoughts are if someone where to lean on the drawer or if the cabinet was being moved and dropped.
I've seen replacement wheels, but they tend to be for specific rails/sliders, and I doubt you'd get a good result without a perfect match. For replacing the entire slider, I'd look for a replacement with a high weight limit. I've seen sliders in the US that are designed for 50kg, which I'm guessing would more than handle your load.
Comment: Your description of the wheel acting like a lever certainly makes the most sense. The weight of our drawers should be nowhere near the limit of the runners but when fully extended it is surely putting a lot more weight on to that single wheel. It seems like the best option will be to get runners that can handle a lot more than our drawers weigh.

How to fix drawer runners


Not able to run a python code in my visual studio code

Question: When I try to run any .py file on my vscode ; it always show this error!
zsh: command not found: python
% which python
python not found

% which python3
/Library/Frameworks/Python.framework/Versions/3.10/bin/python3

while my terminal from other environment shows
(tensorflow) anshumansinha@lawn-128-61-45-180 deepOscillations_try-master % which python
/opt/homebrew/Caskroom/miniforge/base/envs/tensorflow/bin/python

(tensorflow) anshumansinha@lawn-128-61-45-180 deepOscillations_try-master % which python3
/opt/homebrew/Caskroom/miniforge/base/envs/tensorflow/bin/python3

Have I installed my python multiple times? And it is not showing up on my vscode? How to correct this? Also does the honeybrew version only work for a given environment? Because when I go for a new terminal window and write the following, again it stops working
anshumansinha@lawn-128-61-44-2 ~ % which python
python not found
anshumansinha@lawn-128-61-44-2 ~ % which python3
/Library/Frameworks/Python.framework/Versions/3.10/bin/python3
anshumansinha@lawn-128-61-44-2 ~ %

Kindly help me understand what am I doing wrong?
Answer: To use python in place of python3 you should add this line to  ~/.zshrc
alias python=python3

This way you will use your system Python /Library/Frameworks/Python.framework/Versions/3.10/bin/python3.
If you want to use the Python from the tensorflow virtual environment you should activate it also inside VSCode
$ . tensorflow/bin/activate

Comment: `~/.zshrc` it's a file. It's located on directory ` ~` and it's an hidden file, since its name starts with a dot. You can add the line by open the file and just type that line at the end. I personally use Vim `$ vim ~/.zshrc` but you can use your favorite text editor (I think you can also open it with `$ open  ~/.zshrc`).
Comment: I recommend you to uninstall all packages you have already installed with `pip` on your system Python (https://stackoverflow.com/questions/11248073/what-is-the-easiest-way-to-remove-all-packages-installed-by-pip) and install any new packages in the future within a virtual environment dedicated to a specific project
Comment: VSCode it's just an IDE, it has no Python nor packages installed. It all dependes on which Python you areusing and which packages are installed on that Python. You should follow this tutorial (https://stackoverflow.com/questions/11248073/what-is-the-easiest-way-to-remove-all-packages-installed-by-pip) and remove everything you have installed in your basic (system) Python. Then you should learn how to work on virtual environments (https://realpython.com/python-virtual-environments-a-primer/) and install there what you need to use, for example tensorflow
Comment: What's `~/.zshrc` ? and how to add this line to that? additionaly the 2nd line does not work! `no such file or directory: tensorflow/bin/activate`
Comment: I added the lines in my `~/.zshrc` file but it is still showing `anshumansinha@lawn-128-61-44-2 ~ % which python
python not found`
Comment: Here's what I think you should do to be sure of using exactly what you need for your project. 1) Choose an installed version of Python you want to use. You should be able see them all with `$ ls /usr/local/bin/python*`. 2) Once you have chosen one (e.g. `/usr/local/bin/python3.9`) enter your project directory and type `$ /usr/local/bin/python3.9 -m venv venv`. 3) Now activate your virtual environment `$ . venv/bin/activate` Every time you work on your project, you must remember to activate the venv. 4) Pip install whatever package you need, e.g. `(venv) $ pip install tensorflow`
Comment: Is there any step by step method following which I can install tensorflow working both vscode and terminal! I wish to uninstall all the previous ones!
Answer: You have to install two things. Python itself, and the Python extension inside VSCode that allows it to make use of Python.
The VSCode extension must be installed from within VSCode by searching "Python" in the Extension tab on the left side of the screen and installing it.
Comment: I have done both, but still the above happens!
Answer: In mac, python points to the pre-installed python2 by default. But since Monterey 12.3, python2 is no longer pre-installed.
So you need to create an alias for your machine using the following command to make python point to python3.
echo "alias python=/usr/bin/python3" >> ~/.zshrc

If you want to keep using the python 2 version on mac, check out this answer.
Comment: I wish to use my python and tensorflow which I installed from homebrew! ` environment location: /opt/homebrew/Caskroom/miniforge/base` and it shows up on one of my terminals as : `(tensorflow) anshumansinha@lawn-128-61-45-180 deepOscillations_try-master % which python3
/opt/homebrew/Caskroom/miniforge/base/envs/tensorflow/bin/python3` ; but other terminal don't show like this! The keyword `(tensorflow)` is missing in the initial statement! before `anshumansinha@lawn`. I am getting confused in all this!


Is there known generating function having this form: $\sum\frac{m-(i_1 + \ldots + i_k)}{i_1! \ldots i_k!} x_1^{i_1}\ldots x_k^{i_k}$?

Question: The sum is over n-dimensional simplex:
$$
\sum_{0\leq i_ 1+\ldots+i_n \leq m}\frac{m-(i_1 + \ldots + i_k)}{i_1! \ldots i_k!} x_1^{i_1}\ldots x_k^{i_k}
$$
Does this function has a name?
Answer: Assuming $k=n$.
These functions are polynomials in $x_1, \dots x_n$, let's denote them $w_m(x_1,\dots x_n)$. I haven't heard about a name for them, but if we construct a generating function for them it turns out to have a pretty simple form:
\begin{align} & \sum_{m=0}^\infty w_m(x_1,\dots x_n) t^m = \\
&= \sum_{m=0}^\infty \sum_{0\le i_1+\dots i_n\le m} \frac{m-(i_1+\dots +i_n)}{i_1! \dots i_n!} x_1^{i_1}\dots x_n^{i_n} t^m = \\
&= \sum_{0\le i_1,\dots, i_n< \infty} \sum_{m=i_1+\dots i_n}^\infty \frac{m-(i_1+\dots +i_n)}{i_1! \dots i_n!} x_1^{i_1}\dots x_n^{i_n} t^m = \\
&= \sum_{0\le i_1,\dots, i_n<\infty} \sum_{m'=0}^\infty \frac{m'}{i_1! \dots i_n!} x_1^{i_1}\dots x_n^{i_n} t^{m'+(i_1+\dots+i_n)} = \\
&= \sum_{m'=0}^\infty m't^{m'} \sum_{0\le i_1,\dots, i_n<\infty}  \frac{1}{i_1! \dots i_n!} (tx_1)^{i_1}\dots (tx_n)^{i_n} = \\
&= \frac{t}{(1-t)^2} e^{tx_1}\dots e^{tx_n} = \\
&= \frac{t\,e^{t(x_1+\dots+ x_n)}}{(1-t)^2}\end{align}
You have then
$$ w_m(x_1,\dots, x_n) = v_m(x_1+\dots+x_n) $$
where $$v_m(z) = \frac{1}{m!} \left.\frac{d^m}{dt^m}\right|_{t=0} \frac{t e^{tz}}{(1-t)^2} $$
Comment: Thank you! Really cool that it only depends on the sum of $x$s.


How to get the parent component reference

Question: I have a parent component:
<Parent>
<Child (click)=doSomething()></Child>
</Parent>

I want to have a reference to the Parent component so that I can pass it in the method, that would trigger an event that would have a parent ref.:
doSomething() {
// I would like to trigger the event, that would be catch elsewhere in the     app
trigger(new ClickedEvent(referenceToParent));

}

the event would be like:
class ClickedEvent {
constructor (public referenceToParent: Parent) {}
}

How would I achieve that ?
Answer: One of ways of interacting from child to parent component is Parent listens events from child https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#child-to-parent
So, you doSomething method should emit an event, which is handled by parent.
Comment: Actually, I do not want to handle it in parent component. I want to handle it elsewhere in the code :(
Comment: @JerzyGruszka why not make a service that can broadcast and register listeners for the events then?
Comment: I have that, but how to pass a reference to that particular instance?


Which date format to use?

Question: In an application when you are showing a date to someone (and you don't know their preferred format), what date format should you use?  USA or Rest-of-the-world?

For reference if anyone is not sure what these formats are, today's date would be:
  USA = 10/07/2011 or October 7, 2011
  Rest-of-the-world = 07/10/2011 or 7 October 2011

Assuming an equal probability that a user is from the USA or outside the USA, which format should I use?
Note, this question was largely triggered by the comments in another UX question.
Comment: Also, the "rest of the world" doesn't only use DD/MM/YYYY so don't go assuming that everyone except Americans will recognize it either; YYYY-MM-DD is common in many countries like China and Canada
Comment: Nitpicking: [ISO-8601](https://en.wikipedia.org/wiki/ISO_8601) _standard_ date format is YYYY-MM-DD (with hyphen), not YYYY/MM/DD. :-)
Comment: As worded this question can't have a good answer. Can you change the title and contents to something less contentious, like "what are advantages and disadvantages of different date formats"?
Comment: I've never used neither of those nor would I ever be able to properly read those two...  I guess I'm an alien ^^
Comment: @AlexFeinman: The title isn't the full question.  If I wanted to ask about advantages and disadvantages I would have, but I want opinions on a specific situation.
Comment: @AlexFeinman: I see your point about the title though.  Ammended it to be less contentious
Comment: @BenBrocka: I meant something that would be easily readable for people.  The ISO standard is YYYY/MM/DD, but showing a person a date in that format has been shown to be confusing.
Comment: I just mean there aren't two date formats, showing someone used to big endian date is as sure to be confusing as the reverse to someone used to small endian. It makes the unambiguous written-out month and 4 number year all the more important.
Comment: We've covered this to a degree before:  http://ux.stackexchange.com/search?q=date+format
Comment: JohnGB if you are showing the ISO standard format to a small part of the world population (US), then it might be confusing. But 5 times more people than in US, understand it perfectly
Answer: I've recently had to make a similar choice. And, yea, as a programmer, ISO 8601 is the best, but most humans do find it unintuitive, unfortunately.
I find that the problem isn't so bad for either side as long as you don't use pure numerical date formats.
So this 12/10/2011 is certainly ambiguous, but Oct 12 2011 is not, and neither is 12 Oct 2011. So just stick to EEE months, if you can. There's no better.. there's just least surprising to the user.
Comment: yea, but this isn't a hypothetical discussion about unbiased minds.. :)
Comment: ISO 8601 is no less intuitive to an unbiased mind than the rest, it's that most users are used to seeing dates in a specific format, and it's often _not_ ISO. Like the metric system, if we all used it from birth there wouldn't be any question =p
Comment: UBER's CEO had landed to Indian airport with invalid Visa because of the date format confusion http://www.ibtimes.co.in/when-uber-ceo-travis-kalanick-entered-india-without-visa-was-almost-shunted-back-onto-plane-708956
Comment: +1 For noting that the key isn't in the relatve merits of the formats (which we could debate until the cows come home), but in making things unambiguous.
Answer: The short format for one or the other should NOT be used, because the US standard MM/DD/YYYY is ambigious to the "rest of the world" standard DD/MM/YYYY. This means that if the user is not aware that the date format might be different than what he expects, it is not noticed. It is better to use October 7, 2011 or 7th October 2011 because although this might not confirm to the standard the user is used to, it is no doubt which date it actually is.
A good alternative is to use the global standard YYYY-MM-DD which is not ambigous.
If I see 10/07/2011, I immediately read 10th of July, 2011 without further thoughts unless the context indicates that this might be wrong. I might give it a second thought if the application has mainly US targeted audience.
To specifically answer the question in the title: "which is better?" the answer is: None is better! It is an insult to say otherwise.
If anything is better, it would be the global standard 2011-10-07.
Comment: The question is given that you don't know their preferred format.  Obviously if you know that, then you can use that.  There are many situations where you don't know, such as text in a blog post.
Comment: @JohnGB: OK, I have removed my references to reading client locale settings.
Comment: @awe the "rest of the world" standard is DD/MM/YYYY or YYYY/MM/DD. 1.6 billion of people use the latter format so you can't ignore it
Answer: If it's a 50% chance then neither is preferable, the only date format with an inherent superiority in any area is the ISO 8601 date format of YYYY-MM-DD H:i:s because it is computationally easy to sort in all cases by simple "higher or lower number" sorts and there is no ambiguity if you know the format. You can safely bet that almost no non-technical users are going to know the format by default unless their country happens to use it or a similar format.
The solution is to display the full name of the month in any written dates; "October 7th, 2011" can not be misinterpreted. When asking for a date input always state the format you're using near the field (e.g. MM-DD-YYYY).
To decide which format to actually pick, look at your domain. If it's a US domain (.us) or assumed to be a US domain (.com is often used as such for the big sites) some people may assume it's going to follow US conventions and in that case you may as well use US date format, as that's the best/only hint you're going to give. The same for .co.uk, ect. The only "best" here is what your users will most expect.
For related reasons the full 4 number year should always be used to help eliminate ambiguity, there's nothing worse than seeing 10/7/11 as a date format.
Comment: "there is no ambiguity if you know the format" - well, that's true of any format except for truly bad ones like MDYY [11111 is january 11th or november 1st?] What you mean to say, I think, is that since no other all-numeric* format in use begins with the year or uses four digits for anything but the year, then there's no ambiguity if you know _that_. *and the benefit of being all-numeric is really only relevant to the sorting thing.
Answer: Its an old question but I feel its worth adding my 2c.
I worked as a student for a big pharmaceuticals company that was based in both Europe and the US. All staff were trained to write the date in a specific way. I guess to ensure the there were no misunderstandings which would upset regulators but also to ensure dates couldn't be easily modified later. We also had to cross our zeros diagonally and ensure our 1's and 7's were easily distinguishable.

dd MMM yyyy - > 01 JAN 2014

The great thing with this format is that there is no way it can be misread and you don't need to know whether its European, US, ISO, etc to know exactly what was intended. In industries where mistakes pose a potential risk to patients in trials, getting it right is important. It's quite long-winded to write out by hand and you certainly tire of it when you're writing the date 50+ times a day, but the habit stuck and I still do it today having not worked in the industry for over 10 years.
Answer: If possible, don't use either. Use a text abbreviation for the month ('Oct', 'Nov', etc.). Not much bulkier and less open to misreading. A lot more readable, and it tends to look nicer too, because you're not bombarding users with a stream of numbers and human-unfriendly separator symbols.
If your input form allows users to enter the date purely in digits, you can have it automatically parse the data and transform months into text the moment the user changes field focus. This gives instant and unambiguous feedback on the data received.
Comment: Just came across this but it deserves and up vote. I use a modified version of this scheme in that if the month has only 4 letters I use the whole name, otherwise the 3 letter abbreviation. "06 July 2013"
Answer: The most important thing in this is of course what the users need and expect.
Things to do:

provide unambiguous feedback about what the accepted result means (spell it out in text)
accept the yyyy-mm-dd alongside others too
provide a helpful hint about what format you could use so people don't have to find out through trial and error
if possible, provide the user with a way to change the behavior if they want to.

Things not to do:

solely use the browser locale as a way of determining format (not all users have control over that, especially on public computers, and not every user always uses the same format. I prefer English texts to have English settings for numeric and date, and European format for European measures. Intermingling is even more confusing)
religiously block all options that are not iso-something compliant, because it comes at a cost of readability and usability. (The same for spelling it out in text, because it takes up screen estate. If it causes a table to scroll horizontally, it might not be the best option.)
The goal is to prevent dates from being mixed - it is not about conforming everybody to iso-something. Assess the confusion and address it accordingly, but be as broad and providing as you can.
Answer: Base it on where the user is from (use their system settings in a desktop app, and in a web app, base it on their ip address until they log in). Some countries don't even use the Gregorian calender (though it's almost universally understood).
Answer: You should use the long form and toss a coin to choose the format. Based on the information given there is no reason to favor one or the other.
Answer: It is always best to go with a format that will never be confused for another, in which case when you cannot know for sure which part of the world the user's date expectations will be, you should either convert to a named format (12 December 2011) or 2011-12-11. This avoids the question as to whether that is the 11th of December, or the 12th of January, as well as making it immediately obvious which numbers are the year.
If you are able to know locale is dominant, then you can consider supporting that date format, but in those cases you will need to make it clear that it's YYYY-MM-DD (or whatever variant you use), and it's good practice to do that no matter what.

Which date format to use?


Spring Boot 2 upgrade caused HATEOAS href link vs _links issue and now request to that link kicks back out to login screen

Question: We upgraded our apps from spring boot 1.5.19 to 2.2.7.  We have a UI app and an API services app.    The API app returns responses with a links object like below:
"links": [],
"links": [
  {
    "rel": "all",
     "href": "https://server:port/foo/bar{?page,size}"
  }
 ]

Previous the response contained a single "_links" object but now it contains two "links" and one is empty.  We changed the dashboard to grab the "links" object that actually contains data.  However, now whenever we click on any of the links that translate to the href in the "links" object we get kicked back out to the login screen even though we already logged in.  I set logging to debug for spring and there things that seem odd but may be normal:
SecurityContextHolder now cleared, as request processing completed

and
SessionId: null; Not granted any authorities

but I dont really have any idea where to go with them. Anyone know whats going on?
Answer: Solved by adding this:
@Bean
ForwardedHeaderFilter forwardedHeaderFilter() {
    return new ForwardedHeaderFilter();
}