text:
Q: How to Geocode a Google Sheet? I have a spreadsheet in Google Sheets with about 20-30 rows, with the following 6 columns:

ID
Name
Address
Cell_No
Latitude
Longitude

where the last two columns are empty.
What is an easy way, for a novice user who is a non-programmer, to geocode the address and populate the Latitude and Longitude fields with result of geocoding?
I just need to populate the Latitude & Longitude fields. I do not need to see any data on a map.

A: I found this Google Sheets formula in an answer in the Google Forums useful -
=IMPORTXML("http://maps.googleapis.com/maps/api/geocode/xml?address="&C1, "/GeocodeResponse//location")

Replace "C1" in the formula, with the cell that holds the address to geocode

A: GPS Visualizer is a handy site which performs batch geocoding.

To use this free utility, simply enter addresses in the box to the left, one per line, and click "Start geocoding" to find their latitude and longitude.

Note that "Google's policies do not allow output in text format" so you'll need to use another geocoder like Bing or MapQuest.
(Alternatively, and assuming this doesn't break the ToS, you can use Google as the geocoding engine, then download the results as a KMZ and extract the coordinates from this.)

A: Install the geocode plugin avasilable in the Google Sheets add-ons. It's a VBA excel macro, but it will help you if you are not clued up enough with coding.
Then in your main toolbar you should see the Geocode option. CLick it and you have 2 options: from address to lon,lat and other way round.
Remember, that script can do only 1000 records per day! Otherwise you won't be able to carry on, even with your  own macro!

A: 1) There's a bit of code you can add to your spreadsheet and run a macro. The instructions are detailed here: https://vilimpoc.org/blog/2013/07/11/google-spreadsheet-geocoding-macro/ with the code also available at https://github.com/nuket/google-sheets-geocoding-macro

2) CartoDB can pull in a google doc spreadsheet directly from your account, then you can export it back out:

3) Download your Google Drive Spreadsheet to a CSV, then use the MMQGIS Geocode with CSV plugin against the Google Maps API to geocode your spreadsheet

A: Openstreetmap (OSM) API can help finding lat,lon information without any subscription/ API key requirement.

*

*B1 = Address e.g 1600 Pennsylvania Avenue NW, Washington, DC 20500

*Replace space with "%20" in address
B2 =substitute(B1," ","%20")

*Create search link with response in xml format:
B3 ="https://nominatim.openstreetmap.org/search?q="&B2&"&format=xml&addressdetails=1"

*Get lat and lon data in XML format and parse it with XPath filters.
B4 =ImportXML(B3,"//place[1]/@lat")
B5 =ImportXML(B3,"//place[1]/@lon")
Implementation Example:
Get Latitude, Longitude of given address:

A: You can geocode a spreadsheet using Geocodio. You can upload the spreadsheet or just copy/paste the list of addresses, and it'll turn the addresses into latitude/longitude it for you. The first 2,500 addresses per day are free.
Disclosure: I'm a co-founder of Geoocodio.

A: For non programmers I would recommend the following approach:
Use Convert Address to Lat Long tool (CSV2GEO) that is designed to perform  batch geocoding by non programmers.
Here are the steps:

*

*Create your Google Sheet

*Then go File-Download->Excel or CSV

*Load the CSV2GEO tool and upload the file by either dragging it or simply browse from your local directories.

*Click on the header of column C , where the address is stored and select the appropriate address tokens. In the example select all.

*Click "Process Data" and the system will process the first ten rows and display them for you. Check if the addresses appear ok. You can also download into a file the first ten for detailed comparison. If all good, click "Get All Data". Somewhere along the way if you are not registered or logged in, the system will ask you to do that.
And of course, the tool provide daily free geocoding of hundred addresses.

Disclosure: I am the founder of CSV2GEO.

A: *

*Use free Google Sheets Add-on

*Select cells

*Watch it populate in columns Lat & Lon


text:
Q: How to save downloaded file in internal storage in android studio? I have a download button in my app.When I press the download  button it downloads an audio file from provided url.But the problem is I want to save the file in my internal storage folder called "DownloadTestFolder",it is showing an error.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:gravity="center"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Download"
        android:onClick="Download"
        android:id="@+id/download"/>

</LinearLayout>
public class DownloadTest extends Activity {

