text:
Q: Gvim --remote to open file and focus on the newly opened file I got a fairly old gvim (6.3) on CentOS 4.5. There's no --remote-tab-silent option  yet. Instead, I use --remote to open file in same gvim instance. However, there's a problem that all files are opened in gvim in background. The gvim window won't pop to the front. I have to manually switch to it. Is there any way to fix this?
More detail on steps to reproduce:

*

*Open Konsole

*Open first file 'gvim --remote file1'. For the first time open file, gvim will pop to front.

*Switch back to Konsole and open 2nd file 'gvim --remote file2'. The file gets opened in gvim, but gvim window won't pop to front.

A: Does "gvim --remote-expr foreground()" work to bring gVim to the front of the window stack? If this works consistently, you might set up a shell alias to invoke the --remote command then the --remote-expr command.


text:
Q: stay full screen in html 5 I would like to run an online experiment where I would display very short videos (500ms, ~50Kb) full screen. Then collect an answer by asking observers to click on 1 of 2 buttons, then play the next video (50-100 videos in total). So I know I can display videos full screen in HTML5 by asking participants to request it (I can't do that automatically as far as I understand). However it is important for me that the experiment remains full screen during its entire duration (5-10 minutes), including during the response parts where it is not a video but a simple html page with 2 buttons on it. I don't want participants to have to request a full screen on every video. Is it possible in principle? I guess I need to change the page between the video and the response screen, is the refresh going to make the window blink? Ideally, that wouldn't be noticeable by the participants. Finally, is there a way to make sure the participants remained full screen (is there meta-data that tells me if they quit full screen mode)?
Thanks a lot.
Baptiste

A: You cannot force it, it is prohibited by the Chrome Fullscreen API, meaning that, for security reason, in the majority of modern browsers, it must be executed in the context of a user-interactive event firing, not on the terms of the document.
Feel free to browse the Chrome Fullscreen API page, or another answer on Stack Overflow titled, How to Open a Web Page Automatically in Full Screen Mode.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Graphical output of density for the function gammamixEM (package mixtools) I'm using the function gammamixEM from the package mixtools. How can I return the graphical output of density as in the function normalmixEM (i.e., the second plot in plot(...,which=2)) ?
Update:
Here is a reproducible example for the function gammamixEM:
x <- c(rgamma(200, shape = 0.2, scale = 14), rgamma(200,
     shape = 32, scale = 10), rgamma(200, shape = 5, scale = 6))
out <- gammamixEM(x, lambda = c(1, 1, 1)/3, verb = TRUE)

Here is a reproducible example for the function normalmixEM:
data(faithful)
attach(faithful)
out <- normalmixEM(waiting, arbvar = FALSE, epsilon = 1e-03)
plot(out, which=2)

I would like to obtain this graphical output of density from the function gammamixEM.

A: Here you go.
out <- normalmixEM(waiting, arbvar = FALSE, epsilon = 1e-03)

x          <- out
whichplots <- 2
density = 2 %in% whichplots
loglik  = 1 %in% whichplots

def.par    <- par(ask=(loglik + density > 1), "mar") # only ask and mar are changed
mix.object <- x

k    <- ncol(mix.object$posterior)
x    <- sort(mix.object$x)
a    <- hist(x, plot = FALSE)
maxy <- max(max(a$density), .3989*mix.object$lambda/mix.object$sigma)

I just had to dig into the source code of plot.mixEM
So, now to do this with gammamixEM:
x <- c(rgamma(200, shape = 0.2, scale = 14), rgamma(200,
                                                    shape = 32, scale = 10), rgamma(200, shape = 5, scale = 6))
gammamixEM.out <- gammamixEM(x, lambda = c(1, 1, 1)/3, verb = TRUE)

mix.object <- gammamixEM.out

k    <- ncol(mix.object$posterior)
x    <- sort(mix.object$x)
a    <- hist(x, plot = FALSE)
maxy <- max(max(a$density), .3989*mix.object$lambda/mix.object$sigma)

main2 <- "Density Curves"
xlab2 <- "Data"
col2  <- 2:(k+1)

hist(x, prob = TRUE, main = main2, xlab = xlab2,
     ylim = c(0,maxy))

for (i in 1:k) {
  lines(x, mix.object$lambda[i] *
          dnorm(x,
                sd = sd(x)))
}

I believe it should be pretty straight forward to continue this example a bit, if you want to add the labels, smooth lines, etc. Here's the source of the plot.mixEM function.


text:
Q: TableView with XCode 4 I'm new to xcode, and trying to add a tableview.
for some reason, it looks that all the online guides are for older versions of xcode, and I can't find a good explanation for how to connect things.
apparently the xcode4's design is not at all as the older versions design.
can you recommend of a good guide, or maybe give me the answer?
how do I connect the view to the controller? do i need to add files? do I need a navigator?
thanks

A: You can check out this tutorial by Matthijs Hollemans Beginning Storyboards in iOS 5 Part 1
or watch the new Stanford Itunes U Video for iOS 5 apps.
In both they explain detailed how to use storyboard (e.g. with a UITableView).

A: look for Stanford CSP 193 Fall 2011 on iTunesU


text:
Q: Travis CI says JRE is 11 but still won't run JAR of class file version 55 I have a Python application wired up to a Travis CI build. After the tests run, I need to spin up the application and then run a JAR file to complete testing. The JAR file was compiled with Java 11 and is of class file version 55. In my build, I get the following exception:
Exception in thread "main" java.lang.UnsupportedClassVersionError: com/myApp/main/Main has been compiled by a more recent version of the Java Runtime (class file version 55.0), this version of the Java Runtime only recognizes class file versions up to 52.0
at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:756)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:468)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:74)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:369)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:363)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:362)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:352)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
    at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:495)

EDIT: Added rest of exception
To check the Java version in the Travis instance, I have a java -version line that returns the following:
$ java -version
openjdk version "11.0.2" 2019-01-15
OpenJDK Runtime Environment 18.9 (build 11.0.2+9)
OpenJDK 64-Bit Server VM 18.9 (build 11.0.2+9, mixed mode)

So why is the exception acting like the Travis instance is running an earlier version of Java? I had this  same problem locally and was able to fix it by changing my JRE from Java 8 to 11 and never had any problems after that. Is the java -version command not tell me the JRE version like I think it is? Is there a way I can change the JRE of the Travis instance by using the .travis.yml file?
If necessary, here's the relevant parts of .travis.yml:
after_script:
  - chmod +x ~/build.sh
  - chmod 777 ./tests/LPT/myApp.jar
  - bash ~/build.sh
  - java -version # output of this is shown in question
  - sudo java -jar ./tests/LPT/myApp.jar ./tests/LPT/input.json
^ Last line triggers the exception shown in question

A: sudo's default policies generally clear a lot of environment variables for security reasons, and while you're building your application and running your java -version check with normal permissions, you're using sudo java to actually run it. You may be getting a different PATH and/or JAVA_HOME in the two environments.


text:
Q: Checking string match with some other string (multiple condition in same line) I am using below logic for checking particular string matching with other string or not
if (searchTxt == "All" || searchTxt == "WORD1" || searchTxt == 'WORD2' || searchTxt == 'WORD3' || searchTxt == 'WORD4' || searchTxt == 'WORD5') {
}

Above code is working fine but showing warning

Reduce the number of conditional operators (5) used in the expression
  (maximum allowed 3)

.
How to resolve this warning

A: Your code is currently needlessly repetitive.
How aout putting the acceptable options in an array then using a dynamic REGEX to test:
let allowed = ['foo', 'bar', 'etc'];
if (new RegExp('/^('+allowed.join('|')+')$/').test(searchTxt)) { alert('match'); }

A: In this example, you'd be better off with a switch statement; If you want to do the same thing with multiple terms, such as "WORD1" and "WORD2", eliminate the break and put the code you want to do in the last of the matches.

switch(searchTxt){
  case "All":
    // do something
  case "WORD1":
    // do something
  case "WORD2":
    // do something
  case "WORD3":
    // this switch case will do something for
    // "WORD1", "WORD2", "WORD3", "All"
    break;
  case "WORD4":
    // do something
    break;
  case "WORD5":
    // do something
    break;
  default:
    // do something if no match
}


text:
Q: Why UIWebView does not open my link in Safari? I wrote this code:
    if navigationType == UIWebViewNavigationType.LinkClicked {
        UIApplication.sharedApplication().openURL(request.URL!)
        return false
    }

and it works for all normal URLs. But when I click on the image/gif with the next code:

1*IR7oti7mEsYunzp_HhcNig.gif

it opens this gif/URL in my application, inside of UIWebView.
How can I force that it will open that gif/URL in Safari, too?

A: Something must be broken somewhere else in your code.
Working fine like this:
import UIKit

class ViewController: UIViewController, UIWebViewDelegate {

@IBOutlet var webView : UIWebView?

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    self.webView?.loadHTMLString(" 1*IR7oti7mEsYunzp_HhcNig.gif ", baseURL: NSURL(string: "testurl.com"))
}

func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        if navigationType == UIWebViewNavigationType.LinkClicked {
            UIApplication.sharedApplication().openURL(request.URL!)
            return false

        }

    return true
}
}


text:
Q: A proof on a property Legendre symbol In order to show
$$\sum_{0\leq k\leq p-1}\left(\frac{ak^2+bk+c}{p}\right)=\left(\frac{a}{p}\right)$$
with $p$ a prime number greater and equal to 3 and $gcd(b^2-4ac,p)=1$, I started to set $d=b^2-4ac$, and $x=2ak+b$, then the equation becomes
$$\sum_{0\leq x\leq p-1}\left(\frac{x^2-d}{p}\right)=\left(\frac{4a^2}{p}\right).$$
Now use the property of Legendre symbol:
$$\sum_{0\leq x\leq p-1}\left(\frac{x^2-d}{p}\right)=\sum_{0\leq y\leq p-1}(1+\left(\frac{y+d}{p}\right))\left(\frac{y}{p}\right)=\sum_{0\leq y\leq p-1}\left(\frac{y+d}{p}\right)\left(\frac{y}{p}\right)=-1.$$
However, for the RHS $\left(\frac{4a^2}{p}\right)$ doesn't seems to be equal -1, or is it? Did I make any mistakes in my proof?

A: The thing you are trying to show, with $a=1$, $b=0$, $c=2$, $p=3$, gives $-1$ on the left but 1 on the right, so you are trying to prove a falsehood.


