text:
Q: Highlighting values above a threshold using lattice in R xyplot Hi I am trying to highlight values above 35 degrees celsius as red points and add the months as well as year to the x axis. I admittedly modified this script. I am new to R and would really appreciate the help. Also, another package will do.
here is a sample of the data and code.
Date    reference   shade   sun
2010-03-01  NA  50.6221 53.3561
2010-03-02  NA  38.1599 40.3847
2010-03-03  NA  34.8627 38.3919
2010-03-04  NA  33.4927 35.0268
2011-04-22  NA  38.2654 45.972
2011-04-23  NA  38.0786 37.2561
2013-07-18  13.7    13.7    13.7
2013-07-19  18.7    19.1    18.7
2014-05-26  20.6    20.7    23.7
2014-05-27  21.6    22.2    24.6
2014-05-28  17.1    17.7    22.1

require(lattice)

require(RColorBrewer)
colset <- brewer.pal(3, "Set1")

trellis.device(device="pdf", file="nestbox_temp_profiles.pdf", height=11,
             width=7.5, color=TRUE)

lab.reference <- "Reference Area"
lab.shade <- "Shaded Nest-boxes"
lab.sun <- "Sun Exposed Nest-boxes"

my.strip <- function(which.given, which.panel, ...) {
  strip.labels <- c(lab.shade, lab.sun, lab.reference)
  panel.rect(0, 0, 1, 1, col="#ffe5cc", border=1)
  panel.text(x=0.5, y=0.5, adj=c(0.5, 0.55), cex=0.95,
             lab=strip.labels[which.panel[which.given]])
} #--Custom strip function:

Nestemp$Date <- strptime(Nestemp$Date, format="%Y-%m-%d")#--Define X axis date range:

xlim <- range(Nestemp$Date)

d <- seq(from=as.Date("2010-03-01"), to=as.Date("2015-03-01"), by=365/4) #--Define annual quarters for plot grid line markers:

col.raw <- "#377EB8"
col.lm <- "red"

plot1<-xyplot(sun + shade + reference ~ Date, data=Nestemp,
       scales=list(y="free", rot=0),
       strip=my.strip, outer=TRUE, layout=c(1, 3, 1), ylab="Temperature (celsius)", xlab="",
       panel=function(x, y, groups=groups) {panel.grid(h=0, v=0) panel.abline(v=d, col="grey90") panel.xyplot(x, y, ..., type="p", col=col.raw, lwd=0.8) panel.abline(h=35, lty=2, col="red", lwd=1)},

key=list(text=list(c("Nestbox Temperature", "Threshold 35 degrees celsius")),
                title="Daily Maximum Nest box Temperature",
                col=c(col.raw, col.lm), lty=c(1, 2),
                columns=2, cex=0.95,
                lines=TRUE),)

plot1
dev.off()

A: This kind of plot is easy to make using ggplot2 (this example uses the example dataset mtcars):
library(ggplot2)
ggplot(mtcars, aes(x = wt, y = mpg, color = mpg > 30)) + geom_point() +
    scale_color_manual(values = c('red', 'blue'), breaks = c(TRUE, FALSE))

A: I used  a date time stamp to format my date column. I then used @PaulHiemstra 's suggestion with ggplot2.
sample df
Date    sseye   max month   season
2009/10/6   Shaded Nest-boxes   29.9508 11  Non-breeding season
2011/06/7   Sun Exposed Nest-boxes  38.1586 11  Non-breeding season
2013/11/10  Shaded Nest-boxes   29.2015 11  Non-breeding season
2014/05/9   Sun Exposed Nest-boxes  39.4666 11  Non-breeding season

library(scales) # for units
library(ggplot2)
library(gridExtra)
library(plyr)
library(ffbase)

Nestemp2$Date <- as.Date(Nestemp2$Date, format="%Y/%m/%d")
plotnest=ggplot(Nestemp2, aes(x=Date, y=max, color = max > 35)) +
  geom_point() + scale_color_manual(values = c('black', 'red')) +

Next I wanted to add vertical and horizontal lines at particalr dates and a value
geom_hline(yintercept=35, colour="red", linetype="dashed") +
  geom_hline(yintercept=0, colour="black")+
  geom_vline(xintercept=as.numeric(as.Date("2010-04-01")), vjust=0.5, linetype=2) +
  annotate("text", x=as.Date("2010-04-10"), y=25, label=" Not Breeding", angle=90, size=3,  vjust=-1, hjust=1) +
  geom_vline(xintercept=as.numeric(as.Date("2010-10-01"), vjust=0.5), linetype=2) +
  annotate("text", x=as.Date("2010-09-30"), y=25, label=" Breeding", angle=90, size=3,  vjust=-1, hjust=1) +