    DownloadManager downloadManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.download_test);
    }

    public void Download(View view){

        downloadManager=(DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);
        Uri uri=Uri.parse("My Url");
        DownloadManager.Request request = new DownloadManager.Request(uri);
        try{
            request.setDestinationInExternalPublicDir(getFilesDir()+"/DownloadTestFolder","/");
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            Long reference = downloadManager.enqueue(request);

        }catch (Exception e){
            /* Error
        }

    }
}

A: The DownloadManager can only download to external storage, you need to implement your own download manager.
Use this method to save file:
// DownloadFile AsyncTask
    private class DownloadFile extends AsyncTask<String, Void, Bitmap> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Bitmap doInBackground(String... URL) {

            String imageURL = URL[0];

            Bitmap bitmap = null;
            try {
                // Download Image from URL
                InputStream input = new java.net.URL(URL).openStream();
                // Decode Bitmap
                bitmap = BitmapFactory.decodeStream(input);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap result) {

            if (result != null) {
                File dir = new File(mContext.getFilesDir(), "MyImages");
                if(!dir.exists()){
                    dir.mkdir();
                }
                File destination = new File(dir, "image.jpg");

                try {
                    destination.createNewFile();
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    result.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
                    byte[] bitmapdata = bos.toByteArray();

                    FileOutputStream fos = new FileOutputStream(destination);
                    fos.write(bitmapdata);
                    fos.flush();
                    fos.close();
                    selectedFile = destination;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

Usage:

new DownloadFile().execute("url_here");

Note: I have added code for image type file

redpajama_set_name: RedPajamaStackExchange


text:
Q: Accessory Tapped not firing segue in UITableView I have a tableview with static cells.  I am using the cellForRowAtIndexPath: to create my cells.  One of them has an disclosure accessory indicator added to it programmatically.  And its respective method is like so:
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath{
     NSLog(@"aBTFRAIP:accessory tapped");
}

However there is no log in the console.  When I tap the cell, the didSelectRowAtIndexPath: method fires for that cell.  How can I fix this?

A: The accessoryButtonTappedForRowWithIndexPath: method works for the detail-disclosure button (the blue one) and only when the button itself is tapped on, as opposed to tapping on the cell.
If you tap the cell didSelectRowAtIndexPath: will get fired and not accessoryButtonTappedForRowWithIndexPath: like you want.


text:
Q: How to make so every time a user clicks in a button, it safes 2 strings into an Excel sheet in ASP.net? I'm currently building a website that simply presents to the user a string and a button, and what I intend to do is so when the user clicks the button, it then saves the string and another pre-determined string in an excel sheet. The idea is every time the user clicks the button, it saves the string on the street and writes it along with the excel sheet.
However, it's not working the way I intended and the second time the user presses the button, it gives me the following error on the Workbook.Save(); function:
System.Runtime.InteropServices.COMException
This makes it so it only saves the first string but crashes when I try to write the second.
Does anyone know a solution to this problem?
To open the workbook and worksheet I use the following code:
protected void Page_Load(object sender, EventArgs e)
{
    oXL = new Excel.Application();
    oXL.Visible = false;
    TextBox1.Text = line[0];
    if (File.Exists(@"C:\Users\Guilherme\source\repos\PAP\Dados.xlsx") == false)
    {
        oXL.Visible = false;

        oWB = (Excel._Workbook)(oXL.Workbooks.Add(Missing.Value));
    }
    else
    {
        oWB = (Excel._Workbook)(oXL.Workbooks.Open(@"C:\Users\Guilherme\source\repos\PAP\Dados.xlsx"));
    }
}

and
oSheet = (Excel._Worksheet)oWB.Sheets["Folha1"];
oSheet.Activate();

//Add table headers going cell by cell.

lastUsedRow = oSheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell).Row;

oSheet.Cells[1, lastUsedRow] = TextBox1.Text;
oSheet.Cells[2, lastUsedRow] = "Boa Ideia";

oWB.Save();

File.WriteAllLines(@"C:\Users\Guilherme\source\repos\PAP\Ideias.txt", line.Skip(1).ToArray());
Page.Response.Redirect(Page.Request.Url.ToString(), true);
oXL.Visible = true;
oXL.UserControl = true;

If there is any need for more code, just ask in the comments.


text:
Q: How to strsplit using '|' character, it behaves unexpectedly? I would like to split a string of character at pattern "|"
but
unlist(strsplit("I am | very smart", " | "))

[1] "I"     "am"    "|"     "very"  "smart"

or
gsub(pattern="|", replacement="*", x="I am | very smart")

[1] "*I* *a*m* *|* *v*e*r*y* *s*m*a*r*t*"

A: If you are parsing a table than calling read.table might be a better option. Tiny example:
> txt <- textConnection("I am | very smart")
> read.table(txt, sep='|')
     V1          V2
1 I am   very smart

So I would suggest to fetch the wiki page with Rcurl, grab the interesting part of the page with XML (which has a really neat function to parse HTML tables also) and if HTML format is not available call read.table with specified sep. Good luck!

A: | is a metacharacter. You need to escape it (using \\ before it).
> unlist(strsplit("I am | very smart", " \\| "))
[1] "I am"       "very smart"
> sub(pattern="\\|", replacement="*", x="I am | very smart")
[1] "I am * very smart"

Edit: The reason you need two backslashes is that the single backslash prefix is reserved for special symbols such as \n (newline) and \t (tab). For more information look in the help page ?regex. The other metacharacters are . \ | ( ) [ { ^ $ * + ?

A: The problem is that by default strsplit interprets " | " as a regular expression, in which | has special meaning (as "or").
Use fixed argument:
unlist(strsplit("I am | very smart", " | ", fixed=TRUE))
# [1] "I am"       "very smart"

Side effect is faster computation.
stringr alternative:
unlist(stringr::str_split("I am | very smart", fixed(" | ")))

A: Pipe '|' is a metacharacter, used as an 'OR' operator in regular expression.
try
unlist(strsplit("I am | very smart", "\s+\|\s+"))


text:
Q: Scala Case Class Recursive I was trying to recursively create a key, value pair map from a hierarchical case class structure, but no luck.
case class Country(id: Option[Long], name: String, states: Option[List[State]])
case class State(id: Option[Long], name: String, cities: Option[List[City]])
case class City(id: Option[Long], name: String)

So I was trying to extract that in Lists and zip to get the key value pair, then trying to do some recursive computation to obtain the same in the Lists of objects.
      val keys = country.getClass.getDeclaredFields.map(f => f.getName)
      val values = country.productIterator
      val m = (keys zip values.toList).toMap

This gives me 3 keys with their values.
My problem is to solve the recursive way in the List[City] inside State and List[State] inside Country.
Is there any good way to do that? I can't think in any good solution. I was trying to iterate over the map, matching where there is a List and iterate and trying to save this progress in a BufferList.
Has anyone trying to do something like this?
EDIT
I wasn't specific about the desirable output.
I want the child to be other maps, so getting the example from @Tienan Ren I tried to do something like this:
def toMap[T: TypeTag](clazz: scala.Product): Map[String, Any] = {

    def recursion(key: String, list: List[T]): Map[String, Any] = {
      list.toMap
    }

    val keys = clazz.getClass.getDeclaredFields.map(_.getName)

    val values = (keys zip clazz.productIterator.toList) map {
      case (key, value: List[T]) => recursion(key, value)
      case (key, value) => (key, value)
    }

    values.toMap
  }

Where the recursion should receive the list and back a Map.

A: Not sure why would you use Option[List[..]], empty list should be capable of representing the None case. Here is my implementation after removing Option for Lists.
  case class Country(id: Option[Long], name: String, states: List[State])
  case class State(id: Option[Long], name: String, cities: List[City])
  case class City(id: Option[Long], name: String)

The toMap function:
 import reflect.runtime.universe._

 def toMap[T: TypeTag](c: scala.Product): Map[String, Any] = {

   val keys = c.getClass.getDeclaredFields.map(_.getName)

   val z = (keys zip c.productIterator.toList) map {
      case (key, value: List[T]) if typeOf[T] <:< typeOf[scala.Product] =>
        (key, value.map(v => toMap(v.asInstanceOf[scala.Product])))
      case (key, value) => (key, value)
   }

   z.toMap
}

Output:
val country = Country(None, "US", List(State(None, "CA", City(None, "LA") :: Nil)))

println(toMap(country))

This gives you:
Map(id -> None, name -> US, states -> List(Map(id -> None, name -> CA, cities -> List(Map(id -> None, name -> LA)))))


text:
Q: JavaFX: Handle changes in TableColumn I have read this article about how to make TableColumn editable, I have made some modifications to obtain some reusable code as follows:
public static <T> void setEditableColumn(TableColumn<T, String> column, BiConsumer<T,String> modifiedField, String type){

    column.setCellFactory(TextFieldTableCell.forTableColumn());
    column.setOnEditCommit(event->{
        T model = event.getRowValue();
        if(!event.getNewValue().isEmpty()){
            modifiedField.accept(model,event.getNewValue());
        }
    });
}

But I want for this method to return the modified Model.
Iit is clear that I retrieve the modified model inside a lambda expression what are the possible ways of doing this. My objective is to be able to save that model in a database.


text:
Q: Getting the first URL of an image search result with google image API in PHP did you know a php script (a class will be nice) who get the url of the first image result of a google api image search? Thanks
Example.
<?php echo(geturl("searchterm")) ?>

A: I have found a solution to get the first image from Google Image result using Simple HTML DOM as Sarfraz told.
Kindly check the below code. Currently it is working fine for me.
$search_keyword=str_replace(' ','+',$search_keyword);
$newhtml =file_get_html("https://www.google.com/search?q=".$search_keyword."&tbm=isch");
$result_image_source = $newhtml->find('img', 0)->src;
echo '<img src="'.$result_image_source.'">';

A: You should be able do that easily with Simple HTML DOM.
Note: See the examples on their site for more information.

*

*A HTML DOM parser written in PHP5+ let you manipulate HTML in a very easy way!

*Find tags on an HTML page with selectors just like jQuery.


text:
Q: ¿Diferencia entre Spring Boot 2.0 Snapshot y M5? Veo que al crear un proyecto en Spring Initializr , me salen versiones de SpringBoot Snapshot y M5
¿Alguien sabe que significa?

A: Según la documentación oficial de maven la versión SNAPSHOT es la última versión de desarrollo de una dependencia,
Entre los problemas que incluyen son:

*

*puede ser una versión inestable

*puede no parecerse en nada de un día a otro

Debemos de evitarlas como la peste, pero en algunos casos nos vemos obligados a usarlas ya que contienen una característica que no ha salido en las demás versiones o contienen algún parche de seguridad.
Ahora, como te podrás imaginar... el mayor probema con los snapshots es que...
Tienden a desaparecer!
Sí, si buen puedes mantener una versión de desarrollo para cada hito, lo más común es que solamente tengas una versión de desarrollo a la vez, así que cada que subes de versión, también lo hace tu snapshot y es como si desapareciera del repositorio de snapshots.
Ahora en concreto ara el caso de spring, somo dice su documentación oficial usa un versionado semántico de la siguiente manera;
{número}.{tipo de entrega}

donde el número se subdivide en
{mayor}.{menor}.{micro}.

En base a el tipo de cambio que se realice y el tipo de entrega puede ser uno de los siguientes:

*

*BUILD-SNAPSHOT Una liberación actualmente en desarrollo. estos se producen en compilaciónes automáticas diarias y se despliegan al repositorio de snapshots.

*M{número} Una liberación de hito ( milestone en inglés). Normalmente se compilan manualmente, y contienen notas de liberación, se despliegan en el repositorio de hitos.

*RC{número} un candidato a liberación de disponibilidad general. Etos artefctos se producen de manera similar a los hitos, y también se despliegan en el repositorio de hitos.

*RELEASE: Liberación generl, se produce similr a los anteriores, pero se despliega directamente al repositorio de liberaciones de spring y al repositorio Maven Central.


text: Q: How to compute variance decomposition proportions of correlation matrix in python? I'm looking to identify collinear variables in my input matrix X. I'm able to get some metrics like VIF scores, condition number, condition indices, but unable to get variance decomposition proportions. Can someone please help me on how to compute variance decomposition proportions of correlation matrix in python?


text:
Q: cannot locate properties file in java path My code cannot locate the .properties file where i have stored login information.
I have put the file in the src folder to make sure it compiles, and it does correctly.
below is the current location of the file and how i am trying to access it.
I have tried various different paths but no luck.

A: Change your code;
 ResourceBundle bundle = ResourceBundle.getBundle("Selenium/readme");

to
 ResourceBundle bundle = ResourceBundle.getBundle("readme");

A: You don't compile a .properties file, you use it as is.
If you use a FileInputStream it will use the working directory which is set in your Run configuration (most likely the top directory)
But you are loading it as a resource which means it must be in your class path.  The simplest thing to do is to create a sub-directory for your configuration and add this to your programs class path.

A: Read properties file like:
ResourceBundle.getBundle("src/properties/readme.properties"); //Or simply "properties/readme.properties"

Put readme.properties under src/properties directory.

A: you can use this.getClass().getResourceAsStream("readme.properties");
for more information read:

A: I see that the .properties file is not inside the src folder. Also check the build path of your project.It will show you the src folders and the output folders location. Once you build the project using eclipse build project option, make sure your properties file is now available in the output folder.


text:
Q: Django : How to ensure a unique value for a field or group of fields in a record / form I'm using a ModelForm and i'm happy with the default validation and errors.
In my template i use a simple:
{{ form.as_ul }} with a {% if form.errors %} block.
The Model contains among other things those fields :
group1_wish1 = models.CharField(max_length=100, choices=GROUP1CHOICES)
group1_wish2 = models.CharField(max_length=100, choices=GROUP1CHOICES)
group2_wish1 ....
group2_wish2 ....

Each user is not allowed to make the same wish twice for each group : group_wish1 != group_wish2.
Is there a validation option for models that would let me achieve this ?
I've looked at unique but it works at the table level.
Any idea how i could it as simply as possible ?

A: The simplest way should be overriding the form's clean()-method in the definition of your ModelForm (forms.py).
See the Django documentation:
Cleaning and validating fields that depend on each other
ModelForms: Overriding the clean()-method


text:
Q: Delete row from a huge csv file in python I have a huge(240mb) csv file in which the top 2 rows are junk data.I want to remove this junk data and use the data starting after that.
I would like to know what the best options are .Since its a large file creating a copy of the file and editing it would be a time taking process.
Below is the csv eg:-
    junk,,,
    ,,,,
    No,name,place,destination
    1,abx,India,SA

What I would like to have is
 No,name,place,destination
 1,abx,India,SA

A: You can do this with tail quite easily
tail -n+3 foo > result.data

You said top 3 rows but the example has remove the top 2?
tail -n+2 foo > result.data

You can find more ways here
https://unix.stackexchange.com/questions/37790/how-do-i-delete-the-first-n-lines-of-an-ascii-file-using-shell-commands

A: Just throw those lines away.
Use Dictreader to parse the header
import csv

with open("filename") as fp:
  fp.readline()
  fp.readline()

  csvreader = csv.DictReader(fp, delimiter=',')
  for row in csvreader:
    #your code here

A: Due to the way file systems work, you cannot simply delete the lines from the file directly. Any method to do so will necessarily involve rewriting the entire file with the offending lines removed.
To be safe, before deleting your old file, you'll want store the new file temporarily until you are sure the new one has been successfully created. And if you want to avoid reading the entire large file into memory, you'll want to use a generator.
Here's a generator that returns every item from an iterable (such as a file-like object) after a certain number of items have already been returned:
def gen_after_x(iterable, x):
    # Python 3:
    yield from (item for index,item in enumerate(iterable) if index>=x)
    # Python 2:
    for index,item in enumerate(iterable):
        if index>=x:
            yield item

To make things simpler, we'll create a function to write the temporary file:
def write_file(fname, lines):
    with open(fname, 'w') as f:
        for line in lines:
            f.write(line + '\n')

We will also need the os.remove and os.rename functions from the os module to delete the source file and rename the temp file. And we'll need copyfile from shutil to make a copy, so we can safely delete the source file.
Now to put it all together:
from os import remove, rename
from shutil import copyfile

src_file = 'big_file'
tmp_file = 'big_file_temp'
skip = 2

with open(src_file) as fin:
    olines = gen_after_x(fin, skip)
    write_file(tmp_file, olines)

src_file_copy = src_file + '_copy'
copyfile(src_file, src_file_copy)

try:
    remove(src_file)
    rename(tmp_file, src_file)
    remove(src_file_copy)
except Exception:
    try:
        copyfile(src_file_copy, src_file)
        remove(src_file_copy)
        remove(tmp_file)
    except Exception:
        pass
    raise

However, I would note that 240 MB isn't such a huge file these days; you may find it faster to do this the usual way since it cuts down on repetitive disk writes:
src_file = 'big_file'
tmp_file = 'big_file_temp'
skip = 2

with open(src_file) as f:
    lines = f.readlines()

for _ in range(skip):
    lines.pop(0)

with open(tmp_file, 'w') as f:
    f.write('\n'.join(lines))

src_file_copy = src_file + '_copy'
copyfile(src_file, src_file_copy)

try:
    remove(src_file)
    rename(tmp_file, src_file)
    remove(src_file_copy)
except Exception:
    try:
        copyfile(src_file_copy, src_file)
        remove(src_file_copy)
        remove(tmp_file)
    except Exception:
        pass
    raise

...or if you prefer the more risky way:
with open(src_file) as f:
    lines = f.readlines()

for _ in range(skip):
    lines.pop(0)

with open(src_file, 'w') as f:
    f.write('\n'.join(lines))


text:
Q: Saving image in application documents I try to save a image from camera or photo album into application directory. But i cant find what i'm doing wrong.
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
[picker dismissModalViewControllerAnimated:YES];
theimageView.image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];

//obtaining saving path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,    NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:@"latest_photo.png"];

//extracting image from the picker and saving it
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:@"public.image"]){
    UIImage *editedImage = [info objectForKey:UIImagePickerControllerEditedImage];
    NSData *webData = UIImagePNGRepresentation(editedImage);
    [webData writeToFile:imagePath atomically:YES];

    BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:imagePath];
    if(fileExists){
        NSLog(@"image Exists");
    }
}
}

A: Why not use,
UIImage *orgImage = [info objectForKey:UIImagePickerControllerOriginalImage];

And where are failing? Did you get the image properly? or failing to write to document directory?

A: Check if the file in fact exist in file explorer. Maybe the compiler is right.


text:
Q: Missing Reputation Badge My answer in this post
What is ImmutableArray in c#  receives 4 votes.
Answer Badges rules of SO says:

*

*Nice Answer: Answer score of 10 or more

*Good Answer: Answer score of 25 or more
According to rules,shouldn't i get those badges? Not sure,whether i miss any calculation.Can anyone point this?

A: You get the badge for total votes, not for the reputation you earned.
The score of a post is the balance of upvotes and downvotes. Once the vote total (upvotes minus downvotes) goes over 10 you earn a badge.
For example, a post with 10 upvotes and one downvote has a score of 9 and won't be eligible for a badge until it gets another upvote.
4 up votes and 0 downvotes means your answer has a score of 4. The 40 reputation you earned is not the answer score. The two values are separate (reputation is capped for example, but your answer can still gain score by being upvoted).

A: "Score" relates to votes, not points of reputation earned from votes.
"Score" is a bit ambiguous, to be fair.

A: The wording is confusing.  The word "score" should be replaced,
I recommend rewording both to "Answer up-voted ## times or more".
Actually, "up-voting" is a bad use since "score" is the sum of up and down votes.
It does need to be something other than the innocuous "score".


text:
Q: Feh show custom text on image I'm trying to find an example for feh image viewer that you can use to show on screen your custom text.
I wrote my own application which is doing some action and one of them is to show on the image screen and upon the image some additional text is also displayed, which I get from a server response.
All of the documentation that I found does not have enough information.
--info [flag]command_line
          Execute command_line and display its output in the bottom left
          corner of the image. Can be used to display e.g. image dimensions or
          EXIF information. Supports FORMAT SPECIFIERS. If flag is set to ";",
          the output will not be displayed by default, but has to be enabled
          by the toggle_info key.

Does anyone have a command to show text as input or can also be read from a specified file.

A: You can use
--info "command"

which shows the output of the command in the bottom left corner of the picture. From man feh
--info [flag]commandline
        Execute commandline and display its output in the bottom left corner of
        the image.  Can be used to display e.g. image dimensions or EXIF informa‐
        tion.  Supports FORMAT SPECIFIERS.  If flag is set to ";", the output will
        not be displayed by default, but has to be enabled by the toggle_info key.

You can also use
--caption-path captions/

where you have text files with associated names for the picture files and the text in those files will be shown sidewise centered near the bottom of the picture.
-K, --caption-path path
        Path to directory containing image captions.  This turns on caption view‐
        ing, and if captions are found in path, which is relative to the directory
        of each image, they are overlayed on the displayed image.  E.g. with cap‐
        tion path "captions/", and viewing image "images/foo.jpg", the caption
        will be looked for in "images/captions/foo.jpg.txt".

It is also possible to control the size of the text, for example with
--font "yudit/24"

-e, --font font
        Set global font.  Should be a truetype font, resident in the current
        directory or the font directory, and should be defined in the form font‐
        name/points, like "myfont/12".

I don't know if/how to move the output from the default locations except by output of spaces and empty lines to push the actual text to the right or upwards.

Demo commands,
$ find
./captions
./captions/sudodus-background.png.txt
./sudodus-background.png

S feh --caption-path  captions/ --font "yudit/24" \
--info "echo '           This is output from an echo command\n\n'" \
sudodus-background.png

Demo picture,

A: feh --info "echo $mytext" would do what you want – echo just prints the arguments it was given.
To read from a file, use "cat $myfile" instead.


text:
Q: How to query server using UUIDs I have a project I am working on that uses UUIDs. Unfortunately, when I try to query my DB to check if a specific UUID exists it always returns false even if I can see it in it. To check that my program works fine I switched UUIDs to normal Long IDs and all works fine. Any help would be appreciated.
This is how I generate UUIDs in my Entity:
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(insertable = false, updatable = false, nullable = false)
private UUID uuid;

This is my logic check in my service class:
boolean exists = technologyRepository.existsByUuid(t.getUuid());
if (!exists) {
    throw new IllegalStateException("Technology with id " + t.getUuid() + " does not exist." );
}

exists always returns false when using UUIDS
java.lang.IllegalStateException: Technology with id 61b78428-8bbf-4d84-997f-62e0484c21cc does not exist.
this is the UUID stored in my DB:
61b784288bbf4d84997f62e0484c21cc0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
The following is the error message I get by running the query on my H2 server directly:
Values of types "BINARY(255)" and "CHARACTER VARYING(32)" are not comparable; SQL statement: SELECT * FROM TECHNOLOGY WHERE UUID = '61b784288bbf4d84997f62e0484c21cc' [90110-214] 90110/90110

A: in my case I used "String" for the field with UUID in the Java class mapping the table.
The column in the table on the database is a VARCHAR. It has worked ok for me.
  @Entity
  @Access(AccessType.FIELD)
  @Table(name = "TABLE_WITH_UUID")
  @NoArgsConstructor
  @AllArgsConstructor
  public class TableWithUuid implements Serializable {
  private static final long serialVersionUID = 1L;

  [... other fields ...]

  @Column
  @Getter
  @Setter
  private String uuid;

  [... other fields ....]

The code to create the UUID is the following:
    UUID uuid = UUID.randomUUID();
    String uuidString = uuid.toString();

I hope it can help.

A: Adding the parameter columnDefinition = 'BINARY(16) to the @Column annotation solved the issue


text:
Q: Why Redis considered to be CP? In short the brewer's CAP theorem states that any database is either CA,CP or AP
Why do people consider Redis as a CP database?

A: The CAP Theorem refers to distributed computer systems.
Since Redis is not per se distributed (clustering is under development) being CP/CA/PA depends on the clustering implementation.

A: @seppoo0010 is correct.  It is more meaningful to speak of a Redis node in terms of Atomicity, Durability, etc.
Also note that CAP is a somewhat problematic paradigm.  I second Dr. Brewer's recommendation of Coda Hale's informative rant. (See also comments by Daniel Abdi). Also note Jeff Darcy and Dan Weinreb's comments.
Stonebraker disagrees.
[Edit: Dan Weinreb's deep digging of CAP really is quite excellent.  Highly recommended]
Finally, here is "the proof" of CAP.


text:
Q: Gulp-useref is throwing error: "path must be a string" I'm using a gulpfile.js generated by yeoman's gulp-webapp generator and modified slightly by me to fit my needs. For some reason I keep running into an issue when I try to run the build process(default task). The error is thrown during the 'html' task and most of the error references are in `node_modules\gulp-useref\index.js'.
Here is the error output:
stream.js:94
    throw er; //Unhandled stream in pipe.

TypeError: path must be a string
    at Object.fs.openSync (fs.js:427:18)
    at Object.fs.readFileSync (fs.js:284:15)
    at Transform.<anonymous> (C:\dev\project\node_modules\gulp-useref\index.js:54:44)
    at Array.forEach (native)
    at Transform.<anonymous> (C:\dev\project\node_modules\gulp-useref\index.js:50:31)
    at Array.forEach (native)
    at Transform.<anonymous> (C:\dev\project\node_modules\gulp-useref\index.js:41:36)
    at Array.forEach (native)
    at Transform._transform (C:\dev\project\node_modules\gulp-useref\index.js:38:23)
    at Transform._read (C:\dev\project\node_modules\gulp-useref\node_modules\through2\node_modules\readable-stream\lib\_stream_transform.js:184:10)
    at Transform._write (C:\dev\project\node_modules\gulp-useref\node_modules\through2\node_modules\readable-stream\lib\_stream_transform.js:172:12)

Here is the HTML task:
gulp.task('html', ['styles', 'scripts'], function () {
    var jsFilter = $.filter('**/*.js');
    var cssFilter = $.filter('**/*.css');

    return gulp.src(['app/**/*.html','app/**/*.php'])
        .pipe($.useref.assets())
        .pipe(jsFilter)
        .pipe($.uglify())
        .pipe(jsFilter.restore())
        .pipe(cssFilter)
        .pipe($.csso())
        .pipe(cssFilter.restore())
        .pipe($.useref.restore())
        .pipe($.useref())
        .pipe(gulp.dest('dist'))
        .pipe($.size());
});