text:
Q: Send user inputted row to top of DataGrid I have a DataGrid where I moved the blank row for user input to the top with
 ((IEditableCollectionView)MyGrid.Items).NewItemPlaceholderPosition =
                                       NewItemPlaceholderPosition.AtBeginning;

But when a user types in a new row, the row goes to the bottom (sometimes off screen) without any feedback, and the user might think that his new row just disappeared. So I would like to put it on top.
I want to do something like
MyGrid.Insert(0, newRow);

But I don't know what to override to get access to the row as it goes into the DataGrid. Right now I don't explicitly put the user inputted row into the DataGrid, this happens automatically.

A: Here's an example:
    public ObservableCollection<MyDataItem> DataItems
    {
        get
        {
            List<MyDataItem> items = new List<MyDataItem>(5);

            for (int i = 0; i < 5; i++)

            {
                items.Add(new MyDataItem { abc = abc[i], qrt = qrt[i], xyz = xyz[i] });
            }

            var observable = new ObservableCollection<MyDataItem>(items);

            var view = CollectionViewSource.GetDefaultView(observable) as IEditableCollectionView;
            view.NewItemPlaceholderPosition = NewItemPlaceholderPosition.AtEnd;

            return observable;
        }
    }

XAML :
        <DataGrid ItemsSource="{Binding DataItems}" CanUserAddRows="True" />


text:
Q: PHP Session is not read I'm having some "fun" sharing session between magento and Symfony2. It works really well on my computer (mac osx 10.6 + PHP 5.3.3) and here is the mechanism :

*

*User logs in into magento (on foo.example.com)

*User goes on another website (bar.example.com) and is logged as well.

*Session are stored as files under the magento var/session directory.

The session cookie is set to be shared on all .example.com subdomains.
As I said before, it works perfectly on my machine.
I deployed the two applications today on an Ubuntu 8.0.4 server with PHP 5.3.5-dotdeb and configured the session sharing mechanism for my production domains (.example.org).
The session cookie is shared between the two subdomains as well.
And now, the fun begins :

*

*I log in on my magento application on foo.example.org and gets a session cookie with value "abc"

*A file name sess_abc is create in magento var/session directory.

*file owner is www-data:www-data and files rights are -rw-------

*If I refresh the magento page, I'm still logged.

*I go to my other application on bar.example.org

*PHP accepts the session cookie abc but does NOT retrieve the data inside.

*If I do a var_dump($_SESSION), I'll have an empty array

*At the end, the file sess_abc is overwritten and the rights are the same.

*If I refresh this page, my var_dump will provide some informations that symfony wrote into the session.

Do you guys have any thought on why PHP does not retrieve datas from this session file ?
I already tried to chmod go+rw the session file but the result is the same...
A big big big thanx in advance !
EDIT :
Suhosin is enabled.
phpinfo() gives this on bar.example.org

suhosin.session.checkraddr  0   0
suhosin.session.cryptdocroot    On  On
suhosin.session.cryptkey    [ protected ]   [ protected ]
suhosin.session.cryptraddr  0   0
suhosin.session.cryptua Off Off
suhosin.session.encrypt On  On
suhosin.session.max_id_length   128 128
session.auto_start  Off Off
session.bug_compat_42   Off Off
session.bug_compat_warn Off Off
session.cache_expire    180 180
session.cache_limiter   no value    nocache
session.cookie_domain   .example.org    no value
session.cookie_httponly Off Off
session.cookie_lifetime 3600    0
session.cookie_path /   /
session.cookie_secure   Off Off
session.entropy_file    no value    no value
session.entropy_length  0   0
session.gc_divisor  1000    1000
session.gc_maxlifetime  1440    1440
session.gc_probability  1   1
session.hash_bits_per_character 5   5
session.hash_function   0   0
session.name    frontend    PHPSESSID
session.referer_check   no value    no value
session.save_handler    files   files
session.save_path   /www/var/session    no value
session.serialize_handler   php php
session.use_cookies On  On
session.use_only_cookies    On  On
session.use_trans_sid   0   0

A: I don't know you you know, but magento store sessions in "private" folder path/to/magento/var/session... May be on MacOS you could overide your php.ini (trought magento) in oder to overide your session path; But on ubuntu you cannot (/may not) overide you php.ini...
Have you check this ?

A: The problem is sushosin and configuration "suhosin.session.cryptdocroot" and maybe "suhosin.cookie.cryptdocroot". You must turn off this values. With this values On, soshosin crypt session with DocumnetRoot value.
Set this in your sushosin config (suhosin.ini in Ubuntu):
suhosin.session.cryptdocroot = off
suhosin.cookie.cryptdocroot = off

For more details look at here


text:
Q: Security Option is Disabled in Kibana 7 I am new to kibana, exploring kibana 7. there is security feature is disabled. how do i enable that feature? it is paid feature?
I show video on youtube which shows user-management and permission module under security. but when i click on security option under management it shows me Permission Denied Error.

A: XPack Security is a paid feature... until 7.0.1, that is!
If you upgrade to 7.1.0, XPack Security is now FREE (as in free beer) and included in the BASIC license.
Read the announcement here: https://www.elastic.co/blog/security-for-elasticsearch-is-now-free
Enjoy!

A: it is tricky.
please first click the APM which will tell your license is not valid.then you click "check license" which will refresh license (it is a basic and free license when it is setup),after some seconds,go back to the icon management,click it.it will show the security settings.I hope I can help you.


text:
Q: Append value to each array in a numpy array I have a numpy array of arrays, for example:
x = np.array([[1,2,3],[10,20,30]])

Now lets say I want to extend each array with [4,40], to generate the following resulting array:
[[1,2,3,4],[10,20,30,40]]

How can I do this without making a copy of the whole array? I tried to change the shape of the array in place but it throws a ValueError:
x[0] = np.append(x[0],4)
x[1] = np.append(x[1],40)
ValueError : could not broadcast input array from shape (4) into shape (3)

A: You can't do this. Numpy arrays allocate contiguous blocks of memory, if at all possible. Any change to the array size will force an inefficient copy of the whole array. You should use Python lists to grow your structure if possible, then convert the end result back to an array.
However, if you know the final size of the resulting array, you could instantiate it with something like np.empty() and then assign values by index, rather than appending. This does not change the size of the array itself, only reassigns values, so should not require copying.

A: While @roganjosh is right that you cannot modify the numpy arrays without making a copy (in the underlying process), there is a simpler way of appending each value of an ndarray to the end of each numpy array in a 2d ndarray, by using numpy.column_stack
x = np.array([[1,2,3],[10,20,30]])
array([[ 1,  2,  3],
       [10, 20, 30]])

stack_y = np.array([4,40])
array([ 4, 40])

numpy.column_stack((x, stack_y))
array([[ 1,  2,  3,  4],
       [10, 20, 30, 40]])

A: *

*Create a new matrix

*Insert the values of your old matrix

*Then, insert your new values in the last positions
x = np.array([[1,2,3],[10,20,30]])
new_X = np.zeros((2, 4))
new_X[:2,:3] = x
new_X[0][-1] = 4
new_X[1][-1] = 40
x=new_X

Or Use np.reshape() or np.resize() instead


text:
Q: I am running an experiment using Sugar (a SAT-based Constraint Solver) I am using Sugar (a SAT-based Constraint Solver) to run an experiment, for each new experiment I increase the size of the sugar file, which means that the percent of CPU and memory usage should increase. However, the CPU percentage is lower for larger files which don't make sense, can anyone help me to explain this behavior?
the specification of the Sugar and the server used t run the experiment is shown in the image.
machne specifications used in expirement


text:
Q: Ant: Unable to get Ant to copy properties file to classes directory I have a project which I can build and deploy correctly using Ant
I want to build a war file to deploy the project.
I can get everything working except I cannot get the properties file to appear in the classes directory.
My properties file is located here: /h/a/A/I/S/src/Serv/log4j.properties
This is the war section of my build file:
<war destfile="Int.war" webxml="web/WEB-INF/web.xml">
     <lib dir="${libDir}" />

     <classes dir="${outputDir}" includes="/h/a/A/I/S/src/Serv/log4j.properties"/>
     <classes dir="${outputDir}" />

   </war>

I have read the previously asked similar questions here and added the second classes element here which includes the properties file but it did'nt worked for me, any suggestions

A:
In this line, path of .properties file will be assumed by ant as "${outputDir}/h/a/A/I/S/src/Serv/log4j.properties" which is an invalid path in your project..
Try using copy task for moving .properties file to '${outputDir}' directory and then perform war packaging.


text:
Q: Node.js chat app with username variables not working I'm making a chat app in node.js based on a tutorial from socket.io. The purpose is for a user to enter in a username and a message. The chat will display "username: message". The username text field will then disappear after the first entry. I have it all working except for the chat displaying the message with the username. The chat displays four messages instead of one, they say that both variables are undefined.
JS
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
  console.log('a user connected');
  socket.on('disconnect', function(){
    console.log('user disconnected');
  });
});

io.on('connection', function(socket){
  socket.on('chat message', function(msg, usn){
    io.emit('chat message', msg);
    io.emit('chat message', usn);
  });
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});

HTML (Without the style tags)
<!doctype html>

    <title>Lucas Chat</title>

    <form action="">
      <input id="u" autocomplete="off" placeholder="Nickname"/><input id="m" autocomplete="off" placeholder="Message"/><button>Send</button>
    </form>

