text:
Q: Simultaneous object interaction in javascript As a little fun side project, and to gain some more experience, I'm currently trying to create something similar to TIS-100, but with HTML and Javascript. TIS-100 is basically a very simple, very limited assembly interpreter, designed as a programming puzzle.
There's a fixed number of nodes, all of which simulating mini computers running their own code. I have the programing for the instruction set close to finished and the nodes generally work. That is, as long as each of them stays self-contained. That means all the logic has been implemented and can be used already, as long as there's no read from, or write to one of the connections.
Each node has two connections to it's direct neighbors, both vertical and horizontal. One of them is the output (writing to the neighbor) and the other for input (reading from the neighbor).
+----+    +----+    +----+
| No | -> | No | -> | No |
| 1  | <- | 2  | <- | 3  |
+----+    +----+    +----+
 ^  |      ^  |      ^  |
 |  v      |  v      |  v
+----+    +----+    +----+
| No | -> | No | -> | No |
| 4  | <- | 5  | <- | 6  |
+----+    +----+    +----+

The connections kind of act like named pipes in unix. The execution of a node halts, until the program on the other end of the connection reads from it.
For now, the user has to press a button to run the next instruction. All nodes run simultaneously, and I just call each node's runNextInstruction() method when clicking the button.
When getting to a read or write instruction, it calls either readFromConnection(direction) or writeToConnection(direction). This is what I've got so far:
TIS_Node.prototype.readFromConnection = function(direction) {
    this.ioMode = TIS_ioMode.READ;
    this.lastDirection = direction;
    var connection = this._connections[direction];
    console.log(connection.ioMode);
};

All it does for now, is setting the node's state from IDLE to READ, which will prevent the executeNextInstruction() method to execute any other instructions. Precisely, readFromConnection is getting called like below:
// Gets called when a MOV instruction is called.
// Syntax: MOV SOURCE, DEST
TIS_Node.prototype.action_MOV = function(command) {
    var components = command.split(",");
    var source = components[0].trim();
    var destination = components[1].trim();

    source = this.getValue(source);

    switch (destination) {
        case "ACC":
            this.acc = source;
            break;
        case "NIL":
            // Discard
            break;
        // ...
    }
};

TIS_Node.prototype.getValue = function(address) {
    switch (address.trim().toUpperCase()) {
        case "LEFT":
            return this.readFromConnection(TIS_Direction.LEFT);
        case "RIGHT":
            return this.readFromConnection(TIS_Direction.RIGHT);
        // ...
        default:
            return address;
    }
};

The problem I have is getting my head around how to do it. My first naive idea was to just wait in javascript itself until the connection's ioMode changes to WRITE, but that probably won't work and I couldn't even imagine how.
My second idea was just to set the own ioMode to READ and then call a method such as receiveInputValue(direction, value) from the other node when it executes the write instruction. Still, I can't think about how to implement this and still having the correct destination written to (a value can be written to the node's accumulator ACC, discarded via NIL or just handed through to another connection).
On another note:
While everything is fast enough that it seems the nodes run simultaneously, they actually don't. Node 1's runNextInstruction gets called one step in a forEach loop before Node's method. This would also ruin my results. Imagine the following: Node 1 wants to read from node 2. In the exact same time (theoretically) node 2 changes from IDLE to WRITE and wants to hand node 1 the value. Because node 1 de facto gets executed before node 2, when it tried to read the value, node 2 was still in IDLE, thus started waiting.
Is there any easy way around these issues? And can you give me some clues as to how to go on from here?


text:
Q: Check if a list contains a key I am trying to check if a list contains a key.
I have a dictionary that I have sorted and believe it turns it into a list. Now I want to check that list for a key.
Here is my code to give an idea where I am:
drinkDict = {'drink1': drinkTimes[0],'drink2': drinkTimes[1],'drink3': drinkTimes[2],'drink4': drinkTimes[3],'drink5': drinkTimes[4]};
    print drinkDict
    for k, v in drinkDict.items():
        if v == '0':
            del drinkDict[k]
    sorted_x = sorted(drinkDict.items(), key=operator.itemgetter(1))
    print sorted_x
    print (sorted_x[0]
    if 'drink1' in sorted_x.key:
        print "drink1 is present"
        data = pin_update(VALID_BCM_PIN_NUMBERS[0], 0)

Output:
{'drink4': u'4.8', 'drink5': u'0.7', 'drink1': u'1.4', 'drink2': u'2.8', 'drink3': u'0'}
[('drink5', u'0.7'), ('drink1', u'1.4'), ('drink2', u'2.8'), ('drink4', u'4.8')]
('drink5', u'0.7')

I just can't figure out how to detect if sorted_x contains "drink1" or "drink2" etc. etc.
I am not sure on terminology here so please correct me if I'm wrong so I can better search for solutions.

A: You can reuse operator.itemgetter from earlier, except we are looking at the first (0th) entry this time:
'drink1' in map(operator.itemgetter(0), sorted_x) # True

However, you might want to explain why you are doing all of this. It seems like you're dancing around different data structures and I'm not sure for what reason.
To sort the items in the dictionary by the second value:
sortedItems = sorted(drinkDict.items(), key=operator.itemgetter(1))

In general, it looks like you could achieve the same thing using code like:
import operator

drinkDict = {'drink1': '2',
             'drink2': '1',
             'drink3': '4',
             'drink4': '3',
             'drink5': '0'
            }

# removes 'drink5': '0'
filteredDict = {k: v for k, v in drinkDict.items() if v != '0'}

# [('drink2', '1'), ('drink1', '2'), ('drink4', '3'), ('drink3', '4')]
sortedItems = sorted(filteredDict.items(), key=operator.itemgetter(1))

A: You have printed the first item of sorted_x, and you can see it's a tuple, not a string. Checking if the string 'drink_1' is in sorted_x is never going to work.
As Daniel noted in the comment, you probably don't want to work with a sorted list of tuples, it's much easier to do lookups on the dict you have:
if 'drink1' in drinkDict:
   ...

Also note that you sort on the values, which are strings and not numbers. That means that you sort them alphabetically and not numerically. You might want to adjust the sorting key to convert them to float, or just store them as floats to begin with.

redpajama_set_name: RedPajamaStackExchange


text:
Q: excluded_categories parameter in next_post_link() behaving unexpectedly I have a Wordpress template with a single.php page. The page has "next" and "previous" arrows to allow navigating through all posts. I want to exclude posts from some categories from being included in the "next" and "previous" calculation. I have this code:
 // in single.php
 next_post_link( '%link', '← Previous', false, '11 and 13 and 15');

This should show the link to the next post. Posts in categories 11, 13, and 15 should not be considered as per the $ignore_categories parameter.
This works for posts that have only one of the categories listed set, e.g. 15. But posts that  additionally have a non-excluded category (like 16 or 23), do not get excluded and they show up as the next post link.
Is this  the intended behaviour? It doesn't seem to make sense to me.
Is there anything I can do to change it so a post gets excluded whenever it has one of the excluded categories, short of rebuilding the entire functionality?

A: It makes perfect sense, but kind of backwards. I think the query that is executed to "exclude" posts from categories is grabbing all of the categories (this may return category IDs 1, 2, 5, 7, 11, 13, 15, 16, and 23) initially then checking the "exclude_category" param ("11 and 13 and 15") and running the query to grab all posts that BELONG in categories 1, 2, 5, 7, 16, and 23 (skipping over 11, 13, and 23). So technically the returned result is indeed correct.
So you can write a function similar to what i've pasted below:
function prev_next_dont_include( $ids ) {
foreach ( get_categories() as $category ) : // loop thru all WP cats
    if ( !in_array( $category->cat_ID, $ids ) ) : // check if cat id is in $ids
        $categories[] = $category->cat_ID; // build list of real excluded ids
    endif;
endforeach;
return implode( ' and ', $categories ); // "1 and 2 and 5 and 7 and 16 and 23"
}

Now you can use that like this:
previous_post_link('%link',  __( '← Previous Article', 'twentyeleven' ), false, prev_next_dont_include( array( 11, 12, 15 ) ) );

Hopefully this will help someone out as it sure saved me.


text:
Q: Does Adventure Sync also track distance? Adventure Sync can now be activated to track your steps (like a pedometer) while your phone is locked.  Will Pokemon GO still track distance (with GPS) when the phone is unlocked and Pokemon GO running?
I do a bit of bike riding and do not want to lose out on the current (GPS) distance system.  If both tracking systems work, Adventure Sync would be nice to be able to also count my steps around the office and house.

A: Yes, it will still track your progress.
Admittedly, I know this out of ignorance of how the app actually worked to begin with. I was unsure as to how the app tracked the progress of my Pokémon Go progress, so I continued to leave the app open as I walked, and I eventually received an alert - "You have walked 5km", and received 20 Pokeballs upon collection.
The idea of the app is that you don't need to keep the app open, but in doing so, you won't be able to visit Pokestops, or gyms, or catch Pokémon with the app closed - it is used purely to help collect candies for your Buddy, and hatch eggs.

A: Yes, Adventure Sync also tracks distance.
I tested by locking the phone and riding my bike.  The distance ridden did not show up immediately, but it did show up in the app.
If you are using Android, be sure to have Google Fit installed and configured.
Note: If you open the app, distance is tracked as normal (without the refresh lag).


text:
Q: Flutter : How can I get Value of a varibale from a Async method and pass it to Text Widget? I want to show the user some weather data [temperature, condition, cityName]. I am getting the weather data(jsonDecoded) using an Asynchronous method. But I am unable to pass that data to the Text widget. I have tried this Way, but the Text widget shows Null in the emulator.

Here is my Code-
class _MyHomePageState extends State<MyHomePage> {

///want to pass this data to text Widget
var temperature;
var condition;
var cityName;

 initState() {
 LocationData();
}

var Longtitude;
var Latitude;

// By this method I am getting weatherData from another class
LocationData() async {
getlocation GetLocation = getlocation();
await GetLocation.determinePosition();

Latitude = GetLocation.Lattitude;
Longtitude = GetLocation.Longtitude;

NetworkHelper networkHelper = NetworkHelper(
    'https://api.openweathermap.org/data/2.5/weather?
     lat=$Latitude&lon=$Longtitude&appid=$apiKey');

var weatherData = await networkHelper.getData();

temprature = weatherData['main']['temp'];
condition = weatherData['weather'][0]['id'];
cityName = weatherData['name'];

}

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Center(
         child: Column(
           mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                Text(
                temprature.toString(),
                style: MyTextStyle,
                            ),
                Text(
                condition.toString(),
                style: MyTextStyle,
                            ),
                Text(
                cityName.toString(),
                style: MyTextStyle,
                            )
             ],
           ),
         ),
       ),
     );

     // TODO: implement build
     throw UnimplementedError();
  }
 }