A: Short answer: TypeError: path must be a string means that there is an issue with the link/script paths. useref can't find the the file or directory you are pointing it to.
Long answer:
There were two issues I ran into.

*

*The link/script paths needs to be relative to the gulpfile or have an alternate directory to search.

<!-- build:css /styles/main.css -->
<link href="app/styles/base.css">
<link href="app/styles/article.css">
<!-- endbuild -->

OR

<!-- build:css(app) /styles/main.css -->
<link href="/styles/base.css">
<link href="/styles/article.css">
<!-- endbuild -->

*

*The yeoman gulpfile uses multiple alt directories which requires you to put them inside curly braces like this:

<!-- build:css({.temp,app}) /styles/main.css --> Works

But if you only have one alt directory and you leave it in the curly braces it will throw an error.

<!-- build:css({app}) /styles/main.css --> TypeError: path must be a string

This is because it is reading the path as C:\path\to\project\{app}\styles\style.css. This seems like odd behavior to me. I would think that it would iterate through the directories listed in the braces regardless of the length.


text:
Q: Restart Animation with Keyframes I can't for the life of me figure out how to restart my animation. Here's where I've gotten so far.
It's built with svg masking animations.
http://codepen.io/djmaller/pen/myrrbd
I want it to animate on as it currently is. But I want it to hold for a second or the last 10% of the animation, and then fade out before starting over. However I can't figure out how to prevent the animation from starting early. It's like it animates on fine but then it animates off in all random parts. So frustrating.
Does anyone have ideas here?
Am I building it wrong?
I believe the solution lies within the @keyframes in the CSS
HTML
<?xml version="1.0" encoding="utf-8"?>

<polygon id="clipmaskpath1" points="52.3,124.6 1.1,133.9 50.1,143.6"/>

<polygon id="clipmaskpath2" points="66.6,0.2 66.6,0.2 50.1,143.6 112.3,126.4 123.6,51.3"/>

<polygon id="clipmaskpath3" points="189.9,50.2 131.3,0.2 66.6,0.2 189.9,110.7 189.9,50.2"/>

<polygon id="clipmaskpath4" points="313.2,0.2 248.5,0.2 189.9,50.2 189.9,110.7"/>