A: clientside
var socket = io();
  $('form').submit(function(){
    socket.emit('send message', {msg:$('#m').val(),user:$('#u').val()});
    $('#u').css("display", "none")
    $('#m').css("width", "90%")
    $('#m').val('');
    return false;
  });
  socket.on('receive message', function(msg){
    $('#messages').append($('
').text(msg));
  });

and serverside
io.on('connection', function(socket){
  socket.on('send message', function(data){
    io.emit('receive message',data.msg + ':' + data.user);
  });
});


text:
Q: Is it possible to set an element to display only when the  element is removed? For printing purposes, I removed the IMG element, but I wanted an H1 element to be displayed on another portion of the site when the IMG element is removed.
Is this possible?

A: You can use CSS media types for this.
Don't think of it as revealing one element when another is removed; instead think of it as selectively displaying elements depending on whether they are for print or screen.
Here is an example:
<!DOCTYPE html>

Header for print

Header for screen

Save this to a file and view it in a browser, and you will only see "Header for screen".  Print the same page and you will instead see "Header for print".
This technique will work on any element and can be used to set any CSS style for print or screen.


text:
Q: ADC anti-aliasing filter I bought a 16bit, 250kSPS AD7689 ADC. The circuit I am designing will amplify voltage (from 300uV up to 300mV) across a current-sense resistor (by 13x) to match 4.096V reference and feed this into an ADC. Measured voltage will either be DC or <1kHz square wave.
Do I need an anti-aliasing filter before ADC even tho I am just interested in "static DC voltage" (I am not interested in transient voltage)? If so, what should the cut-off frequency be (higher than 1kHz because of odd harmonics?)? Also what filter order should I use? 1st order seems enough to me, as 1kHz is way below half of Nyquist frequency.

A: You need to make sure that noise from aliasing is low enough one way or another.
You mention the signal being 1 kHz square wave, but then say you are only interested in "static DC voltage".  Those together make no sense.  I'll assume you want to measure the top and bottom levels of this square wave.
The first thing to do is decide how fast you can sample.  Aliasing problems reduce with higher sample rate.  You say the A/D can do 250 kHz sample rate, but you haven't said if the system it is connected to can do that.  In any case, that is way more than you need.
Try two poles of ordinary R,C filtering at maybe 10 kHz or so.  If you sample at 250 kHz, then the only signals above 125 kHz will cause aliasing.  Those will be attenuated by about 12.52 = 156.
Only you can answer how much frequency content there will be above 125 kHz, and whether attenuating that by 156 (44 dB) is good enough.  From your description, I'm guessing it is.  If you're not sure, throw another pole at 10 kHz or so at it.
In general, you want to do only enough filtering in analog to reduce aliasing noise to acceptable levels.  If you want to find some "average" or whatever, do that digitally after sampling.  Digital filters don't suffer from inaccuracies due to part variations, temperature, or non-linear behavior of parts.
For the digital filter, you have to decide what settling time you want.  Filter the sample stream so that a step still settles to within your maximum allowed time to within your maximum allowed error.

A: Yes, you always need an anti-aliasing filter

I am just interested in "static DC voltage"

Which explicitly says "hey, I want a low pass" (to only let through very low frequencies, ie. "the average voltage).
The cutoff frequency depends on what frequency you operate the ADC on – just because it can do 250kS/s doesn't mean it has to run at 250 kHz. You'll have to control the sampling instants by driving the CNV pin yourself, e.g. with your MCU.
But yeah, since it seems that you're only after very low frequencies, go for a very low cutoff frequency – the lower that cutoff frequency, the less noise energy in your signal.
Thus, design of that filter will not really be defined by the cutoff frequency alone, but also by the stop-band attenuation (which might be important to you, but I don't know anything about your signal source, other than it being in a range where simple pieces of conductor can act as antenna and introduce voltages with a comparable magnitude of voltage). And, of course, by technical feasibility – a 10F / 100MΩ RC low pass is a terribly hard thing to build :)
EDIT: As Pipe pointed out, the ADC comes with a built-in single pole selectable switched cap LPF. Might totally suffice – even more so as table 11 from the datasheet says you can configure it to ¼ of the bandwidth. Note, however, that the "less bandwidth means less noise power" still applies; it really depends on what signal your looking at whether this is sufficient or not!
EDIT: as a software-defined radio guy¹, I can only say: go and upvote Olin's answer. He's saying the right thing: A digital filter is easier to implement and far less problematic than an analog one.
Of course, you should still make sure you don't have aliasing in your digital signal – there's nothing a digital filter can do about that once it happened. However, that just means you need strong stopband suppression above \$\frac{f_{sample}}2\$, not a cutoff far below that. It's just mathematical fact that filters can't have infinitely sharp transition from pass- to stopband, so you'd naturally choose one that has a cutoff frequency solidly below the nyquist limit. But that again stresses the fact that cutoff frequency isn't the most critical design parameter here – it's suppression for frequencies above the nyquist limit that might be present in your signal, and that is usually also a function of how "ideal" you can assume your components to be.
For example: If you'd be building a very low cutoff RC filter, you might be tempted to use very large capacitors – but these often have high ESR.

¹SDR's motto is: sample now, ask questions later

A: Measuring a step change to 16 bits requires 16*6/9 = 11 time constants of settling. More detailed, this is $$bits * (6db/bit) / (9dB/neper)$$ Once the settling has occurred, the ADC can grab a sample; lets allocate 10uS for that.
What is our budget? 1KHz/2 = 500uS/step; 500uS - 10uS = 490uS for settling by 11 Tau; our longest Tau allowed is 40+uS; or 25,000 radian/second; divide by 2pi and the F3dB is ~~4KHz.
With a 4KHz Low Pass Filter, you have high frequency rolloff and accurate measuring of the 1KHz squarewave---but you have to time the ADC start-convert edge to 10uS before 1Khz edge.
Here is model of your system: 300mvpp, amplified by generic opamp 13X, into 16-bit ADC. I inserted 10mV of 60Hz and 120Hz into the Gargoyles Power Supply Interferer, and surprise the power-supply trash limits your measurement to 15.2 bits. But your thermal-noise is also high. However, Vquant sets the floor.
I used the Generic ADC Worksheet to evaluate the settling requirements.


text:
Q: in place sort returns None for empty list Why is it that [].sort() != [] but instead [].sort() = None?
Logically, it seems that the first case should be true.

A: It's because lists are mutable. [].sort() doesn't return a new list, it just changes the existing one, so the return value is nothing, or None. It's the same reason when you go to sort, you don't have to do something like list = list.sort(), you just do list.sort()

A: The Python docs cover this in at least two distinct places:

The sort() and reverse() methods modify the list in place for economy
  of space when sorting or reversing a large list. To remind you that
  they operate by side effect, they don't return the sorted or reversed
  list.

- note 7 under Mutable Sequence Types

You can also use the list.sort() method of a list. It modifies the
  list in-place (and returns None to avoid confusion). Usually it's less
  convenient than sorted() - but if you don't need the original list,
  it's slightly more efficient.

- Sorting Basics under the HOWTO on sorting

A: It's because sort always returns None, it's an in-place sort. Use sorted instead.
>>> sorted([]) == []
True


text:
Q: How to apply PostGIS ST_Within to all rows in a column I'm trying to use PostGIS to determine what political district (polygon) each geo-location took place in. In one table I have the shapefile loaded into a table called 113th_congress_shp, and in the other I have a list of events that took place given in the form POINT(long lat) in a table called gdelt_full_geo. My goal is to be able to apply ST_Within to each event in a particular column and have it return the political district that it applies to.
I'm coming from more of an R background so I am used to being able to do vector operations on an entire column. So, I am wondering how to do that in PostgreSQL. Using the following code I am able to get one row:
SELECT statefp, cd113fp, geoid, namelsad
FROM public."113th_congress_shp"
WHERE ST_Within(ST_SetSRID((SELECT action_coord FROM public.gdelt_full_geo LIMIT 1), 4269)::geometry, geom);

However, when I do:
SELECT statefp, cd113fp, geoid, namelsad
FROM public."113th_congress_shp"
WHERE ST_Within(ST_SetSRID((SELECT action_coord FROM public.gdelt_full_geo), 4269)::geometry, geom);

I get the following error:

"ERROR:  more than one row returned by a subquery used as an
  expression SQL state: 21000"

When I do the following, I get every globaleventid from the gdelt_full_geo table where the lat long falls within a polygon from the 113th_congress_shp table. However, I am unable to join the specific statefp and namelsad that the point falls into from the 113th_congress_shp table to the globaleventid from the gdelt_full_geo table so that I know what polygon the eventid belongs to.
SELECT a.globaleventid
FROM public.gdelt_test a
WHERE EXISTS (
        SELECT x.statefp, x.namelsad
        FROM public."113th_congress_shp" x
        WHERE ST_Within((
                ST_SetSRID(a.action_coord , 4269))::geometry
                , x.geom)
        )
        ;

A: Your query requires a scalar subquery, but your subquery results in more than one row.
You need some kind of JOIN to relate the two tables,for example:

SELECT a.statefp, a.cd113fp, a.geoid, a.namelsad
FROM public."113th_congress_shp" a
WHERE EXISTS(
        SELECT 1
        FROM public.gdelt_full_geo x
        WHERE ST_Within(
                ST_SetSRID(x.action_coord , 4269)::geometry
                , a.geom)
        )
        ;

A: After the suggestion from @wildplasser I was able to start digging in the right direction and was able to achieve what I wanted, such that all geoeventid's were joined to their respective congressional districts by doing:
SELECT a.globaleventid, x.statefp, x.namelsad
FROM public.gdelt_full_113 a
JOIN public."113th_congress_shp" x
ON ST_Within(ST_SetSRID(a.action_coord , 4269)::geometry, geom)


text:
Q: Get http.post in javascript then send a response There's plenty of ways to do this in php, but I'm not a serverside, so is there a way to do this in pure JS?

A: Pure JS? Yes, but only on the server (the specifics would depend on which SSJS implementation you use, Express + NodeJS is popular at present).
You can't receive a POST request on the client. The client makes the request. The server makes the response. That is how HTTP works.

A: <script>
function showHint(str) {
    if (str.length == 0) {
        document.getElementById("txtHint").innerHTML = "";
        return;
    } else {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
            }
        };
        xmlhttp.open("GET", "gethint.php?q=" + str, true);
        xmlhttp.send();
    }
}
</script>

See more


text:
Q: jQuery: It is not sorted in ascending and descending order, but simply makes a reverse There is a fairly large table, but on a DIV). It is necessary to give her the opportunity to sort by price.
The code below should sort the rows in ascending and descending order of the price, but instead it just does the reverse. Tell me, please, what is my mistake?

jQuery(function ($) {
    var thead = $('#tsection .thead');
    var tbody = $('#tsection .tbody');
    var price = tbody.find('.price').text().replace(/[^0-9]/gi, '');
    var rows = tbody.find('.list_item');

    var ascending = false;

    $('#tsection').on('click', '.thead .price', function () {

        var sorted = $(rows).sort(function (a, b) {
            return (ascending ==
                ($(a).find(price).html()) <
                ($(b).find(price).html())) ? 1 : -1;
        });
        ascending = ascending ? false : true;

        $(tbody).append(sorted);

    });

});
.thead div {
    display: inline-block;
    width: 100px;
    padding: 10px;
    border-bottom: 1px solid #333;
}

.thead .price:after {
    font-family: "Font Awesome 5 Free";
    font-weight: 900;
    content: "\f0dc";
    margin-left: 2px;
}

.tbody .list_item div {
    display: inline-block;
    width: 100px;
    padding: 10px;
}
<link href="https://use.fontawesome.com/releases/v5.0.13/css/all.css" rel="stylesheet">

Name

Country

Price

Time

Mark

USA

From 1 920 $

9 months

Piter

Colombia

2 220 $

2,5 months

Martin

Chine

From 820 $

6 months

Jacob

Israel

From 935 $

4,7 months

I'm a beginner, killed the day and didn't figure it out. I will be grateful for any help)