A: Try doing this after you've fetched the weatherData:
setState(() {
  temprature = weatherData['main']['temp'];
  condition = weatherData['weather'][0]['id'];
  cityName = weatherData['name'];
});

There are more things you will run into that won't be top-notch... I suggest that you e.g. checkout the FutureBuilder() widget and see how that could be used in your case.

A: If in LocationData method if you're getting the correct value in temperature, condition and cityname then issue with you're not using setState there.
As widget will not re-render until setState is used and thus variable displays old values there for temperature/condition.
Use setState in LocationData.
setState(() {
  temprature = weatherData['main']['temp'];
  condition = weatherData['weather'][0]['id'];
  cityName = weatherData['name'];
});


text: Q: How do I write a sample space notationally, given a combination? Say I have $\beta_1, \beta_2, \beta_3, ... \beta_n$. How do I write the notation for the sample space of, say, the products of $nC2$ of them, i.e. {$(\beta_1*\beta_2),(\beta_1*\beta_3),...(\beta_{n-1}*\beta_n)$}? I want to be able to iterate through the list, and be able to multiply each of those elements in that sample space by some function, for example.


text:
Q: How do I import the _id index from a MongoDB collection as a hash index for a PostgreSQL table (from a CSV export from MongoDB)? I want to be able to keep track of the _id index values that get the MongoDB collection uses when I export the MongoDB collection (via CSV) and import the data into a PostgreSQL DB table (basically for archiving older data not frequently reported on from a MongoDB collection to a PostgreSQL DB table).
That said, if I ever wanted to add the records back into MongoDB for any reason, I want to ensure that the _id MongoDB collection values stay aligned with other collections in MongoDB and tables in PostgreSQL.
MongoDB uses a BSON object 24 character hash for its index (_id) and I want to be able to archive the data from MongoDBto a PostgreSQL DB using that _id value. It looks like it's possible to set a PostgreSQL table column datatype to character(24) and set it to the primary key as a hash using CREATE INDEX idx_hash ON 'pg_table_name_goes_here' USING HASH (_id); rather than requiring it to be a BSON like I originally though I would have to do, but will that work in a typical PostgreSQL table JOIN? and is there a better way to do this?
To put it another way, I'm taking a fair amount of data (about 5 to 8+ Million records a month) that is originating from a MongoDB and trying to archive previous/older data into PostgreSQL. So I want to keep that archived data in PostgreSQL exactly (or as close as possible) the same, in the event I might want to move the archived PostgreSQL back into some kind of NoSQL datastore in the future. In the meantime, I want to make querying the data in PostgreSQL as fast as possible. I want identical index columns / values.
Is this possible (using PostgreSQL v12 and MongoDB v4.4)?
I've been going down some pretty deep rabbit holes and finding a lot of weird and bizarre things about PostgreSQL.  I've traditionally used the MySQL family of Relational DBs and PostgreSQL has some great features but it's been a little more awkward to get the hang of than I expected.  I stumbled across this video series, and it makes sense: idx and seems to fit my use case as well as line up with your above comment. FWIW I did find this: pgbson but the complexity for deployments doesn't seem worth it.

A:
MongoDB uses a BSON object 24 character hash for its index (_id)

Values are stored in columns in a relational database, not "in an index". To store such a character (aka "string") value, create a column of type varchar(24) to hold the _id value from MongoDB.
If you want to ensure uniqueness, then create a unique B-Tree index on the column or defined it as the primary key.
Something along the lines:
create table mongo_data
(
  id varchar(24) primary key,
  ... other columns ...
);

The fact that the value is computed by a "hash algorithm" in MongoDB has nothing to do with a "hash index" in Postgres.


text:
Q: How can I add the most common mercurial commands to an Eclipse toolbar? I'm sick of doing Right Click -> Team -> Commit etc. every time I want to access a Mercurial command, and I'm not inclined to learning new keyboard shortcuts.

Is there an easy way to add the most important Mercurial commands
  (push, pull, commit, update, merge, ...) to an Eclipse toolbar
without writing my own plugin to do the job?

It's possible for git (right click on toolbar -> customize perspective -> git), so I'm having a hard time believing that nobody came up with a plugin to accomplish the same for Mercurial.
All I found after an extensive search was this unassigned proposal in the issue tracker of the MercurialEclipse plugin bitbucket repository. It has had the status new even though it was proposed nearly three years ago, so I don't suppose the developer is going to implement it in the near future...
Any pointers in the right direction would be greatly appreciated.

A: I don't think that there is a way to add custom toolbars to Eclipse without writing a plug in to do it.  Other people have asked similar questions: How do I add buttons to the Eclipse toolbar?
The top answer for How to add undo / redo buttons to toolbar in Eclipse? does seem to indicate that it's not too hard to write a plugin for Eclipse.  You'd have the task of finding out correct command ids to be able to do this.
Alternatively, you could show the Team Synchronize view which would then need you to right click on the Uncommitted node and select Commit.  Not many fewer clicks but less mouse travelling.


text:
Q: Java Socket connection from app to java server I am setting up an chat app. I have a server, written in java with socket, that connects perfectly to an example code in java. But when I try the exact same code with android studio over the app it doesnt work for some reason.
I have tried to run it with a code outside of the app and it worked. I have got the user permissions on so it can connect to the internet. I have tried to connect to the server on the console and it worked.
The client:
class Client implements Runnable{
    int freePort;

    @Override
    public void run() {
        connect();
    }

    private void connect(){
        System.out.println("Connecting");
        try {
            Socket socket = new Socket("localhost",1336);
            System.out.println("Connected");
            DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
            freePort = dataInputStream.readInt();
            System.out.println(freePort);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

The server:

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

public class DeclarationServer {
    private int numberOfClients = 0;
    DeclarationServer(){
        try {
            ServerSocket serverSocket = new ServerSocket(1336);
            while (true) {
                System.out.println(serverSocket.getLocalPort() + "__" + serverSocket.getLocalSocketAddress());
                Socket socket = serverSocket.accept();

                System.out.println(socket.getLocalSocketAddress());
                DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
                dataInputStream.readUTF();
                DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
                dataOutputStream.writeInt(1339+numberOfClients);
                dataOutputStream.flush();
                dataOutputStream.close();
                numberOfClients++;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

The error message:
I/System.out: Connecting
D/ActivityThread: add activity client record, r= ActivityRecord{5f45e99 token=android.os.BinderProxy@712539a {com.example.birke.testapp/com.example.birke.testapp.MainActivity}} token= android.os.BinderProxy@712539a
D/ZrHung.AppEyeUiProbe: notify runnable to start.
W/System.err: java.net.ConnectException: failed to connect to localhost/127.0.0.1 (port 1336) from /:: (port 32940): connect failed: ECONNREFUSED (Connection refused)
        at libcore.io.IoBridge.connect(IoBridge.java:137)
        at java.net.PlainSocketImpl.socketConnect(PlainSocketImpl.java:137)
        at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:391)
        at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:231)
        at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:213)
        at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:436)
        at java.net.Socket.connect(Socket.java:621)
        at java.net.Socket.connect(Socket.java:570)
        at java.net.Socket.<init>(Socket.java:450)
        at java.net.Socket.<init>(Socket.java:218)
W/System.err:     at com.example.birke.testapp.Client.connect(MainActivity.java:151)
        at com.example.birke.testapp.Client.run(MainActivity.java:145)
        at java.lang.Thread.run(Thread.java:784)
    Caused by: android.system.ErrnoException: connect failed: ECONNREFUSED (Connection refused)
        at libcore.io.Linux.connect(Native Method)
        at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:118)
        at libcore.io.IoBridge.connectErrno(IoBridge.java:151)
        at libcore.io.IoBridge.connect(IoBridge.java:129)
        ... 12 more

A: Look into this line,

failed to connect to localhost/127.0.0.1 (port 1336) from /:: (port
  32940): connect failed: ECONNREFUSED (Connection refused)

That means, the localhost is refusing the connection most probably, the service/server is not running on the specific port. You would be able to connect to the localhost if the server was running in the same android device.
Solution
Pass the IP (private IP if both client and server are in the same network otherwise public IP) of the server instead of localhost while initializing Socket,
Socket socket = new Socket("192.168.XXX.XXX",1336);


text:
Q: PATH doesn't change after restart Mac OS I've got stuck with it.
I try to edit path in order to work with mysql from iTerm.
I tried different ways to edit my PATH:
1) typing command in terminal export PATH="/usr/local/mysql/bin:$PATH"
2) edit .bash_profile
3) edit .bashrc
Everything works pretty well until I restart my Mac.
Here is what my constant PATH looks like
echo $PATH
/Users/lyubakov/.nvm/versions/node/v6.2.2/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin

A: On MAC OS X there is no use of ~/.bash_profile but ~/.bashrc.
make sure you hadn't override PATH in other places that run after the line you added.
You didn't give us enough information of your system configuration... such as the bashrc, bash_profile of the user.

A: @Alex Lyubakov - Any Question ? If you use the zsh they never reads the profiles from the bash.
you must change the zsh profiles like .zshrc
at the end of man zsh is a list of files where you can do your changes


text:
Q: Reporting Stepwise Regression G'day. For my research i calculated a backward stepwise regression for my first time using
step(lm(Outcome ~ Predictor1 + Predictor2 + Predictor1*Predictor2, data = df),direction="backward")

receiving the results.
But now i am a not sure what exactly to report. Are there certain values who are standard to report in a stepwise regression?


text:
Q: Recover master key from active LUKS partition I have an open LUKS partition (open meaning that it is decrypted and mounted) the passphrase to which I would like to recover. It used to be possible to just add a new key slot by recovering the master key and using this to set the new slot as described in section 6.10 of the FAQ here. However, this does not work for the device in question. The command
dmsetup table --target crypt --showkey /dev/mapper/<device>

is, according to the FAQ, supposed to print something like (this is not my key, this is copied from the FAQ):
0 200704 crypt aes-cbc-essiv:sha256 a1704d9715f73a1bb4db581dcacadaf405e700d591e93e2eaade13ba653d0d09 0 7:0 4096

where the a1704d9715f73a1bb4db581dcacadaf405e700d591e93e2eaade13ba653d0d09 bit is the key. Instead, I now get
[...] :64:logon:cryptsetup:<device UUID> [...]