<polygon id="clipmaskpath5" points="313.2,0.2 256.2,51.3 267.5,126.4 329.7,143.6"/>

<polygon id="clipmaskpath6" points="378.7,133.9 327.5,124.6 329.7,143.6"/>

<clipPath id="clipmaskA">
<use xlink:href="#clipmaskpath1" style="overflow:visible;"/>
</clipPath>

<clipPath id="clipmaskB">
<use xlink:href="#clipmaskpath2" style="overflow:visible;"/>
</clipPath>

<clipPath id="clipmaskC">
<use xlink:href="#clipmaskpath3" style="overflow:visible;"/>
</clipPath>

<clipPath id="clipmaskD">
<use xlink:href="#clipmaskpath4" style="overflow:visible;"/>
</clipPath>

<clipPath id="clipmaskE">
<use xlink:href="#clipmaskpath5" style="overflow:visible;"/>
</clipPath>

<clipPath id="clipmaskF">
<use xlink:href="#clipmaskpath6" style="overflow:visible;"/>
</clipPath>

<polygon id="A" style="clip-path:url(#clipmaskA)" points="52.3,124.6 1.1,133.9 50.1,143.6"/>

<polygon id="B" style="clip-path:url(#clipmaskB)" points="66.6,0.2 66.6,0.2 50.1,143.6 112.3,126.4 123.6,51.3"/>

<polygon id="C" style="clip-path:url(#clipmaskC)" points="189.9,50.2 131.3,0.2 66.6,0.2 189.9,110.7 189.9,50.2"/>

<polygon id="D" style="clip-path:url(#clipmaskD)" points="313.2,0.2 248.5,0.2 189.9,50.2 189.9,110.7"/>

<polygon id="E" style="clip-path:url(#clipmaskE)" points="313.2,0.2 256.2,51.3 267.5,126.4 329.7,143.6"/>

<polygon id="F" style="clip-path:url(#clipmaskF)" points="378.7,133.9 327.5,124.6 329.7,143.6"/>

And CSS
  svg {
  display:block;
  width:380px;
  height:144px;
  margin: 0 auto;
 }

/*Shape Fills*/

#A, #D, #F {
  fill:#FFA95A;
  }

#B, #E {
  fill:#FF8300;
  }

#C {
  fill:#FFB571;
  }

/* Opacity Animation */

@keyframes fade{
  90%{opacity:1}
  100%{opacity:0}
}

.fade{
  animation:fade infinite running 2s ease-in-out;
}

/*Mask Animations*/

#svg-logo #clipmaskA {
animation: move-mask-1 infinite running 2s ease-in-out;
}

#svg-logo #clipmaskB {
animation: move-mask-2 infinite running 2s ease-in-out;
}

#svg-logo #clipmaskC {
animation: move-mask-3 infinite running 2s ease-in-out;
}

#svg-logo #clipmaskD {
animation: move-mask-4 infinite running 2s ease-in-out;
}

#svg-logo #clipmaskE {
animation: move-mask-5 infinite running 2s ease-in-out;
}

#svg-logo #clipmaskF {
animation: move-mask-6 infinite running 2s ease-in-out;
}

/* Mask Translations */

@keyframes move-mask-1 {
  0% {transform: translate(-99.99%,0%)}
  15% {transform: translate(0,0)}
}

@keyframes move-mask-2 {
  16% {transform: translate(-18%,99.99%)}
  30% {transform: translate(0,0)}
}

@keyframes move-mask-3 {
  31% {transform: translate(-99.99%,-99.99%)}
  45% {transform: translate(0,0)}
}

@keyframes move-mask-4 {
  46% {transform: translate(-99.99%,99.99%)}
  60% {transform: translate(0,0)}
}

@keyframes move-mask-5 {
  61% {transform: translate(-20%,-99.99%)}
  75% {transform: translate(0,0)}
}

@keyframes move-mask-6 {
  76% {transform: translate(-99.99%,0)}
  90% {transform: translate(0,0)}
}

A: I just figured out that at the beginning of each @keyframe animation I needed to at a 0% translation that matches with where the mask is at the next step.
Before I had
@keyframes move-mask-2 {
  16% {transform: translate(-18%,99.99%)}
  30% {transform: translate(0,0)}
}

I fixed it by adding the line with 0%
@keyframes move-mask-2 {
  0%% {transform: translate(-18%,99.99%)}
  16% {transform: translate(-18%,99.99%)}
  30% {transform: translate(0,0)}
}


text:
Q: How to use Bearer Token on Git repository In my API testing automation framework, I'm using Bearer Token to validate the API. This token is in properties file. I cannot commit this property file on github as it contains api token. Can someone suggest how to use this API token when api testing framework will be invoked from jenkins it will take this git repo so how it will take the api access token(Bearer)?
How can I use api Bearer Token securely on github?

A: In your repository, you can store data as secrets, so they are not exposed to anyone by just viewing the repository.
Then you can use these secrets in a pipeline, for example as environment variables:
steps:
  - name: Hello world
    env:
      super_secret: ${{ secrets.SuperSecret }}

So you code has to be able to work with environment variables.


text:
Q: IE8 and "Img that was delivered securely" warning In my https application I am loading some images. If Img src is not available I will show the default image - I got this js that will do the job for IE also:
$(document).ready(function(){
  $("img").each(function(index) {
    $(this).error(function() {
      this.src = "/shared/ts/web/images/missing_img.gif";
    });
    $(this).attr("src", $(this).attr("src"));
  });
});

It works great with IE10, but with IE8 I have a security warning:
Do you want to view only the webpage content that was delivered securely?
If I click on yes -> I cannot see the missing_img.gif, if I click on no everything is ok.
Can you tell me why am I getting this warning and what can I do to remove it?
I don't want to change the client default IE8 settings.

A: From the looks of it you are not delivering that particuar image via https. Any resource that is not delivered by https can potentially be modified or read by an attacker whilst in transit. This will throw errors in some browsers, whilst others (such as Chrome) will 'cross out' your 'https' bit in the url to show that not all elements are secure.
To fix it, make sure that all the resources you deliver are via https. So in this case you might want to force it by doing
this.src = "https://mysite.com/shared/ts/web/images/missing_img.gif";

I'm not entirely sure why this isn't automatically using https. Maybe someone else can enlighten you on that one.

A: It's because your image (because you didn't specify https:// as protocol) gets the http:// protocol..
Since this on your secure site, it'll try to load "http://domain.com/shared/ts/web/images/missing_img.gif" and that's "not secure content on a secure site"
I think you can fix this by either make the path absolute (include the entire part of it including https://your-domain.com), or use "//" (double slashes) and omit the http(s): part, so it'll take the same protocol as the site (https when the site is secure, http otherwise).


text:
Q: Joomla FlippingBook plugin non-flash solution I need to create a version of an existing Joomla website that will be viewed by mobile devices, still in Joomla.
The existing website uses the FlipingBook component in order to display certain books. The component uses Flash, and it has a non-flash SEO version that doesn't look very good, also it doesn't have the "flipping" feature that it is supposed to provide.
Another thing is that it saves and uses the books in tables of its own. My website has to use the database of the existing website.
In conclusion, I need to figure out a way to view the existing data as organised by the FlippingBook component, in a non-flash way on my mobile version website.
Can anyone suggest some solution to this issue, or maybe another component or plugin, except me creating a new Joomla component?


text:
Q: Problem rendering characters with Freetype and OpenGL I've trying to develop a simple 2D game engine and I need to be able to draw text, so I decided to use the famous, freetype library.
My current goal is to render every character from 0 to 255, and store the appropriate information in a glyph object, top and left positions of the character, width and height and an OpenGL texture. (In the future I wish to remove having 1 texture per glyph, but before starting to work on that I need my characters to be displaying correctly).
First I got all characters garbled but then I checked out this question and figured out I had to copy the bitmap buffer into a new one with OpenGL required texture sizes(i.e. a power of two for both width and height). From there on, every character looked great, so I tried different font sizes to see if everything was working out OK, guess what...it wasn't, on small font sizes(i.e <30) every character with a small width ('l', 'i', ';', ':') showed up garbled.
http://img17.imageshack.us/img17/2963/helloworld.png
All distorted characters had a width of 1, which came out to two, because that's the first power of two, here's the code for rendering each character.
bool Font::Render(int PixelSize)
{
    if( FT_Set_Pixel_Sizes( mFace, 0, PixelSize ) != 0)
        return false;

    for(int i = 0; i < 256; ++i)
    {
        FT_UInt GlyphIndex;

        GlyphIndex = FT_Get_Char_Index( mFace, i );

        if( FT_Load_Glyph( mFace, GlyphIndex, FT_LOAD_RENDER ) != 0)
            return false;

        int BitmapWidth = mFace->glyph->bitmap.width;
        int BitmapHeight = mFace->glyph->bitmap.rows;

        int TextureWidth = NextP2(BitmapWidth);
        int TextureHeight= NextP2(BitmapHeight);

        printf("Glyph is %c, BW: %i, BH: %i, TW: %i, TH: %i\n", i, BitmapWidth, BitmapHeight, TextureWidth, TextureHeight);

        mGlyphs[i].SetAdvance(mFace->glyph->advance.x >> 6);
        mGlyphs[i].SetLeftTop(mFace->glyph->bitmap_left, mFace->glyph->bitmap_top);

        GLubyte * TextureBuffer = new GLubyte[ TextureWidth * TextureHeight ];

        for(int j = 0; j < TextureHeight; ++j)
        {
            for(int i = 0; i < TextureWidth; ++i)
            {
                TextureBuffer[ j*TextureWidth + i ] = (j >= BitmapHeight || i >= BitmapWidth ? 0 : mFace->glyph->bitmap.buffer[ j*BitmapWidth + i ]);
            }
        }

        for(int k = 0; k < TextureWidth * TextureHeight; ++k)
            printf("Buffer is %i\n", TextureBuffer[k]);

        Texture GlyphTexture;

        GLuint Handle;
        glGenTextures( 1, &Handle );

        GlyphTexture.SetHandle(Handle);
        GlyphTexture.SetWidth(TextureWidth);
        GlyphTexture.SetHeight(TextureHeight);

        glBindTexture(GL_TEXTURE_2D, Handle);

        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

        glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

        glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, TextureWidth, TextureHeight, 0, GL_ALPHA, GL_UNSIGNED_BYTE, TextureBuffer);

        mGlyphs[i].SetTexture(GlyphTexture);

        delete [] TextureBuffer;
    }

    return true;
}

The only solution I could find was a little if statement, changing the TextureWidth to 4 if it has the value of 2, and that way the text looks fine in every font size. But this doesn't make any sense to me, why would OpenGL reject width of 2 textures? Oh, and I've determined that the problem does not lie within the buffer, I printed it out and it looks just fine.
Can you think of any reason why this is happening?
Here's the rest of the (extremely) messy code, in case the problem does not lie within the Render function.
int NextP2(int Val)
{
    int RVal = 2;

 while(RVal < Val) RVal <<= 1;

 return RVal;
}

class Texture
{
    public:
        void Free() { glDeleteTextures(1, &mHandle); }