A: You can't use $(a).find(price) like you're doing, you have to do it like:
var sorted = $(rows).sort(function(a, b) {
  return (ascending ==
    +($(a).find('.price').text().replace(/[^0-9]/gi, '')) <
    +($(b).find('.price').text().replace(/[^0-9]/gi, ''))) ? 1 : -1;
});

Because if you run a console.log($(a).find(price).html()) you will notice it returns undefined.
Demo

jQuery(function($) {
  var thead = $('#tsection .thead');
  var tbody = $('#tsection .tbody');
  var price = tbody.find('.price').text().replace(/[^0-9]/gi, '');
  var rows = tbody.find('.list_item');

  var ascending = false;

  $('#tsection').on('click', '.thead .price', function() {

    var sorted = $(rows).sort(function(a, b) {
      return (ascending ==
        +($(a).find('.price').text().replace(/[^0-9]/gi, '')) <
        +($(b).find('.price').text().replace(/[^0-9]/gi, ''))) ? 1 : -1;
    });
    ascending = ascending ? false : true;

    $(tbody).append(sorted);

  });

});
.thead div {
  display: inline-block;
  width: 100px;
  padding: 10px;
  border-bottom: 1px solid #333;
}

.thead .price:after {
  font-family: "Font Awesome 5 Free";
  font-weight: 900;
  content: "\f0dc";
  margin-left: 2px;
}

.tbody .list_item div {
  display: inline-block;
  width: 100px;
  padding: 10px;
}
<link href="https://use.fontawesome.com/releases/v5.0.13/css/all.css" rel="stylesheet">

Name

Country

Price

Time

Mark

USA

From 1 920 $

9 months

Piter

Colombia

2 220 $

2,5 months

Martin

Chine

From 820 $

6 months

Jacob

Israel

From 935 $

4,7 months


text:
Q: Using .htaccess for multiple redirects I have a web site that has the file extension of .php. As of right now I have it setup to rewrite that server side using .htaccess to drop the .php from the file name making it example.com/filename, I also have it set to redirect/filename to /filename/. I now want to make it redirect /filename.php to /filename/. How can I do this?
What I have now is:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(([^/]+/)*[^./]+)/$ /$1.php

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
RewriteRule (.*)$ /$1/ [R=301,L]
</IfModule>

A: This will do the redirect and send the 301 status code, which tells browsers and search engines that it is a permanent redirection.
RewriteRule ^(.*)\.php$ $1/ [R=301,NC]


text:
Q: Representation of infinite group having finite image Let G be infinte group and  $\phi$: G $\longrightarrow$ $GLn(\Bbb{C})$ be any representation such that image set of $\phi$ is finite, ( i.e. $Im\phi$ is finite set.)
Questions are
1) Is this representation is completely reducible? (if yes hint for proof)
2) Is this representation is always unitary representation? (if yes hint for proof)
Maschke's theorem said that every representation of a finite group is completely reducible. (But in our case G is infinite group)


text:
Q: Corollary of Projection Theorem I am having difficulty proving the following:
If $M$ is a closed, proper, subspace of a Hilbert space $\mathfrak{H}$, then there exists a non-zero vector $y$ in $\mathfrak{H}$ with $y \perp M$.
Any help would be great.
Thanks.

A: Take any $x \in \mathfrak{H}$ such that $x$ is not in $M$. Then by the projection theorem, there exists an $z$ in $M$ such that $||x-y||$ is minimum. Show that $(x-y) \perp M$.


text:
Q: Database model for hierarchy Country - Organization - Suborganization - User Good day, I need to create an organizational structure which should support following hierarchies:
Country - Organization - User
Country - Organization - Suborganization - User

I thought about having three tables. Table Country (column id is three-letter ISO 3166-1 alpha-3):
CREATE TABLE `country` (
  `id` CHAR(3) NOT NULL,
  `country` VARCHAR(40) NOT NULL,
  PRIMARY KEY (`id`)
);

Table Organization:
CREATE TABLE `organization` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `country_id` CHAR(3) NOT NULL,
  `parent_id` INT(11) NULL DEFAULT NULL,
  `name` VARCHAR(40) NOT NULL,
  PRIMARY KEY (`id`),
  INDEX `idx_organization_1` (`parent_id` ASC),
  CONSTRAINT `fk_customer_country_1`
    FOREIGN KEY (`country_id`)
    REFERENCES `country` (`id`)
    ON DELETE CASCADE
    ON UPDATE CASCADE,
  CONSTRAINT `fk_organization_organization_1`
    FOREIGN KEY (`parent_id`)
    REFERENCES `organization` (`id`)
    ON DELETE CASCADE
    ON UPDATE CASCADE
);

Table User:
CREATE TABLE `user` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `organization_id` INT(11) NULL DEFAULT NULL,
  `username` VARCHAR(45) NOT NULL,
  `password` CHAR(32) NOT NULL,
  PRIMARY KEY (`id`),
  INDEX `idx_user_organization_1` (`organization_id` ASC),
  CONSTRAINT `fk_user_organization_1`
    FOREIGN KEY (`organization_id`)
    REFERENCES `organization` (`id`)
    ON DELETE CASCADE
    ON UPDATE CASCADE);

Table Country exists to prevent an organization be assigned an unsupported country code. I don't want to use MySql's enum. Although I'm working with MySql currently I need my schema to be independent on the specific DB.
Is this good design or is there a better one? I doubt because of following questions. I can do it "somehow" but I'd like to know best practice approach.

*

*A suborganization has a country code foreign key but country code is allready specified in the parent organization. I feel it's a kind of duplicity.

*If I delete a row in table country will cascade delete fail if the DB attempts to delete suborganization before deleting it's parent organization?

*Is null in foreign keys supported by all DBs? Organizations have null parent_id but parent_id is used in the self referencing forign key fk_organization_organization_1.

*Country code used in foreign keys is CHAR(3). Would it be faster is it would be INT(3)?

I'd appreciate any ideas. Many thanks. Vojtech

A: *

*I would make country_id nullable to avoid such duplication. Also
you can implement some application-level control to assure that at
least one of (country_id, parent_id) is not null.

*Deletion must
be successfull as long as the both references defined with "ON
DELETE CASCADE" clause

*All the DBs I have worked with support
nullable foreign keys: Oracle, DB2, MySQL, SQL Server, Postgre

*The difference is most probably negligible


text:
Q: Error 1004 when clearing a row in excel using vba I'm currently building a macro for excel and when I try and run it it randomly breaks
on lines when I try to clear a column.
It ALWAYS throws error 1004 and I don't know how to fix it since I'm quite new to Excel VBA.
This is the code it breaks on (with varying columns):
Worksheets(Sheet).Range("A3", Range("A3").End(xlDown)).Clear

Is this the wrong way of doing it? Should I use another function to clear columns?
Thanks in advance.

A: Each time you don't specify to which worksheet a range refers to, it is refered to the active worksheet. Try
Worksheets(Sheet).Range("A3", Worksheets(Sheet).Range("A3").End(xlDown)).Clear


text:
Q: How do I cleanly implement a delay between `print`s? I have a program which has two threads: the first one, constantly receives data, the second one, once some data has been received, it processes it every 60 seconds.
Within this second thread, there's also a sort of 'debug' printing happening, which I need to slow down to 3 minutes in between prints.
This is roughly the pseudocode of what's happening:
def data_stream():
    data.append(new_data)

def process_data():
    data.update()
    print(data)
    time.sleep(60)

def main():
    # I handle threading here

As you can see I want to add an if statement or something before the print to make sure that the printing is done once every 3 minutes. How can I do this?

A: Have a counter initially set to 0. Each time process_data wakes up from sleeping (every 60 seconds), it increments the counter by 1. When the counter reaches 3, it has been 180 seconds or 3 minutes since the last print. So, it issues the print operation and resets the counter back to 0.
OR
If the sleep duration is variable:
Instead of a counter, initialize a variable next_print_time with a call to time.time() + 180. This will be when you want to do the next print operation. Then every time you wake up, call time.time() and compare the result with next_print_time to determine whether you should print or not and compute and save in next_print_time a new value if you did just print. It gets a bit tricky when
N, the number of seconds between calls to your function does not evenly divide 180. If N is much smaller than 180, then it is probably adequate just to compare the current time of day with next_print_time and if it is greater, then print. But let's say N was 80. After 2 calls you would still have 20 seconds to go. But if you wait for one more call, you would be 60 seconds late. In that case I would do the print now. But in computing the next expiration time next_print_time, I would ALWAYS add 180 to the current value of next_print_time so that you AVERAGE one print every 180 seconds.


text:
Q: How to find all solutions of $\cos(z) = 0$, where $z\in\mathbb{C}$? I am stuck on finding all solutions of the equation $\cos(z) = 0$, where $z\in\mathbb{C}$.
I found this proof, however, I cannot figure out the logic behind the last few steps.
\begin{align}
\cos(z) &= \dfrac{e^{iz}+e^{-iz}}{z} \\\\
&= 0 \\\\
e^{iz}+e^{-iz} &= 0 \\\\
e^{i(x+iy)} &= -e^{-i(x+iy)} \\\\
e^{ix}e^{-y} &= -e^{ix}e^y \\\\
e^{ix}e^{-y} &= e^{i\pi}e^{-ix}e^y \\\\
e^{-y}e^{ix} &= e^ye^{i(\pi-x)} \\\\
|e^{-y}e^{ix}| &= |e^ye^{i(\pi-x)}|
\end{align}
This is where I get a bit confused. It follows from the modulus that,
[
e^{-y} = e^y
]
but why? Are we just shaving off the imaginary component? Or is it because $e^{-y}$ is real so it acts as the radius in $re^{i\theta}$?
So we have
\begin{align}
-y &= y \\\\
y &= 0 \\\\
e^{ix} &= e^{i(\pi-x)}
\end{align}
Therefore we have from this that, $x - (\pi - x)= 2\pi k, \forall k\in\mathbb{Z}$... but why is that? Where is the $2\pi k$ coming from? I understand it has to do with the unit circle... is $i = 2\pi k$?
From that result we have
\begin{align}
2x &= \pi + 2\pi k \\\\
x &= \dfrac{\pi}{2} + \pi k \\\\
z &= \dfrac{\pi}{2} + \pi k, \forall k\in\mathbb{Z}
\end{align}
When I tried this problem on my own I did,
\begin{align}
\cos(z) &= \dfrac{e^{iz}+e^{-iz}}{2} \\\\
&= 0 \\\\
e^{iz} + e^{-iz} &= 0 \\\\
e^{iz} &= -e^{-iz} \\\\
e^{iz} &= e^{i\pi}e^{-iz} \\\\
e^{iz} &= e^{i(\pi-z)} \\\\
z &= \pi - z \\\\
2z &= \pi \\\\
z &= \dfrac{\pi}{2}
\end{align}
But this does not result in the infinite solutions it should result in.