in this position. For this device, which is an external USB drive. For internal disks, it works as expected.
The device UUID it prints is the same as the one you get in the UUID line when calling
sudo cryptsetup luksDump /dev/<USB device>

This seems to be the case for all encrypted external disks (as opposed to internal drives, for which it works as expected). I do not understand why there should be this kind of difference between internal and external disks. As far as I can tell the encryption is the same (twofish-xts-essiv:sha256), cryptsetup version is 2.0.2. Kernel is 4.15.0.
EDIT: I notice that it may have something to do with this, that somehow there was a version change from LUKS1 to LUKS2 with keys not being accessible from userspace any longer in LUKS2. I still do not understand, however, why there would be this difference between internal and external disks; I used the same LUKS version to decrypt/open them.


text:
Q: Dompdf Create a A4 page with 4 equals parts I try to create a A4 page with 4 parts.
There is a white separator between the 2 first squares and the it breaks the page at square 3.
And quite strange the image does not appear in square 3!

<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Header and Footer example</title>

Square 1

Square 2

Square 3

Square 4

The PHP part is quite basic:
$options = new \Dompdf\Options();
$options->set('isRemoteEnabled', true);
$options->set('isPhpEnabled', true);
$dompdf = new \Dompdf\Dompdf($options);
$dompdf->set_option('dpi', 300);
$dompdf->set_paper('A4', 'portrait');
$dompdf->load_html($html);
$dompdf->render();
$output = $dompdf->output();
file_put_contents('test.pdf', $output);

NOTE
I also tried with tables but with same issue.

  Square 1
  Square 2

  Square 3
  Square 4

[![enter image description here][1]][1]
[![enter image description here][2]][2]
[1]: https://i.stack.imgur.com/AIqek.png
[2]: https://i.stack.imgur.com/VFpMs.png


text:
Q: web application architecture (javascript client side + ASP.NET server side) This question comes from the following post:
OWIN cookie authentication get roles on client side
I've created a separate thread for the question since it is more general than one in the post above.
In short:
Let's say we have a web application with javascript as client side + ASP.NET web api as server side and also an identity server. Only authenticated users can access web api endpoints, some of them accessible only for specific roles of user.
Now the client side of application should show specific items based on what role user is in. For example: user in administrator role can see an extra tab: manage items. There are two approaches to achieve this:

*

*When rendering client side application, one could call an endpoind in web api which would return what roles user have. Based on that result, show/hide items in html.

*When application loads, an endpoint, which returns how the structure should look like (for example: json string) would be returned, and based on that structure client application would be rendered. No show/hide html on client side based on roles in such case.
Now regarding 1st point: some could argue that there is a security leak, since malicious user can modify html to see elements that he is not supposed to see. But in this case he will not see any content from database and will not be able to load/update it since he will not be authorized to do that based on his role which is checked in server side.
2nd point seems more valid since we keep all identity related information logic on server side. And also all unnecessary content is not in html (while in 1st point it's hidden) - so that leads to better performance? In this case though if for example developing angular application, the json structure of application should include such information as name of angular controller and route for example. Would that not add complexity to developing application?
Assume that the application itself have a lot of roles and a lot of items should be visible/not visible based on these roles.
Pros/cons between 1st and 2nd? Thanks!

A: I stick always with the first suggested point.
As you mentioned the second choice will add more complexity for developing. For the 1st there is no security leak. If you don't want your users to modify the html and to access forbidden areas in your application simply use ng-if instead of ng-show. If you are not familiar - ng-if will not just hide the content with display: none;. It will completely remove it from the DOM and this leading the user unable to show that content as it is not in the DOM.
Read this for more detailed explanation for ng-if and ng-show: what is the difference between ng-if and ng-show/ng-hide
I usually have an endpoint getting information about the user - including it's role and save that user into a service (factory). This gives me the flexibility to use it everywhere in the application and check if the user has access or not to certain parts of it.


text:
Q: KeyError when training a model with pyspark.ml on AWS EMR with data from s3 bucket I am training a machine learning model with pyspark.ml on .json data from an s3 bucket on AWS EMR in a JupyterLab notebook. The bucket is not mine, but I think access works fine because data preprocessing, feature engineering etc. works fine. But when I call the cv.fit(training_data) function, the training process runs until it almost finishes (indicated by the status bar), but then throws an error:
Exception in thread cell_monitor-64:
Traceback (most recent call last):
  File "/opt/conda/lib/python3.7/threading.py", line 917, in _bootstrap_inner
    self.run()
  File "/opt/conda/lib/python3.7/threading.py", line 865, in run
    self._target(*self._args, **self._kwargs)
  File "/opt/conda/lib/python3.7/site-packages/awseditorssparkmonitoringwidget-1.0-py3.7.egg/awseditorssparkmonitoringwidget/cellmonitor.py", line 178, in cell_monitor
    job_binned_stages[job_id][stage_id] = all_stages[stage_id]
KeyError: 6571

I could not find any information on this error yet. What is going on?
This is my pipeline:
train, test = clean_df.randomSplit([0.8, 0.2], seed=42)

va1 = VectorAssembler(inputCols="vars", outputCol="vars")

scaler = StandardScaler(inputCol="to_scale", outputCol="scaled_features")

va2 = VectorAssembler(inputCols=["more_vars","scaled_features"], outputCol="features")

gbt = GBTClassifier()

pipeline = Pipeline(stages=[va1, scaler,va2,gbt])

paramGrid = ParamGridBuilder()\
    .addGrid(gbt.maxDepth, [2, 5])\
    .addGrid(gbt.maxIter, [10, 100])\
    .build()

crossval = CrossValidator(estimator=pipeline,
                          estimatorParamMaps=paramGrid,
                          evaluator=MulticlassClassificationEvaluator(metricName='f1'),
                          numFolds=3)

cvModel = crossval.fit(train)

Second, I have a hunch that I might by resolved in Python 3.8; can I install Python 3.8 on EMR?

A: We are having the same problem. We are using Hyperopt and we just added try except to avoid this issue. The Error keeps appearing but it keeps running.
It seems that the error affects the bars showing the progress inside the spark jobs on the EMR notebook but it completes the pipeline.
# Defining the hyperopt objetive
def objetive(params):
    try:
        # Pipeline here with Vector Assembler and GBT
        return {'loss': -metrics_val.areaUnderPR,
                "status": STATUS_OK,
                "output_dict": output_dict}
    except Exception as e:
        print("## Exception", e)
        return {'loss': 0,
                "status": STATUS_FAIL,
                "except": e,
                "output_dict": {"params": params}}

The Exception we got is the following:
Exception in thread cell_monitor-18:
Traceback (most recent call last):
  File "/opt/conda/lib/python3.7/threading.py", line 926, in _bootstrap_inner
    self.run()
  File "/opt/conda/lib/python3.7/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "/opt/conda/lib/python3.7/site-packages/awseditorssparkmonitoringwidget-1.0-py3.7.egg/awseditorssparkmonitoringwidget/cellmonitor.py", line 178, in cell_monitor
    job_binned_stages[job_id][stage_id] = all_stages[stage_id]
KeyError: 2395

But we got the output from all hyperopt:
100%|##########| 5/5 [34:36<00:00, 415.32s/trial, best loss: -0.3907675279893325]

A: This is not an error in your code. The key error is referencing the stage number which does not exist. It is some kind of internal Spark monitoring error. I do not However, it does not seem to affect the running of the application.


text:
Q: rank with the sum Below is the table:
category         weightage      As_of_date
123abc           50             1/1/2020
456abc           100            1/2/2020
456abc           100            1/3/2020
678def           200            1/4/2020
678def           200            1/4/2020
123def           50             2/1/2020
123def           50             2/1/2020
123def           50             2/3/2020
123def           50             2/1/2020
123def           50             6/7/2020

where I want to rank the category based on weightage desc, expected results:
category         weightage      As_of_date     dense_rank
123abc           50             1/1/2020       4
456abc           100            1/2/2020       3
456abc           100            1/3/2020       3
678def           200            1/4/2020       1
678def           200            1/4/2020       1
123def           50             2/1/2020       2
123def           50             2/1/2020       2
123def           50             2/3/2020       2
123def           50             2/1/2020       2
123def           50             6/7/2020       2

what was already tried: select desnse_rank() over (partition by category order by weightage desc), but I need to rank it based on sum(weightage) per category.

A: With a CTE you can do the calculations one by one. First calculate the dense rank for sum per category (ranked_by_sum), then join back to the original table to get the dense rank value for the individual rows:
WITH test_data (category, weightage, as_of_date) AS
(
SELECT '123abc',50, TO_DATE('1/1/2020','DD/MM/YYYY') FROM DUAL UNION ALL
SELECT '456abc',100,TO_DATE('1/2/2020','DD/MM/YYYY') FROM DUAL UNION ALL
SELECT '456abc',100,TO_DATE('1/3/2020','DD/MM/YYYY') FROM DUAL UNION ALL
SELECT '678def',200,TO_DATE('1/4/2020','DD/MM/YYYY') FROM DUAL UNION ALL
SELECT '678def',200,TO_DATE('1/4/2020','DD/MM/YYYY') FROM DUAL UNION ALL
SELECT '123def',50, TO_DATE('2/1/2020','DD/MM/YYYY') FROM DUAL UNION ALL
SELECT '123def',50, TO_DATE('2/1/2020','DD/MM/YYYY') FROM DUAL UNION ALL
SELECT '123def',50, TO_DATE('2/3/2020','DD/MM/YYYY') FROM DUAL UNION ALL
SELECT '123def',50, TO_DATE('2/1/2020','DD/MM/YYYY') FROM DUAL UNION ALL
SELECT '123def',50, TO_DATE('6/7/2020','DD/MM/YYYY') FROM DUAL
), ranked_by_sum (category,sum_weightage, drnk)
AS
(
SELECT category, SUM(weightage),DENSE_RANK () OVER (
        ORDER BY SUM(weightage) DESC )
  FROM test_data
  GROUP BY category
)
SELECT t.category, t.weightage, t.as_of_date, r.drnk
  FROM test_data t
       JOIN ranked_by_sum r ON t.category = r.category
  ORDER BY r.drnk DESC

CATEGO  WEIGHTAGE AS_OF_DATE        DRNK
------ ---------- ----------- ----------
123abc         50 01-JAN-2020          4
456abc        100 01-FEB-2020          3
456abc        100 01-MAR-2020          3
123def         50 02-JAN-2020          2
123def         50 06-JUL-2020          2
123def         50 02-JAN-2020          2
123def         50 02-JAN-2020          2
123def         50 02-MAR-2020          2
678def        200 01-APR-2020          1
678def        200 01-APR-2020          1

A: You can do it without a self-join using SUM as an analytic function in a nested sub-query:
SELECT category,
       weightage,
       as_of_date,
       DENSE_RANK() OVER (ORDER BY total_weightage DESC) AS dense_rank
FROM   (
  SELECT t.*,
         SUM(weightage) OVER (PARTITION BY category) AS total_weightage
  FROM   table_name t
)

Which, for the sample data:
CREATE TABLE table_name (category, weightage, as_of_date) AS
SELECT '123abc',50, DATE'2020-01-01' FROM DUAL UNION ALL
SELECT '456abc',100,DATE'2020-02-01' FROM DUAL UNION ALL
SELECT '456abc',100,DATE'2020-03-01' FROM DUAL UNION ALL
SELECT '678def',200,DATE'2020-04-01' FROM DUAL UNION ALL
SELECT '678def',200,DATE'2020-04-01' FROM DUAL UNION ALL
SELECT '123def',50, DATE'2020-01-02' FROM DUAL UNION ALL
SELECT '123def',50, DATE'2020-01-02' FROM DUAL UNION ALL
SELECT '123def',50, DATE'2020-03-02' FROM DUAL UNION ALL
SELECT '123def',50, DATE'2020-01-02' FROM DUAL UNION ALL
SELECT '123def',50, DATE'2020-07-06' FROM DUAL;

Outputs:

CATEGORY
WEIGHTAGE
AS_OF_DATE
DENSE_RANK

678def
200
01-APR-20
1

678def
200
01-APR-20
1

123def
50
02-JAN-20
2

123def
50
02-MAR-20
2

123def
50
06-JUL-20
2

123def
50
02-JAN-20
2

123def
50
02-JAN-20
2

456abc
100
01-MAR-20
3

456abc
100
01-FEB-20
3

123abc
50
01-JAN-20
4

db<>fiddle here


text:
Q: React Native app not building for Android - SyntaxError: \u can only be followed by a Unicode character sequence My App is running fine on iOS but will not run on Android. I spent ages last week getting it working, and thought it was , and the problem has returned.

Logs show
Full logs here in case there is other stuff relevant. https://pastebin.com/by6uCmPW
SyntaxError: \u can only be followed by a Unicode character sequence

When I reload I then get a white screen, no errors are shown, and I can't get past this, and it does not change whether i connect to the debugger or not.

I've looked at the source and the error is coming from the following line

Which is this from the React Native source https://github.com/facebook/react-native/blob/a974c140db605ecbdf8d3faa7a079b7e2dcebb09/Libraries/ReactNative/YellowBox.js#L263
After refreshing, I get the following error in logcat, although nothing in the emulator.

06-14 13:52:10.467: E/art(2691): No implementation found for
  com.facebook.react.bridge.Inspector
  com.facebook.react.bridge.Inspector.instance() (tried
  Java_com_facebook_react_bridge_Inspector_instance and
  Java_com_facebook_react_bridge_Inspector_instance__)

A: Ok, I had the same issue and this is the solution I came up with that in order to make it work, I've added console.disableYellowBox = true; to index.android.js after the all imports lines.

As per React Native docs
YellowBoxes can be disabled during development by using console.disableYellowBox = true;. Specific warnings can be ignored programmatically by setting an array of prefixes that should be ignored: console.ignoredYellowBox = ['Warning: ...'];.

RedBoxes and YellowBoxes are automatically disabled in release (production) builds.

It's not an ideal workaround and probably still require some tinkering but by doing that I was able to compile the app.
Then in order to go a couple of steps deeper, I removed the recent addings (console.disableYellowBox = true; from index.android.js) and
replaced {stacktraceVisible ? '\u{25BC}' : '\u{25B6}'} Stacktrace from \src\node_modules\react-native\Libraries\ReactNative\YellowBox.js
with one of those next things:

*

*{stacktraceVisible ? '\u25BC' : '\u25B6'} Stacktrace

*{stacktraceVisible ? '-' : '-'} Stacktrace
It seems to fix the problem but not sure how elegant this way is and how you would be able to update every time after yarn or npm i.

A: What oddly worked for me was moving the entire project into another folder


text:
Q: Error when Azure Logic Apps Reply to Email in Outlook.com with HTML content I am using Azure logic apps to auto-reply email using outlook.com connector.
When I use plain text in the reply it works fine like following:

It works as intended and replies to the new email with the text.
But when I use HTML in the comment it gives error:
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.

Is it possible to include HTML in the email reply action for outlook.com in logic apps?


text:
Q: CSS styles are not working in my jsp file im my java ee jsp-servlet application I am building a web application in using JSP/Servlet and I'm having issues applying my CSS styles in my JSP files. All my JSP are in WEB-INF/ directory and my CSS file is the styles directory at the same level as the WEB-INF. I am using Eclipse Oxygen.
Here is the directory structure of my web app.

Here the content of my web.xml file
<servlet>
    <servlet-name>home</servlet-name>
    <servlet-class>com.skillupsoft.tp.servlets.HomeServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>home</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <servlet>
    <servlet-name>CreationClient</servlet-name>
    <servlet-class>com.skillupsoft.tp.servlets.CreationClient</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>CreationClient</servlet-name>
    <url-pattern>/creationClient</url-pattern>
  </servlet-mapping>

  <servlet>
    <servlet-name>CreationCommande</servlet-name>
    <servlet-class>com.skillupsoft.tp.servlets.CreationCommande</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>CreationCommande</servlet-name>
    <url-pattern>/creationCommande</url-pattern>
  </servlet-mapping>

Here is CreationCommande servlet.
public class CreationCommande extends HttpServlet {

    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        this.getServletContext().getRequestDispatcher("/WEB-INF/creerCommande.jsp").forward(request, response);

    }
}