        void SetHandle(GLuint Handle) { mHandle = Handle; }
        void SetWidth(int Width) { mWidth = Width; }
        void SetHeight(int Height) { mHeight = Height; }

        inline GLuint Handle() const { return mHandle; }
        inline int Width() const { return mWidth; }
        inline int Height() const { return mHeight; }
    private:
        GLuint mHandle;
        int mWidth;
        int mHeight;
};

class Glyph
{
    public:

        void SetAdvance(int Advance) { mAdvance = Advance; }
        void SetLeftTop(int Left, int Top) { mLeft = Left; mTop = Top; }
        void SetTexture(Texture texture) { mTexture = texture; }

        Texture & GetTexture() { return mTexture; }
        int GetAdvance() const { return mAdvance; }
        int GetLeft() const { return mLeft; }
        int GetTop() const { return mTop; }

    private:
        int mAdvance;
        int mLeft;
        int mTop;
        Texture mTexture;

};

class Font
{
    public:
        ~Font() { for(int i = 0; i < 256; ++i) mGlyphs[i].GetTexture().Free(); }
        bool Load(const std::string & File);
        bool Render(int PixelSize);

        Glyph & GetGlyph(unsigned char CharCode) { return mGlyphs[CharCode]; }

    private:
        FT_Face mFace;
        Glyph mGlyphs[256];

};

I think that's about everything, please let me know if you've found the problem.
Best Regards and Thanks in Advance,

A: I bet I stumbled upon exactly the same problem with freetype and OpenGL last week.
OpenGL default is to consider that texture data rows are aligned on 4 bytes boundaries. This causes problems when texture width becomes 2 or 1 which are valid power-of-2 sizes.
Does setting the row alignment to 1 byte boundaries fix your problem ? Using
glPixelStore(GL_UNPACK_ALIGNMENT, 1)

HTH

A: You probably ran into a texture-wrapping issue.
The pixels rendered on one border of your texture 'bleed' over to the other side in OpenGls attempt to tile the texture. correctly.
If i am correct, changing you wrapping parameters to
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);

should make opengl clamp your texture at its edges, and draw your small textures correctly.
Update
I found something on a tutorial page:

If a small font's bitmaps are not
  aligned with the screen pixels,
  bilinear interpolation will cause
  artifacts. An easy fix for this is to
  change the interpolation method from
  GL_LINEAR to GL_NEAREST, though this
  may lead to additional artifacts in
  the case of rotated text. (If rotating
  text is important to you, you may want
  to try telling OpenGL to super sample
  from larger font bitmaps.)

A: Prepare yourself to support >256 characters (That is history)
and Right-to-left and left-to-right text flow as well as topdown flow.
Just a different topic hint for english speakers.

A: Use Freetype with ICU. Freetype alone can't render the glyphs properly. Use ICU for that.


text:
Q: R: ggplot: Combine geom_points using dplyr with group averages I'd like to add 2 different ggplots together using dplyr and ggplot:
iris_setosa<- iris %>% filter( Species == "setosa")%>%
           do(plots=ggplot(data=.) +
           aes(x=Petal.Width, y=Petal.Length) + geom_point()

iris_virginica<- iris %>% filter( Species == "virginica")%>%
           do(plots=ggplot(data=.) +
           aes(x=Petal.Width, y=Petal.Length) + geom_point()

Another way to ask: how do I filter by 2 variable names and then add them together in same ggplot using dplyr and color variable points differently?
Thank you.

A: Is this what you want?
library(tidyverse)

theme_set(theme_bw())

# Mean per Species
plt1 <- iris %>%
  filter(Species %in% c("setosa", "virginica")) %>%
  group_by(Species) %>%
  mutate(mean_length = mean(Petal.Length, na.rm = TRUE),
         mean_width  = mean(Petal.Width,  na.rm = TRUE)) %>%
  ungroup() %>%
  ggplot(., aes(x=Petal.Width, y=Petal.Length, color=Species)) +
  geom_point() +
  facet_grid(~ Species, scales = "free_x") +
  geom_hline(aes(yintercept = mean_length, linetype = c("Mean length"))) +
  geom_vline(aes(xintercept = mean_width,  linetype = c("Mean width")),
             show.legend = FALSE)

plt1 + scale_linetype_manual(NULL,
                              values = c(5, 3),
                              labels = c("Mean length", "Mean width")) +
  guides(color = guide_legend(order = 1)) +
  # Move legends closer to each other
  theme(
        legend.spacing.y = unit(0.05, "cm"),
        legend.margin = margin(0, 0, 0, 0),
        legend.box.margin = margin(0, 0, 0, 0))

# Mean for all Species
plt2 <- iris %>%
  filter(Species %in% c("setosa", "virginica")) %>%
  mutate(mean_length = mean(Petal.Length, na.rm = TRUE),
         mean_width  = mean(Petal.Width,  na.rm = TRUE)) %>%
  ggplot(., aes(x=Petal.Width, y=Petal.Length, color=Species)) +
  geom_point() +
  geom_hline(aes(yintercept = mean_length, linetype = c("Mean length"))) +
  geom_vline(aes(xintercept = mean_width,  linetype = c("Mean width")),
             show.legend = FALSE)

plt2 + scale_linetype_manual(NULL,
                             values = c(1, 4),
                             labels = c("Mean length (all)", "Mean width (all)")) +
  guides(color = guide_legend(order = 1)) +
  theme(
    legend.spacing.y = unit(0.05, "cm"),
    legend.margin = margin(0, 0, 0, 0),
    legend.box.margin = margin(0, 0, 0, 0))

Created on 2018-05-23 by the reprex package (v0.2.0).


text:
Q: Pattern match multiple dates According to this answer, I can match against DateTime.MinValue like this:
let result =
  match date with
  | d when d = DateTime.MinValue -> 1
  | _                            -> 0

How do I do this, if I have a match like this?
let result =
  match (startDate, endDate) with

This doesn't work:
let result =
  match (startDate, endDate) with
  | d when d = DateTime.MinValue, e when e = DateTime.MinValue  -> 0

Compiler error for the second when:
Unexpected keyword 'when' in pattern matching. Expected '->' or other token.

A: when can be added to a whole pattern, not to nested patterns, so you need something like this:
match (startDate, endDate) with
| d, e when d = DateTime.MinValue && e = DateTime.MinValue -> 0
| _ -> 1

Note that in this case, pattern matching is not really necessary, and you can go for a simpler if:
if d = DateTime.MinValue && e = DateTime.MinValue then
    0
else
    1

A: A possible alternative might be a partial active pattern, by moving part of the logic into it. The rule is matched when all tupled patterns are matched, and a partial active pattern is matched when it returns a Some value.
The partial active pattern here is of type DateTime -> unit option, as we going to ignore the return value anyway.
let (|IsMinValue|_|) d =
    if d = DateTime.MinValue then Some() else None

match startDate, endDate with
| IsMinValue, IsMinValue -> 0
| _ -> 1

A: I also would use a partial active pattern. But i would add arguments to the pattern that makes it more re-usable.
let (|IsEqual|_|) shouldBe actual =
    if actual = shouldBe then Some actual else None

let isMinDate startDate endDate =
    match startDate, endDate with
    | IsEqual DateTime.MinValue d, IsEqual DateTime.MinValue e -> 1
    | _ -> 0


text:
Q: Android Ratingbar displaying with shadow
Im showing a basic dialog API 21+ in which a ratingbar is being shown. It works fine on most devices but on some others it's being displayed like in the image.
I tried setting the height to 48dp, and setting the secondaryProgressTint to transparent.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="16dp">
    <RatingBar
        android:id="@+id/rate_this_app"
        android:layout_width="wrap_content"
        android:layout_height="48dp"
        android:max="5"
        android:numStars="5"
        android:progressTint="@color/red"
        android:rating="5"
        android:secondaryProgressTint="@android:color/transparent"
        android:stepSize="1" />

</LinearLayout>

I just want to eliminate those background shadows. I don't understand where they're comimg from, I'm not using any custom drawables for the stars.


text:
Q: How to ignore bad images in iraf imstat Suppose I have three fits images (file1.fits, file2.fits, and file3.fits).The middle one(file2.fits) is a bad image. When i run imheader it shows ![result]
file1.fits[1092,736][ushort]: bias
file2.fits[1092,736][ushort]: ASAS135406
file3.fits[1092,736][ushort]: flat
But when i run imstat it shows Result
ERROR: Pixel storage file is truncated (file2.fits)
It gave the result for the first image, but the execution stops as soon as it encounters a bad file. How to ignore the bad file and continue the execution


text:
Q: How to clone a space in Bluemix How to clone a space in Bluemix

*

*Keeping the same organization, but clone the space?

*or cloning the organization?
We have several developers working on similar stuff, therefore i am seeking for an easy way to duplicate or clone a "master organization" or space. Both would be sufficient. What would be the easiest way.

A: There is currently no way to clone orgs or spaces.

A: AFAIK, the only solution you have right now is to automatize runtime and services provisioning, apps deployment and configuration via script. So it is easy to reproduce the environment in any org/space you need as many times as you need.
Of course, it requires manual work to create those scripts the first time, but usually are part of a Continuous Integration and Continuous Delivery solution.


text:
Q: OAuth 2.0 How to validate token expiration date I am using MVC Web API inside MVC project.I use AuthorizeForAPI custom Attribute to valid the token. Everything is working great. My question is how to validate token expiration date so if the the token has expired i will send a message from server tells the user that your token has been expired
public class AuthorizeForAPI : AuthorizeAttribute
{

    public override void OnAuthorization(HttpActionContext actionContext)
    {
        string AccessTokenFromRequest = "";
        if (actionContext.Request.Headers.Authorization != null)
        {
            // get the access token
            AccessTokenFromRequest = actionContext.Request.Headers.Authorization.Parameter;

            var user = HttpContext.Current.User.Identity;
            if (!user.IsAuthenticated)
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, "Unauthorized user");

            }
        }
    }
}

A: using
 AccessTokenExpireTimeSpan = TimeSpan.FromDays(22), //22 day b4 expired