A: Hint for your own attempt: Just because two exponentials are equal, that doesn't mean the exponents are equal.

A: Maybe a faster trick is $$e^{iz} - e^{-iz} = e^{-iz}(e^{2iz} - 1) = 0$$
Then the right factor has to be zero, since the left factor can not.

A: To understand the proof that you found, this properties might be useful:
$\bullet$ For $x\in\mathbb{R}$, you have $e^{ix}=\cos x+i\sin x$, in particular $|e^{ix}|=1$.
$\bullet$ If $x\in\mathbb{R}$ and $e^{ix}=1$, then this means $\cos x+i\sin x=1$, comparing real and imaginary parts, this implies that $\cos x=1$ and $\sin x=0$, this happens when $x=2\pi k$ for some $k\in\mathbb{Z}$.


text:
Q: Is java multi thread can optimize multiple file writing I have a file of 400+ GB like:
ID Data ...4000+columns
001 dsa
002 Data
… …
17201297 asdfghjkl

I wish to chunk down the file as per ID to get faster data retrieval as like:
mylocation/0/0/1/data.json
mylocation/0/0/2/data.json
.....
mylocation/1/7/2/0/1/2/9/7/data.json

my code is working fine but whatever writer I'm using with loop end closing it takes at least 159,206 milisoconds for 0.001% completion of file creation.
In that case can multithread be an option to reduce Time complexity (as like writing 100 or 1k files at a time)?
My Current code is:
int percent = 0;
File file = new File(fileLocation + fileName);
FileReader fileReader = new FileReader(file); // to read input file

BufferedReader bufReader = new BufferedReader(fileReader);
BufferedWriter fw = null;
LinkedHashMap<String, BufferedWriter> fileMap = new LinkedHashMap<>();
int dataCounter = 0;

while ((theline = bufReader.readLine()) != null) {
    String generatedFilename = generatedFile + chrNo + "//" + directory + "gnomeV3.json";
    Path generatedJsonFilePath = Paths.get(generatedFilename);
    if (!Files.exists(generatedJsonFilePath)) {// create directory
        Files.createDirectories(generatedJsonFilePath.getParent());
        files.createFile(generatedJsonFilePath);
    }
    String jsonData = DBFileMaker(chrNo, theline, pos);
    if (fileMap.containsKey(generatedFilename)) {
        fw = fileMap.get(generatedFilename);
        fw.write(jsonData);
    } else {
        fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(generatedFilename)));
        fw.write(jsonData);
        fileMap.put(generatedFilename, fw);
    }
    if (dataCounter == 172 * percent) {// As I know my number of rows
        long millisec = stopwatch.elapsed(TimeUnit.MILLISECONDS);
        System.out.println("Upto: " + pos + " as " + (Double) (0.001 * percent)
        + "% completion successful." + " took: " + millisec + " miliseconds");
        percent++;
    }
    dataCounter++;
}
for (BufferedWriter generatedFiles : fileMap.values()) {
    generatedFiles.close();
}

A: That really depends on your storage. Magnetic disks really like sequential writes, so multithreading would probably have a bad effect on their performance. However, SSDs may benefit from multithreaded writing.
What you should do is Either separate your code to 2 threads, where one thread creates the buffers of data to be written to disk and the second thread only writes the data. This way your disk would always keep busy and not wait for more data to be generated.
Or to have a single thread that generates the buffers to be written, but to use java nio in order to write the data asynchronously, while going on to generate the next buffer.


text:
Q: Dynamically referencing a String in Strings.xml in Android Say I have the following my strings.xml file:
<string name="string0">Lorem</string>
<string name="string1">ipsum</string>
<string name="string2">dolor</string>

In my activity an ID is set based on the clicking of a button.  If the top button is clicked the id is 0, middle is 1 and bottom button is 2.
What would the syntax look like for referencing one of the three strings?
I know R.string.string0 works but I want to do something equivalent to:
R.string["string"+currentID]

where I derive the string to use based on the ID.
Just not sure what the syntax would look like in Java/Android.
Thanks in advance,
Tony

A: Could you not just use a string array in your resources instead of separate string entries?

A: That's a bad approach. It's slow. It'd be better to have an internal integer array with all the R.string IDs.
If you really insist on using a string-based approach, use Resources.getIdentifier().


text:
Q: Bash Script with Parsing Argument in Linux I want to write a bash script :
schedsim.sh [-h] [-c x] -i pathfile

Where :
• -h: print the current username.
• -c x : get an option-argument x and print out (x + 1). If no argument was found, print the default value is 1.
• -i pathfile: print the size of pathfile. The pathfile is a required argument. If no argument was found, print out an error message.
This is what I've done so far :
x=""
path=""
while getopts ":hc:i:" Option
do
case $Option in
h) echo -e "$USER\n"
;;
c) x=$optarg+1
;;
i) path=$(wc -c <"$optarg")
;;
esac
done

if [ -z "$x"]
then
 echo -e "$x\n"
else
 echo 1
fi

if [ -z "$path"]
then
 echo $path
else
 echo "Error Message"
 exit 1
fi

How to finish the option-argument,required-argument part and the error message part?

A: A rewrite:
while getopts ":hc:i:" Option; do
    case $Option in
        h)  echo "$USER"
            ;;
        c)  x=$(($OPTARG + 1))
            ;;
        i)  if [[ -f $OPTARG ]]; then
                size=$(wc -c <"$OPTARG")
            else
                echo "error: no such file: $OPTARG"
                exit 1
            fi
            ;;
    esac
done

if [[ -z $x ]]; then
    echo "you used -c: the result is $x"
fi

if [[ -z $size ]]; then
    echo "you used -i: the file size is $size"
fi

Notes:

*

*OPTARG must be in upper case.

*you need $((...)) for bash arithmetic

*check that the file exists before using it

*use a sensible filename (path does not represent the size of a file)

*there must be a space before ]

*echo -e "value\n" is too much work: you just want echo "value" unless you want to process escape sequences in the value:
$ var="foo\tbar\rbaz"
$ echo "$var"
foo\tbar\rbaz
$ echo -e "$var\n"
baz bar

$

Update: responding to comments: simplified and more complete option handling; expanded error handling.
#!/bin/bash
declare -A given=([c]=false [i]=false)
x=0
path=""

while getopts ":hc:i:" Option; do
    case $Option in
        h)  echo "$USER"
            ;;
        c)  x=$OPTARG
            given[c]=true
            ;;
        i)  path=$OPTARG
            given[i]=true
            ;;
        :)  echo "error: missing argument for option -$OPTARG"
            exit 1
            ;;
        *)  echo "error: unknown option: -$OPTARG"
            exit 1
            ;;
    esac
done

# handle $x
if [[ ! $x =~ ^[+-]?[[:digit:]]+$ ]]; then
    echo "error: your argument to -c is not an integer"
    exit 1
fi
if ! ${given[c]}; then
    printf "using the default value: "