And here is my jsp file : creerCommande.jsp
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Création d'une commande</title>
<link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/styles/style.css"/>

        <form action="creationCommande" method="get">
            <fieldset>
                <legend>Informations client</legend>
                Nom*
                <input type="text" id="nomClient" name="nomClient"
                        value="" size="20" maxlength="20">

                Prénom
                <input type="text" id="prenomClient" name="prenomClient"
                        value="" size="20" maxlength="20">

                Adresse de livraison*
                <input type="text" id="adresseClient" name="adresseClient"
                        value="" size="20" maxlength="20">

                Numéro de téléphone*
                <input type="text" id="telephoneClient" name="telephoneClient"
                        value="" size="20" maxlength="20">

                Adresse email
                <input type="email" id="emailClient" name="emailClient"
                        value="" size="20" maxlength="60">

            </fieldset>
            <fieldset>
                <legend>Informations commande</legend>

                Date *
                <input type="text" id="dateCommande" name="dateCommande"
                        value="" size="20" maxlength="20" disabled="disabled">

                Montant*
                <input type="text" id="montantCommande" name="montantCommande"
                        value="" size="20" maxlength="20">

                Mode de paiement*
                <input type="text" id="modePaiementCommande" name="modePaiementCommande"
                        value="" size="20" maxlength="20">

                Statut de paiement
                <input type="text" id="statutPaiementCommande" name="statutPaiementCommande"
                        value="" size="20" maxlength="20">

                Mode de livraison
                <input type="text" id="modeLivraisonCommande" name="modeLivraisonCommande"
                        value="" size="20" maxlength="20">

                Statut de la livraison
                <input type="text" id="statutLivraisonCommande" name="statutLivraisonCommande"
                        value="" size="20" maxlength="20">

            </fieldset>
            <input type="submit" value="Valider">
            <input type="reset" value="Remettre à zéro">
        </form>

Notice that I've referenced my css file il the jsp code like this:
<link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/styles/style.css"/>
I am a little bit confuse because this code worked last week and today it does'nt work anymore.
Thanks

A: The location of static web assets are mal-configured in your project.
Move the styles folder into WEB-INF folder. It will work fine.

A: First make a resources folder inside webcontent. Then move css folder inside resources folder. Now In your servlet-context.xml file write
<resources mapping="/resources/**" location="/resources/"/>

And in your jsp page write
<link rel="stylesheet" type="text/css" href="
      <c:url value="/resources/css/style.css"/> "/>

If you haven't add jstl add
<dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

in your pom.xml
And add this tag <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
on the top of jsp page.


text:
Q: Entity Framework 6 - Dependency Injection with Unity - Repository pattern - Add or Update exception for many to many relationship I have a problem when adding new values with a many to many mapping in Entity Framework. I know about the unit of work pattern but in our solution we would like to keep a simple repository pattern and not a unit of work class that contains everything. Is this possible or should I just implement Unit of Work right away?
If I don't use iSupplierRepository below a supplier will be added, but it will always add a new one even though there already exists one with that name.
Error:

The relationship between the two objects cannot be defined because
  they are attached to different ObjectContext objects.

Repository example:
public class SupplierRepository : IntEntityRepository<Supplier, DbContext>, ISupplierRepository
{
    public SupplierRepository(DbContext context) : base(context, context.Suppliers)
    {
    }
}