also
     var user = HttpContext.Current.User.Identity;
                    if (!user.IsAuthenticated)
                    {
                        actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, "Unauthorized user");
                    }
    else
        {
actionContext.Request.CreateErrorResponse(HttpStatusCode.NonAuthoritativeInformation, "Expired Token"
        }


text:
Q: Why are forms not submitted if there is more than one unnamed input? <form method="POST" action="">
    <input type="text" />
    <input type="text" />
</form>

(JSFiddle)
Press enter on the input. Then delete one of the inputs and press it again. When we have two inputs inside of the form, the form is not submitted (we need a button then). Why is that?

A: The default behavior of HTML forms with a single input is to submit on enter. As soon as you add a second input, pressing enter will no longer submit the form. The presense or lack of names has nothing to do with it.

A: The original idea was that very simple forms, typically consisting just of a text input box e.g. for searching, should be easy and quick: the user just types a search word and hits Enter. Controls of other types, such as checkboxes, do not affect this. Virtually all browsers implemented this idea.
But, according to the old idea, if there are several text input boxes, there are too big risks of premature form submission: the user hits Enter, expecting to get to the next field, or maybe just by accident.
Yet, IE introduced (in IE 4) the feature that makes Enter in a text input box submit the form, even if the form contains several such elements. Later, other browsers followed suit, and nowadays this (mis?)behavior appears to be "standard." This feature has been claimed to be an usability improvement, and in some special cases, it really is. More often, it is a risk, and therefore pages often try to use client-side scripting to prevent it.
However, at least on most modern browsers, this only happens when the form has a submit button. But if you omit the submit button, users will get puzzled, as most forms have a submit button or buttons.

A: Unless you put a button or input[type=submit] somewhere in the form. The button can be wrapped inside visibility:hidden css if you don't want it to show up.


text:
Q: Loop a function over speaker list I do have a problem concerning a function-build. I try to accomplish the following:
I do have a dataset df which contains a couple of variables, and amongst other things a text vector. This text vector should be cleaned (stemming, delete stop-words,...), processed through a supervised classification-algorithm and the result (readme.results$est.CSMF[[2]]) stored.
The function wasn't that hard to script, but what makes a big headache is the repetition of this function. I want to repeat/loop this list over a unique speaker list and over different points of time.
df_select <- df[df$date >= "1990-12-20" & df$date <= "1994-11-10",]

liste = list()

for(i in 1:)
{
  df_select <- subset(df_select, df_select$speaker == paste(speaker_list[i]))
  {
  complete_fun <- function(){

    df_sample <- sample_n(df_select , 200, replace = T)

    df_sample$text <- as.character(df_sample$text)

    df_sample$text <- tolower(df_sample$text)
    df_sample$text <- tm::removeNumbers(df_sample$text)
    df_sample$text <- tm::removePunctuation(df_sample$text)
    df_sample$text <- str_replace_all(df_sample$text, "  ", "")

    df_sample$text <- tm::removeWords(x = df_sample$text, stopwords(kind = "german"))

    setwd("~/test")

    fn1 <- function(N) {
      for(i in 1:length(N)) {
        file.out <- paste("data", i, ".txt", sep = "")
        write.table(N[i], file.out)
      }
    }

    fn1(df_sample$text)

    #### README - Classification Algorithm ####

    undergrad.results = undergrad(sep = ";", ignore.case=T, stem=T)
    undergrad.preprocess <- preprocess(undergrad.results)
    readme.results <- readme(undergrad.preprocess,n.subset=300)
    readme.results$est.CSMF[[2]]

  }
  liste[[length(liste)+1]] = readme.results$est.CSMF[[2]]
  }
  df_select <- df
}

A: Without your data I have no opportunity to test this, but something like this would be a better approach.
Define the functions by themselves.
setwd("~/test")

fn1 <- function(N) {
  for(i in 1:length(N)) {
    file.out <- paste("data", i, ".txt", sep = "")
    write.table(N[i], file.out)
  }
}

complete_fun <- function(x){

  df_sample <- sample_n(x, 200, replace = T)

  df_sample$text <- as.character(df_sample$text)

  df_sample$text <- tolower(df_sample$text)
  df_sample$text <- tm::removeNumbers(df_sample$text)
  df_sample$text <- tm::removePunctuation(df_sample$text)
  df_sample$text <- str_replace_all(df_sample$text, "  ", "")

  df_sample$text <- tm::removeWords(x = df_sample$text, stopwords(kind = "german"))

  fn1(df_sample$text)

  #### README - Classification Algorithm ####

  undergrad.results = undergrad(sep = ";", ignore.case=T, stem=T)
  undergrad.preprocess <- preprocess(undergrad.results)
  readme.results <- readme(undergrad.preprocess,n.subset=300)
  readme.results$est.CSMF[[2]]

}

Then we can create a loop that use this function and stores its output in a list
df_select <- df[df$date >= "1990-12-20" & df$date <= "1994-11-10",]

liste = list()

for (i in 1:length(speaker_list))
{
  df_select <- subset(df_select, df_select$speaker == paste(speaker_list[i]))
  liste[[i]] <-  complete_fun(df_select)

  #not necessary
  # df_select <- df
}


text:
Q: Is there any software which can filterout voice from a music track? Being an electronics and telecommunication engineer, I know its not possible .. (practically When I tried to use frequency bandpass filter .. For every range of frequency I used to get the voice unfiltered (where as music gradually diminishes) .. But I just want to know whether the world knows some trick .. ;)

A: Technically, it's next to impossible to remove specific sound from a waveform containing many sounds. The problem is similar to trying to find which car the city pollution belongs to.
That said, 'voice removal' techniques do exist, and rely on a few principles:

*

*If you take any digital mono sound, invert (or flip) the phase and mix-it over itself you will obtain a silent file. (-5 + 5 = 0)

*If you take a stereo sound, invert the phase of the left channel and mix-it over the right channel, you will obtain the sound of the difference between the left and right channel (-3 + 5 = 2) or, if you will, the stereo content minus the mono content.

*Voice is usually in mono, while most of the music is stereo.

To perform basic voice removal, follow these steps in any sound editing software:

*

*Open a stereo sound file

*Open another copy of the sound file and swap the channels (left becomes right, and vice versa)

*Invert the phase of both channels in your second sound file

*Mix your second soundfile back into your original sound file (mix at 100% level (or 0dB) on both your source and destination)

You will only hear the stereo sounds. If the voice was mono and dead center, you won't hear it. Unfortunately, you will also have chopped off any other mono sounds which will likely wreck the joy of listening to it. Furthermore, in real life chances are that stereo reverb was added to the voice so you will still hear that, as well as stereo choruses.
You could probaly push the technique further, such as limiting the process to the normal human range frequencies so that lower bass and higher treble sounds remain untouched, etc.
Lots of fun, but probably not what you were looking for.
TL;DR The best technique remain to sneak into a studio, steal the original instrument recordings and remix them without the voice. And that's what they do when they release "instrumentals".

A: This app claims to do what you want Music Morpher and this also http://www.blazeaudio.com/howto/vocalremover/

A: Being a producer of hip hop myself I know it's nearly impossible to do this without the original project file
I get begged all the time by dj's to send the master of the instrumental because they could not "filter out voices from the track"
The only trick I know of is looping which only works with short hip hop beats.

A: I want to add up some important points here. It's hardly possible to remove vocal sound from a music track. There are some software manufacturers that have announced that they can REMOVE the vocal but it's not true. All they can do is (all that is possible is) REDUCTION of it. Some tracks comprise stereo effects on vocal too. That is the worst case we might have to face, because all we can try to do is COMPRESSING one part of the track.
All I did with the software I tried is band rejection of 50Hz to ~=4000Hz. We must have to have a compromise between the voice o/p and instrumental effects, because the more we try to reduce the voice, the more we lose the instruments in the track.
I do agree with all the points written by mtone.
I tried my best. I could finally came up with some reduction of vocal effects in music tracks, but not LITERAL removal.
musicmorpher, blaze audio products and Power sound editor pro, etc., are suitable software. :-)


text:
Q: Does geodesics from solving full field equations are same as path from energy-momentum tensor? As we know, if we had an energy-momentum tensor in all space-time we could obtain the metric tensor by solving field equations.
Also i think if we had an energy-momentum tensor then we have distribution of matter in space-time which means we know its motion and its path.
Now my question is that if we calculate the geodesics from the metric, does this geodesic is same as the path obtained from energy-momentum tensor?

A: I will say that there is a subtle caveat here, that makes the answer not quite a pure "yes":
The Einstein equation factors in the back-reaction of matter -- if I have a mass distribution, then that matter will set up a gravitational field.  Then, that gravitational field will tell that mass how to move.  Any motion will change the gravitational field, which will then change the motion of the matter distribution.  Therefore, if we solved the Einstein equation for a full matter distribution, all of these influences would be noted -- one end of the distribution would be pulled to the other, and the distribution would emit gravitational radiation as it moved, and lose matter.
Pure geodesic motion, however, only applies to particles whose mass is so small relative to the curvature around them that we can effectively ignore the gravitational field that they set up, and that are so small that the curvature of spacetime is essentially constant over the surface of the object.  It is only these particles that travel along geodesics.  If you relax either assumption, then the motion of the object will be predicted by the Einstein equation, but not by the geodesic equations.

A: Yes. By definition geodesics come from a metric.
The way you get geodesics from the energy momentum tensor is
by deriving the metric tensor from it using Einstein's equations:
$$G_{\mu \nu} + \Lambda g_{\mu \nu}= {8\pi G\over c^4} T_{\mu \nu}$$
and that is the spacetime metric of general relativity.
So the geodesics must be the same since they minimize the same metric.


text:
Q: JQuery DataTables with ServerSide Processing in Spring (with Java and Thymeleaf) I have a Spring Boot application using Java and Thymeleaf. In it, I have a page with a JQuery DataTable. This table has thousands of rows in it, and so while I currently just put it all on the page and let JQuery handle it entirely, I want to switch to using ServerSide processing for the paging, sorting, etc.
I am set up to do this on the back-end, where I can pass a start and end row number and sort information dynamically to my SQL query. However, my issue is that I just can't figure out exactly how DataTables is trying to notify me via controller when the user clicks the 'next page' button, or a sort button. Where/how can my controller pick up this information, so that I can plug it into my SQL query and return what is necessary?
So, lets say I have an example object, like a "Person".
public class Person {

    private static String PERSON_IMAGE = "";
    private static String PERSON_IMAGE_2 = "";

    private String name;
    private String socialSecurity;
    private String birthdate;
    private String gender;
    private String personImage;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSocialSecurity() {
        return socialSecurity;
    }

    public void setSocialSecurity(String socialSecurity) {
        this.socialSecurity = socialSecurity;
    }

    public String getBirthdate() {
        return birthdate;
    }

    public void setBirthdate(String birthdate) {
        this.birthdate = birthdate;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getPersonImage() {
        if(null != birthdate) {
            return PERSON_IMAGE;
        } else {
            return PERSON_IMAGE_2;
        }

    }
}

So, on my Thymeleaf HTML page, I used to have the following: (Version 1)

            Name
            Social Security
            Birthdate
            Gender

            name
            socialSecurity
            birthdate
            gender

My page controller was very simple, and just passed in a full list of people, as follows: (Version 1)
@GetMapping("/ApplicationName/MyDataTablePage")
public String myDataTablePage(Model model) {

    SearchCriteria searchCriteria = new SearchCriteria();
    searchCriteria.setOrderByString("name");
    searchCriteria.setUsePaging(false);
    searchCriteria.setFIRST_NUMBER(null);
    searchCriteria.setLAST_NUMBER(null);

    model.addAttribute("peopleList", myMapperService.getPeople(searchCriteria)); //returns an ArrayList<Person>

    return "/pages/MyDataTablePage";
}

And finally, my Javascript used to have the following: (Version 1)
$(document).ready(function() {
    $('#myDataTable').DataTable({
        "destroy" : true,
        "scrollY" : 300,
        "scrollCollapse" : true,
        "paging" : true,
        "autoWidth" : true,
        "ordering" : true,
        "searching" : false,
        "order" : [ [ 0, 'asc' ] ],
        "pageLength" : 20,
        "lengthChange" : false,
        "pagingType" : "full_numbers",
        "dom" : '<"top"ip>rt<"bottom"fl><"clear">'
    });
});

This worked, but I wanted to switch the DataTable to use serverside processing, and so the first step was to (1) change the main page controller to stop appending the list of People to the model, (2) to create a new controller which would return my ArrayList as JSON for the DataTable to call by itself, (3) to change the html of the main page to no longer provide any tbody tag to the DataTable, and (4) to change the javascript where the table is created to put the data in by itself.
=============================================================
That led me to version 2 of the following elements.
My changed Thymeleaf HTML page: (Version 2)