fi
echo $(( 10#$x + 1 ))

# handle $path
if ! ${given[i]}; then
    echo "error: missing mandatory option: -i path"
    exit 1
fi
if ! [[ -f "$path" ]]; then
    echo "error: no such file: $path"
    exit 1
fi
echo "size of '$path' is $(stat -c %s "$path")"

A: I think what you're looking for is "argument parsing" in bash. Please take a look at this excellent answer: https://stackoverflow.com/a/14203146/3380671
Regarding this required/optional part: initialize the variable with an empty string and just check the string's length after the argument parsing.
FILE_PATH=""
# Do the argument parsing here ...
# And then:
if [ -z "$FILE_PATH" ]
then
  echo "Please specify a path. Aborting."
  exit 1
fi


text:
Q: Adding a partition in Yocto Generated Image I am building an Yocto Image for Intel Board.
By default the image while installing creates three partitions:

*

*boot

*rootfs

*swap

I need to add one more partition to it for storing my initrd image.. Which is the place I have to modify..

A: You need to check which WKS_FILE is used with bitbake -e | grep ^WKS_FILE=. You can look here for more informations on how to use WIC.


text:
Q: How do I group by an ID within a child collection I have a collection of A. A contains several properties, including a collection of B. B contains an ID. Using just the collection of A, how do I group by B.ID ??
A bit more detail:
public class Config
{
    public int Id { get; set; }
    public List<Feature> Features { get; set; }
}

public class Feature
{
    public string Title { get; set; }
    public int Id { get; set; }
}

If I had a collection of Config, I need to group by Feature.Id so that I had a result that looked something like this:
- Feature 1
    - Config1
        -Id
        -Features
    - Config2
        -Id
        -Features
    - Config3
        -Id
        -Features
- Feature 2
    - Config1
        -Id
        -Features
    - Config2
        -Id
        -Features
    - Config3
        -Id
        -Features
- Feature 3
    - Config1
        -Id
        -Features
    - Config2
        -Id
        -Features
    - Config3
        -Id
        -Features

How might I achieve that using LINQ?

A: listConfigs.SelectMany(c=>c.Features).GroupBy(f=>f.Id)


text:
Q: Get m Rows starting from nth row in dynamic MySql table The scenario is to list the photos uploaded by an User and his friends sorted by upload datetime. I have a MySql table Photo which is dynamic and contains the photos uploaded by all users.
Initially i get 10 rows of data by the below query. By the time i get next 10 rows, users will have uploaded more photos. So how can i select the next 10 rows starting from the row i already got before?
select * from photo p where p.handle in (select handle from friends where user = '$handle') or p.handle='$handle' order by uldatetime desc limit ".$start.", 10;

A: You must be having some Auto increment primary key in your database. And say you are fetching the records n reverse order,. say you had 50 records when you started displaying the results

*

*you fetched record from 50 to 41

*Mean while 5 more records got inserted so your last Id increased from 50 to 55

*now instead of displaying last 20 records fetch last 10 records having the primary key < 41 thus it will give you 40 to 31 irrespective of the records being inserted in the mean time

So your query would be updated as
select * from photo p where p.handle in (select handle from friends where user = '$handle') or p.handle='$handle' AND photo.[primarykey of photo table] < [last photo id displayed till now] order by uldatetime desc limit 0, 10;
replace [last photo id displayed till now] and [primarykey of photo table] with the respective variable and field.


text:
Q: ide does not find packages shim and proto packages in $GOPATH I have been setting up a small Hyperledger fabric application. It is already running and I can add delete and change users.
But until now I have been using nano to code until now.
I want to change to a proper ide (goland) for the sake of autocompletion and so on.
The problem is: On my local machine it can not find the packages
"github.com/hyperledger/fabric/core/chaincode/shim"
"github.com/hyperledger/fabric/protos/peer"

The gopath is set up correctly but the two packages are not in the folders. I.e also a local go build does not work.
The packages are present on the CLI though.
How can I install the dependencies so that I also have them on my local machine? And is this even desired and if so why not?
ps: I have already tried
go get -u github.com/hyperledger/fabric/core/chaincode/shim
the resulting error is:
package github.com/hyperledger/fabric/core/chaincode/shim: cannot find package "github.com/hyperledger/fabric/core/chaincode/shim" in any of:
    /usr/local/go/src/github.com/hyperledger/fabric/core/chaincode/shim (from $GOROOT)
    /home/funuser/go/src/github.com/hyperledger/fabric/core/chaincode/shim (from $GOPATH)

A: The issue is, the shim and protos were moved to stand-alone repositories several months ago, you need to do a go get on github.com/hyperledger/fabric-chaincode-go/shim and github.com/hyperledger/fabric-protos-go and change your import references to these new repos:
import (
   "fmt"
   "github.com/hyperledger/fabric-chaincode-go/shim"
   pb "github.com/hyperledger/fabric-protos-go/peer"
)

A: Unfortunately, go get only imports go code files.  Other assets like the raw proto files are excluded. An option is to check-out the git repo in $GOPATH/src/github.com/hyperledger/fabric

A: this worked for me https://www.programmersought.com/article/17446289383/
additional any one using this thread now need to update the pkgs to
"github.com/hyperledger/fabric-chaincode-go/shim"
pb "github.com/hyperledger/fabric-protos-go/peer"


text:
Q: System wont boot from degraded RAID6 I have a Debian Wheezy with 3 Partitions as RAID6. MD0 is for Root and OS, MD1 is for SWAP and MD2 for Files. While copy files to MD2 the system reports kernel panic and halts. I have had shutdown on the hard way. When I boot the system I get the message:
md0: cannot start dirty degraded array
md0: failed to run raid set
failed to run_array md0 inpu/output error
...
md0 is already in use
gave up waiting for root device common problems...
alert! dev/disk/by-uuid/eb8r..... does not exist.
dropping to a shell!
cant access tty job control turned off
((initframs)

proc/mdstat shows for md0 missing Partion sdg2. mdadm detail shows:
Raid Devices: 7
Total Devices: 6
Active D: 6
Working: 6
0...active sync sda2
...
6 removed sdf2

I am unsure what to do.

A: Restore from backup.
The next time you build the machine, make md0 RAID1 and only the large data stores RAID6.
Or better, invest in a hardware RAID card.


text:
Q: How to share self-returning method-chain with ANY class? UPDATE: I got it! It turns out that the "GENERICS" comment from Boris the Spider was exactly the clue I needed.
Original question and broken code first, solution below that. My generic design for needer-needable below that.
Original question and non-working code
On and off for the past few years, I have been trying to make self-returning method-chains "sharable" with other classes. This is to avoid the big pain of having to duplicate every self-returning function in every sub-class. The basic idea is that you pass the "needer" class to the "needable" class to start configuration, and then pass the needer back when configuration is over. The "needed" object is set internally.
For example:
ConfigUser cu = (new ConfigUser()).
   cfgFavNum().twentySeven().increment().timesTwo().endCfg().
   firstName("Kermit").lastName("Frog");

where
firstName("Kermit").lastName("Frog")

are part of the ConfigUser class, and
twentySeven().increment().timesTwo().endCfg()

comes from a separate "config the number" class. endCfg() returns the "needer" class (ConfigUser), at which point you should be able to continue the chain back in ConfigUser. But you can't. In the below code...and in every attempt I have made, I end up with the same error:
        C:\java\ConfigUser.java:4: cannot find symbol
        symbol  : method firstName(java.lang.String)
        location: interface NeedsFavNum
                 cfgFavNum().twentySeven().increment().timesTwo().endCfg().
                                                                          ^

If you comment out everything after endCfg() it reveals the problem:
ConfigUser cu = (new ConfigUser()).
   cfgFavNum().twentySeven().increment().timesTwo().endCfg();//.
   //firstName("Kermit").lastName("Frog");

         C:\java\ConfigUser.java:15: incompatible types
         found   : NeedsFavNum
         required: ConfigUser
                        cfgFavNum().twentySeven().increment().timesTwo().endCfg();//.
                                                                               ^

It can't return ConfigUser, which is sub-class of NeedsFavNum, which is the interface for all classes "needing" the favorite-number-config.
Of course, you can duplicate all the  functions so they ALL return ConfigUser-s, but that defeats the purpose of sharing chains. The purpose is to share these chains among ANY class, not just sub-classes.
Is there any way to achieve this, or to rethink the whole issue? I'm starting to think that it is simply not possible.
The details are in the below code. It works (...up to these compilation errors, anyway): copy it into a file named ConfigUser.java and give it a try.
Thank you for helping me.
public class ConfigUser implements NeedsFavNum  {
   public static final void main(String[] igno_red)  {
      ConfigUser cu = (new ConfigUser()).
         cfgFavNum().twentySeven().increment().timesTwo().endCfg().
         firstName("Kermit").lastName("Frog");

      cu = (new ConfigUser()).                  cfgFavNum().twentySeven().increment().timesTwo().endCfg();//.
      //         firstName("Kermit").lastName("Frog");
   }
//init
   public static final int iDEFAULT_FAV = 8;
   int iFav = -1;
   String sName1st = null;
   String sNameLast = null;
//funcs
   public ConfigUser()  {
   }
   public ConfigUser firstName(String s_s)  {
      sName1st = s_s;
   }
   public ConfigUser lastName(String s_s)  {
      sNameLast = s_s;
   }
   public FavNumConfigurator cfgFavNum()  {
      return  new FavNumConfigurator(this, iDEFAULT_FAV);
   }
   public ConfigUser setNumReturnNeeder(int i_favFullyConfigured)  {
      iFav = i_favFullyConfigured;
      return  this;
   }
}
interface NeedsFavNum  {
   ConfigUser setNumReturnNeeder(int i_fav);
}
class FavNumConfigurator  {
   NeedsFavNum nfn = null;
   int iFav = -1;
   public FavNumConfigurator(NeedsFavNum nf_n, int i_defaultFav)  {
      nfn = nf_n;
      iFav = i_defaultFav;
   }
   public FavNumConfigurator twentySeven()  {
      iFav = 27;
   }
   public FavNumConfigurator timesTwo()  {
      iFav = iFav * 2;
   }
   public FavNumConfigurator increment()  {
      iFav += 1;
   }
   public NeedsFavNum endCfg()  {
      return  nfn.setNumReturnNeeder(iFav);
   }
}

Solution with working code
It turns out that the "GENERICS" comment from Boris the Spider was exactly the clue I needed. Instead of the "needable" class being
FavNumConfigurator

now its
FavNumConfigurator<R extends FavNumNeeder>

where FavNumNeeder is the "needer" interface for any class needing the favorite-number configuration chain. Now the endCfg() function can return exactly the class I want.
Here's the fixed example (it works--copy and save it as ConfigUser.java):
/**

The main class: the "needer".

 **/
public class ConfigUser implements NeedsFavNum  {
   public static final void main(String[] igno_red)  {
      ConfigUser cu = (new ConfigUser()).
         cfgFavNum().twentySeven().increment().timesTwo().timesTwo().endCfg().
         firstName("Kermit").lastName("Frog");

      System.out.println("name:         " + cu.sName1st + " " + cu.sNameLast);
      System.out.println("favorite-num: " + cu.iFav);

      //---OUTPUT:
      //name:         Kermit Frog
      //favorite-num: 112
   }
//init
   public static final int iDEFAULT_FAV = 8;
   int iFav = -1;
   String sName1st = null;
   String sNameLast = null;
//funcs
   public ConfigUser()  {
   }
   //Self-returning configurers...START
      public ConfigUser firstName(String s_s)  {
         sName1st = s_s;
         return  this;
      }
      public ConfigUser lastName(String s_s)  {
         sNameLast = s_s;
         return  this;
      }
   //Self-returning configurers...END
   //Start fav-num configuration. Returns the "needable"
   public FavNumConfigurator<ConfigUser> cfgFavNum()  {
      return  (new FavNumConfigurator<ConfigUser>(this, iDEFAULT_FAV));
   }
   //Called by the "needable" in endCfg()
   public ConfigUser setNumReturnNeeder(int i_favFullyConfigured)  {
      iFav = i_favFullyConfigured;
      return  this;
   }
}

//The "needer" interface, for all classes needing favorite-number
//configuration
interface NeedsFavNum  {
   ConfigUser setNumReturnNeeder(int i_fav);
}

//The "needable" class: A shareable function-chain for favorite-number
class FavNumConfigurator<R extends NeedsFavNum>  {
   R nfn = null;
   int iFav = -1;
   public FavNumConfigurator(R nf_n, int i_defaultFav)  {
      nfn = nf_n;
      iFav = i_defaultFav;
   }
   //Self-returning configurers...START
      public FavNumConfigurator<R> twentySeven()  {
         iFav = 27;
         return  this;
      }
      public FavNumConfigurator<R> timesTwo()  {
         iFav = iFav * 2;
         return  this;
      }
      public FavNumConfigurator<R> increment()  {
         iFav += 1;
         return  this;
      }
   //Self-returning configurers...END
   public R endCfg()  {
      nfn.setNumReturnNeeder(iFav);
      return  nfn;
   }
}

Generic needer-needable design
Here is my design of a generic needer-needable solution that implements the above fix. The hardest part was avoiding circular dependencies between ConfigNeedable and ConfigNeeder.
public interface Chainable  {
   Chainable chainID(Object o_id);
   Object getChainID();
}
public interface ConfigNeedable<O,R extends ConfigNeeder> extends Chainable  {
   boolean isAvailableToNeeder();
   ConfigNeedable<O,R> startConfigReturnNeedable(R c_n);
   R getActiveNeeder();
   boolean isNeededUsable();
   R endCfg();
}
public interface ConfigNeeder  {
   void startConfig();
   boolean isConfigActive();
   <O> Class<O> getNeededType();
   <O> void setNeeded(O o_fullyConfigured);
}

Here is the same (working) example that uses this design, but since it depends on implementations in my personal library (which is unreleased at the moment, because it's changing minute to minute as I'm working on it), it won't compile. Hopefully it will help someone to see.
import  xbn.lang.chain.ChainableComposer;
import  xbn.lang.chain.ConfigNeeder;
import  xbn.lang.chain.SimpleConfigNeedable;
import  xbn.lang.chain.SimpleConfigNeeder;

public class ConfigNeedableNeederXmpl  {
   public static final void main(String[] igno_red)  {
      UserSettings us = (new UserSettings()).
         cfgFavInt().twentySeven().timesTwo().increment().endCfg().name("President Obama");
      System.out.println("name=" + us.sName);
      System.out.println("favorite number=" + us.iFav);
   }
}
class UserSettings implements ConfigNeeder  {
   private SimpleConfigNeeder scn = new SimpleConfigNeeder(Integer.class);
   public static final int iDEFAULT_FAV = 8;
   public int iFav = -1;
   public String sName = null;

   public UserSettings name(String s_name)  {
      sName = s_name;
      return  this;
   }
   public FavNumConfigurator cfgFavInt()  {
      FavNumConfigurator fnc = new FavNumConfigurator();
      fnc.startConfigReturnNeedable(this);
      return  fnc;
   }
   //ConfigNeeder: composition implementation...START
      public <O> void setNeeded(O i_fullyConfigured)  {
         scn.setNeeded(i_fullyConfigured);
         iFav = (Integer)scn.getElimNeeded();
      }
      public void startConfig()  {
         scn.startConfig();
      }
      public boolean isConfigActive()  {
         return  scn.isConfigActive();
      }
      public <O> Class<O> getNeededType()  {
         return  scn.getNeededType();
      }
      public void endConfig()  {
         iFav = (Integer)scn.getElimNeeded();
      }
   //ConfigNeeder: composition implementation...END
}
class FavNumConfigurator extends SimpleConfigNeedable<Integer,UserSettings>  {
   public FavNumConfigurator()  {
      super(33, true);
   }
   public FavNumConfigurator(Integer o_defaultNeeded, boolean b_defaultNeededUsable)  {
      super(o_defaultNeeded, b_defaultNeededUsable);
   }
   public FavNumConfigurator set(int i_i)  {
      try  {
         updateObject(i_i);
      }  catch(RuntimeException rtx)  {
         throw  newRTXWChainID("set", rtx);
      }
      return  this;
   }
   public FavNumConfigurator twentySeven()  {
      updateObject(27);
      return  this;
   }
   public FavNumConfigurator timesTwo()  {
      updateObject(getNeededInProcess() * 2);
      return  this;
   }
   public FavNumConfigurator increment()  {
      updateObject(getNeededInProcess() + 1);
      return  this;
   }
}

A: What you're looking for is effectively the C++ Curiously recurring template pattern.
You can put all your "shared" self-returning bits in a base abstract class, then extend it.
For example:
public abstract class Base<T extends Base<T>>
{
   protected abstract T self();

   protected String name;
   protected String address;

   public T withtName(String name)
   {
       this.name = name;
       return self();
    }

   public T withAddress(String address)
   {
       this.address = address;
       return self();
   }

}

class MyClass extends Base<MyClass>
{
    private String someOtherThing;

    public MyClass withSomeOtherThing(String thing)
    {
        this.someOtherThing = thing;
        return self();
    }

    @Override
    protected MyClass self()
    {
        return this;
    }
 }

Now you can do:
MyClass mc =
    new MyClass()
        .withAddress("111 elm")
        .withtName("Bob")
        .withSomeOtherThing("foo");


text:
Q: Need to re-render view and re-initialise controller in AngularJS I have a form that I want to reset. If I use the $setPristine method in Angular, this gets me some of the way.
However, if you look at the following isolated case, you will see that when you press the reset button to reset the form, a save message will be logged to the console. This is where I would write the code to save any changes made to the form to the server.
http://jsbin.com/OLIziRe/14/edit
In this example, save is logged when the value is different. This includes when the form is set to pristine, as the previous value will be whatever it was before the form was reset, and the new value will be undefined.
I do not want this behaviour. I only want to log the save message if there are changes — if the form is reset, there should be no "previous value".
The only solution I can come up with is to do some trickery in order to re-render the view and re-initialise the controller, thus losing all previous state.
http://jsbin.com/OLIziRe/12/edit
What would be the AngularJS way to do this?

A: You can do just like that with your first solution :
var app = angular.module('myApp', []);

app.directive('someDirective', function () {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function (scope, element, attrs, ctrl) {

        scope.$watch(function () {
          return ctrl.$modelValue;
        }, function (newValue, lastValue) {
          // Only save if the values do not match
          if(scope.someForm.$dirty){
            console.log(newValue !== lastValue ? 'save' : '');
          }
        });

    }
  }
});

Before the console.log you check if the form is in $dirty state, i.e if the user have set a value to the form.
When you do a $setPristine() you reset the form in $pristine state so the $dirty state is false.
Hope it helps !


text:
Q: MSBuild not able to build Nuget package because it's storing binaries in the wrong folder I have a Visual Studio solution which has several projects. One of them, which is called Extensions is supposed to build a Nuget package. Problem is that if I use MSBuild to build the solution (by executing msbuild from the command prompt), I get the following error for the Nuget package build task:
"C:\git\repo\dirs.proj" (default target) (1:7) ->
"C:\git\repo\sources\dirs.proj" (default target) (2:5) ->
"C:\git\repo\sources\dev\Sdk\CompanyName.ProductName.Extensions.csproj" (default target) (7:6) ->
(GenerateNuspec target) ->
  C:\Program Files\dotnet\sdk\5.0.408\Sdks\NuGet.Build.Tasks.Pack\build\NuGet.Build.Tasks.Pack.targets(221,5): error : Could not find a part of the path 'C:\git\ess\target\distrib\Debug\Amd64\CompanyName.ProductName.Extensions'. [C:\git\ess\sources\dev\Sdk\CompanyName.ProductName.Extensions.csproj]

Here is the CSPROJ file I have for this project:
<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <TargetFramework>netcoreapp3.1</TargetFramework>
        <AssemblyName>CompanyName.ProductName.Extensions</AssemblyName>
        <RootNamespace>CompanyName.ProductName.Extensions</RootNamespace>
        <TargetsForTfmSpecificBuildOutput>$(TargetsForTfmSpecificBuildOutput);IncludeCoreAssets</TargetsForTfmSpecificBuildOutput>
        <DebugType>full</DebugType>
        <DebugSymbols>true</DebugSymbols>
        <NuspecFile>CompanyName.ProductName.Extensions.nuspec</NuspecFile>
        <PackageOutputPath>$(DistribRoot)\$(Configuration)\$(Platform)\$(MSBuildProjectName)</PackageOutputPath>
        <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
        <SkipAssemblyComVisible>true</SkipAssemblyComVisible>
        <IncludeBuildOutput>false</IncludeBuildOutput>
        <OutputPath>$(DistribRoot)\$(Configuration)\$(Platform)\$(MSBuildProjectName)</OutputPath>
        <AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
        <NuspecBasePath>$(OutputPath)</NuspecBasePath>

    </PropertyGroup>

    <ItemGroup>
        <ProjectReference Include="..\Core\CompanyName.ProductName.Core.csproj" PrivateAssets="All" />
    </ItemGroup>

    <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
        <PlatformTarget>x64</PlatformTarget>
    </PropertyGroup>

    <Target DependsOnTargets="ResolveReferences" Name="IncludeCoreAssets">
        <ItemGroup>
            <BuildOutputInPackage Include="@(ReferenceCopyLocalPaths->WithMetadataValue('ReferenceSourceTarget', 'ProjectReference'))" />
        </ItemGroup>
    </Target>
</Project>

I personally think the issue is that for some reason when MSbuild is trying to create the Nuget package, it's trying to find the Extensions project DLLs in this path: \target\distrib\Debug\Amd64\CompanyName.ProductName.Extensions\, even though it actually built and stored the said binaries in this path earlier: \target\distrib\CompanyName.ProductName.Extensions\. <--- This is something I checked manually myself by examining the 'target' folder after running msbuild.
Visual Studio however doesn't have this issue. When I build this solution within Visual Studio, it stores the binaries for this Extensions project in \target\distrib\Debug\AnyCPU\CompanyName.ProductName.Extensions\ folder, which I think matches the pattern defined in the CSPROJ file:
<OutputPath>$(DistribRoot)\$(Configuration)\$(Platform)\$(MSBuildProjectName)</OutputPath>
Visual Studio also stored the Nuget package in this folder, which is also correct as per the <PackageOutputPath> spec mentioned in the CSPROJ file.
So can someone suggest why MSbuild is storing the built DLLs of this project in \target\distrib\CompanyName.ProductName.Extensions\, but is trying to find them in \target\distrib\Debug\Amd64\CompanyName.ProductName.Extensions\ ?
I think the issue is that for some reason, MSbuild isn't adhering to the <OutputPath> spec mentioned above when it's storing the built DLLs for this project.


text:
Q: Howto transform each set of two elements of a source list into a transformed list? I have a List<String> with elements like:
"<prefix-1>/A",
"<prefix-1>/B",
"<prefix-2>/A",
"<prefix-2>/B",
"<prefix-3>/A",
"<prefix-3>/B",

that is, for every <prefix>, there are two entries: <prefix>/A, <prefix>/B. (My list is already sorted, the prefixes might have different length.)
I want the list of prefixes:
"<prefix-1>",
"<prefix-2>",
"<prefix-3>",

What is a good way to transform a source list, when multiple (but always a constant amount of elements) correspond to one element in the transformed list?
Thank you for your consideration

A: If the prefixes are always a constant length, you can trim them out and put them into a Set:
List<String> elements = // initialize here
Set<String> prefixes = new HashSet<String>();
for( String element : elements) {
    String prefix = element.substring(0,"<prefix-n>".length());
    prefixes.add(prefix);
}
// Prefixes now has a unique set of prefixes.

You can do the same thing with regular expressions if you have a variable length prefix, or if you have more complex conditions.

A: Here is a solution that does not change the order of prefixes in the result. Since the elements are pre-sorted, you can take elements until you find a prefix that differs from the last taken element, and add new elements to the result, like this:
List<String> res = new ArrayList<String>();
String last = null;
for (String s : src) {
    String cand = s.substring(0, s.lastIndexOf('/'));
    // initially, last is null, so the first item will always be taken
    if (!cand.equals(last)) {
        // The assignment of last happens together with addition.
        // If you think it's not overly readable, you can move it out.
        res.add(last = cand);
    }
}

Here is a demo on ideone.

A: If the number if structurally similar elements is always the same, then you cam just loop over the beginning of the list to find out this number, and then skip elements to construct the rest.

A: public List<String> getMyList(prefix){
List<String> selected= new ArrayList<String>();

for(String s:mainList){
    if(s.endsWith(prefix.toLower())) // or .contains(), depending on
        selected.add(s);     // what you want exactly
}

return selected;

}


text:
Q: How can a spirit inhabit a jade bracelet? In The Empty Grave, we see that Penelope Fittes

 has a ghostly consultant, Ezekiel, whose Source is a jade bracelet that she wears.

However, every spirit that we've seen is tied to a piece of its body. It's somewhat of a fundamental tenet: Lucy's Lurker to its skull, the spirits in the Fittes crypt to their teeth,

Marissa Fittes to her body,

and so forth.
How does a spirit end up tied to a jade bracelet?

A: Caveat: I only read the first two books of the series.
Mortal remains aren't the only source of supernatural activity.
In the first publication of   What Binds the Departed to Us? Marissa Fittes proposed that :

certain objects connected to violent deaths or other traumas might
become 'psychically charged', and so act as a 'source' or 'gateway'
for supernatural activity. Human remains, precious belongings, or
indeed any potential object of desire might fall into this category,
as might the exact location of a murder or accident. ~Jonathan
Stroud - A Whispering Skull, ch 11

The source of the unfortunate Annabel Ward's ghost was her necklace,  given to her by her lover:

He indicated the small silver-glass box, which sat quietly between the
butter and the teapot. It glittered in the sunshine; inside, the
golden necklace could just be seen.
'But how can it be the Source?' I cried. 'It should've been her
bones.'
He shook his head pityingly. 'It only seemed that way because her
ghost vanished the moment you covered her body with the silver net.
But obviously you'd covered the necklace too, in the self-same action,
which was more than enough to seal it up. Then, when you pinched the
necklace—'
"…"
I held up my hands to silence them. 'Yes, yes. I understand all that.
But that's not what I'm saying. What I mean is, the Source is whatever
the Visitor is most attached to, isn't it? It's what it holds most
dear. So surely it really ought to have been her bones.' I reached
out, picked up the glass case by its cord and turned it in my fingers,
so that the pendant and spool of chain inside slid softly to and fro.
'But instead it turns out to be this. This necklace is more
significant to the spirit of Annabel Ward than her own bodily remains
. . . Isn't that a little odd?'
'No different from that motorbike rider we had one time,' George
pointed out.
~Jonathan Stroud: The Screaming Staircase,  ch 12

Of course Annie Ward was a type two,  and the biker maybe not even that, but a type one,  but probably the principle is the same: the source of a ghost is not limited to human remains.
Type threes are exceedingly rare, so we don't know that much about them, but so far nothing indicates that they're more choosy in selecting their sources.


text:
Q: Remove / hide browser generated "Waiting for someapicall.com..." in lower left corner? Is there a way to hide this "Waiting for..." alert during an api call? It shows up in the lower left corner of Chrome roughly where you see URLs when you hover links.
It seems browser-specific because I see it in Chrome but not in Firefox. Is it specific to api.airtable?
I have no idea where to begin researching this.

A: I don't think there is a way to remove it. According to W3Schools, there was: https://www.w3schools.com/jsref/prop_win_status.asp
It used to be called window.status. I think they removed it for a security reason. Now, no browsers support it. I even checked jsfiddle.net and it didn't work for Chrome. However, it is supported in Opera 12 and before. If you would like to set it in that:
window.status = "";

For other purposes, window.status still updates when the status has changed in the bottom left. That means you can read this bar, but you can't write to it.
However, as user13861136 said, you can add an aria-label="" to prevent it from appearing when hovering onto the respective element. This, however, won't work when the HTML file is being requested.
If you want to remove it from when you hover on <a> tags, then you can simply remove the href attribute and replace it with an onclick, which will run either window.open('https://example.com/') or window.location.href='https://example.com/' or something else if your target attribute is different. This will, however, remove all the browser defaults for the tag. This can be fixed by adding an empty href attribute like this: href="".
JSFiddle

A: You Unfortunately cannot remove this, this is permanent to every browser application, it also protects you from getting rickrolled.. However i think you can fix this with aria-label=""


text:
Q: When I'm starting the test I see 'data:,' in the chrome address bar and after few seconds the chrome window get closed When I'm starting the test I see 'data:,' in the chrome address bar and after few seconds the chrome window get closed instead of starting navigating to the url.
OS & Chrome info
Mac OS version: '10.11.1'
chrome version: Version 58.0.3029.110 (64-bit)
ChromeDriver: 2.29.461585
Driver info: driver.version: ChromeDriver
Code:
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

 /**
 * Created by sangita on 03/06/17.
 */
 public class GmailSigninTest {
 @Test
  public void gmailloginShouldBeSuccessful() throws
  InterruptedException {
 //1. Go to Gmail website
   System.setProperty("Webdriver.chrome.driver","/Users/sangita/Downloads/chromedriver");
    WebDriver driver = new ChromeDriver();
    Thread.sleep(50000);
    driver.get("http://www.gmail.com");

    System.out.println("Hello Google...");
    driver.quit();

}

}

Console error:
objc[10065]: Class JavaLaunchHelper is implemented in both
/Library/Java/JavaVirtualMachines/jdk1.8.0_73.jdk/Contents/Home/bin/java and/Library/Java/JavaVirtualMachines/jdk1.8.0_73.jdk/Contents/Home/jre/lib/libinstrument.dylib.
One of the two will be used. Which one is undefined.
Starting ChromeDriver
2.29.461585(0be2cd95f834e9ee7c46bcc7cf405b483f5ae83b) on port 47628 Only local connections are allowed.
org.openqa.selenium.SessionNotCreatedException: session not created
exception
from disconnected: unable to connect to renderer
(Session info: chrome=58.0.3029.110)
(Driver info: chromedriver=2.29.461585
(0be2cd95f834e9ee7c46bcc7cf405b483f5ae83b),platform=Mac OS X 10.11.1
x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 3.61 seconds
Build info: version: '3.4.0', revision: 'unknown', time: 'unknown'
System info: host: 'Sangitas-MacBook-Pro.local', ip: '192.168.1.121', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.11.1', java.version: '1.8.0_73'
Driver info: driver.version: ChromeDriver

at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:215)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:167)
at org.openqa.selenium.remote.JsonWireProtocolResponse.lambda$new$0(JsonWireProtocolResponse.java:53)
at org.openqa.selenium.remote.JsonWireProtocolResponse.lambda$getResponseFunction$2(JsonWireProtocolResponse.java:91)
at org.openqa.selenium.remote.ProtocolHandshake.lambda$createSession$22(ProtocolHandshake.java:365)
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
at java.util.Spliterators$ArraySpliterator.tryAdvance(Spliterators.java:958)
at java.util.stream.ReferencePipeline.forEachWithCancel(ReferencePipeline.java:126)
at java.util.stream.AbstractPipeline.copyIntoWithCancel(AbstractPipeline.java:498)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:485)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.FindOps$FindOp.evaluateSequential(FindOps.java:152)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.findFirst(ReferencePipeline.java:464)
at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:368)
at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:159)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:142)
at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:82)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:637)
at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:250)
at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:236)
at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:137)
at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:184)
at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:171)
at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:124)
at GmailSigninTest.gmailloginShouldBeSuccessful(GmailSigninTest.java:16)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)