Inherited repositories:
public class IntEntityRepository<TEntity, TContext> : EntityRepository<TEntity, TContext, int>
    where TEntity : class, IEntity<int>
    where TContext : BaseIdentityDbContext
{
    public IntEntityRepository(TContext context, IDbSet<TEntity> set) : base(context, set)
    {
    }

    public override async Task<TEntity> GetAsync(int id)
    {
        return (await GetAsync(entity => entity.Id == id)).SingleOrDefault();
    }
...

 public abstract class EntityRepository<TEntity, TContext, TId> : IEntityRepository<TEntity, TId>
    where TEntity : class, IEntity<TId>
    where TContext : BaseIdentityDbContext
{
    protected TContext Context { get; }
    protected IDbSet<TEntity> Set { get; }

     protected EntityRepository(TContext context, IDbSet<TEntity> set)
     {
         Context = context;
         Set = set;
     }

     public abstract Task<TEntity> GetAsync(TId id);
...

Unity:
container.RegisterType<ISupplierRepository, SupplierRepository>();
container.RegisterType<IContactRepository, ContactRepository>();

Controller:
private readonly IContactRepository iContactRepository;
private readonly ISupplierRepository iSupplierRepository;

public ContactsController(IContactRepository iContactRepository, ISupplierRepository iSupplierRepository)
{
    this.iContactRepository = iContactRepository;
    this.iSupplierRepository = iSupplierRepository;
}

[HttpPut]
[Route("UpdateContact/{id}")]
public async Task<IHttpActionResult> UpdateContact(ContactViewModel contactVm, int id)
{
    try
    {
        var supplierList = new List<Supplier>();
        foreach (var contactVmSupplier in contactVm.Suppliers)
        {
            var supplier = await iSupplierRepository.GetAsync(contactVmSupplier.Id);
            supplierList.Add(supplier);
        }

        var contactOriginal = await iContactRepository.GetAsync(id);
        var updatedContact = Mapper.Map<ContactViewModel, Contact>(contactVm, contactOriginal);
        updatedContact.Suppliers = supplierList;

        await iContactRepository.UpdateAsync(updatedContact);
        return Ok();
    }
    catch (Exception e)
    {
        throw new Exception("Could not update a contact", e);
    }

}

Viewmodels:
public class ContactViewModel
{
    public int Id { get; set; }

    public string Name { get; set; }

    public ICollection<SupplierViewModel> Suppliers { get; set; }
}

public class SupplierViewModel
{
    public int Id { get; set; }

    public string Name { get; set; }
}

Models:
public class Contact : IEntity<int>
{
    public Contact()
    {
        Suppliers = new List<Supplier>();
    }

    [Key]
    public int Id { get; set; }

    public DateTime Created { get; set; }

    public DateTime Updated { get; set; }

    public string Name { get; set; }

    public ICollection<Supplier> Suppliers { get; set; }

}

public class Supplier: IEntity<int>
{
    public Supplier()
    {
        Contacts = new List<Contact>();
    }
    [Key]
    public int Id { get; set; }

    public DateTime Created { get; set; }

    public DateTime Updated { get; set; }

    public string Name { get; set; }

    public virtual ICollection<Contact> Contacts { get; set; }
}

A: If you install the Unity bootstrapper for ASP.NET Web API package,  a UnityHierarchicalDependencyResolver is available which will use a new child container for each IHttpController resolution effectively making all registrations with a HierarchicalLifetimeManager resolved per request so that all repository instances in a controller will use the same DbContext.
The NuGet package will also install some bootstrapping code in App_Start which uses WebActivatorEx.  You can either use this approach or change to align with what you are using right now.  Based on your posted code it would look something like:
public static void ConfigureUnity(HttpConfiguration config)
{
    var container = new UnityContainer();
    container.RegisterType<DbContext>(new HierarchicalLifetimeManager());
    container.RegisterType<ISupplierRepository, SupplierRepository>();
    container.RegisterType<IContactRepository, ContactRepository>();
    config.DependencyResolver = new UnityHierarchicalDependencyResolver(container);
}

A: Update: Use Randy Levy's answer instead.

My recommendation here is not to use Repository or UoW at all. EF already has them implemented. You'll encounter a lot of issues trying to re-implement them.
As to specific issue you encounter with exception: you have to use the same DbContext for your entities. At the same time, you wouldn't like to use DbContext as Singleton and use it per-request instead. A possible solution for it might be found here.
Application_BeginRequest(...)
{
  var childContainer = _container.CreateChildContainer();
  HttpContext.Items["container"] = childContainer;
  childContainer.RegisterType<ObjectContext, MyContext>
     (new ContainerControlledLifetimeManager());
}

Application_EndRequest(...)
{
  var container = HttpContext.Items["container"] as IUnityContainer
  if(container != null)
    container.Dispose();
}

A: Solved it like this, dependency injection is from the tutorial Dependency Injection in ASP.NET Web API 2.
https://learn.microsoft.com/en-us/aspnet/web-api/overview/advanced/dependency-injection
App_Start -> WebApiConfig
public static void Register(HttpConfiguration config)
{
    UnityConfig.ConfigureUnity(config);
...

UnityConfig:
public static void ConfigureUnity(HttpConfiguration config)
{
    var context = new DbContext();
    var container = new UnityContainer();
    container.RegisterType<ISupplierRepository, SupplierRepository>(new InjectionConstructor(context));
    container.RegisterType<IContactRepository, ContactRepository>(new InjectionConstructor(context));
    config.DependencyResolver = new UnityResolver(container);
}


text:
Q: Plotting ellipses based on subset of data I'm comparing isotope data between two species of fish in R. Specifically, i want to look at niche size (roughly inferred by size of ellipse around the points). I've attached a plot to show the sort of plot I'm making (three fish on plot but one is being ignored statistically) Isotope plot
The problem is, my sample sizes are 68 for species 1 (blue marlin), and 15 for species 2 (striped marlin), and i need to examine the effect different sample sizes will have on the size of the 95% confidence ellipse.
How this issue is typically tackled is to essentially plot the 15 samples i have for species 2 against a subset of 15 samples from species 1. If the line of the ellipse is slightly transparent, and I plot it several 100 times, the darker areas will reveal the 'true niche'.
I have managed to plot my points, but have no idea how to plot 100s of ellipses based on random subsets of my data?
My data is set out in the following columns: 'fish.id' - which has blue marlin (BM) and striped marlin (SM); '15N' - which has my nitrogen values; and '13C' - which has my carbon values.
`fish.id`  `15N` `13C`
   <chr> <dbl> <dbl>
 1 BkM6F    14    15
 2 BkM7F    10    16
 3 BkM8F    11    16
 4 BkM9F    11    18
 5 BM12F    13    17
 6 BM14F    13    20
 7 BM17F    11    17
 8 BM18F    15    19
 9 BM19F    13    17
10 BM22F    13    16
# … with 79 more rows

This is what I have so far:
#plot with all points
plot(Isotope$`13C`,Isotope$`15N`,type='n',
     main = 'Marlin 13C vs 15N', xlab = '13C', ylab = '15N')
points(Isotope$`13C`[substr(Isotope$fish.id,1,2)=='Bk'],
       Isotope$`15N`[substr(Isotope$fish.id,1,2)=='Bk'], pch=15, col = 'black')
points(Isotope$`13C`[substr(Isotope$fish.id,1,2)=='BM'],
       Isotope$`15N`[substr(Isotope$fish.id,1,2)=='BM'], pch=16, col = 'dodgerblue3')
points(Isotope$`13C`[substr(Isotope$fish.id,1,2)=='SM'],
       Isotope$`15N`[substr(Isotope$fish.id,1,2)=='SM'], pch=17, col = 'cadetblue3')

#attempt at subsetting data
plot( )

for(i in 1:1000) {

  sampl1 <- sample(1:15,size=15,replace=TRUE)
  sampl2 <- sample(1:69,size=15,replace=TRUE)

  temp.data1 <- data1[sampl1,]
  temp.data2 <- data2[sampl2,]

}

Cheers for the help!

A: Here is something to get you started that takes my earlier comments into account. First, reproducible data so we are talking about the same thing:
dat <- structure(list(species = structure(c(1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("Bk", "BM"), class = "factor"),
    N15 = c(13.06, 11.57, 13.28, 13.45, 11.91, 12.01, 14.04,
    11.97, 13.46, 11.27, 13.37, 14.23, 11.32, 11.58, 12.1, 12.42,
    12.63, 11.52, 13.72, 12.3, 14.49, 14.01, 13.24, 15.03, 12.93,
    12.71, 13.1, 12.26, 14.74, 14.18), C13 = c(17.51, 15.37,
    15.4, 15.73, 16.84, 15.79, 16.78, 15.85, 18.32, 16.61, 17.07,
    18.05, 14.08, 15.9, 15.65, 18.27, 18.95, 18.46, 17.58, 18.24,
    16.28, 17.54, 16.65, 15.51, 18, 18.09, 17.42, 18.68, 18.38,
    16.62)), class = "data.frame", row.names = c(NA, -30L))
str(dat)
'data.frame':   30 obs. of  3 variables:
 $ species: Factor w/ 2 levels "Bk","BM": 1 1 1 1 1 1 1 1 1 1 ...
 $ N15    : num  13.1 11.6 13.3 13.4 11.9 ...
 $ C13    : num  17.5 15.4 15.4 15.7 16.8 ...

Making species a factor simplifies using it to specify colors, symbols:
idx <- as.numeric(dat$species)
sym <- 15:16
cls <- c("dodgerblue3", "cadetblue3")
col1 <- c(col2rgb(cls[1]))
col1 <- rgb(col1[1], col1[2], col1[3], 64, maxColorValue=255) # 25% transparency
col2 <- c(col2rgb(cls[2]))
col2 <- rgb(col2[1], col2[2], col2[3], 64, maxColorValue=255)
alpha.col <- c(col1, col2)

This creates symbols for each group, colors for each group, and transparent colors:
library(car)
plot(N15~C13, dat, xlim=c(12, 21), ylim=c(10, 17), xlab="13C", ylab="15N", pch=sym[idx], col=cls[idx])
dataEllipse(dat$C13, dat$N15, groups=dat$species, levels=.95, center.cex=1.25, add=TRUE, plot.points=FALSE,
     col=alpha.col)

Which creates the following plot:


text:
Q: 'Regular Expression' VS 'String Comparison operators / functions' This question is designed around the performance within PHP but you may broaden it to any language if you wish to.
After many years of using PHP and having to compare strings I've learned that using string comparison operators over regular expressions is beneficial when it comes to performance.
I fully understand that some operations have to be done with Regular Expressions down to there complexity but for operations that can be resolved via regex AND string functions.
take this example:
PHP
preg_match('/^[a-z]*$/','thisisallalpha');

C#
new Regex("^[a-z]*$").IsMatch('thisisallalpha');

can easily be done with
PHP
ctype_alpha('thisisallalpha');

C#
VFPToolkit.Strings.IsAlpha('thisisallalpha');

There are many other examples but you should get the point I'm trying to make.
What version of string comparison should you try and lean towards and why?

A: Looks like this question arose from our small argument here, so i feel myself somehow obliged to respond.
php developers are being actively brainwashed about "performance", whereat many rumors and myths arise, including sheer stupid things like "double quotes are slower". Regexps being "slow" is one of these myths, unfortunately supported by the manual (see infamous comment on the preg_match page). The truth is that in most cases you don't care. Unless your code is repeated 10,000 times, you don't even notice a difference between string function and a regular expression. And if your code does repeat 10,000 times, you must be doing something wrong in any case, and you will gain performance by optimizing your logic, not by stripping down regular expressions.
As for readability, regexps are admittedly hard to read, however, the code that uses them is in most cases shorter, cleaner and simpler (compare yours and mine answers on the above link).
Another important concern is flexibility, especially in php, whose string library doesn't support unicode out of the box. In your concrete example, what happens when you decide to migrate your site to utf8? With ctype_alpha you're kinda out of luck, preg_match would require another pattern, but will keep working.
So, regexes are not slower, more readable and more flexible. Why on earth should we avoid them?

A: Regular expressions actually lead to a performance gain (not that such microoptimizations are in any way sensible) when they can replace multiple atomic string comparisons. So typically around five strpos() checks it gets advisable to use a regular expression instead. Moreso for readability.
And here's another thought to round things up: PCRE can handle conditionals faster than the Zend kernel can handle IF bytecode.
Not all regular expressions are designed equal, though. If the complexetiy gets too high, regex recursion can kill its performance advantage. Therefore it's often reconsiderworthy to mix regex matching and regular PHP string functions. Right tool for the job and all.

A: PHP itself recommends using string functions over regex functions when the match is straightforward. For example, from the preg_match manual page:

Do not use preg_match() if you only want to check if one string is contained in another string. Use strpos() or strstr() instead as they will be faster.

Or from the str_replace manual page:

If you don't need fancy replacing rules (like regular expressions), you should always use this function instead of ereg_replace()  or preg_replace().

However, I find that people try to use the string functions to solve problems that would be better solved by regex. For instance, when trying to create a full-word string matcher, I have encountered people trying to use strpos($string, " $word ") (note the spaces), for the sake of "performance", without stopping to think about how spaces aren't the only way to delineate a word (think about how many string functions calls would be needed to fully replace preg_match('/\bword\b/', $string)).
My personal stance is to use string functions for matching static strings (ie. a match of a distinct sequence of characters where the match is always the same) and regular expressions for everything else.

A: They're both part of the language for a reason. IsAlpha is more expressive. For example, when an expression you're looking at is inherently alpha or not, and that has domain meaning, then use it.
But if it is, say, an input validation, and could possibly be changed to include underscores, dashes, etc., or if it is with other logic that requires regex, then I would use regex. This tends to be the majority of the time for me.

A: Agreed that PHP people tend to over-emphasise performance of one function over another. That doesn't mean the performance differences don't exists -- they definitely do -- but most PHP code (and indeed most code in general) has much worse bottlenecks than the choice of regex over string-comparison. To find out where your bottlenecks are, use xdebug's profiler. Fix the issues it comes up with before worrying about fine-tuning individual lines of code.


text:
Q: Horizontal list menu: Calculated equal % width I am very new to sass/compass and I am now experimenting with mixins. The example below shows the code for a simple ribbon style horizontal menu which is already inheriting @include horizontal-list mixin, bundled with compass.
This static menu has four list items and therefore I have set the li width as 25%
My question. Does Compass have a method for calculating an equal percentage width value for the list items in a dynamic menu with an undefined number of items?
Something like, Total li/100 = x% li width
    @mixin ribbon-menu {

        ul {
            padding: 0;
        }
        li {
            width: 25%;
            border-right: 1px solid $white;
            text-align: center;
        }
        li.last {
            border-left: 0;
        }
        li.leaf {
            padding: 0;
        }
        a {
            display: block;
            text-decoration: none;
            padding: 10px;
            color: $white;
        }
        a:link, a:visited {
            background: $black;
        }
        a:active, a:hover, a:focus {
            background: $red;
        }
}

A: Hopefully this will help you.
http://lea.verou.me/2011/01/styling-children-based-on-their-number-with-css3/
@for $i from 1 through 4 {
   li:first-child:nth-last-child(#{$i}),
   li:first-child:nth-last-child(#{$i}) ~ li {
   width: 100% / $i }
 }


text:
Q: Update all checkbox in nested recycler View when button in Fragment is clicked Hello I am struggling with this problem. I have a RecyclerView with checkboxes items which is nested in another RecyclerView. My problem is that I want all the checkbox to be unchecked when the user click in a button in the fragment. So how could I access the checkbox view holder from my fragment button? Thank you.
Please be comprehensive with the mistakes in my code I am beginner, self-taught and it is my first app. Any help would be really appreciated.
fragment_index_category_filter.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="4dp"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".Fragments.IndexCategoryFilterFragment">

    <!-- TODO: Update blank fragment layout -->
    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/appBarLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/white"
        android:gravity="center"
        app:layout_constraintTop_toTopOf="parent"
        android:theme="@style/AppTheme.AppBarOverlay">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/home_activity_tb"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:contentInsetLeft="0dp"
            app:contentInsetRight="0dp"
            app:contentInsetEnd="0dp"
            app:contentInsetStart="0dp"
            android:gravity="center"
            android:layout_gravity="center"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

            <RelativeLayout
                android:id="@+id/toolbar"
                android:padding="8dp"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <com.google.android.material.button.MaterialButton
                    android:id="@+id/close_filters"
                    android:layout_width="32dp"
                    android:layout_height="32dp"
                    android:layout_alignParentStart="true"
                    android:layout_centerVertical="true"
                    android:insetLeft="0dp"
                    android:insetTop="0dp"
                    android:insetRight="0dp"
                    android:insetBottom="0dp"
                    android:padding="0dp"
                    app:fabCustomSize="50dp"
                    app:icon="@drawable/cancel"
                    app:iconGravity="textStart"
                    app:iconPadding="0dp"
                    app:iconSize="32dp"
                    app:shapeAppearanceOverlay="@style/ShapeAppearanceOverlay.MyApp.Button.Circle" />

                <com.google.android.material.textview.MaterialTextView
                    android:id="@+id/appBarTitle"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true"
                    android:text="Category list"
                    android:textAllCaps="false"
                    android:textColor="@color/black"
                    android:textSize="24sp" />

                <com.google.android.material.button.MaterialButton
                    android:id="@+id/save_filters"
                    app:icon="@drawable/ic_check_ok"
                    app:iconSize="32dp"
                    app:iconGravity="textStart"
                    android:layout_width="32dp"
                    android:layout_height="32dp"
                    android:padding="0dp"
                    app:iconPadding="0dp"
                    android:insetLeft="0dp"
                    android:insetTop="0dp"
                    android:insetRight="0dp"
                    android:layout_alignParentEnd="true"
                    android:layout_centerVertical="true"
                    android:insetBottom="0dp"
                    app:shapeAppearanceOverlay="@style/ShapeAppearanceOverlay.MyApp.Button.Circle"
                    app:fabCustomSize="50dp"
                   />

            </RelativeLayout>
        </androidx.appcompat.widget.Toolbar>
    </com.google.android.material.appbar.AppBarLayout>

    <RelativeLayout

        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@+id/appBarLayout"
        android:id="@+id/shortcuts_filter">

        <com.google.android.material.button.MaterialButton
            android:id="@+id/clear_filters"
            style="@style/Widget.MaterialComponents.Button.OutlinedButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:padding="0dp"
            android:text="Clear all"
            android:textAllCaps="false"
            android:textSize="12sp" />
        <com.google.android.material.button.MaterialButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="0dp"
            android:id="@+id/select_all_filters"
            android:textSize="12sp"
            android:text="Select all"
            android:layout_alignParentEnd="true"
            android:textAllCaps="false"
            style="@style/Widget.MaterialComponents.Button.OutlinedButton"/>

    </RelativeLayout>

    <androidx.recyclerview.widget.RecyclerView
        android:layout_margin="8dp"
        app:layout_constraintTop_toBottomOf="@+id/shortcuts_filter"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/categorySection_rv"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
        android:orientation="vertical"/>

</androidx.constraintlayout.widget.ConstraintLayout>

IndexCategoryFilterFragment.java
 public class IndexCategoryFilterFragment extends Fragment {
        //Initialize variable
        List<String> streamFiltersList;
        RecyclerView categorySection_rv;
        FirebaseDatabase firebaseDatabase;
        DatabaseReference dbCategoryReference;
        StreamFilterManager streamFilterManager;
        MaterialButton save_filters, clear_filters, close_fragment;
        FiltersViewModel filtersListObserver;
        private FirebaseAuth mAuth;
        FirebaseUser firebaseUser;
        String userId;
        SectionAdapter sectionAdapter;
        List<Letter> letterList;
        List<Category> categoryInLetter = new ArrayList<>();
        public FilterInterface interfaceListener;

        public IndexCategoryFilterFragment() {
            // Required empty public constructor
        }

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            if (container != null) {
                container.removeAllViews();
            }
            // Inflate the layout for this fragment
            mAuth = FirebaseAuth.getInstance();
            firebaseUser = mAuth.getCurrentUser();
            userId = firebaseUser.getUid();

            View view = inflater.inflate(R.layout.fragment_index_category_filter, container, false);
            save_filters = view.findViewById(R.id.save_filters);
            categorySection_rv = view.findViewById(R.id.categorySection_rv);
            clear_filters = view.findViewById(R.id.clear_filters);
            close_fragment = view.findViewById(R.id.close_filters);
            firebaseDatabase = FirebaseDatabase.getInstance();
            dbCategoryReference = firebaseDatabase.getReference("CategoryIndexed");

            save_filters.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    streamFilterManager.logOutFromUserSession();
                    streamFilterManager.writeListInPref(getContext(), streamFiltersList, userId);
                    Log.d("streamFilter", "onClick: " + streamFiltersList);
                    filtersListObserver = new ViewModelProvider(requireActivity()).get(FiltersViewModel.class);
                    filtersListObserver.setFiltersList(streamFiltersList);
                    getParentFragmentManager().beginTransaction().replace(R.id.fragment_container, new Home(), "home").commit();
                }
            });
            close_fragment.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getParentFragmentManager().popBackStack();
                }
            });
            letterList = new ArrayList<>();
            categoryInLetter = new ArrayList<>();
            sectionAdapter = new SectionAdapter(getContext(), letterList);
            categorySection_rv.setAdapter(sectionAdapter);
            firebaseCategoryIndex();

            return view;
        }

        @Override
        public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
        }

        @Override
        public void onResume() {
            super.onResume();
            streamFilterManager = new StreamFilterManager(getContext(), userId);
            streamFiltersList = streamFilterManager.readFilterList(getContext(), userId);
            if (streamFiltersList == null) {
                streamFiltersList = new ArrayList<>();
            }
            clear_filters.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    checkboxUpdate();
                }
            });

        }

        private void firebaseCategoryIndex() {
            // First recycler
            Query queryLetter = dbCategoryReference.orderByChild("index");
            queryLetter.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot snapshot) {
                    letterList.clear();
                    for (DataSnapshot dsLetter : snapshot.getChildren()) {
                        Letter letter = dsLetter.getValue(Letter.class);
                        letterList.add(letter);

                    }
                    sectionAdapter.notifyDataSetChanged();
                    Log.d("letterList", "letterList: " + letterList.size());
                }

                @Override
                public void onCancelled(@NonNull DatabaseError error) {

                }
            });

        }

        // solutions testing
        public interface FilterInterface {
            void clearSelectAllFilters(Button allFilters);
        }

        private void checkboxUpdate() {
            // 1. get ith item of the parent recyclerView
            for(int i = 0 ; i< sectionAdapter.getItemCount();i++){
                SectionAdapter.ViewHolder viewHolder = (SectionAdapter.ViewHolder) categorySection_rv.findViewHolderForAdapterPosition(i);
                RecyclerView recyclerView = viewHolder.section_item_rv;
                ItemSectionAdapter itemSectionAdapter = (ItemSectionAdapter) recyclerView.getAdapter();
                itemSectionAdapter.update();
            }

        }
    }