            Name
            Social Security
            Birthdate
            Gender

My changed page controller: (Version 2)
@GetMapping("/ApplicationName/MyDataTablePage")
public String myDataTablePage(Model model) {

    return "/pages/MyDataTablePage";
}

My new DataTables controller:
@RequestMapping(path = "/ApplicationName/Data/Person", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public List<Person> getPersonData() {
    System.out.println("I was called!");

    SearchCriteria searchCriteria = new SearchCriteria();
    searchCriteria.setOrderByString("name");
    searchCriteria.setUsePaging(false);
    searchCriteria.setFIRST_NUMBER(null);
    searchCriteria.setLAST_NUMBER(null);

    return myMapperService.getPeople(searchCriteria); //returns an ArrayList<Person>
}

My changed (much more complicated) Javascript: (Version 2)
$(document).ready(function () {
     $('#myDataTable').DataTable({
         'destroy' : true,
         'serverSide' : true,
         'sAjaxSource': '/ApplicationName/Data/Person',
         'sAjaxDataProp': '',
         'order': [ [ 0, 'asc' ] ],
         'columns':
         [
            {  'data': 'name',
                'render': function(data, type, row, meta){
                    if(type === 'display'){
                        data = '' + data + ''
                    }
                    return data;
                }
            } ,
            { 'data': 'socialSecurity'} ,
            { 'data': 'birthdate'} ,
            { 'data': 'gender'}
         ],
         'scrollY' : 300,
         'scrollCollapse' : true,
         'paging' : true,
         'autoWidth' : true,
         'ordering' : true,
         'searching' : false,
         'pageLength' : 20,
         'lengthChange' : false,
         'pagingType' : 'full_numbers',
         'dom' : '<"top"ip>rt<"bottom"fl><"clear">'
     });
 });

=============================================================
And that works, too. Especially if I remove the "'serverSide' : true," configuration - the DataTable works exactly like it used to before I made the above changes, but now it calls my new Data JSON controller instead of using a model attribute.
Problem:
However, with the "'serverSide' : true," configuration added to the DataTable, each time I go to a new 'page' of the table, it just recalls my "/Clinic/Detail/Data/Patient" controller each time.
But, I need DataTables to pass my controller information about what page the user has selected, or what column the user tried to sort on. I also need to pass the table (dynamically) the total number of rows there are (count) so that DataTables can properly set up the page numbers for the user.
Is DataTables sending some additional parameters to my controller that I can pick up? Something like a @PathVariable("whatever")?
I feel like I am so close to getting this working, but I'm stuck at this point.
I would really appreciate any help!

A: I found 2 solutions:

*

*Look at this post: Spring Boot + Bootstrap + Thymeleaf Datatable

*Look at this github project: spring-data-jpa-datatables

A: I have managed to solve my issue.
My HTML for the table remained the same, as follows:

            Name
            Social Security
            Birthdate
            Gender

My Controller for the page remained the same, as follows:
@GetMapping("/ApplicationName/MyDataTablePage")
public String myDataTablePage(Model model) {

    return "/pages/MyDataTablePage";
}

My Controller for the Table which retrieves the data needed to change. First, it needed to get the @RequestParam that datatables was sending, which included all the parameters that I needed regarding how many records I needed to show, which record I needed to sort at, and which cell was being sorted on. Second, instead of just returning a List<Person>, it needed to return a well-formed JSON object with certain parameters that Datatable uses to decide how many pages to show on screen, as well as the data List<Person> itself.
@RequestMapping(path = "/ApplicationName/Data/Person", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public TableBean getPersonData(@RequestParam Map<String, String> allRequestParams) {

    TableParameters tableParameters = myMapperService
            .getTableParameters(allRequestParams);

    return myMapperService.mapTableBean(tableParameters); //returns an TableBean which contains the ArrayList<Person>
}

In order for this to work, I needed to make a few new classes and methods. First, I made a TableParameters bean which holds all of the parameters for my Data Table:
public class TableParameters implements Serializable {
    private static final long serialVersionUID = 1L;

    private Integer iDisplayStart;

    private Integer iDisplayLength;

    private Integer iColumns;

    private String sSearch;

    private Boolean bRegex;

    private Integer iSortingCols;

    private Integer sEcho;

    private Integer sortedColumnNumber;

    private String sortedColumnName;

    private String sortedColumnDirection;

    // ... getters and setters

}

And then I needed to make a method that would pull these variables off of the Request Parms and map them to the new bean. This tells me what to use in my SQL as far as how to sort, and which numbers to start on and return.
private static String iDisplayLength = "iDisplayLength";
private static String iDisplayStart = "iDisplayStart";
private static String iColumns = "iColumns";
private static String sSearch = "sSearch";
private static String bRegex = "bRegex";
private static String iSortingCols = "iSortingCols";
private static String sEcho = "sEcho";
private static String iSortCol_0 = "iSortCol_0";
private static String sSortDir_0 = "sSortDir_0";

public TableParameters getTableParameters(Map<String, String> allRequestParams) {

    TableParameters finalBean = new TableParameters();

    if (null != allRequestParams.get(bRegex)) {
        finalBean.setbRegex(new Boolean(allRequestParams.get(bRegex)));
    }
    if (null != allRequestParams.get(iColumns)) {
        finalBean.setiColumns(new Integer(allRequestParams.get(iColumns)));
    }
    if (null != allRequestParams.get(iDisplayLength)) {
        finalBean.setiDisplayLength(new Integer(allRequestParams.get(iDisplayLength)));
    }
    if (null != allRequestParams.get(iDisplayStart)) {
        finalBean.setiDisplayStart(new Integer(allRequestParams.get(iDisplayStart)));
    }
    if (null != allRequestParams.get(iSortingCols)) {
        finalBean.setiSortingCols(new Integer(allRequestParams.get(iSortingCols)));
    }
    if (null != allRequestParams.get(sEcho)) {
        try {
            finalBean.setsEcho(new Integer(allRequestParams.get(sEcho)));
        } catch (Exception e) {
            // ignore
        }
    }
    if (null != allRequestParams.get(sSearch)) {
        finalBean.setsSearch(allRequestParams.get(sSearch));
    }

    int numberOfColumnsSortedOn = 0;
    if (allRequestParams.containsKey(iSortingCols) && null != allRequestParams.get(iSortingCols)) {
        numberOfColumnsSortedOn = new Integer(allRequestParams.get("iSortingCols")).intValue();
    }

    if (numberOfColumnsSortedOn > 0) {
        if (null != allRequestParams.get(iSortCol_0)) {
            finalBean.setSortedColumnNumber(new Integer(allRequestParams.get(iSortCol_0)));
        }
        if (null != allRequestParams.get(sSortDir_0)) {
            finalBean.setSortedColumnDirection(allRequestParams.get(sSortDir_0));
        }
        String keyForName = "mDataProp_" + finalBean.getSortedColumnNumber();
        if (null != allRequestParams.get(keyForName)) {
            finalBean.setSortedColumnName(allRequestParams.get(keyForName).toUpperCase());
        }
    }
    return finalBean;
}

Similarly, the Return json object TableBean needed to be created which has, not lonly a List<Person> on it, but also the necessary count information that datatable uses to show page numbers to the user. This is what is now returned in the table controller method, instead of just the basic list.
public class TableBean implements Serializable {
    private static final long serialVersionUID = 1L;

    private int iTotalRecords;

    private int iTotalDisplayRecords;

    private String sEcho;

    private List data;

    public TableBean(int iTotalRecords, int iTotalDisplayRecords, String sEcho, List data) {
        super();
        this.iTotalRecords = iTotalRecords;
        this.iTotalDisplayRecords = iTotalDisplayRecords;
        this.sEcho = sEcho;
        this.data = data;
    }

    // ... getters and setters
}

And the mapTableBean method that pulls it all together by actually calling the database to get the records.
public TableBean mapTableBean(TableParameters tableParameters) {
    int iTotalRecords = database.getCount();
    int iTotalDisplayRecords = iTotalRecords;
    if (null != tableParameters.getsEcho()){
        String sEcho = tableParameters.getsEcho().toString();
    }
    List data = database.search(tableParameters.getiDisplayStart(), tableParameters.getiDisplayLength(),
            tableParameters.getSortedColumnName(),
            tableParameters.getSortedColumnDirection().equalsIgnoreCase("asc"));

    return new TableBean(iTotalRecords, iTotalDisplayRecords, sEcho, data);
}

Finally, the Javascript had to be altered so that DataTables knows to look at the variable titled 'data' for its list of Beans shown in the table itself, by adding the 'sAjaxDataProp': 'data', configuration.
$(document).ready(function () {
     $('#myDataTable').DataTable({
         'destroy' : true,
         'serverSide' : true,
         'sAjaxSource': '/ApplicationName/Data/Person',
         'sAjaxDataProp': 'data',
         'order': [ [ 0, 'asc' ] ],
         'columns':
         [
            {  'data': 'name',
                'render': function(data, type, row, meta){
                    if(type === 'display'){
                        data = '' + data + ''
                    }
                    return data;
                }
            } ,
            { 'data': 'socialSecurity'} ,
            { 'data': 'birthdate'} ,
            { 'data': 'gender'}
         ],
         'scrollY' : 300,
         'scrollCollapse' : true,
         'paging' : true,
         'autoWidth' : true,
         'ordering' : true,
         'searching' : false,
         'pageLength' : 20,
         'lengthChange' : false,
         'pagingType' : 'full_numbers',
         'dom' : '<"top"ip>rt<"bottom"fl><"clear">'
     });
 });

And voila, now the server side processing is functional.


text:
Q: How to show all categories in MediaWiki Main or other pages? I want to display all the categories in main page or any other page in MediaWiki just like how it displays in Special:Categories page.
Any help is appreciated.

A: The only built-in ways to display all categories are the special pages Special:Categories and Special:AllPages (in a default MediaWiki setup the categories are in NS 14, so Special:AllPages?namespace=14). Of those two, AllPages is transcludible, meaning that you can do like this on your main page:
{{Special:AllPages|namespace=14}}

If you want more control over the output, I suggest you use an extension like Semantic MediaWiki (advanced, full control), or CategoryTree (but as you noted, you will have to organize your category in a tree structure, with a common root).


text:
Q: How do I install boot manager? How can I install boot-manager to ubuntu 12.04? I have tried sudo apt-get install boot-manager but it does not work.
Why I want is because I will close some startup application in order to optimize system performance.
EDIT:
error:
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package boot-manager

A: Running these commands in a Terminal window (Ctrl+Alt+T) should do it for you:
sudo apt-get update
sudo apt-get install bum

When trying to find a package like that, it helps to use the Synaptic Package Manager. When I searched 'boot-manager' in it, the 'bum' package came up.

A: sudo apt-get install bum

try to use this command.


text:
Q: How can I emulate WHERE 1 in a dynamic query? I'm making a query dynamically like this:
$query = "SELECT u.*
          FROM users u
          WHERE date_time > unix_timestamp(DATE_SUB(now(), INTERVAL 1 $range))";

Also $range contains a word like this:
switch ($_GET['range']){
   case "week":
      $range = "WEEK";
   case "month":
      $range = "MONTH";
   case "year":
      $range = "YEAR";
   case "ALL":
      $range = <I don't know what should I put here to get the expected result>;
}

As I've said above, I want to set something as $range value to make  the WHERE clause something like WHERE 1. How can I do that?

A: Perhaps use a case statement in your where clause?
 $query = "SELECT u.*
           FROM users u
           WHERE CASE {$range}
                 WHEN 'ALL' then TRUE
                 ELSE date_time > unix_timestamp(DATE_SUB(now()
                                  , INTERVAL 1 {$range}))
                 END";

A: switch ($_GET['range']){
  case "week":
  $range = "WEEK";
 case "month":
  $range = "MONTH";
 case "year":
  $range = "YEAR";
 case "ALL":
  $range = null;
}

$query = "SELECT u.*
      FROM users u
      WHERE 1=1 ";
if(!empty($range)) {
  $query .= " AND date_time > unix_timestamp(DATE_SUB(now(), INTERVAL 1 $range))";
}

Add datetime where clause conditionally; WHERE 1=1 will always be true. So the next condition's result will matter on the final result

A: I think what Adam was suggesting is something like this:
$where = '';

switch ($_GET['range']) {

    case "week":
       $where = "date_time > unix_timestamp(DATE_SUB(now(), INTERVAL 1 WEEK))":
        break;

    case "month":
       $where = "date_time > unix_timestamp(DATE_SUB(now(), INTERVAL 1 MONTH))":
        break;

    case "year":
       $where = "date_time > unix_timestamp(DATE_SUB(now(), INTERVAL 1 YEAR))":
        break;

    default:
        $where = '';
}

$query = "SELECT u.* FROM users u WHERE $where";

Assume reporting with other criteria? Where the string concatenation gets messy. Adding 'AND' between parts. Suppressing WHERE keyword entirely?  Where OOP code to represent the SQL query can be useful.

A: Let's start with the fact that your switch statement doesn't have break statements and isn't going to work the way you expect.
Here is what I'd suggest:
$query = "SELECT u.*
          FROM users u";

$range = false;

if (isset($_GET['range'])) {
    switch ($_GET['range']){
       case "week":
          $range = "WEEK";
          break;
       case "month":
          $range = "MONTH";
          break;
       case "year":
          $range = "YEAR";
          break;
       default:
          $range = false;
    }
}

if ($range) {
  $query .= " WHERE date_time > unix_timestamp(DATE_SUB(now(), INTERVAL 1 $range))";
}

A: I would define an array with valid ranges and validate the user input first. Then build the query dynamicly.
$validRanges = [
    'year'  => 'YEAR',
    'month' => 'MONTH',
    'week'  => 'WEEK',
    'ALL'   => null
];

if (isset($_GET['range']) && !isset($validRanges[$_GET['range']])) {
    $range = $validRanges[$_GET['range']]);
} else {
    // it's up to you, what to do in this case
    throw new Exception('Range is not valid or missing');
}

if ($range === null) {
    $rangeCondition = '1=1';
} else {
    $rangeCondition = "date_time > unix_timestamp(NOW() - INTERVAL 1 $range)";
}

$query = "SELECT u.*
          FROM users u
          WHERE $rangeCondition";


text:
Q: Macro to run specific Run configuration I have several Run configuration's in PyCharm:

*

*one is for celery

*second is for restarting rabbit

*third is for main script run

Do not ask me why I need these configurations, I just want to use 3 shortcuts to run three Run configuration's separately.
So I decided to create macros for each one. But macro does not record choosing specific Run configuration.
Any ideas?

A: Macro

*

*Open the run configurations menu (F10 in my setup)

*Type the name of the config to run

*Press enter

Bug on Mac OS
Not sure who could be impacted, but I ran into an annoying bug on the old macbook I'm hanging on to: Pycharm correctly receives each key at recording time (as can be seen in the macro window). But when replaying, instead of inputing the chars it seems to 'type' using my keyboard layout (BÉPO, french), using QWERTY locations !
Workaround:

*

*Switch your computer to QWERTY

*Run the macro recording

*Type the config name as with your usual keyboard

*Press enter (although the run config window will probably no longer be showing anything)

*Stop recording

*Switch back to your usual keyboard

For my example, my working macro is saying Typing: "ka;iqrc" !

A: I've created plugin to be able to use shortcuts to execute Run/Debug Configurations: Run Configuration as Action.
After loading of this plugin it register all Run/Debug configurations as actions. So you can assign shortcut for them, add them to toolbars, etc.

It works for all Jetbrains IDEs based on IntelliJ platform: CLion, PyCharm, PhpStorm, etc.


text:
Q: Best way to have bijection between $\mathbb N$ and $n$ infinite sets of $\mathbb N\times \mathbb N\times...\times \mathbb N$? I tried to search for a way to have bijection between $n$ indexed infinite sets of $\mathbb N\times \mathbb N\times...\times \mathbb N$,  and integers where each set is an arbitrary multiple of $\mathbb N$, but found nothing.
What is the best formula to accomplish the goal?

A: Consider the first $n$ primes sorted in the usual order then there is a bijection between elements of $\mathbb{N}^n$ and powers of these primes. So for say, $n=3$ we would have the primes $2,3,5$ and we'd map $(x,y,z) \rightarrow 2^x3^y5^z$ and this is a bijection by construction. Since this is a subset of $\mathbb{N}$ we can write them in the usual order which would be something like $2,3,4,5,6,8,9,10,12,15,16,18,20,24,...$ for $n=3$. From here the bijection to the naturals is obvious and so the composition of these two functions is also a bijection giving us a bijection between $\mathbb{N}^n$ and $\mathbb{N}$.

A: Consume the elements of the $n$ sets in a round-robin way.
You can even handle a countable infinity of sets by increasing the number of sets on each round.

A: Iterate Cantor's pairing function.  See "Pairing function - Wikipedia" https://en.m.wikipedia.org/wiki/Pairing_function.
Geometrically, the resulting "tuple function" is utterly trivial: put the numbers in an array and wind your way back and forth starting from the upper left hand corner.


text:
Q: MySQL Query Concerning Average of Rows Greater than Median in Group Im having a problem trying to figure out the following and not even 100% sure if this task can be done from pure mysql query alone.
I need to select rows that share the same ID and Type while keeping track of their TimeStamps.
SELECT ObjectId, TimeStamp, Count(ObjectId) As theCount FROM
   (Select ObjectId, TimeStamp, RelationType, ObjectType From Table
      Group By ObjectId, TimeStamp) As tmp
      WHERE RelationType = 'A'
      AND ObjectType = 'B'
      GROUP By ObjectId
      HAVING Count(ObjectId) >= 0 ORDER By theCount DESC

The part of finding and counting the number of rows that are similar enough for me to select is easy but I am having trouble with the next part.
I need to keep track of all the TimeStamps after the median TimeStamp and get the average of those TimeStamps above the median TimeStamp. I need to get the average of those TimeStamps above their Median so I can order them DESC.
If my question is not clear enough or any questions please post so I can return a comment. I have spent many hours trying to different ways to achieving my goal but the only code that I feel is correct is the posted query above.
The below code is where I am right now. I am getting the average of all the grouped items but like I said I only need the average of the TimeStamps above the group median.
SELECT * FROM( SELECT ObjectId, PostDate, Count(ObjectId) AS Count, AVG(TimeStamp) AS Average
   FROM (Select ObjectId, TimeStamp, RelationType, ObjectType
      FROM Relations Group By ObjectId, TimeStamp
   ) As tmp
WHERE RelationType = 'A' AND ObjectType = 'B'
GROUP By ObjectId HAVING Count(ObjectId) >= 1
AND AVG(TimeStamp) > MIN(TimeStamp)
ORDER By Count DESC ) AS tmp2 ORDER BY Average DESC, Count LIMIT 10

            RETURNS:

            ObjectId: 112717 // Count: 2 // Average: 20151030188390.5
            ObjectId: 166047 // Count: 4 // Average: 20151023363026.25
            ObjectId: 166312 // Count: 3 // Average: 20151022171454.332
            ObjectId: 166309 // Count: 2 // Average: 20151022170765.5
            ObjectId: 166307 // Count: 2 // Average: 20151022170765.5
            ObjectId: 165163 // Count: 2 // Average: 20151021188390.5
            ObjectId: 133214 // Count: 2 // Average: 20151021188388
            ObjectId: 165164 // Count: 2 // Average: 20151021188388
            ObjectId: 165831 // Count: 2 // Average: 20151021184532.5
            ObjectId: 165822 // Count: 2 // Average: 20151021184532.5


text:
Q: Retrieving ArrayList.get randomly using JSP object in javascript function So I have an arraylist containing my data to display within my jsp file. I am trying to display this data in a table; however I want to grab items from the arraylist at a random index. This is done with r, yet I cannot simply type r rather than 5 when executing the following command.
"<%=allData.get(5).getRow_position()%>";

Hence how can I call this randomly when I can't use r as a parameter concatenate the string to get the string to add to my table? Thanks!
Code:
function updateDisplay(numIterate){
var table = document.getElementById("infoTable");
var startingRow = 1;

for(var i = 0; i < numIterate; i++){

var row = table.insertRow(startingRow);

var max = <%=allData.size()%>;
var min = 1;
var r = Math.floor(Math.random() * (max-min))+min;

var rowPosition = row.insertCell(0);
var headline = row.insertCell(1);
var agency = row.insertCell(2);
var dateEntered = row.insertCell(3);
var enteredBy = row.insertCell(4);

rowPosition.innerHTML = "<%=allData.get(5).getRow_position()%>";
headline.innerHTML = "<%=allData.get(5).getHeadline()%>";
agency.innerHTML = "<%=allData.get(5).getAgency()%>";
dateEntered.innerHTML = "
<%=allData.get(5).getDateEntered()%>".substring(0,10);
enteredBy.innerHTML = "<%=allData.get(5).getEnteredBy()%>";
startingRow+=1;
}

A: Are you looking for something like this -
//on Top
<%@page import="java.util.*" %>
//Also before you use rand and put max and min value
<%Random rand;
int r = rand.nextInt((max - min) + 1) + min; %>
//Replace 5 with r in your code