text:
Q: Which Doctors have enjoyed longest and shortest period of their lives? As the title says, which incarnations of the Doctor lived longest and shortest? Here, I am not talking about age, but the period. For example, when The Master increased the age of The Doctor by 900 years, that would be counted as 1 year.

A: tl;dr: Elevent is the longest, followed by One. The shortest is harder to pin down but it's definitely either Eight, Nine, or The War Doctor.

As far as I know, the incident you mentioned with Ten being artificially aged 900 years is the only time The Doctor's age has increased in non-real-time (for him). So, the answer to both questions "who lived the longest" and "who aged the most" are otherwise the same.
The longest was Eleven, because of the roughly 900 years he spent on Tenzalore near the end of his life; prior to that, I believe the First Doctor was around 450 years old when he regenerated.
The shortest is a bit hard to pin down because Doctor Who was pretty sloppy with their ages and timelines prior to Ten's incarnation. If we just look at the classic show, it's pretty easy. We know that both Six and Seven, spent approximately 50 years as The Doctor before regenerating, which is smaller than any other classic regeneration by about 2/3.
However, around the time of the Last Great Time War, things go really wonky. Eight claimed to be about 1000 years old when he first appeared, and Nine later claimed to be about 1100 years old (indirectly, assuming he was ~200 when he stole the TARDIS). That means he spent around 100 years being both the Eighth Doctor and the War Doctor, with no way of knowing where that cut-off is.
Even worse, Ten later claims to be 903, meaning he somehow aged backwards between Nine and Ten.
So we really have no idea how long Eight, Nine or the War Doctor spent as The Doctor, but there's no way all three of them were The Doctor for more than 50 years. At least Eight or War must have been The Doctor for less than 50 years, and I suspect Nine is as well, since we watched almost his entire run as The Doctor occur in real-time with Rose.