My df column consists of multiple factors for nest location (sun, shade and a reference location) so I used facet wrap to make a panel plot consisting of the factor  ~ssey (three levels (sun, shade and reference). I cannot post a picture but it looks sweet.
ylab("Temperature (c)") +
  facet_wrap( ~ sseye, ncol=1) +                  #this is what puts them in a grid
  scale_y_continuous(limits=c(0,60)) +

  theme_bw() + theme(
  strip.text.x = element_text(size=16),           #sets the size of the title to each grid section as 10
  strip.background = element_blank(),             #removes the grey background in the title of each grid section
  axis.text.x = theme_text(size=16),               #sets the x axis tick text size to 8
  axis.text.y = theme_text(size=16),               #sets the y axis tick text size to 8
  axis.title.x=theme_blank(),                     #removes the x axis title
  axis.title.y=theme_text(size=16, vjust = .3),               #sets the y axis title to size 10
  axis.line=theme_segment(colour="black"),        #sets the axis lines
  panel.grid.minor = theme_blank(),               #removes minor grid lines
  panel.grid.major = theme_blank(),               #removes major grid lines
  panel.border=theme_blank(),                     #removes the border around the graph
  panel.background=theme_blank(),                 #removes the grey background of the plot
  legend.justification=c(10,10),
  legend.position=c(10,10), # Position legend in top right
  legend.title=element_blank(),
  legend.text = theme_blank(),
  legend.title = theme_blank(),                   #removes the legend title
  legend.key = theme_blank())

plotnest


text:
Q: Get the previous event action in jquery I'm trying to get the previous event action by using jquery

$(document).on("click","#det",function(e){
    $(this).next("#moredet").fadeToggle("slow");
});

what i want is when row of id "det" is clicked then the next of clicked row of id "moredet" will become fade and when i clicked any other row of id "det" then the previous fadein row will fadeout and next row of id "moredet" of clicked row will fadein.

A: Don't use duplicate id use class.Its rule violation. You can use next and prev with size to check condition  to solve your problem.

$(document).on("click", ".det", function(e) {
  if ($(this).next('tr').size() > 0) {
    $(this).next(".moredet").fadeToggle("slow");
  } else {
    $(this).prev(".moredet").fadeToggle("slow");
  }
});

    1

    2

    3

redpajama_set_name: RedPajamaStackExchange


text:
Q: need help understanding data section of wav file I was reading THIS TUTORIAL on wav files and I have some confusions.
Suppose I use PCM_16_BIT as my encoding format. So this should mean each of my sound samples need 16 bits to represent them shouldn't it?
But in this tutorial, the second figure shows 4 bytes as one sample. Why is that? I suppose because it is trying to show the format for a stereo recorded wav file, but what if I have a mono recorded wav file? Are the left and right channel values equal in this case, or one of the channel values is 0? How does it work?

A: Yes, for 16bit stereo you need 4 bytes. For mono, you just need two bytes for 16bit PCM. Check this out:
http://www.codeproject.com/Articles/501521/How-to-convert-between-most-audio-formats-in-NET
Also read here:
http://wiki.multimedia.cx/index.php?title=PCM


text:
Q: Automate report making VBA I'm trying to automate a report making, i have to copy/paste data from .txt files that are in the same carpet, to do so i use a window because using the path is inefficient when using in other computers. Errors i encounter:

*

*I want the data type of all the cells to be text so i can transform
the date into dd/mm/yyyy

*It only modifies some files and some not.
I've tried tons of macros i've made but i can't fix the errors.
Sub REP_DET_Report()
myBook = ActiveWorkbook.Name
Set nav = CreateObject("shell.application")
folder = nav.browseforfolder(0, "PICK FOLDER", 0, "c:\").items.Item.Path
ChDir folder & "\"
file = Dir("*.txt")
Do While file <> ""
Workbooks.OpenText file, origin:=xlWindows, startrow:=1, DataType:=xlDelimited

Dim objRange1 As Range
'Set up the ranges
Set objRange1 = Range("A1:A1048576")

'Do the first parse
objRange1.TextToColumns _
Destination:=Range("A1"), _
FieldInfo:=Array(Array(1, xlTextFormat), Array(2, xlTextFormat), Array(3, xlTextFormat), Array(4, xlTextFormat), Array(5, xlTextFormat), Array(6, xlTextFormat), Array(7, xlTextFormat), Array(8, xlTextFormat), Array(9, xlTextFormat), Array(10, xlTextFormat)), _
DataType:=xlDelimited, _
Tab:=False, _
Semicolon:=False, _
Comma:=False, _
Space:=False, _
other:=True, _
OtherChar:="|"

other = ActiveWorkbook.Name
ActiveSheet.Copy before:=Workbooks(myBook).Sheets(1)
Workbooks(other).Close False
file = Dir()
Loop
End Sub


text:
Q: Fetch aggregate data from NSManagedObject using another expression as argument to sum: expression Is it possible to use expression as argument for sum: expression?
I have entity (NSManagedObject class) Drink with properties costPerDrink, numberOfDrinks and drinkingDate.
I would like to get sum of total costs (numberOfDrinks multiplied by costPerDrink) within time period. While I have no problems getting sum on single property (e.g. sum of numberOfDrinks within time period), when I try to use sum expression on another (multiply) expression I got error:
NSInvalidArgumentException, reason: Unsupported argument to sum :
(
    "costPerDrink * numberOfDrinks"
)

See code:
// Init fech
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Drink" inManagedObjectContext:[Service appContext]];
[request setEntity:entity];

// Return dictionary
[request setResultType:NSDictionaryResultType];

// Set conditions
[request setPredicate:[NSPredicate predicateWithFormat:@"(drinkingDate>=%@) AND (drinkingDate<=%@)", self.startDate, self.endDate]];

// Set 1st column to be returned - count of drinks
NSExpression *drinksExpression = [NSExpression expressionForKeyPath:@"numberOfDrinks"];
NSExpression *sumDrinksExpression = [NSExpression expressionForFunction:@"sum:" arguments:[NSArray arrayWithObject:drinksExpression]];
NSExpressionDescription *sumDrinksResultDescription = [[NSExpressionDescription alloc] init];
[sumDrinksResultDescription setName:@"sumDrinks"];
[sumDrinksResultDescription setExpression:sumDrinksExpression];
[sumDrinksResultDescription setExpressionResultType:NSInteger32AttributeType];

// Set 2nd column to be returned - total cost
NSExpression *costExpression = [NSExpression expressionForKeyPath:@"costPerDrink"];
NSExpression *totalExpression = [NSExpression expressionForFunction:@"multiply:by:"
                                                            arguments:[NSArray arrayWithObjects:costExpression,
                                                                                drinksExpression, nil]];
NSExpression *sumCostExpression = [NSExpression expressionForFunction:@"sum:" arguments:[NSArray arrayWithObject:totalExpression]];
NSExpressionDescription *sumCostResultDescription = [[NSExpressionDescription alloc] init];
[sumCostResultDescription setName:@"sumCost"];
[sumCostResultDescription setExpression:sumCostExpression];
[sumCostResultDescription setExpressionResultType:NSDecimalAttributeType];

// Add expressions to fetch
[request setPropertiesToFetch:[NSArray arrayWithObjects: sumDrinksResultDescription, sumCostResultDescription, nil]];

// Execute fech
NSError *error;
NSArray *result = [[Service appContext] executeFetchRequest:request error:&error];

I perfectly understand that particular problem can be solved by adding auto-calculated totalCost property to Drink entity and then using sum: in fetch without multiply:by: expression but question remains - is it possible to use expression as argument for sum: expression?


text:
Q: Why do I need a space in this regex? I'm trying to match either the Eu or U.s. using PHP's preg_match_all.
Given the following sentence:

The Eu is better than the U.s. in certain ways.

I can match both Eu and U.s. if I use:
preg_match_all("/\b(Eu|U\.s\. )\b/", $input_lines, $output_array);

but not if I use:
preg_match_all("/\b(Eu|U\.s\.)\b/", $input_lines, $output_array);

Why do I need a space after the . in order for my regex to work?

A: The metacharacter \b is an anchor like the caret and the dollar sign. It matches at a position that is called a "word boundary". This match is zero-length.
There are three different positions that qualify as word boundaries:

*

*Before the first character in the string, if the first character is
a    word character(\w).

*After the last character in the string, if the last    character is
a    word character.

*Between two characters in the string,    where one is a word
character and the other is not a word character.

so in your case which is number 3 the U.s. bounded like this:  \b U \b .\b s \b .

A: What @mmta41 said. Here is a test:
$re = '/(eu|\bU\b.\bs\b.)/mi';
$str = 'U.s.,u.S., U.S. , u.s.. ,Eu,eU, EU , eu.Europe UseuUs Europe';

preg_match_all($re, $str, $matches);

print_r($matches);

see http://sandbox.onlinephpfunctions.com/code/9f435a11609606cf7f8d4f5e330d443989911c5b


text:
Q: Ubuntu apps on Windows with WSL uninstalled I installed WSL with the Ubuntu distro on my Windows 11 laptop.  I wanted to show some Ubuntu GUI applications, so I installed tasksel.  Then, from tasksel, I installed Ubuntu Desktop and few more things.
Now, I've uninstalled Ubuntu from the "Apps & Features".  But after uninstalling, I still have Ubuntu apps in the Windows Start menu.
I've also disabled "Windows Subsystem for Linux" in "Turn Windows Features on or Off", but wsl.exe is still here, too.
How do I remove these items?
I'm new to Linux and Stack Exchange. I'm sorry, but my English isn't perfect. I'm Czech.

A: There are two parts that you are asking about:
wsl.exe remaining after uninstall/disable
First, the wsl.exe command itself comes with a base Windows 11 installation and can't be uninstalled.  Even with Windows Subsystem for Linux completely disabled, it will still exist as an "installer" so that you can wsl --install to reconfigure it.  By itself, wsl --install will:

*

*Enable the WSL feature

*Enable the Virtual Machine Platform feature (a subset of Hyper-V for WSL2)

*Install the latest official Linux kernel available for WSL2.

*Install an Ubuntu distribution.

Once WSL itself is enabled, then wsl.exe is used to control your Ubuntu (or other) distribution.
Ubuntu GUI app icons remaining in the Windows Start menu after uninstalling Ubuntu
As for the Start menu items created for Ubuntu GUI apps ...
I'm going to over-summarize slightly here to skip some of the technical details - Those particular Start menu icons are created by WSLg monitoring  for changes in the /usr/share/applications.
When a new .desktop file is created there of the right type, Windows creates a link to wslg.exe in the Start Menu that can launch that particular app.
When a corresponding .desktop file is removed (typically via sudo apt remove <package>), the Start menu link is removed.
However, if you completely remove the Ubuntu distribution from WSL itself, then WSL can no longer monitor it for changes.  While it would be nice if WSL "cleaned up" these Start menu items when a distribution is uninstall entirely, that's just not the case right now.

Updated:  As of the latest Preview release of WSL (available to Windows 11 users in the Microsoft Store), this is reported to be fixed:

Remove WSLg icons when a distro is uninstalled.

You can easily delete these manually, but make sure you remove the right thing:

*

*Find any one of the items that you want to remove in the Start menu.

*Right-click it, choose "Open File Location" (or your local equivalent, of course).

*You should find all of the Start Menu items for WSL in that folder, under the "Programs" folder.  Make note of the folder name.

*Left-click the "Programs" folder in the File Explorer address bar to move up one-directory (or via Backspace)

*Right click on the folder where those items were (likely named "Ubuntu"), then choose "Show more options", then "Delete".

All of the Start menu items that were created by WSLg/Ubuntu should be gone.


text:
Q: "That heresies should arise, we have the prophesie of Christ..."
That heresies should arise, we have the prophesie of Christ; but that old ones should be abolished, we hold no prediction.

This is a quote from Religio Medici (1643) by Thomas Browne. It's quoted in Contact by Carl Sagan.
How does this sentence structure work? What does this mean? I'm particularly confused by the use of "that."

A: Both sentences are versions of

It was said that X would happen == That X would happen was said.

The verbal phrase "We have a prophesie that.."
is similar to "We have a law that..   "He made an announcement that...
So,without the inversion and with some "" (round what was foretold) ""   and (<< backshift) shown

1 We have the propehsie of Christ that ""  heresies should (<< shall) arise,"" ; 2  but...  we hold no prediction that ""old ones
  should (<< will) be abolished.""

A: In both sentences, the order of the clauses has been inverted. This can be done to shift the focus of the sentence towards the clause that is moved forward.
In a standard construction, I could say:

We have (a prophesy that heresies will arise); but we have no (prediction that old ones will disappear).

By simply moving the italic parts to the front we get:

That heresies will arise, we have a prophesy; but that old ones will disappear we have no prediction.

Note that you might add an of after the verb in both sentences. It is common to add that to refer back to the clause that was moved to the front:

That heresies will arise, we have a prophesy of; but that old ones will disappear we have no prediction of.

A: It's inversion:

That heresies should arise, we have the prophesie of Christ; but that
  old ones should be abolished, we hold no prediction.

is a re-ordering of:

We have the prophesie of Christ that heresies should arise; but we hold no prediction that old ones should be abolished.

A: To paraphrase, I would say, "Christ predicted that there would be new heresies that would arise, so the author can be confidant that they will appear, but He said nothing about when old heresies would vanish, so the author makes no prediction about them."  This is in keeping with Browne's observation that supposedly-suppressed heresies seem to pop up elsewhere.
In each independent clause, there is a relative subordinate clause introduced by "that."  The first, "That heresies should arise," modifies "the prophesie of Christ" (or stands in apposition to it).  The second, "that old ones should be abolished," modifies "prediction."


text:
Q: Integrating a function by representing it as a power series I'm trying to integrate this function with power series
$$\int2\cos^2(x)e^{-x}\,\mathrm dx$$
Since I know the Maclaurin series for $\cos(x)$ is $\sum_{n=0}^{\infty}
\dfrac{(-1)^nx^{2n}}{(2n)!}$ and $e^x$ is $\sum_{n=0}^{\infty} \dfrac{x^{n}}{n!}$ then
$$\int2\cos^2(x)e^{-x}\,\mathrm dx = \int2\left(\sum_{n=0}^{\infty}
\dfrac{(-1)^nx^{2n}}{(2n)!}\right)^2 \left(\sum_{n=0}^{\infty} \dfrac{(-1)^nx^{n}}{n!}\right)\,\mathrm dx$$
However, I'm not certain that this is leading me forward. Usually these types of problems in early calculus involve representing the function under one sum and integrating the series as a polynomial. Is there something that I'm missing?

A: Hint:
$$\cos^2x=\frac{1+\cos 2x}{2}$$
$$\cos(2x)e^{-x}= \left(\sum_{n=0}^{\infty}  \dfrac{(-1)^n2^{2n}x^{2n}}{(2n)!}\right) \left(\sum_{m=0}^{\infty} \dfrac{(-1)^mx^{m}}{m!}\right)=\sum_{n=0}^{\infty}\sum_{m=0}^{\infty}\frac{(-1)^{n+m}2^{2n}x^{2n+m}}{(2n)!m!}{}$$


text:
Q: recovering lost Google chrome tabs Normally when Google Chrome closes it saves my tabs and when I re-open Google Chrome all my tabs are restored. But it doesn't do that all the time.
I don't suppose there's any way to get those tabs back? I could look through my browser history but just because I visited a website yesterday or the day before or whatever doesn't mean I had an open tab to it.
I mean, if my computer was shut off unexpectedly I could understand why it wouldn't save the tabs, but half of the time Chrome fails to save tabs for something like Windows Automatic Updates.

A: You can view these tabs via the "Recent Tabs" menu under the drop-down menu.  It all stays synced through your account, so closed tabs from all instances of Chrome will be available.  I believe this is all retained until the browser history itself gets cleared (not automatically from computer reboot).


text:
Q: Use interface to pass data in Kotlin I need to pass data to class from activity. I use interface, but i have problem with initialization.
My class:
class Methods  {

fun processingResponse(finalMessage: String) {

    var mcontext: Context? = null
    var message : Message =  Message()
    var access = "Access Granted"
    var out = "Logged"
    var Stateconnect = false
    var safetyCheck = 0

    if (access in finalMessage) {

        val msg = finalMessage.split("=", ":")
        accessLevel = msg[0]
        sessionId = msg[1].toInt()
        safetyCheck = msg[2].toInt()
        var namePlc = msg[3]

        interfaceData.sendData("Connect")
        //Stateconnect = true
    } else if (out in finalMessage) {

        interfaceData.sendData("Disconnect")

        println("log out okey")

    }
}}

My interface:
interface SendDataInterface {fun sendData(str: String )}

and My activity:
class LoginIn : AppCompatActivity(), SendDataInterface {

override fun sendData(str: String)
{

    var handler = Handler(Looper.getMainLooper())
    handler.post( Runnable() {

        fun run() {
            buttonChange(str)
        }
    })} fun buttonChange(str : String) {

        if (str == "Connect") {
            Connection.setBackgroundColor(Color.RED)
            Connection.setText("Disconnection")
            loadMaintenancePage()

        } else if (str == "Disconnect") {

            Connection.setBackgroundColor(Color.GREEN)
            Connection.setText("Connection")
        }
    }

}
The error that i have is the interface isn't initialize.
How I can initialize the interface?

A: You have to create an instance of SendDataInterface in your class Methods.

A: var interfaceData:SendDtaInterface=Object:SendDtaInterface{
override fun sendData("Connect"){
}
}
interfaceData.sendDat("connect")enter code here


text:
Q: Sass compiler throws 'undefined mixin' error when mixins are kept in seperate folder Here is the screenshot of my website structure.

In my mixins file, I have created all the necessary sass mixins.
I have created this mixin for border radius:
 @mixin border-radius($radius) {
  -webkit-border-radius: $radius;
     -moz-border-radius: $radius;
      -ms-border-radius: $radius;
       -o-border-radius: $radius;
          border-radius: $radius;
}

Now when I try to use this for my button class in _button.scss in modules folder , I get undefined variable error. Whereas when I use the same mixin in the _button.scss file itself, I don't get any error.
in my _button.scss file i have included the mixin as under
button{
    background-color: $theme-color;
    border: 0px solid;
    padding: 0.7rem 3rem;
    @include border-radius(2rem);

}

What is the issue exactly. I want to keep all my mixins in a seperate file to keep the structure neat.

A: you have to include the mixin with @include or @import
https://sass-lang.com/documentation/at-rules/mixin

A: Ad as * end of line
Example:
@use  './mix' as *;

A: Only answering because I got the same error for a different reason.
The solution for me was to reorder my imports. As it turns out I was referencing a mixin that wasn't imported yet. Check to be sure you aren't using a mixin prior to it's being imported.

A: as Waseem Wisa said you add @use 'mix' as *;
or
you can edit your file like this:
'''
@use 'mix';
button{
    background-color: $theme-color;
    border: 0px solid;
    padding: 0.7rem 3rem;
    @include mix.border-radius(2rem);

}

'''
or add index.scss file to your scss folder then forward all module files in it like :
_index.scss (this is file name)
`forward 'mix';`

after that add this file to your main.scss
`@use 'index' as *;`

A: To elaborate on Brian's answer make sure you import the _mixins.scss file in the main sass file.
On the top simply do this.
// style.scss
@import "mixins";

This will fix the undefined error.

A: First import the mixin sass file in your style.scss file. Be sure to import the file first before importing the globals and variables file.
For example like this,
@import "_variables";
@import "_mixins";
@import "_globals";
@import "_header";


text:
Q: Unity5.3 Json how to construct a complex Json object using unities new Json utility I have a 2 part question.
First i am trying to write the code that can write a json file that looks like this.
{
"Restaurants":[
     {
       "Name" : "Asami",
       "ID" : 0,
       "Plates" :
       [
         {
           "title" : "Plate1 ",
           "color" : "Red ",
           "price" : 5
         },
         {
           "title" : "Plate1 ",
           "color" : "Green ",
           "price" : 6
         },
         {
           "title" : "Plate1 ",
           "color" : "Blue ",
           "price" : 7
         },
         {
           "title" : "Plate1 ",
           "color" : "Yellow ",
           "price" : 8
         }
       ]
     }
  ]
}

The code i have sofar is this.
using System;
using System.Collections;
using System.IO;
using UnityEngine;
using System.Collections.Generic;

public class UnityJsonTest : MonoBehaviour {

public string aName;
public int aId = 0;
public string aPlate1, aPlate2;
public Color aColor1, aColor2;
public int aPrice1, aPrice2;

// Use this for initialization
void Start ()
{
    Restaurant1 rester = new Restaurant1();

    rester.MainName = aName;
    rester.Character1[0].Name = aName;

    string rjson = JsonUtility.ToJson(rester);

    File.WriteAllText(Application.dataPath + "/player.json", rjson.ToString());

    MyClass myObject = new MyClass();
    myObject.level = 1;
    myObject.playerName = "Dr Charles Francis";

    string json = JsonUtility.ToJson(myObject);

    File.WriteAllText(Application.dataPath + "/test.json", json.ToString());
}

// Update is called once per frame
void Update () {

}
}

[Serializable]
public class MyClass
{
public int level;
public string playerName;
}

[Serializable]
public class Restaurant1
{
public string MainName;
public Character1[] Character1;
}

[Serializable]
public class Character1
{
public string Name;
public int Id;
public Plate1[] Plate1;
}

[Serializable]
public class Plate1
{
public string Title;
public Color Color;
public int Price;
}

if you look at the MyClass myObject = new MyClass(); and the 2 lines after that. it works perfectly. That is the example from the Unity Docs.
but when i tried to use that and make it abit more complex i seem to have missed something.
in the line
Restaurant1 rester = new Restaurant1();

rester.MainName = aName; //This works.

rester.Character1[0].Name = aName;

// This does NOT work. in unity i get a "NullReferenceException: Object reference not set to an instance of an object"
and i have absolutely no idea why. What am i doing wrong here?
The second part of my question is what is the best way to write this thing so that i can set the number of "Plates" objects to a user defined amount? and then i would assume i need a for loop to fill in each of the plate objects?
I have searched far and wide for examples on this but all the examples are done like the myClass. very simple with no explanation on how to build something more complex.
If you guys could help that would be amazing :)
Thanks in advance.

A: You are so close. You are only missing two steps. rester.Character1 is a class and at the-same time, an array.
For it to work, you must declare the size of the array. Let's use 4 for this example:
rester.Character1 = new Character1[4];

Then you have to initialize each Character1  class in the element by creating a new instance of each of them:
 for (int i = 0; i < rester.Character1.Length; i++)
 {
     rester.Character1[i] = new Character1();
 }

Done! Now, you can call rester.Character1[0].Name = aName; without any problems. Arrays are trick but you must undertand these steps.

The second part of my question is what is the best way to write this
  thing so that i can set the number of "Plates" objects to a user
  defined amount? and then i would assume i need a for loop to fill in
  each of the plate objects?

Accessing Plates is tricky because that's an array inside another array. You need multiple for loops to easily do that. You can get Input with from the user with UI/InputField then use that to create number of Plates.
public InputField plateAmount;

//Declare size of each plate array. Get the amount of plates from the InputField/Player then convert it into int with Convert.ToInt32.
for (int i = 0; i < rester.Character1.Length; i++)
{
    rester.Character1[i].Plate1 = new Plate1[Convert.ToInt32(plateAmount.text)];
}

Now create instance of each plate like we did for the Character1 class but this one requires multiple for loops which is also called Nested Loop due to array that is inside another array.
//Create new Instance of Plate1 classes
for (int i = 0; i < rester.Character1.Length; i++)
{
    for (int j = 0; j < rester.Character1[i].Plate1.Length; j++)
    {
        rester.Character1[i].Plate1[j] = new Plate1();
    }
}


text:
Q: How can I check if a JS file has been included already? I have split my javascript in different files. I want to prevent, that javascript files are loaded twice. How can I do that?

A: Sometimes the js file was loaded by other means (via js for example).
That's when window.performance can come in handy. Instead of checking among the script tags, as suggested in other answers, we can check among the resources loaded, with:
let resources = performance.getEntries()
    .filter(e => e.entryType === 'resource')
    .map(e => e.name);
if (resources.indexOf("//domain.com/path/to/script.js") === -1) {
    // Script was not yet loaded.
}

The window.performance browser compatibility is not bad nowadays:
https://caniuse.com/mdn-api_performance_getentries
If we want to check both the script tags (for all script tags in the DOM up to that point, including URLs of scripts that may not yet have been loaded) and the window.resources (for all scripts loaded up to that point, including the ones loaded via js), we could put it together in a function:
function is_script_already_included(src){
  const found_in_resources = performance.getEntries()
      .filter(e => e.entryType === 'resource')
      .map(e => e.name)
      .indexOf(src) !== -1;
  const found_in_script_tags = document.querySelectorAll(`script[src*="${src}"]`).length > 0;
  return found_in_resources || found_in_script_tags;
}

A: Don't include them twice. It's you who's doing the includes, after all.
If you're doing those inclusions dynamically, though, you may check whether some global function or object has been set by the script. For example, if I have the script below in a file:
Foo = function () {};

And then I include it like this:
<script src="../foo.js"></script>

Before that script tag is parsed by the browser, Foo is undefined. After the tag is processed, Foo is a Function. You could use some logic based on that to determine whether you should include some file or not.

A: Here's a test to see if a script has been included based on the path to the js file:
function isScriptAlreadyIncluded(src){
    var scripts = document.getElementsByTagName("script");
    for(var i = 0; i < scripts.length; i++)
       if(scripts[i].getAttribute('src') == src) return true;
    return false;
}

It will work for all scripts not loaded through AJAX, though you may want to modify it if you have jsonp code running.

A: I have tackled this using a generic self-invoking function added at the bottom of each dynamically loaded script.
First -  by declaring a new empty array in my base file or a script that will always be loaded, ie the main page in my case index.php
var scriptsLoaded = new Array();

Then add a self executing function to the end of the loaded script:
(function () { scriptsLoaded.push( 'this_script_name.js' ) })();

With this approach any filename in the scriptsLoaded array should only refer to scripts that have been fully loaded already. Simply checking this array would indicate whether a script has been loaded which can also be used as a check for whether to execute on-load style functions for whatever the script is needed for

A: Not using any framework (that I know of), you can only do so by checking if a certain variable  in the global scope has already been declared.
You could declare a variable var include1 = true; inside include1.js, and do something like
if (window.include1 !== true) {
    // load file dynamically
}

A: You would need to manually track this and make sure. UweB's suggestion would also work.
You could also check out Require.js which could help you to organize your files.


text:
Q: How to invoke a .bat file and send a String using ProcessBuilder in java I need to be able to achieve following in my Java project-
    1) Invoke a .bat file using ProcessBuilder class
    2) send command to that subprocess (.bat application) using Process.getOutPutStream()