SectionAdapter.java
public class SectionAdapter extends RecyclerView.Adapter<SectionAdapter.ViewHolder> implements IndexCategoryFilterFragment.FilterInterface {
    Context context ;
    List<Letter> letterList;

    DatabaseReference categoryListRef;

    public SectionAdapter(Context context, List<Letter> letterList) {
        this.context = context;
        this.letterList = letterList;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.section_category,parent,false);
        return new SectionAdapter.ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        List<Category> letterCategoryList = new ArrayList<>();
        Letter letter = letterList.get(position);
        holder.section_letter.setText(letter.getIndex());
        holder.section_title_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int visible = holder.section_item_rv.getVisibility();
                if (visible == View.VISIBLE){
                    holder.section_item_rv.setVisibility(View.GONE);
                } else {
                    holder.section_item_rv.setVisibility(View.VISIBLE);
                }
            }
        });
        categoryListRef = FirebaseDatabase.getInstance().getReference("CategoryIndexed").child(letter.getIndex()).child("content");
        ItemSectionAdapter itemSectionAdapter = new ItemSectionAdapter(letterCategoryList);
        categoryListRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                for (DataSnapshot dsLetterContent : snapshot.getChildren()){
                    Category category = dsLetterContent.getValue(Category.class);
                    category.setCheckState(true);
                    Log.d("letterList", "letterList: "+ category.getCategoryName() + " "+ category.isCheckState());
                    letterCategoryList.add(category);
                }
                itemSectionAdapter.notifyDataSetChanged();
            }
            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });
        holder.section_item_rv.setAdapter(itemSectionAdapter);

    }

    @Override
    public int getItemCount() {
        return letterList.size();
    }

    @Override
    public void clearSelectAllFilters(Button allFilters) {

    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public MaterialTextView section_letter;
        public RecyclerView section_item_rv;
        public LinearLayout section_title_ll;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            section_letter = itemView.findViewById(R.id.section_letter);
            section_item_rv = itemView.findViewById(R.id.section_item_rv);
            section_title_ll = itemView.findViewById(R.id.section_title_ll);

        }
    }

}