I am able to achieve the 1st part, but unable to achieve the 2nd part
So the idea is to open a bat file(oddJobTest.bat)  which is another Java program on my local, and send some specific commands to that. This java application actually contains some Switch Case logic that i can only trigger if i could pass the specific String/commands.
for e.g-
- If i pass "bac", then do Begin Transation Logic
- If i pass "eac", then do End Transaction logic
CoreCashMqttClient.connect();
File oddJobTest = new File("C:/spool/oddjob/build/distributions/oddjob-
0.2.1-SNAPSHOT/oddjob-0.2.1-SNAPSHOT/bin");
    //Use of"/K" makes sure that the OddJob.bat remains active.
ProcessBuilder pbOddJob = new ProcessBuilder("cmd.exe", "/K",
"Start","oddjobTest.bat");
    pbOddJob.directory(oddJobTest);
    try {
        p = pbOddJob.start();

        System.out.println(p.toString());

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

    String payload = ""; // pass some data
    CoreCashMqttClient.publish(payload);
    Thread.sleep(5000);
    OutputStreamWriter writer = new OutputStreamWriter(p.getOutputStream());
    try {
        writer.write("bac");
    } catch (IOException e) {
        e.printStackTrace();
    }

With the below code- i am expecting that the command line that opened as a SubProcess should receive "bac" as a String
OutputStreamWriter writer = new OutputStreamWriter(p.getOutputStream());
writer.write("bac");


text:
Q: jquery animation on floating elements I'm new in javascript and I've a problem animating floating elements with jquery and hope someone can help me to fix it.
I would to be able to make a 100% width horizontal accordion.
For this, I have some floating divs in a wrapper. With javascript, i divide the wrapper's width by the number of divs ( in percentage ). Then, on click, the div selected take the big size and the others the small size. The problem is during the animation, the last div goes at bottom. At the finish, it goes at the good place. I've seen the problem depend of the window's size. In some case, it's ok, but not always.
Here is a fiddle link : test
I've the solution to put the total width at 99% by making the open size for example at 69% instead of 70% but i really need to have it at 100% width and really don't know how make it.
It could be nice if someone can help me to resolve this problem or find another solution.
PS: excuse my english :-)

A: The problem is that you have two independent animations running that are not perfectly synchronized and you expect the total percentage of the two to always be less than 100%.  When you start them both at the same time, sometimes this doesn't happen and as soon as the total goes over 100%, the last one gets pushed to the next row.
The simplest workaround is to slightly delay the one you are growing so the total is always less than 100%.  You can see a .delay(50) added to the second animation to make sure the growing element is always behind the shrinking element so the total is always less than 100%.  Working demo: http://jsfiddle.net/jfriend00/Fkb5K/.
Snippet of code where .delay(50) was added:
if (!$el.hasClass('current'))
    {

        // Animate other columns to smaller size
        $otherItems
        .removeClass('curCol')
        .stop(true)
        .animate({ 'width': $closedItemsWidth }, 500, 'linear')
        .css({"cursor":"pointer"});

        // Animate current column to larger size
        $el
        .addClass('curCol')
        .stop(true)
        .delay(50)
        .animate({ 'width' : $openItemWidth }, 500, 'linear')
        .css({'cursor' : 'default'});

    // Make sure the correct column is current
    $otherItems.removeClass('curCol');
    $el.addClass('curCol');

    }

Probably the best solution is a custom animation that changes both width percentages in the exact same animation (only one animation, not two) so they are always in perfect sync.
Here's a custom animation.  It removes the animation of the element that you are growing and instead adds a step function callback on all the ones that are shorter.  The step function gets call anytime one of the elements changes size in an animation.  In that step function, it sums the width of the shorter elements at that point in time and sets the longer one to track it exactly for a perfect sum of 100% every time.
// On click
$grid.delegate('#grid > .col', 'click', function () {
    // Settings
    var $el = $(this);
    var $allItems = $grid.children('.col');
    var $otherItems = $allItems.not($el);

    if (!$el.hasClass('current')) {
        // Animate other columns to smaller size
        $otherItems.stop(true)
        .removeClass('curCol')
        .animate({ 'width': $closedItemsWidth}, {step: function(prop, fx) {
            var cumWidth = 0;
            var item = this;
            $otherItems.each(function() {
                // haven't changed the width of this item yet, so use new width
                if (this == item) {
                    cumWidth += fx.now;
                } else {
                    cumWidth += parseFloat(this.style.width);
                }
            });
            $el.css({width: (100 - cumWidth) + '%'});
        }, duration: 500 }, 'linear')
        .css({"cursor":"pointer"});

        // Animate current column to larger size
        $el.addClass('curCol').css({'cursor' : 'default'});
    }
})

Working demo here: http://jsfiddle.net/jfriend00/7zubL/


text:
Q: does pd.concat by default keep order of DataFrames in the list Apologize if this has been asked/answered - can't find similar posts with Google.
I have dfs = [df1, df2, df3, ...] If I run pd.concat(dfs), is it guaranteed that it preserves the order of df1, df2, df3, ...?


text:
Q: iOS Document folder is not a directory and/or is missing Trying to archive an array of Codable elements.
do {
   let data = try PropertyListEncoder().encode(elements)
   let success = NSKeyedArchiver.archiveRootObject(data, toFile:self.archiveURL.path)
   print(success ? "Successful save" : "Save Failed")
} catch {
   print("Save Failed")
}

For some reason path (archiveURL) is constantly wrong:
let archiveURL = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first!

is returning always URL like this:

file:///Users/userName/Library/Developer/CoreSimulator/Devices/deviceID/data/Documents

but searching through folders I see no /Documents folder. Has something changed recently? It used to work few weeks back (pretty sure). Super annoying and I can't find any workaround/fix for that.

A: I believe this is a (new-ish) "feature" of the iOS simulators - not all of the ususal directories exist when an app is initially installed.
Fortunately it's easy to create them, e.g. for the applicationSupport directory I do this in my apps:
let fileManager = FileManager.default
let directory = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first!
if !fileManager.fileExists(atPath: directory) {
  try fileManager.createDirectory(atPath: directory, withIntermediateDirectories: true, attributes: nil)
}

A: This happens in Simulators running iOS 11.x and up.
Before iOS 11, the Simulator created the global (app independent) Documents folder on startup. Since iOS 11.x (don't know if it was a special point release), this does not happen anymore.
Be aware that NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
returns this global documents path only in (unit) tests, not when running the app. If you run the app, you get the application specific Documents folder which is still created when installing the app in the simulator.
This seems to be a bug on Apple side. If you run into this issue (as it seems you have), please file a bug report at https://developer.apple.com/bug-reporting/.

A: You cannot (over)write the Documents directory, you have to append a file name.
And why do you archive the data? You can write the property list data directly to disk.
And never ever print a meaningless literal string in the catch clause, print at least the actual error.
let fileName = "myPropertyList.plist"
let fileURL = archiveURL.appendingPathComponent(fileName)
do {
   let data = try PropertyListEncoder().encode(elements)
   try data.write(to: fileURL)
} catch {
   print("Save Failed", error)
}


text:
Q: How to render AdaptiveCard in ReactNative correctly? I'm using React Native and trying to replicate the StockUpdate card from here Example Adaptive Cards
Currently Rendered Card
How do I set the correct HostConfig? I believe the rendering is off because the config isn't setup correctly.


text:
Q: Android expandable listview in an android expandable listview, i need to make thechildren displayed, only on pressing the expand collapse nodes..ie; i do notwant to show the children on pressing the row of the expandable listview..how can i accomplish it?
Regards,
Rony

A: I guess you want the expandable listview always expand without click group?
 You can check this question How to keep ExpandableListView in expanded status? and Expandable ListView .


text:
Q: How add random numbers to a text file I am trying to add numbers that are randomly generated into my text file as i read a name from one file into another.
Here is my code:
def dogs():
    total_cards = int(input("How many cards do you wish to play with? "))
    N = int(total_cards)
    Y = int(N/2)
    Z = int(N/2)

    with open("dogs.txt") as f:  # Opens needed file
            with open("dogswrite.txt", "w") as f1:  # My own file for player names
                for i in range(Y):
                    line_name = next(f).strip()  # Lists the input number of results each on a new line
                    line_name = line_name + "\n"
                    f1.write(line_name)
                    with open ("dogswritecpu.txt", "w") as f2:  # File for CPU names
                        for i in range(Z):
                            line_name = next(f).strip()
                            line_name = line_name + "\n"
                            f2.write(line_name)
dogs()

Currently the dogswrite text file reads with each being on a new line:
Molly
Dave
Tim

I want to the file to read as
Molly, 1 , 30, 48, 100

then a new line.
The same happens to Dave and Tim.
Thanks for all the help.
Class Code:
class Dog_card_player: #creates the class
    def __init__(self,name):
        self.name = name
        self.exercise = exercise
        self.friendliness = friendliness
        self.intelligence = intelligence
        self.drool = drool

    def Card_stats_player(self): #creates the stats for the card
        print("Name: " + self.name)
        print("Exercise: " + self.exercise)
        print("Friendliness: " + self.friendliness)
        print("Intelligence: " + self.intelligence)
        print("Drool: " + self.drool)

def Printing_card_player():
    with open ("dogswrite.txt") as f1:
        Dog_name_player = Dog_card_player(f1.readline())
        Dog_name_player.Card_stats_player()

A: import random

s= ', '.join(str(random.randint(1,100)) for i in range(4))

line_name = 'Molly'
line_name =  line_name+', '+s+"\n"
print(line_name) #  f1.write(line_name)

Output:
Molly, 42, 37, 39, 43

random.randint(a, b) Return a random integer N such that a <= N <= b.
  Alias for randrange(a, b+1).

What it basically means is that here end is not exclusive if your range is (7,42) both 7 and 42 are inclusive ie they can be part of result.
>>> random.randint(0,1)
1
>>> random.randint(0,1)
0
>>> random.randint(0,1)
1
>>> random.randint(0,1)
1

don't confuse it with normal range(start, end) that we use with for loop, in which end is exclusive.
>>> list(range(0,1))
[0]
>>> list(range(0,2))
[0, 1]

str.join(iterable)
       Return a string which is the concatenation of the strings in iterable. A TypeError will be raised if there are any non-string
  values in iterable, including bytes objects. The separator between
  elements is the string providing this method.


text:
Q: windows classic theme on windows 7 using java 7 u45 and greater I have a Swing application that gets deployed on clients machine using a JNLP. Earlier we were using Java 5/6 to run the application on client machine and did support only pre Windows Vista operating systems. We also force the application to have "Windows Classic" look and feel by introducing -swing.noxp=true parameter in the JNLP file. This made sure that the application always had a classic look and feel.
But, now with the new requirement we have to support Java 7 and Windows 7/8 as well. In the Java 7u45 document I read that -swing.noxp is no longer supported. This eventually means that I can not use this parameter for the application to default to classic look and feel.
I tried launching the application with Windows 7 and Java 7u51 without the "-swing.noxp" parameter. This made the application look like Windows 7 default theme which gave a weird look and feel to the application (I can post the comparative snap shots if need be).
My question here is, does Java 7 have some parameter (in place of -swing.noxp) which will do the trick for me(because client want the application to have the same look and feel as pre Java 7 upgrade.)?
I know I can change the PLAFs and all but that is a huge code change. I am looking for something simple and similar to -swing.noxp
Thanks for the help in advance.


text:
Q: Function to create a "stepped," diagonal line First off, sorry if this is a basic question or one that has been asked before. I really don't know how to phrase it, so it's a hard question to google.
I'm looking for a function that will generate a line similar to the one below
       __/
    __/
 __/
/

I'm pretty good at math, but for some reason this seems to be stumping me as it seems like it should be really simple.
In case it helps, I am planning on using it to drive an animation, so that it moves, pauses, moves, pauses, etc. using the current time (zero through infinity) as the input.
I am using an "Absolute," system (IE: if I were to jump to frame 35, the math needs to be able to calculate frame 35 without knowing the frames before it), so I can't do anything like if (floor(sin(time)) + 1 > 0) { add 1 }

A: Here is one example:
$$ f(x)=\left\vert \frac{x-1}{2}-\left\lfloor\frac{x}{2}\right\rfloor\right\vert+\frac{x-1}{2}$$

A: John Wayland's answer was good, and worked on the project I needed, but after playing around on a different project I came up with a more "tweakable," function that does the same thing, but allows changing of parameters.
D is the duration of one cycle, T is the amount of time the transition should take, and A is the amount of change between cycles.
$$cycle(x) = A(max\{\frac{(x \mod D) -D}{T} + 1, 0\} + \lfloor \frac{x}{D} \rfloor)$$
Breakdown
Create saw wave with intended duration
$$(x \mod D)$$
clamp it so that only 1 unit is greater than 0
$$max\{(x \mod D) - D + 1, 0\}$$
set duration of transition
$$max\{\frac{(x \mod D) -D}{T} + 1, 0\}$$
create stepped line, where each step is the duration of one cycle
$$\lfloor\frac{x}{D}\rfloor$$
Add the two together so that each step of the previous functions "lifts," each cycle up by 1 unit
$$max\{\frac{(x \mod D) -D}{T} + 1, 0\} + \lfloor \frac{x}{D} \rfloor$$
Finally multiply the whole thing by A to set the amount of desired change between cycles.

As a bonus, you can also wrap the max function in a smoothstep function and get a very nice smooth graph for animation
$$S(x)=x^2(3-2x)$$
$$cycle(x) = A(S(max\{\frac{(x \mod D) -D}{T} + 1, 0\}) + \lfloor \frac{x}{D} \rfloor)$$


text:
Q: How do I add a background image on a JFrame using a JLabel? I am trying to display a background image on the JFrame using a JLabel. The code runs and the buttons appear, but the image does not. I have researched for solutions, yet I have not found one for my code specifically. Any help would be greatly appreciated.
/**
 * Adds details to interface and programs buttons
 *
 * Imani Davis
 * Final Project
 */

import java.awt.*;
import java.awt.GridBagLayout;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.ImageIcon;
import javax.swing.border.EmptyBorder;

public class Use_PF_Interface extends JFrame implements Pet_Fish_Interface
{
    // instance variables - replace the example below with your own
    private JFrame window;
    private JPanel panel1, panel2, panel3;
    private JLabel lblBackgroundImage = new JLabel();
    private JButton feedButton = new JButton("Feed Fish");
    private JButton playGamesButton = new JButton("Play Game");

    /**
     * Constructor for objects of class Use_PF_Interface
     */
    public Use_PF_Interface()
    {
        setTitle("Virtual Pet Fish");
        setSize(650, 650);

        //initializes panels and panel layout
        panel1 = new JPanel();
        panel2 = new JPanel();
        panel3 = new JPanel();
        panel1.setLayout(new FlowLayout());
        panel2.setLayout(new FlowLayout());
        panel3.setLayout(new FlowLayout());

        lblBackgroundImage.setLayout(new FlowLayout());

        //sets background image of panel
        lblBackgroundImage.setIcon(new ImageIcon("C:\\Users\\This PC\\Desktop\\OCEAN2.JPEG"));
        panel1.add(lblBackgroundImage);
        validate();

        //adds button to panels
        panel2.add(feedButton);
        panel2.add(playGamesButton);

        //add panels to frame
        add(panel1);
        add(panel2);

    }

}

A: JFrame uses a BorderLayout by default, a BorderLayout can only manage a single component within any of the five available positions it provides, this means that panel2 is most likely the only component getting shown.
An alternative is to add you components to the JLabel, but remember, JLabel doesn't have a default layout manager.  Also, remember, JLabel only uses the icon and text properties to calculate its preferred size, so if the contents require more space, they will be clipped.
Start by having a look at How to Use BorderLayout for more details
Also, remember, most Swing components are opaque generally, so you need to set them transparent when you want to do something like this

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Use_PF_Interface extends JFrame {
    // instance variables - replace the example below with your own

    private JPanel panel2;
    private JLabel lblBackgroundImage = new JLabel();
    private JButton feedButton = new JButton("Feed Fish");
    private JButton playGamesButton = new JButton("Play Game");

    /**
     * Constructor for objects of class Use_PF_Interface
     */
    public Use_PF_Interface() {
        setTitle("Virtual Pet Fish");
        setSize(650, 650);

        //initializes panels and panel layout
        panel2 = new JPanel();
        panel2.setOpaque(false);
        panel2.setLayout(new FlowLayout());

        lblBackgroundImage.setLayout(new FlowLayout());

        //sets background image of panel
        lblBackgroundImage.setIcon(new ImageIcon("..."));
        lblBackgroundImage.setLayout(new BorderLayout());

        //adds button to panels
        panel2.add(feedButton);
        panel2.add(playGamesButton);

        lblBackgroundImage.add(panel2);

        add(lblBackgroundImage);

    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new Use_PF_Interface();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

}

A: Try this,
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;

public class ImageInFrame {
    public static void main(String[] args) throws IOException {
        String path = "Image1.jpg";
        File file = new File(path);
        BufferedImage image = ImageIO.read(file);
        JLabel label = new JLabel(new ImageIcon(image));
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(label);
        f.pack();
        f.setLocation(200,200);
        f.setVisible(true);
    }
}


text:
Q: Show that T is a rotation through an angle, and find the angle $T\left[\begin{array}{c}x \\ y \end{array}\right] = \frac{1}{\sqrt{2}}\left[\begin{array}{c}x+y \\ -x+y \end{array}\right]$
This is my attempt, but I'm stuck. Can someone continue?
$T\left[\begin{array}{c} x \\ y \end{array}\right] = \left[\begin{array}{cc} \cos θ & -\sin θ \\ \sin θ & \cos θ \end{array}\right] \left[\begin{array}{c}x \\ y \end{array}\right]$
$= \left[\begin{array}{c} x\cos θ - y\sin θ \\ x\sin θ + y\cos θ \end{array}\right]$

A: You want to find a rotation matrix that has the same effect as the matrix you have. You can then easily find the angle of rotation. We can write it like this to make it clearer (I've just re-written your first equation as a
matrix product rather than the way you have it):
$$
\left( \begin{array}{ccc}
\cos\theta & -\sin \theta  \\
\sin\theta & \cos \theta   \end{array} \right) \left(
\begin{array}{c}
x\\
y\\
\end{array}
\right)= \left( \begin{array}{ccc}
\frac{1}{\sqrt{2}} &\frac{1}{\sqrt{2}} \\
-\frac{1}{\sqrt{2}} & \frac{1}{\sqrt{2}} \end{array} \right) \left(
\begin{array}{c}
x\\
y\\
\end{array}
\right)
$$
so you can see we need to find the angle $\theta$ such that:
$$ \cos\theta=\frac{1}{\sqrt{2}} \;\;\text{  and  } \;\; -\sin\theta=\frac{1}{\sqrt{2}}\\
\sin\theta=-\frac{1}{\sqrt{2}} \;\;\text{  and  } \;\; \cos\theta=\frac{1}{\sqrt{2}}
$$
which is a consistent set of equations with a solution: $$\theta=\frac{\pi}{4}$$
So we can then interpret it as a rotation by an angle of $\pi/4$ radians or $45^\circ$.

Hopefully this makes it a little clearer how I got the right hand side of the first equation:
$$ T \left(\begin{array}{c}
x\\
y\\
\end{array}
\right) =\frac{1}{\sqrt{2}}\left(\begin{array}{c}
x+y\\
-x+y\\
\end{array}
\right)=\frac{1}{\sqrt{2}}\left( \begin{array}{ccc}
1 & 1  \\
-1 & 1   \end{array} \right)\left(\begin{array}{c}
x\\
y\\
\end{array}
\right)=\left( \begin{array}{ccc}
\frac{1}{\sqrt{2}} &\frac{1}{\sqrt{2}} \\
-\frac{1}{\sqrt{2}} & \frac{1}{\sqrt{2}} \end{array} \right) \left(
\begin{array}{c}
x\\
y\\
\end{array}
\right)$$


text:
Q: Makefile for running docker container with pseudo TTY I have a following Makefile:
start: delete-network create-network start-container delete-network

start-container:
    docker run -it --rm --network docky docky bash

create-network:
    docker network create docky

delete-network:
    docker network remove docky 2> /dev/null || true

Unfortunately when I call make start, delete-network task is ignored after I exit from cotainer. How can I execute all tasks?

A: If running the container and cleaning up is the goal, this will do it:
start: delete-network create-network start-container

start-container:
    docker run -it --rm --network alpine alpine sh; docker network remove alpine

create-network:
    docker network create alpine

delete-network:
    docker network remove alpine 2> /dev/null || true

and a version without duplication:
start: create-network start-container delete-network

start-container:
    -docker run -it --rm --network alpine alpine sh

create-network:
    docker network create alpine || true

delete-network:
    docker network remove alpine 2> /dev/null || true


text:
Q: MySQL #1093 - You can't specify target table 'giveaways' for update in FROM clause I tried:
UPDATE giveaways SET winner = '1' WHERE ID = (SELECT MAX(ID) FROM giveaways)

But it gives:

#1093 - You can't specify target table 'giveaways' for update in FROM clause

This article seems relevant but I can't adapt it to my query. How can I get it to work?

A: Based on the information in the article you linked to this should work:
update giveaways set winner='1'
where Id = (select Id from (select max(Id) as id from giveaways) as t)

A: This is because your update could be cyclical... what if updating that record causes something to happen which made the WHERE condition FALSE? You know that isn't the case, but the engine doesn't. There also could be opposing locks on the table in the operation.
I would think you could do it like this (untested):
UPDATE
    giveaways
SET
    winner = '1'
ORDER BY
    id DESC
LIMIT 1

Read more

A: update giveaways set winner=1
where Id = (select*from (select max(Id)from giveaways)as t)

A: create table GIVEAWAYS_NEW as(select*from giveaways);

update giveaways set winner=1
where Id=(select max(Id)from GIVEAWAYS_NEW);

A: Make use of TEMP TABLE:
as follows:
UPDATE TABLE_NAME SET TABLE_NAME.IsActive=TRUE
WHERE TABLE_NAME.Id IN (
    SELECT Id
    FROM TEMPDATA
);

CREATE TEMPORARY TABLE TEMPDATA
SELECT MAX(TABLE_NAME.Id) as Id
FROM TABLE_NAME
GROUP BY TABLE_NAME.IncidentId;

SELECT * FROM TEMPDATA;

DROP TABLE TEMPDATA;

A: You can create a view of the subquery first and update/delete selecting from the view instead..
Just remember to drop the view after.


text:
Q: sysV init.d: what does the priority really mean? The docs for chkconfig are a bit loose on what the priority number actually means, and the docs for init don't even mention priority on my machine.
Say you have the following:
/etc/rc.d/rc3.d/S01foo
/etc/rc.d/rc3.d/S02bar

Which one is run first?  The one with the higher priority (bar)?  Or is the priority number more of a start-order number, so the lower numbers are started before the higher numbers?
What if it was K01foo and K02bar. Which one would be stopped first?  Greater priority one, or is it more of a "stop-order"?

A: After some experimentation I was able to figure it out.
It's more of an 'order from least to greatest' process.
In other words, the lower the priority number, the sooner the job will stop/start.
S01foo will start before S02bar, and K01foo will stop before K02bar.
Hopefully this saves someone 15 minutes.


text:
Q: Handling tasks that never terminate in python3 asyncio Sometimes async tasks have no meaningful termination condition - for instance, in the program below, the "rate_limiter" task generates a stream of tokens on a queue, at a fixed rate, forever.
import asyncio
import sys

@asyncio.coroutine
def rate_limiter(queue, rate):
    """Push tokens to QUEUE at a rate of RATE per second."""
    delay = 1/rate
    while True:
        yield from asyncio.sleep(delay)
        yield from queue.put(None)

@asyncio.coroutine
def do_work(n, rate):
    for i in range(n):
        yield from rate.get()
        sys.stdout.write("job {}\n".format(i))

def main():
    loop   = asyncio.get_event_loop()
    rate   = asyncio.Queue()
    rltask = loop.create_task(rate_limiter(rate, 10))
    wtask  = loop.create_task(do_work(20, rate))
    loop.run_until_complete(wtask)

main()

This program works perfectly except that the asyncio library considers it a programming error to just throw away rltask when there's nothing left to rate-limit; you get a complaint like
...
job 18
job 19
Task was destroyed but it is pending!
task: <Task pending coro=<rate_limiter() running at rl.py:9>
      wait_for=<Future pending cb=[Task._wakeup()]>>

(whether or not in debug mode).
I can kludge around this with, like, an Event that tells the rate_limiter coroutine to break out of its loop, but that feels like extra code to no real benefit.  How are you supposed to deal with this sort of situation when using asyncio?
EDIT: I was unclear: what I am looking for is something like the daemon flag on threads: something that makes it so I don't have to wait for a particular task, ideally expressed as an annotation on the task itself, or its coroutine.  I would also accept an answer that demonstrates that there is no such mechanism.  I'm already aware of workarounds.

A: To avoid "Task was destroyed but it is pending!" warning, you could mark a never ending coroutine as finished on exit from the program if you set a dummy result for the corresponding future object:
#!/usr/bin/env python3.5
import asyncio
import itertools
from contextlib import closing, contextmanager

@contextmanager
def finishing(coro_or_future, *, loop=None):
    """Mark a never ending coroutine or future as done on __exit__."""
    fut = asyncio.ensure_future(
        coro_or_future, loop=loop)  # start infinite loop
    try:
        yield
    finally:
        if not fut.cancelled():
            fut.set_result(None)  # mark as finished

async def never_ends():
    for c in itertools.cycle('\|/-'):
        print(c, end='\r', flush=True)
        await asyncio.sleep(.3)

with closing(asyncio.get_event_loop()) as loop, \
     finishing(never_ends(), loop=loop):
    loop.run_until_complete(asyncio.sleep(3))  # do something else

It assumes that your coroutine does not require an explicit cleanup before the process exits. In the latter case, define an explicit procedure for the cleanup: provide methods that could be called (e.g., server.close(), server.wait_closed()), or pass an event (asyncio.Event) that a caller should set on shutdown, or raise an exception (such as CancelledError).
The benefit of introducing finishing() is to detect bugs i.e., you should not ignore the warning unless it is explicitly silenced by the finishing() call.

A: .cancel() the task and then wait for it be cancelled, catching the CancelledError outside:
# vim: tabstop=4 expandtab

import asyncio
import sys

@asyncio.coroutine
def rate_limiter(queue, rate):
    """Push tokens to QUEUE at a rate of RATE per second."""
    delay = 1/rate
    while True:
        yield from asyncio.sleep(delay)
        yield from queue.put(None)

@asyncio.coroutine
def do_work(n, rate):
    for i in range(n):
        yield from rate.get()
        sys.stdout.write("job {}\n".format(i))

def main():
    loop   = asyncio.get_event_loop()
    rate   = asyncio.Queue()
    rltask = loop.create_task(rate_limiter(rate, 10))
    wtask  = loop.create_task(do_work(20, rate))
    loop.run_until_complete(wtask)
    rltask.cancel()
    try:
        loop.run_until_complete(rltask)
    except asyncio.CancelledError:
        ...
    loop.close()

main()


text:
Q: Named arguments without natural defaults in Julia The question is about 'best practice' in Julia. I have read this and this. I have a function
function discount_rate(n, fv, pmt, pv; pmt_type = 0)
...
end

The problem right now is I have to call the method like so
discount_rate( 10, 10, 10, -10 )

It's not clear what these arguments mean -- even I forget. What I'd love to do is write
discount_rate( n = 10, fv = 10, pmt = 10, pv = -10 )

That's clearer: easier to read and understand. But I can't define my method by making these arguments keywords arguments or optional arguments because they don't have natural defaults. From the point of view of design, is there a recommended way around this?

A: Could do the following:
function discount_rate(;n=nothing,fv=nothing,pmt=nothing,pv=nothing,pmt_type=0)
    if n == nothing || fv == nothing || pmt == nothing || pv == nothing
        error("Must provide all arguments")
    end
    discount_rate(n,fv,pmt,pv,pmt_type=pmt_type)
end

function discount_rate(n, fv, pmt, pv; pmt_type = 0)
    #...
end

A: As a follow up, it got a little tedious to have to (re)write the keywords-only counterparts for the functions I already had. Inspired by Iain's answer above, I wrote a macro that essentially does the same thing...
macro make_kwargs_only( func, args... )
 quote
  function $( esc( func ) )( ; args... )
   func_args = [ arg[2] for arg in args ]
   return $( esc( func ) )( func_args... )
  end
 end
end

And so, for example
f( a, b ) = a/b
@show f( 1, 2 )
f(1,2) => 0.5

Creating its keywords-only counterpart gives
@make_kwargs_only f a b
@show f( a = 1, b = 2 )
f(a=1,b=2) => 0.5

Note however this is not the general case. Here the order of the argument is crucial. Ideally I would've liked the macro to work the same way for both f( a = 1, b = 2 ) and f( b = 2, a = 1 ). That is not the case.
@show f( b = 2, a = 1 )
f(b=2,a=1) => 2.0

So for now, as a hack, I use methods( f ) if I can't remember the order of the arguments. Any suggestion on how to rewrite the macro to handle both cases is welcome...maybe a way to sort func_args within the macro's function definition based on the function signature of func?

A: It is worth noting that Julia introduced mandatory keyword arguments in v0.7:
julia> foo(; a) = a
foo (generic function with 1 method)

julia> foo()
ERROR: UndefKeywordError: keyword argument a not assigned
Stacktrace:
 [1] foo() at ./REPL[1]:1
 [2] top-level scope at none:0

A: Is this answer any different in 1.5? In Python, whenever I write a function with several arguments, I usually call it with keyword arguments. It doesn't seem like there's a clean way to do that in Julia without either (1) giving them default values (could be sentinal values, as suggested by Iain) or (2) making them mandatory keyword arguments (as suggested by gTcV).


text:
Q: KeystoneJS com Mongo remoto Boa noite!
Estou começando a estudar KeystoneJS versão 0.3.17. Seguindo o "Getting started" do site oficial, nos pré requisitos pede-se nodejs e o mongodb, porem quero usar esse serviço cloud do mongodb.
Como poderia fazer essa integração? É possível? Pois, não instalei o mongodb em meu computador e quando vou executar o comando node keystone acontece esse erro.

Edit: Para conexão remota o KeystoneJS disponibiliza no arquivo .env a propriedade MONGO_URI=mongodb://your-server/database-name

Testei a conexão remota pelo command line usando esse comando: mongo "mongodb://***-shard-00-00-nalfi.mongodb.net:27017,***-shard-00-01-nalfi.mongodb.net:27017,***-shard-00-02-nalfi.mongodb.net:27017/test?replicaSet=***-shard-0" --authenticationDatabase admin --ssl --username *** --password ***, a conexão é feita com sucesso.
Quando configuro a propriedade MONGO_URI no .env, dessa forma: MONGO_URI=mongodb://***:***@***-shard-00-00-nalfi.mongodb.net:27017,***-shard-00-01-nalfi.mongodb.net:27017,***-shard-00-02-nalfi.mongodb.net:27017/test?ssl=true&replicaSet=***-shard-0&authSource=admin, é retornado um erro de autenticação.
Estou usando exatamente as mesmas credenciais e nomes do banco e replica.

Edit: O problema estava nos caracteres da senha usada. Não seu por qual motivo mas a senha não pode ter o caractere "@" nessas condições de conexão.


text:
Q: REST API HATEOAS issue I am reading about HATEOAS in API response, so I have this case, the user will hit this URL first

*

*/payments, this URL will return a list of allowed payment methods, and I am thinking to return a links key which contains the endpoints of those allowed payment methods, but those links need a params should be build/filled by the integrator, is it valid to return HATEOAS in this case, the links are using GET verb.

Thank you,

A:
is it valid to return HATEOAS in this case, the links are using GET verb.

HATEOAS: your guiding principle is "how would I do it in web pages?"
In your case, a simple implementation might be that you have a /payments page, and a number of links (pay with paypal, pay by credit card, etc).  Each of those links would GET a new web page that had a form on it, that would show the consumer what information was required for that type of payment.  Those forms might immediately submit the payment (which would probably be a POST, with the form arguments in the content body), or they would link to a confirmation page (GET, with the form arguments appearing as query parameters), which would show the user a summary of the payment, with a confirm button that would do the POST as before.
Building a REST api with HATEOAS is the same thing, designed for an program, rather than a person, to consume.  So your links key would contain endpoints for the forms of the allowed payment methods, and those forms would appear with a links key that connects the form to the payment methods.


text:
Q: Can not delete record from SQLite iPhone When I run this code in iPhone simulator ,I can not delete record from DB . If I run this query in SQLite DB Browser it works well. Here is my code
SQLiteDB *sqliteConnect=[[SQLiteDB alloc] init];
sqlite3 *database;

if(sqlite3_open([sqliteConnect.databasePath UTF8String], &database)==SQLITE_OK)
{
    sqlite3_stmt *compiledstatement;

    const char *sqlstmt="delete from searchHistory where id = (select min(id) from searchHistory) ";

    if(sqlite3_prepare_v2(database, sqlstmt, -1, &compiledstatement, NULL)==SQLITE_OK)
    {
        sqlite3_step(compiledstatement);

        if(SQLITE_DONE != sqlite3_step(compiledstatement))

            NSAssert1(0,@"Error while creating delete statement => %s",sqlite3_errmsg(database) );
    }
    NSLog(@"delete DONE");
    sqlite3_finalize(compiledstatement);
}
sqlite3_close(database);

When I run using debugger  , I get following error =>
2011-04-08 08:42:34.049 MyApp[1838:20b] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Error while creating delete statement => not an error'

SQLiteDB is my class which contains logic for init & checkAndCopyDB methods. My DB gets copied in documents directory. Other DB operations works fine. Please help me. Thanks

A: you're calling sqlite3_step twice?
Try this :
{
    int result = sqlite3_step(compiledstatement);

    if(SQLITE_DONE != result)

        NSAssert1(0,@"Error while creating delete statement => %s",sqlite3_errmsg(database) );
 }

A: Perhaps try:
if(SQLITE_DONE != sqlite3_step(compiledstatement))
    NSAssert1(0,@"Error while creating delete statement => %s",sqlite3_errmsg(database));


text:
Q: Sharing data between android apps on the same device by same publisher where no one app is host I have looked through so many similar stackoverflow posts but none of them seem to solve my specific problem. I want something like the iOS Shared Keychain storage, that any app signed by the same certificate can read and write to. The only answer everywhere is using Content Providers, but unfortunately with Content Providers, it seems that one app needs to be the host, and the other apps are the clients. I seek more of a peer-to-peer style of data sharing, where I have many apps but my users may have perhaps downloaded only a small subset of them (but more than one). There is data that will be shared between those apps, and any of the apps may be uninstalled at any time, and more apps by the same vendor might get installed at any time. In any case, the data should persist as long as there is at least one app by that vendor. When all apps are uninstalled, only then should that data be destroyed. These apps do have a common package name, but a unique application name.
Any suggestions?


text:
Q: How to send a stored template and also specify reply_to, from.name and from.email? Here it is explained how to specify these properties when sending inline content, but when sending a stored template it is said that they are forbidden.
I tried to send an email by specifying the ID of the template and also the forbidden properties: reply_to, from.name and from.email, and the forbidden properties were ignored.
I see setting the Reply-To header as something normal, not unusual, when sending a transactional email, and I find it strange that I cannot do this when sending a stored template. Setting the From name and email from code and not from the SparkPost template editor also seems a good functionality to have.
My code looks like this (it uses the SparkPost NodeJS API and the emails with their substitution data are successfully sent with this code so the problem is not in the substitution_data, recipients or in the callback parts of this code):
client.transmissions.send({
    transmissionBody: {
        content: {
            template_id: 'my-first-email',
            reply_to: 'example@sparkpostbox.com', // example email address
            from: {
                name: 'My Name',
                email: 'example2@sparkpostbox.com'
            }
        },
        substitution_data: { /* ... */ },
        recipients: [ /* ... */ ]
    }
}, function (err, res) { /* ... */ });

Update: I found this question in the SparkPost Support Center but it does not help me.
Update 2: I also found this support question which may help a little but I still need a way to set the Reply-To header and I am not sure yet if the From email address (not the From name, about which I am sure from the linked article that it can do this) can use dynamic substitution data.
Update 3: I sent an email to SparkPost Support and received the following answer:

The Product Manager relayed that we do not have a time frame of when
  this feature will be in the product. Please keep an eye on our website
  and slack channel for updates.

As I have tested and accepted an answer for this question, I think they did not understand me well. But it is a happy end, after all.

A: If you specify template_id, you can't specify any other options in the content object. So if you want to customize the template, you'll need to add substitution variables in your template.
One thing to note is that if you use substitution variables in your From: header, that will mean you cannot edit that template using the UI, since there is a hard requirement (in the UI) that you use a verified sending domain.

A: As Dave Gray mentions above, you can use substitution variables in your template to set custom 'From name', 'From email' and 'Reply-To' fields.
Here's an example template showing how that looks:
{
  "content": {
    "from": {
      "name": "{{fromName}}",
      "email": "{{fromEmail}}"
    },
    "subject": "{{subject}}",
    "html": "Hi! I am an HTML part.",
    "text": "I am a text part.",
    "reply_to": "{{replyTo}}"
  }
}

As Dave also points out, you'll need to use the API to update your stored template with these fields.  Here's a gist with some JS to do that.
Then you can set fromName, fromEmail and replyTo in your transmission:
{
  "recipients": [
    "..."
  ],
  "content": {
    "template_id": "your-dynamic-template"
  },
  "substitution_data": {
    "fromName": "Your Name",
    "fromEmail": "you@yourdomain.com",
    "replyTo": "youagain@yourotherdomain.com"
  }
}


text:
Q: python3,boto3,aws ec2 instance's second ip obtain Somehow, I had to get second eth1 private ip address of ec2 instances using python3. I can get only ec2 instance-id. I managed to do it,but it is not good code I think.
I tried filters but failed. Instead I use like below.
ec2 = boto3.client('ec2')
def get_sec_ip(instance_id):
    res=ec2.describe_instances(InstanceIds=[instance_id])
    print(res['Reservations'][0]['Instances'][0]['NetworkInterfaces'][1]['PrivateIpAddress'])```

instance_id = 'i-03a0d15992b7bf'
get_sec_ip(instance_id)

Is there anybody who did this result using ec2.describe_instances' filters?

A: An other possibility is to use Instance object:
 ec2 = boto3.resource('ec2')
 instance = ec2.Instance(instance_id)
 print(instance.network_interfaces[1].private_ip_address)

The filter is not used for limiting output, but limiting number of instance descriptions return. For example, the describe_instances can return 10 instances (not in your case, but in general), and Filters can limit it to only 2 based on some criteria, e.g. instances only in a given subnet.


text:
Q: Sans-serif to go with EB Garamond (no math)? Suggestions for a good sans-serif font to go with (complement) EB Garamond? Math and non-Western European support are not required. Text is fiction, not academic or scientific. English with an occasional word or phrase in French.
I'm using LuaLaTeX from TexLive 2013 on Windows 7 but that should not matter.
Too many choices, too little time.

A: Assuming the usage will be for headers or elements like folios, my choice would be Optima, which has a classical structure and so won't clash too much. If that's not to your liking, Syntax is a choice advocated on Typophile for this sort of thing, but its higher x-height would require some scaling down.

A: Another good choice could be Myriad or Frutiger. Myriad and Minion come with Adobe Reader, and work quite well together (see What best combination of fonts for Serif, Sans, and Mono do you recommend?). There are plenty of nice choices, though. If you don't need bold, Calluna Sans is free, as well as Fontin Sans.
EB Garamond With Myriad Pro

Minion and Myriad (bold)

Minion and Myriad (regular):

A: You haven't told us just how the text strings set in serif and sans-serif will be juxtaposed. If the serif and sans-serif text strings can occur side by side in running text, I'd apply the following criteria to guide my search for a suitable sans-serif: (a) match the x-height of the Roman font (very easy to achieve via fontspec's option Scale=MatchLowercase), (b) the sans-serif font shouldn't be all that compressed, (c) it should feature a dual-level g (as opposed to a single-level g employed by Helvetica and Myriad), (d) it should have fairly slender strokes (unlike, say, Gill sans), and (e) still look sufficiently different from Garamond.
For my own writing work that involves Garamond Roman fonts (any "Garalde", really) as the main text font, I've found that Palatino Sans -- yes, there really is such a thing! -- works very well as a companion font.
The following screenshot shows several groups of font choices. In each selection, the first main text line is in EB Garamond, the second in the sans-serif of choice, and the third alternates words using serif and sans-serif. IMNSHO, Palatino Sans harmonizes quite nicely with EB Garamond, while still having a true "sans-serif" character as opposed to, say, Optima. Of course, Optima (also by Hermann Zapf, the creator of Palatino and Palatino Sans) has frequently been called a "serifless Roman font", as opposed to a "true" sans-serif font.

Naturally, this form of juxtaposition of serif and sans-serif fonts assumes that it's meaningful to make such a juxtaposition. If your documents don't contain serif and sans-serif elements in close proximity, the evaluation given in this answer may not be particularly relevant for you.
% !TEX TS-program = lualatex
\documentclass{article}
\usepackage{fontspec}
\setmainfont{EB Garamond}  % EB Garamond is the "roman" font
\defaultfontfeatures{Scale=MatchLowercase}

%% Macro to load sans-serif font and print several test strings
\newcommand\fourlines[1]{%
\setsansfont{#1}
\texttt{#1}

The quick brown fox jumps over the lazy dog.

\textsf{The quick brown fox jumps over the lazy dog.}

The \textsf{quick} brown \textsf{fox} jumps \textsf{over} the \textsf{lazy} dog.}

\begin{document}

\fourlines{Palatino Sans Com}

\medskip
\fourlines{Optima nova LT Pro}

\medskip
\fourlines{Linux Biolinum O}

\medskip
\fourlines{Gill Sans MT}

\medskip
\fourlines{Helvetica Neue}

\medskip
\fourlines{Myriad Pro}

\medskip
\fourlines{Calibri}
\end{document}

A: There's another font which I found a pretty good match for EB Garamond (especially for section headings): Eau de Garamond (https://github.com/CatharsisFonts/EauDeGaramond). What's especially great about this open source font family (licensed: OFL) is that contains different weights (Hairline, Thin, Light, Semilight, Regular, Medium, Bold) and small caps.

Code to reproduce (adapted from Mico's answer here)
% !TEX TS-program = lualatex
\documentclass{article}
\usepackage{fontspec}
\setmainfont{EB Garamond}  % EB Garamond is the "roman" font
\defaultfontfeatures{Scale=MatchLowercase}
\setsansfont{EauTestText}

\begin{document}
The quick brown fox jumps over the lazy dog.

\textsf{The quick brown fox jumps over the lazy dog.}

The \textsf{quick} brown \textsf{fox} jumps \textsf{over} the \textsf{lazy} dog.

\textsc{The quick brown fox jumps over the lazy dog.}

\textsf{\textsc{The quick brown fox jumps over the lazy dog.}}
\end{document}

A: If you don't mind an organic sans serif, you could use Linux Biolinum which is part of the libertine package; Libertine is a more modern (but still classical) typeface than Garamond, but the pairing still works rather well in my opinion (and if you want to pair a Garalde typeface with a sans serif, you probably don't care that much about period accuracy) -- although I wouldn't use bold sans (a double anachronism) for headers:
\documentclass{article}
\usepackage[sf,scale=0.95]{libertine} % sets biolinum as sf only
\usepackage{ebgaramond}
\begin{document}
\section*{\sffamily\mdseries Lorem Ipsum Redux}
Cras viverra metus rhoncus sem. \textsf{Nulla et lectus vestibulum} urna fringilla ultrices.
\end{document}

The current libertine package automatically uses otf by loading fontspec if the document is compiled using xelatex or lualatex, but the above works using pdflatex as well.
If you prefer a more classical sans serif, or really would like to use bold sans, you can try Pablo Impallari's Quattrocento Sans:
\usepackage[sf,scaled=0.9]{quattrocento}
...
\section*{\sffamily Lorem Ipsum Redux}

I think the typeface is okay for headings even in bold, but too wide to use in the text body.

A: Typewolfe suggests pairing Garamond with Gill Sans, but here (along with two more links that my low reputation wouldn't let me submit) Helvetica (helvet or tgheros in TeX) is recommended as a companion typeface.


text:
Q: How to prove that $(a\cos\alpha)^n + (b\sin\alpha)^n = p^n$ under the following conditions? How to prove that $(a\cos\alpha)^n + (b\sin\alpha)^n = p^n$ when then line $x\cos\alpha + y\sin\alpha = p$ touches the curve  $$\left (\frac{x}{a} \right )^\frac{n}{n-1} + \left (\frac{y}{b} \right )^\frac{n}{n-1}=1$$
What I've tried:
I've equated the derivative of the given line with the general derivative of the given curve but couldn't proceed to any meaningful step thereafter.

A: At the tangent point (x, y), the normal of the two curves are parallel, so we can get
 $$\{\cos \alpha, \sin \alpha \}//\{\frac{x^\frac{1}{n-1}}{a^\frac{n}{n-1}}, \frac{x^\frac{1}{n-1}}{a^\frac{n}{n-1}}\} $$
so we get the equation:
$$\frac{x^\frac{1}{n-1}}{a^\frac{n}{n-1}\cos \alpha}=\frac{x^\frac{1}{n-1}}{a^\frac{n}{n-1}\sin \alpha}=k$$
Hence:
$$x=k^{n-1}a^n(\cos\alpha)^{n-1}$$ $$y=k^{n-1}b^n(\sin\alpha)^{n-1}$$
Take x and y into $x\cos\alpha + y\sin\alpha = p$ we get:
$$k^{n-1}((a\cos\alpha)^n+(b\sin\alpha)^n)=p$$
Take x and y into $\left (\frac{x}{a} \right )^\frac{n}{n-1} + \left (\frac{y}{b} \right )^\frac{n}{n-1}=1$ we get:
$$k^n((a\cos\alpha)^n+(b\sin\alpha)^n)=1$$
Therefore:$$k=1/p$$
Take K into $k^n(a^n\cos\alpha^n+b^n\sin\alpha^n)=1$  get the result:
$$(a\cos\alpha)^n + (b\sin\alpha)^n = p^n$$


text:
Q: Indexing words of a text I have text who looks like this

*mmm* we have a dog
  *ppp* we are going home
  *SSS* we have gone home

In this text the text between * is the reference to a book with page nr and line nr. In this case I just reduced it to three letters.
I want to create an array with each word as key and the line number as value:
Array
(
    [we] => Array
    (
        [0]=>*mmm*,
        [1]=>*ppp*,
        [2]=>*SSS*
    )
    [have] => Array
    (
        [0] => *mmm*,
        [1] => *SSS*
    )
)

and so on....
Secondly I want to create an array with two words following each other as key and the line number as value
Array
(
    [we have] => array([0] => *mmm*, [1] => *SSS*),
    [have a] => array([0 => *mmm*),
    [a dog] => array([0] => *mmm*),
    [dog we] => array([0] => *mmm*),
    [we are] => array([0] => *ppp*)
)

Notice that when two words are not in the same line (as in [dog we]) it is the reference of the first word that should be used as value.
I think I found the solution to the first problem. I transformed the text in an array
$text = array ([0]=>*mmm*, [1]=>"we", [2]=>"have", and so on...
And then:
foreach ($text as $word)
{
    if($word[0] == "*")
    {
        $value = $word;
        continue;
    }
    else
    {
        $key = $word;
        if (array_key_exists($key,$dictionary))
        {
            array_push($dictionary[$key], $value);
        }
        else
        {
            $dictionary[$key] = array($value);
        }
    }
    return $dictionary;

For the creation of an array with two words I did the following
foreach ($text as $word)
{
    if($word[0] == "*")
    {
        $value = $word;
        continue;
    }
    else
    {
        $key1 = $word;
        $key2 = $text[array_search($key1,$text)+1];
        if ($key2[0] == "*")
        {
            continue;
        }
    else
    {
        $key = $key1.$key2;
        if (array_key_exists($key,$dictionary))
        {
            array_push($dictionary[$key], $value);
        }
        else
        {
            $dictionary[$key] = array($value);
        }
    }
    return $dictionary;
}

This doesn't work becaue of the $key = $key1.$key2;. It seems that when the key is [we have] (as in our text in mmm) and later on the key should be [we are] the program doesn't make the difference. In fact each time the first word is "we" he automatically adds the second word "have" even if it should be "are". So this means that in going through each word of the text $key1 is not restaured to zero but each time the first word is "we" the value will be put under the key "we have".
Anyone have a solution for this or maybe the whole thing can be done simplier?
PS I hope I didn't forgot to many {} I'm typing this on an small screen without a good overview

A: In the following code snippet, tokenize() enumerates 1-word tokens and 2-word tokens, as well as their position, reduce() does aggregation by tokens. See if it works in your case.
<?php
$text = array('*mmm*', 'we', 'have', 'a', 'dog', '*ppp*', 'we', 'are', 'going', 'home', '*SSS*', 'we', 'have', 'gone', 'home');

function tokenize($text, $initPosition) {
  $words = array();
  $position = $initPosition;

  foreach ($text as $value) {
    if ($value[0] === '*') {
      $position = $value;
    } else {
      $words[] = array('token' => $value, 'pos' => $position);
    }
  }

  $temp = $words;
  for ($i = 0; $i < count($temp); $i++) {
    if (isset($temp[$i + 1])) {
      $token = $temp[$i]['token'] . ' ' . $temp[$i + 1]['token'];
      $words[] = array('token' => $token, 'pos' => $temp[$i]['pos']);
    }
  }
  return $words;
}

function reduce($words) {
  $dictionary = array();
  foreach ($words as $value) {
    if (isset($dictionary[$value['token']])) {
      $dictionary[$value['token']][] = $value['pos'];
    } else {
      $dictionary[$value['token']] = array();
      $dictionary[$value['token']][] = $value['pos'];
    }
  }
  return $dictionary;
}

$words = tokenize($text, '*mmm*');
$dictionary = reduce($words);
print_r($dictionary);


text:
Q: Should I override templated base class's function in specialized derived class? I have been coding on VC++ 2015 platform and I always get unresolved external symbol error on non-overridden base class functions. Here is the example :
//BaseClass.h
template<class T>
class BaseClass {
public:
   T* setRootPath(std::string&& rootPath);
....
}

//Implementations are in BaseClass.cpp

//ChildClass.h
class ChildClass:public BaseClass<ChildClass> {
public:
   ChildClass* setWidth(const int width);
   //No redefinition of "setRootPath" and hope not necessary
....
}

//Implementations are in ChildClass.cpp and i included BaseClass.cpp in this file as well

When I compile this code it throws no error. On the other hand during linkage time it says that it cannot find the required symbol for setRootPath with appropriate templating. Why can't it find "ChildClass* setRootPath(std::string&& rootPath)" function?
What I want to ask is that "Should I declare the function with an appropriate return type in ChildClass while I want to use the very same definition from the BaseClass"?
The error thrown by MSVC is :
error LNK2001: unresolved external symbol "public: class ChildClass * __cdecl BaseClass<class ChildClass>::setRootPath(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > &&)" (?setRootPath@?$BaseClass@VChildClass@3@$$QEAV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z)

Thanks for your help in advance.


text:
Q: Query WikiData using Wikipedia categories I'm wondering if it's possible to write a WikiData SparkQL query that can retrieve all entities under a category?
For example: the wikipage of Barak Obama has a bunch of categories including: "African-American Christians", "African-American educators", "African-American feminists", "African-American lawyers"
I'm trying to find a way to select all "humans" what match those categories. The wikidata page of Obama doesnt have any of those categories so I'm not sure how to query this.
Thanks

A: SELECT * WHERE {
  wd:Q76 wdt:P910 ?category .
  ?link schema:about ?category; schema:isPartOf <https://en.wikipedia.org/>; schema:name ?title .
  SERVICE wikibase:mwapi {
     bd:serviceParam wikibase:endpoint "en.wikipedia.org";
                     wikibase:api "Generator";
                     mwapi:generator "categorymembers";
                     mwapi:gcmtitle ?title;
                     mwapi:gcmprop "ids|title|type";
                     mwapi:gcmlimit "max".
     ?member wikibase:apiOutput mwapi:title.
     ?ns wikibase:apiOutput "@ns".
     ?item wikibase:apiOutputItem mwapi:item.
  }
}

adapted from here


text:
Q: Bootstrap Collapse Showing Child Elements When Collapsed I'm trying to have a collapsible panel that contains multiple controls - text boxes, labels, drop downs etc, but whenever I use the following code, the collapse animation shows, but the items are still visible.
This is a sample of what I'm trying to do:
<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Collapsible List Group

Click on the collapsible panel to open and close it.

          Collapsible list group

              Text Here
              <input id="txtbox" type="text"/>

Some screenshots to show what I'm talking about:
Not Collapsed:

Collapsed:

A: Try removing the "show" class from the field you wish to collapse:
Edit: Include the class "in" when wanting to show uncollapsed by default.

Collapsible List Group

Click on the collapsible panel to open and close it.

              Collapsible list group

                  Text Here
                  <input id="txtbox" type="text"/>


text:
Q: Compare double ids, group into one I have a table "stats" that consists 3 ids and qty.
From this table, I want to return id_part, id_proj and qty.

The solution is partly here, the only problem is that when the ids are double, it should show only one row with summed qty.
For example:
P1, J4, 1700
P3, J1, 600
P3, J4, 1700
SELECT id_part, id_proj, qty
FROM stats
ORDER BY id_part, id_proj;

I have tried with case, also I somehow wanted to compare first row with second, but no luck.

A: Use Group By with sum(qty) on id_part to get a single result.
Code:
SELECT id_part, id_proj, sum(qty)
FROM stats
Group BY id_part
ORDER BY id_part, id_proj;


text:
Q: How to generate a trusted ssl certificate for the backend of an application developed with spring-boot I have a web application developed with spring boot and Angular. The frontend is running on ngnix web server , the backend is running on embedded tomcat for spring boot , both of them are hosted on a Debian VM on ovh cloud, so it's secured with ovh basic Let's Encypt basic security for ssl offered by OVH.
My problem is that the certificate is regenerated (each 3 months ovh regenerate a new one ) and my backend could not recognize anymore the calls coming from the front end.
I made some researches on how to use the certificates generated by ovh ( use the privatekey.pem and fullchain.pem (under /etc/letsencrypt/live/mydomain)  with openssl to generate a PKCS12 file to be put on the backend server )
I put the generated .p12 file in my spring app and configured mu application.properties but with no success!
server.ssl.key-store-type=PKCS12
# The path to the keystore containing the certificate
server.ssl.key-store=classpath:keystore/my-keystore.p12
# The password used to generate the certificate
server.ssl.key-store-password=mypassword
# The alias mapped to the certificate
server.ssl.key-alias=myalias

So how do I generate a trusted SSL certificate for my  backend server?
I don't know if I'm in a good way with these steps or not, since I'm totally new with all this stuff but If someone could explain me the flow, how to proceed I will be so much grateful !
Thanks in advance