ItemSectionAdpater.java
public class ItemSectionAdapter extends RecyclerView.Adapter<ItemSectionAdapter.ViewHolder> implements IndexCategoryFilterFragment.FilterInterface {
    List<Category> categoryList;

    public ItemSectionAdapter(List<Category> categoryList) {
        this.categoryList = categoryList;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.index_category_name_item,parent,false);

        return new ItemSectionAdapter.ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Category category = categoryList.get(position);
        holder.indexItemCategory.setText(category.getCategoryName());
        holder.cb_categoryItem.setChecked(category.isCheckState());
    }

    @Override
    public int getItemCount() {
        return categoryList.size();
    }

    @Override
    public void clearSelectAllFilters(Button allFilters) {

    }

    public class ViewHolder extends RecyclerView.ViewHolder {
            public TextView indexItemCategory;
            public CheckBox cb_categoryItem;
            public RelativeLayout category_item_rl;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            indexItemCategory = itemView.findViewById(R.id.indexItemCategory);
            cb_categoryItem = itemView.findViewById(R.id.cb_categoryItem);
            category_item_rl = itemView.findViewById(R.id.category_item_rl);
        }
    }

    public void update() {
        categoryList.forEach(category -> category.setCheckState(false));
        notifyDataSetChanged();
    }

}

A: Make a public method in adapter and then pass your new data with changed checked values to true, and then notify the adapter like shown below (or update the existing method with the code given below).
public void updateList(ArrayList<Category> categoryList) {
        this.categoryList = categoryList;
        notifyDataSetChanged();
}

then simply call this method wherever you need with the adapter object in your fragment.


text:
Q: PostCSS compiling SASS media queries out of order? I'm using a simple webpack build with PostCSS. If I don't declare a specific media query mixin in the first section of the page's SCSS, but use that specific media query mixin in a following section, that media query outputs after the other breakpoints (even though I have them defined in a specific order in my mixins file). Here's my code:

_variables.scss
$sm-screen: 576px;
$md-screen: 768px;
$lg-screen: 992px;
$xl-screen: 1200px;

_mixins.scss
@mixin sm-screen {
  @media screen and (min-width: #{$sm-screen}) {
      @content;
  }
}

@mixin md-screen {
  @media screen and (min-width: #{$md-screen}) {
      @content;
  }
}

@mixin lg-screen {
  @media screen and (min-width: #{$lg-screen}) {
      @content;
  }
}

@mixin xl-screen {
  @media screen and (min-width: #{$xl-screen}) {
      @content;
  }
}

@mixin screen-size($screen) {
  @media screen and (min-width: $screen) {
      @content;
  }
}

_page.scss
// ————————————————————————————————————————————————————————————
// HERO SECTION
// ————————————————————————————————————————————————————————————
  #hero-section {
    .hero-heading {
      font-size: 2rem;
    }

    @include sm-screen {
      .hero-heading {
        font-size: 5rem;
      }
    }

    @include lg-screen {
      .hero-heading {
        font-size: 6.5rem;
      }
    }

    @include xl-screen {
      .hero-heading {
        font-size: 6.5rem;
      }
    }
  }

// ————————————————————————————————————————————————————————————
// INTRO SECTION
// ————————————————————————————————————————————————————————————
  #intro-section {
    .icon-group {
      background: red;
    }

    @include md-screen {
      .icon-group {
        background: yellow;
      }
    }

    @include xl-screen {
      .icon-group {
        background: blue;
      }
    }
  }

main.scss (importing files)
@import "/base/variables";
@import "/base/mixins";
@import "page";

As you can see in _page.scss, I like to declare breakpoints right within each section (or row) as I go down the page. The problem is since I didn't declare the @include md-screen breakpoint on the first section, HERO SECTION, it comes after the @include xl-screen breakpoint in the output CSS and overrides the styles of the largest breakpoint:

output CSS:
body.home #intro-section .icon-group {
  background: red;
}

@media screen and (min-width:1200px) {
  body.home #intro-section .icon-group {
    background: blue;
  }
}

@media screen and (min-width:768px) {
  body.home #intro-section .icon-group {
    background: yellow;
  }
}

Does this mean that my practice of declaring the breakpoints on each section is not the best way? Should I declare all breakpoints at the end of each file, that way if nothing changes in one section at a specific breakpoint, I don't need to declare that breakpoint at all to get it to compile in the correct order? Is there a way to get media queries to output in the order they're declared in the mixins file, regardless of when the mixins are called in the CSS?
My intent is to get the breakpoints to output from smallest to largest since I'm using the mobile-first, min-width approach. I would love to apply the media queries like I'm doing, but if there's a better way (such as at the end of files), so be it.


text:
Q: Interface extending multiple interfaces i am using spring & have 2 interfaces,
interface A {
    public void a();
}

interface B {
    public void B();
}

and their implementations
class AImpl implements A {
    public void a(){ // TODO }
}
class BImpl implements B {
    public void b(){ // TODO }
}

Now I create an interface C
    interface C extends A, B {}

Is there any way I can get a bean of type C with method definations of AImpl & BImpl

A: You can't make a CImpl that extends AImpl and BImpl as Java doesn't support multiple inheritance for classes.
But you can do something like this:
class CImpl implements C {
    private A a;
    private B b;

    public CImpl(A a, B b) {
        this.a = a;
        this.b = b;
    }

    public void a() {
        a.a();
    }

    public void b() {
        b.b();
    }
}

And create your CImpl with:
CImpl c = new CImpl (new AImpl(), new BImpl());

If you use Spring (as your tags imply) you can configure AImpl, BImpl and CImpl as Beans and use autowiring for the constructor of CImpl.


text:
Q: Retrieving data from an array of check boxes in a Django template In a Django template, I'm displaying some usernames (or unames) along with check boxes like so:
<form method="POST" action="{% url 'process_unames' %}">
    {% csrf_token %}
    {% for name in unames %}
        <input type="checkbox" name="target{{ forloop.counter0 }}" value="{{ unames|index:forloop.counter0 }}" checked>{{ name }}

    {% endfor %}
    <button name="duration" value="{{ value }}" type="submit">Submit</button>
</form>

And then in the function process_unames, I'm trying to retrieve all checked unames via:
def process_unames(request, *args, **kwargs):
    uname_list = request.POST.getlist('unames')

This is consistently yielding an empty list, regardless of which uname I check or uncheck. How do I fix this? An illustrative example would be great.

In case it matters, I haven't declared any form in forms.py with this Django template. Moreover, note that index is a custom template tag which does the following (and I can vouch it's correctly working):
from django.template.defaulttags import register

@register.filter(name='index')
def index(List, i):
    return List[int(i)]

A: You are checking the wrong variable. You access the input by its name.
So for a single  value you would retrieve the data for a form like this
<input type="checkbox" name="user_name" value={{uname}}>

via
request.POST.get('user_name')

See: https://docs.djangoproject.com/en/1.10/topics/forms/#the-work-that-needs-to-be-done
And if you have loop, you still give each relevant input the same name and use request.POST.getlist() to access the values as a list.
See: https://stackoverflow.com/a/23470119/630877

A: You don't have any fields called "unames" in the template. You have a bunch of unrelated checkboxes called "targetX" where X is a number. Replace that with just name="unames" and your code will work.
Note two things: firstly, you should be using Django's forms framework; and secondly, your filter is pointless because {{ name }} would already by the value in unames, since that is what you are iterating over (and, indeed, you are already using that as the label).
{% for name in unames %}
    <input type="checkbox" name="unames" value="{{ name }}" checked>{{ name }}

{% endfor %}


text:
Q: Lag when drawing something to move with mouse I am having some trouble with drawing rectangles at the mouse position. The painted rectangle lags behind the mouse cursor when the mouse is moved. Is there a way to ensure the rectangle moves exactly on the mouse and does not lag behind?
Here is a little example, although because this is just a single rectangle the lag is very slight, but it is there. In the larger program I am painting a ton of them at a time though only moving the one.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;

import javax.swing.*;

public class MouseTest {
    JFrame window;
    DrawPanel content;

    public MouseTest(){
        window = new JFrame("Test");
        content = new DrawPanel();
        window.setContentPane(content);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setVisible(true);
        window.pack();
    }

    public static void main (String[] args){
        MouseTest test = new MouseTest();
    }

    private class DrawPanel extends JPanel implements MouseMotionListener {
        int mouseX;
        int mouseY;

        private DrawPanel(){
            setBackground(Color.BLUE);
            setPreferredSize(new Dimension(400,400));
            addMouseMotionListener(this);
        }

        public void paintComponent(Graphics g){
            super.paintComponent(g);
            g.setColor(Color.RED);
            g.fillRect(mouseX, mouseY, 20, 20);
        }

        @Override
        public void mouseDragged(MouseEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void mouseMoved(MouseEvent e) {
            mouseX = e.getX();
            mouseY = e.getY();
            repaint();

        }
    }

}

A: Tthe first thing to do is move all of your Swing/AWT code into the EDT.  In your application it may not matter, but it is a good habit to get into.
I couldn't reproduce your lag with either approach, however.
public static void main (String[] args)
{
    SwingUtilities.invokeLater(
        new Runnable()
        {
            public void run()
            {
                MouseTest test = new MouseTest();
            }
        });
}

See this article for more information on Swing Threading.

A: Maybe way off on this but when you say "lag behind" do you mean the cursor is not in the center of the rectangle?  Your code has the cursor pointing to the top left corner of the rectangle, you need to offset it to center it.

A: Even if this is more work i recommend for any such task that you only invalidate and repaint the region that has changed. This will save many cycles (imagine drawing the complete backgound all the time...).
You will see great improvements.
EDIT
I tested it myself with this example
    public void mouseMoved(MouseEvent e) {
        repaint(mouseX, mouseY, 20, 20);
        mouseX = e.getX();
        mouseY = e.getY();
        repaint(mouseX, mouseY, 20, 20);
    }

and must admit the improvements are a little academic ( at least for my computer). Anyway, this technique should be used on more complex paint methods.. (where you finally will see improvements)
EDIT
And more cheat: If you still dislike the mismatch between where you think the cursor is and what the system thinks, try switch off the cursor (http://www.java2s.com/Code/Java/2D-Graphics-GUI/HidethemousecursoruseatransparentGIFasthecursor.htm) to give the user a better feedback.

A: The rectangle lags because your class processes every motion event. If it processed only the most recent event, then the rectangle would be up-to-date (although it might have large jumps in position). One way to do this is to run a separate thread that draws the rectangle based on the current mouse position, which is updated by the mouseMoved() method. You'll have to synchronize access to the mouse position variable.


text:
Q: Google Forms regex validation for proper name Trying to validate strings such as...

*

*My Company Name (pass)

*my ComPany name (fail)

*my Company Name (fail)

*my company name (fail)

*MY Company Name (pass)

*COMPANY (pass)
Want it to match a proper name format (caps on first letter of each word)...

*

*My Company Name

I can use the following regex and it works great over at https://regex101.com/.  But when I try to use it in a Google Form validation it does NOT work.  I think Google does not like the \p flags.
^([\p{Lu}]\p{L}*\s*)+$

Is there a way to convert that to a regex that does not use the \p flag?  I tried the following regex string and it did NOT do the trick either...
^([[A-Z]][a-z]*\s*)+$

A: This regex will work
^(?:[A-Z](?:[A-Z]*|[a-z]*))(?:\s+[A-Z](?:[A-Z]*|[a-z]*))*$

Regex Demo
Regex Breakdown
^ #Start of string
(?:[A-Z](?:[A-Z]*|[a-z]*)) #Match at least one group starting with alphabets [A-Z]
(?:\s+[A-Z](?:[A-Z]*|[a-z]*))* #Check whatever follows contains space and meets the same requirement as above
$ #End of string

A: If you don't necessary need Unicode, try this:
^(([A-Z]+)|([A-Z][a-z]+))(\s+(([A-Z]+)|([A-Z][a-z]+)))*$
Each word may look like COMPANY or Company, but not like company, with spaces between words (after the 2nd).
Matches: My Company Name, MY COMPANY Name, COMPANY.
Does not match: my ComPany name, my Company Name, my company name.
(([A-Z]+) matches ALL UPPERCASE
([A-Z][a-z]+) matches Capitalized
(...)|(...) matches first or second group
* allows 0 or many Words after the first word
\s+ matches one or multiple spaces before words after the 2nd
^ - start of string, $ - end of string
A simpler solution if MyCompanyName and MYCOMPANy are also acceptable (first letter capitalized):
^([A-Z][a-z]*\s*)+$
Tested with regex101


text:
Q: Grouping and sorting Folders and Files in a ListView I'd like to display folders and files in a ListView the same way they are in the windows explorer i.e. folders first, then the files, and both groups sorted alphabetically.
I thought at first about using 2 ListViewGroup (one for Folders and one for files), but not only I can't hide the group header, it's not active when the ListView is in List mode.
Another solution would be to keep 2 underlying lists (one for folders and one for files) and populate the ListView from the 2 lists (first the folders and then the files). But this seems a bit clumsy as I'd have to sort my 2 lists and refresh the ListView content every time the user sorts the ListView.
Can anybody suggest solution to this issue? I feel like there's a simple answer and/or that I've missed something in the ListView control...

A: OK after a bit more searching here's how I've implemented this.
I used the custom sort functionality in the list view (see how to on http://support.microsoft.com/kb/319401).
The only change is in the Compare function of the ListViewColumnSorter.
If both X and Y items are of the same type (Folder or File) I return the "normal" result based on the item name sort. And if not, I return -1 if X is a folder and 1 if not.
That way folders always come first and both folders and files are sorted alphabetically
Each list view item gets is identified as a folder or file by its Tag property set when the items are added to the list.

A: One way to handle this is to use a TreeView for the folders (on the left), and a Listview for the files (on the right). Whenever the selection changes in the Treeview, you can update the file names in the Listview.


text:
Q: How to center a fixed sized main layout in android? I want my layout to be fixed sized say: 320dp by 480dp as a default for ldpi screen resolution.
So when the user has a 720x1280 device the layout would still be 320x480 but would be centered.
Any suggestions? I want to avoid creating multiple layouts for each resolution.

A: <?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <RelativeLayout android:layout_width="320px"
        android:layout_height="480px"
        android:layout_centerInParent="true"
        android:background="@color/white">

    </RelativeLayout>

</RelativeLayout>

Hope this is what you want.

A: For your parent view container, you should just set the layout_width and layout_height to the desired size and then make its layout_gravity equal to center.  So, in your case you would use the following
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="320dp"
    android:layout_height="480dp"
    android:layout_gravity="center" >

    <!-- The rest of your layout -->

</LinearLayout>

That should center the view and keep it the desired size.  It should be noted that you can use any layout, not just LinearLayout.
Hope this helps!  Good luck.


text:
Q: Deploying a jersey grizzly service to tomcat with spring I am new to jersey and using it for the first time one of my RESTful services. I was able to build and run the "maven way" as given in the jersey download site. It uses the http container (grizzly),
Now, I want to deploy this as a war file on tomcat or generic 3.0 servlet containers.
I know that I need to have a war package + web.xml file.
My question is,

*

*what do I put in this web.xml?

*how do I add the tomcat plugin to maven build dependency? so that I can run this

mvn clean compile package tomcat7:run

*If I need to add the spring framework later, how easy is that? How can I do that?


text:
Q: How to get the highest predicted value in multiclass classification problem using H2O AI? When predicting values in a multiclass classification problem, I would like to get the probability of the predicted value.
I tried to solve this by using H2O's apply function:
predicted_df = modelo_assessor.predict(to_predict_h2o_frame)
predicted_df.apply((lambda x: x.max()), axis=1)

But it does not work:

'ValueError: unimpl bytecode instr: CALL_METHOD'

Maybe it doesn't work because h2o.max does not have axis parameter as h2o.mean does???
I couldn't find the documentation of which operations are supported on apply function.
I would like to solve the problem using h2o data manipulation similarly to this pandas code:
    predicted_df = modelo_assessor.predict(to_predict_h2o_frame).as_data_frame()
    predicted_df['PROB_PREDICTED']=predicted_df.iloc[:,1:].max(axis=1)

A: This is happening whenever using apply. Use the example from H2O documentation:
I was able to solve the problem by downgrading to Python 3.6.x
http://docs.h2o.ai/h2o/latest-stable/h2o-py/docs/frame.html#h2oframe
python_lists = [[1,2,3,4], [1,2,3,4]]
h2oframe = h2o.H2OFrame(python_obj=python_lists,
                        na_strings=['NA'])
colMean = h2oframe.apply(lambda x: x.mean(), axis=0)

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-43-8da6b76c71bd> in <module>
      2 h2oframe = h2o.H2OFrame(python_obj=python_lists,
      3                         na_strings=['NA'])
----> 4 colMean = h2oframe.apply(lambda x: x.mean(), axis=0)

~/anaconda3/envs/h2o1/lib/python3.7/site-packages/h2o/frame.py in apply(self, fun, axis)
   4910         assert_is_type(fun, FunctionType)
   4911         assert_satisfies(fun, fun.__name__ == "<lambda>")
-> 4912         res = lambda_to_expr(fun)
   4913         return H2OFrame._expr(expr=ExprNode("apply", self, 1 + (axis == 0), *res))
   4914

~/anaconda3/envs/h2o1/lib/python3.7/site-packages/h2o/astfun.py in lambda_to_expr(fun)
    133     code = fun.__code__
    134     lambda_dis = _disassemble_lambda(code)
--> 135     return _lambda_bytecode_to_ast(code, lambda_dis)
    136
    137 def _lambda_bytecode_to_ast(co, ops):

~/anaconda3/envs/h2o1/lib/python3.7/site-packages/h2o/astfun.py in _lambda_bytecode_to_ast(co, ops)
    147         body, s = _opcode_read_arg(s, ops, keys)
    148     else:
--> 149         raise ValueError("unimpl bytecode instr: " + instr)
    150     if s > 0:
    151         print("Dumping disassembled code: ")

ValueError: unimpl bytecode instr: CALL_METHOD