text:
Q: Validar evento Onclick en JavaScript Quiero realizar una validación en un botón para limpiar mis forms al dar click en botón salir :
if (document.getElementById('btnsalirmodalf').onclick == true) {
    document.getElementById('asignadoa').value == '';
    document.getElementById('Estatus').value == '';
    document.getElementById('porcentaje').value == '';
    document.getElementById('exampleFormControlTextarea1').value == '';
    document.getElementById('exampleFormControlTextarea2').value == '';
}

El problema es que no se si en está parte:
document.getElementById('btnsalirmodalf').onclick == true

estoy haciendolo bien ya que no me realiza ningún cambio al dar click en salir. Tienen una sugerencia por favor?.

A: Crea una función que haga lo que necesitas y al momento de encerar (poner en blanco el input), asigna el valor de "" solamente con un "=" no con dos.
Intenta con este código:

function limpia() {
  document.getElementById("asignadoa").value = "";
  document.getElementById("Estatus").value = "";
}
<button type="button" id="btnsalirmodalf" onclick="limpia()">Limpiar</button>
<input type="text" id="asignadoa"/>
<input type="text" id="Estatus" />
...

A: Tienes que definir una función al hacer click en el botón.
document.getElementById('btnsalirmodalf').onclick = () => {
  // Código a ejecutar al hacer click
}

Dentro de la función del click tienes que definir los elementos a los cuales les vas a cambiar el valor. Para eso te funciona tu document.getElementById. Pero en tu ejemplo estás utilizando == en lugar de =.
document.getElementById('btnsalirmodalf').onclick = () => {
  document.getElementById('asignadoa').value = '';
  document.getElementById('Estatus').value = '';
  document.getElementById('porcentaje').value = '';
  document.getElementById('exampleFormControlTextarea1').value = '';
  document.getElementById('exampleFormControlTextarea2').value = '';
}


text:
Q: EasyPHP Can't link database to PHP file First time posting here as i am clueless on how to fix my problem, I've been searching for the past 2 hours on a fix but haven't been able to find one.
I have my website up and running, mostly html, then I have a login page which is supposed to be connected to a EasyPHP database, but I cannot link the login page to the database, I have a connectivity.php file to initiate the connection and check the username and password but I keep receiving errors.
Login Page Code:

<title>Sign In</title>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="css/style.css"/>

Home

Gallery

Videos

Discography

Register

About

Alex Turner

                Matt Helders

                    Jamie Cook

                        Nick O'Malley

                            Andy Nicholson

<fieldset style="width:30%"><legend>LOG-IN HERE</legend>

<form method="POST" action="connectivity.php">

User
<input type="text" name="user" size="40">

Password
<input type="password" name="pass" size="40">

<input    id="button" type="submit" name="submit" value="Log-In">
</form>

</fieldset>

If you do not have an account please register
HERE
otherwise access is restricted to member pages

Connectivity.php Page
I have Changed the code around on this a lot looking for a solution, any ovbious mistake is more than helpful as my brain is fried at the moment.
I also recieved these errors if they're helpful
Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in G:\EasyPHP-DevServer-14.1VC11\data\localweb\my portable files\Website\connectivity.php on line 9
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''Ryan' AND pass = '1234'' at line 1

Here is the page code
<?php
define('DB_HOST', 'localhost'); /*Database host 127.0.0.1 which is local host*/
define('DB_NAME', 'Users'); /*Database Name*/
define('DB_USER','usename');
define('DB_PASSWORD','');

/*Establishing a connection to the database
*/
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());
/*
$ID = $_POST['user'];
$Password = $_POST['pass'];
*/
function SignIn()
{
session_start();   //starting the session for user profile page
if(!empty($_POST['user']))   //checking the 'user' name which is from Register.html, is it empty or have some text

/*SQL Query to validate the Username and and password combination */
{
$query = mysql_query("SELECT `ID`, `Pass` FROM `username` = '$_POST[user]' AND pass = '$_POST[pass]'") or die(mysql_error());
$row = mysql_fetch_array($query) or die(mysql_error());
if(!empty($row['userName']) AND !empty($row['pass']))
{
$_SESSION['userName'] = $row['pass'];
echo "SUCCESSFULLY LOGIN TO USER PROFILE PAGE...";

}
else
{
    echo "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY...";
}
}
}
if(isset($_POST['submit']))
{
SignIn();
}

?>

ANY help with this at all is greatly appreciated!
Thank's for taking the time to read this and help out if you decide to.
-Ryan

A: $query = mysql_query("SELECT `ID`, `Pass` FROM `username` = '$_POST[user]' AND pass = '$_POST[pass]'") or die(mysql_error());

should be
$query = mysql_query("SELECT `ID`, `Pass` FROM TABLE_NAME WHERE `username` = '$_POST[user]' AND pass = '$_POST[pass]'") or die(mysql_error());

TABLE_NAME is the name of table for which you are doing query

redpajama_set_name: RedPajamaStackExchange


text:
Q: R ggplot2 bar chart change color of specific bars I have this dataframe called earningsCont that I will use to make a stacked bar chart:
                       Total     Ghost
JPYUSD          -39837298.85         0
GBPUSD           -1981571.03 -39837299
EURUSD           -1251394.07 -41818870
MXNUSD            -498204.15 -43070264
NZDUSD            -333466.88 -43568468
PLNUSD            -215056.56 -43901935
CNYUSD            -143457.92 -44116992
AUDUSD            -130047.28 -44260449
CADUSD             -94396.57 -44390497
CHFUSD             -46730.39 -44484893
HKDUSD             -24084.79 -44531624
BRLUSD                  0.00 -44555709
Diversification  -4276539.06 -40279169
Portfolio       -40279169.44         0

I then melt it to look like this:
              Var1  Var2        value
1           JPYUSD Total -39837298.85
2           GBPUSD Total  -1981571.03
3           EURUSD Total  -1251394.07
4           MXNUSD Total   -498204.15
5           NZDUSD Total   -333466.88
6           PLNUSD Total   -215056.56
7           CNYUSD Total   -143457.92
8           AUDUSD Total   -130047.28
9           CADUSD Total    -94396.57
10          CHFUSD Total    -46730.39
11          HKDUSD Total    -24084.79
12          BRLUSD Total         0.00
13 Diversification Total  -4276539.06
14       Portfolio Total -40279169.44
15          JPYUSD Ghost         0.00
16          GBPUSD Ghost -39837298.85
17          EURUSD Ghost -41818869.88
18          MXNUSD Ghost -43070263.95
19          NZDUSD Ghost -43568468.11
20          PLNUSD Ghost -43901934.98
21          CNYUSD Ghost -44116991.55
22          AUDUSD Ghost -44260449.46
23          CADUSD Ghost -44390496.75
24          CHFUSD Ghost -44484893.32
25          HKDUSD Ghost -44531623.72
26          BRLUSD Ghost -44555708.50
27 Diversification Ghost -40279169.44
28       Portfolio Ghost         0.00

I use this code to make the chart:
ggplot(data=earningsCont, aes(x=Var1, y=value, fill=Var2, order=-as.numeric(Var2))) + geom_bar(stat="identity")+
    theme_bw() + theme(panel.border = element_blank(), panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(), axis.line = element_line(colour = "black")) +
    labs(x="", y="") +
    scale_y_continuous(labels = comma) +
    ggtitle("Earnings at Risk:  Unhedged (USD)") +
    scale_fill_manual(values = c(wfGold, wfWhite))+ guides(fill=FALSE)

That makes it look like the attached picture.  As you can see, one of the sets of columns, "Ghost," is white so you can't see it.  The other is all gold.  I just want to change the last two gold columns to colors that I have defined as wfGreen and wfRed.
Also, why do I have to melt it before I turn it into a bar chart?  Is there now way to say series1=earningsCont$Total and series2=earningsCont$Ghost?

A: You're coloring your bars based on the value of Var2, which contains no information about whether the element is one of the last two columns ('Diversification' and 'Portfolio'). You need a grouping column in your dataframe which contains this information. You can add this manually, or using the following (clunky) code:
earningsConst.plot <- within(earningsConst, {
  Var3 <- ifelse(Var2 == "Ghost", "Ghost",
    ifelse(Var1 == "Diversification", "Div",
      ifelse(Var1 == "Portfolio", "Port",
        "Total")))
})

This should create a new dataframe identical to the last, but with a four-level coloring column Var3 to give to the fill aesthetic. You can tweak your original code to plot like this:
ggplot(data=earningsCont.plot, aes(x=Var1, y=value, fill=Var3, order=-as.numeric(Var2))) + geom_bar(stat="identity")+
    theme_bw() + theme(panel.border = element_blank(), panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(), axis.line = element_line(colour = "black")) +
    labs(x="", y="") +
    scale_y_continuous(labels = comma) +
    ggtitle("Earnings at Risk:  Unhedged (USD)") +
    scale_fill_manual(values = c(wfGold, wfRed, wfWhite, wfGreen))+ guides(fill=FALSE)

Note that as you didn't dput your data I was unable to test this code (I opted not to manually type in your whole dataframe). While I'm farily certain that this should work, it's possible I've made a small mistake somewhere. If you find one, let me know- or better yet dput(earningsConst) so as to have an easily-reproducible example.


text:
Q: Scraping data in R Is there any way to scrape data in R for:
General Information/Launch Date
from this Website: https://www.euronext.com/en/products/etfs/LU1437018838-XAMS/market-information
So far, I have used this code, but the generated XML file does not contain Information that I Need:
library(rvest)
library(XML)

url <- paste("https://www.euronext.com/en/products/etfs/LU1437018838-XAMS/market-information",sep="")

download.file(url, destfile = "scrapedpage.html", quiet=TRUE)
content <- read_html("scrapedpage.html")

content1 <- htmlTreeParse(content, error=function(...){}, useInternalNodes = TRUE)

A: What you are trying to scrap is in an AJAX object called factsheet (I dont know javascript so I cant tell you more).
Here is a solution to get what you want :
Get the URL of the data used by javascript using the network analysis from your browser (XHR thing). See here.
library(rvest)
url <- read_html("https://www.euronext.com/en/factsheet-ajax?instrument_id=LU1437018838-XAMS&instrument_type=etfs")
launch_date <- url %>% html_nodes(xpath = "/html/body/div[2]/div[1]/div[3]/div[4]/strong")%>%
  html_text()


text:
Q: How to ceate my own user type using jadira usertype I have my class MyClass that can be seralized/deserialized to/from string.
I looking for a simplest way use it as a hibernate property and serialize using jadira.
class MyClass {
    @ToString
    public String toString() {}

    @fromString
    public static MyClass fromString(String encoded) {}
}

And then, use it in an entity
@Entity
class MyEntity {
    @Type(type="org.jadira.usertype....")
    private MyClass field;
}

My question is what should I write inside @Type?
Thank you.

A: Try something like:
@TypeDef(name="BoundType", typeClass="org.jadira.usertype.bindings.PersistentBoundClass")
....
@Type(type = "BoundType", parameters = { @Parameter(name="javaClass", value="MyClass"), @Parameter(name="hibernateClass", value="java.lang.String.class")})


text:
Q: Left div is static while the right div is scrolling I'm trying to recreate the effect seen in the about and work section on this website: http://www.melaniedaveid.com/
I want to be able to scroll down and once the div on the left is reached, only the right side is scrolling now. I'm assuming both are wrapped in a div and the right div's overflow is scrolled to, but I'm unsure how to lock the div in place until reaching the bottom.
Any help would be appreciated, thanks!

A: When this question was asked, the CSS position: sticky was already a thing, but people probably thought it would be too much of a hassle to try and implement what you're asking using solely CSS.
I, however, have spent the last half and hour-ish building this for you out of sheer boredom. Here we go.
Now, the code itself is a bit long, so I've put it in a collapsed snippet down below. Alternatively, it's also on this JSFiddle, so you can save the link for later usage or something.
The structure I used is as follows:

With section as a parent, each article would behave as you described (fixed on the left until all images have scrolled by on the right).
Inside article, we have an aside tag which contains everything that shows up on the left side (the fixed side).
This aside tag contains position: sticky and top: 0 to specify that until every child of the article is scrolled by, it should remain 0 pixels away from the top of the page.
Each figure tag is one image (or, if you wish, content-filled element) that should be scrolled by before the left side starts moving.
It's easier to understand when you run the snippet:

* {
    margin: 0;
    border: 0;
    padding: 0;
    outline: 0;
    box-sizing: border-box;
}

html, body, section, article, aside {
    min-height: 100%;
}

article > aside {
    position: sticky;
    top: 0;
    width: 50%;
    height: 100vh;
}

figure {
    margin-left: 50%;
    height: 100vh;
}
figure:first-of-type {
    margin-top: -100vh;
}

/* * * * * * * * * * * * * * * * * * * * * * *\
|* Coloring and styling so things look cute  *|
\* * * * * * * * * * * * * * * * * * * * * * */
article > aside {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    color: #fff;
}

article:nth-of-type(1) > aside {  background-color: #3c3;  }
article:nth-of-type(2) > aside {  background-color: #c33;  }

figure {
    background-image: url(http://via.placeholder.com/500x500);
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center;
    border-bottom: 1px solid #444;
}

h1 {
    font-size: 30px;
    font-family: sans-serif;
    font-weight: normal;
    font-style: italic;
}
p {
    font-size: 18px;
}
hr {
    width: 50%;
    background-color: #fff;
    margin: 30px;
    height: 1px;
}

.spacing {
    margin: 30px auto;
    padding: 30px;
    line-height: 1.5;
    max-width: 500px;
}
.spacing:first-letter {
    line-height: 1;
    font-size: 30px;
    font-weight: bold;
}

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
    quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
    consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
    cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
    proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

 Section I

 Your content goes here

 Section II

 Your other content goes here

 Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
    quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
    consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
    cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
    proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Upsides

*

*It does exactly what you're asking;

*It does not use any JavaScript, which should make things a bit faster;

*I think it's great and my mom agrees.

Downsides

*

*It likely only works when section is intended to take up the entire page, i.e. when it occupies 100% of the height of the page. I've relied on the vh unit (honestly because I couldn't figure out a good way to only use percentages) and that will always refer to the full page size, even if the parent element of section is smaller. Refer to Upside #1, though, because that's the main reason I kept it.

*Browser Support™:

*

*The viewport unit vh: Internet Explorer 9+

*The position: sticky: Edge 16+, Chrome 56+ (no support on Internet Explorer)

*Your question has a jquery tag, implying all my effort was meaningless. Maybe some bypasser will find it useful, though.

I'm not really good at conclusions, but it's been fun. I hope this helps you or someone else out. Cheers!

A: the effect you're looking for is called "sticky"
Basically, you listen for the scroll event and set the css property position: fixed to your element A conditionally -> until the bottom position of element A is equal or greater than element B's bottom position


text:
Q: python error codecs.charmap_encode(input,errors,encoding_map) UnicodeEncodeError: 'charmap' codec can't encode characters I am running sparql query to people's name  from dbpedia for a give movie
After getting data I am displaying name as well as putting into Mysql
I am getting normal names but at one pointit threw an error
I got an error:
Traceback (most recent call last):
  File "TestSparql.py", line 172, in <module>
    print person_Name
  File "C:\Python27\Lib\encodings\cp437.py", line 12, in encode
    return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode characters in position 16-21: character maps to <undefined>

could some one explain what this error means and why it might have come?

A: That error means that Python is not able to encode as unicode your strings. Further details at http://wiki.python.org/moin/UnicodeEncodeError
In order to help you, many details are missing:

*

*SPARQL Python implementation you are using to query DBpedia

*The printing code that produces such error

*Some environment details (you charset configuration and so on)


text:
Q: How to check if 6 different numbers are already in my lottery database I want to make one more rule, in which it tells me if the 6 numbers of the lottery already came out winner, this code shows how many times a number has come out, but I want one more rule, that if you choose 6 numbers that are already in the database that Say choose another number. I think I can use Json, what do u think?
<form method="post" action="verificador.php">
      <input style="width:41px;height:33px;border-radius:50%;" type="text" name="chk1">
      <input style="width:41px;height:33px;border-radius:50%;" type="number" name="chk2">
      <input style="width:41px;height:33px;border-radius:50%;" type="number" name="chk3">
      <input style="width:41px;height:33px;border-radius:50%;" type="number" name="chk4">
      <input style="width:41px;height:33px;border-radius:50%;" type="number" name="chk5">
      <input style="width:41px;height:33px;border-radius:50%;" type="number" name="chk6">
      <input style="width:41px;height:33px;border-radius:50%;" type="number" name="chk7">
      <input style="width:20%;height:33px;border-radius:10%" type="submit" name="Chequear" value=Chequear>

$sql = "SELECT COUNT(*) AS Count FROM bolas WHERE bola1='$bola1' or bola2='$bola1'or bola3='$bola1'or bola4='$bola1' or bola5='$bola1'or bola6='$bola1'or bola7='$bola1'";
$sqldos ="SELECT COUNT(*) AS Countdos FROM bolas WHERE bola2='$bola2' or bola1='$bola2' or bola3='$bola2'or bola4='$bola2'or bola5='$bola2' or bola6='$bola2'or bola7='$bola2'";
$sqltres ="SELECT COUNT(*) AS Counttres FROM bolas WHERE bola3='$bola3'or bola1='$bola3' or bola2='$bola3'or bola4='$bola3'or bola5='$bola3' or bola6='$bola3'or bola7='$bola3'";
$sqlcuatro ="SELECT COUNT(*) AS Countcuatro FROM bolas WHERE bola4='$bola4'or bola1='$bola4' or bola2='$bola4'or bola3='$bola4'or bola5='$bola4' or bola6='$bola4'or bola7='$bola4'";
$sqlcinco ="SELECT COUNT(*) AS Countcinco FROM bolas WHERE bola5='$bola5'or bola1='$bola5' or bola2='$bola5'or bola3='$bola5'or bola4='$bola5' or bola6='$bola5'or bola7='$bola5'";
$sqlseis ="SELECT COUNT(*) AS Countseis FROM bolas WHERE bola6='$bola6'or bola1='$bola6' or bola2='$bola6'or bola3='$bola6'or bola4='$bola6' or bola5='$bola6'or bola7='$bola6'";
$sqlsiete ="SELECT COUNT(*) AS Countsiete FROM bolas WHERE bola7='$bola7'or bola1='$bola7' or bola2='$bola7'or bola3='$bola7'or bola4='$bola7' or bola5='$bola7'or bola6='$bola7'";

$result=$conn->query($sql);
$row = $result->fetch_assoc();

$resultdos=$conn->query($sqldos);
$rowdos = $resultdos->fetch_assoc();

$resulttres=$conn->query($sqltres);
$rowtres = $resulttres->fetch_assoc();

$resultcuatro=$conn->query($sqlcuatro);
$rowcuatro = $resultcuatro->fetch_assoc();

$resultcinco=$conn->query($sqlcinco);
$rowcinco = $resultcinco->fetch_assoc();

$resultseis=$conn->query($sqlseis);
$rowseis = $resultseis->fetch_assoc();

I hope to use json or mysql query

A: You can shrink this to one sql:
$values = "$bola1,$bola2,$bola3,$bola4,$bola5,$bola6,$bola7";

select count(*) as total from bolas
where bola1 in ($values) and bola2 in ($values)
and bola3 in ($values) and bola4 in ($values)
and bola5 in ($values) and bola6 in ($values) and bola7 in ($values)


text:
Q: How to make facebook posts public via API call I downloaded the facebook sdk for php.  I created a php script to post a message to my facebook wall.  The problem is that the post is "private" and only seen by me.  How do I make it public for every one to see?  Here's the line of code executing the post:
$facebook->api("/me/feed", "post", array(
    message => $_REQUEST['msg'] ? $_REQUEST['msg'] : 'Forgot to check for msg',
    picture => "http://cdn.papyimg.com/wp-content/uploads/2011/03/Windows-95-500x312.png",
    link => "http://en.wikipedia.org/wiki/Windows_95",
    name => "Go windows 95",
    caption => "Caption - this is the best operating system in the world!",
    privacy => array('value'=>'EVERYONE'),
));

I have an argument for privacy based on my understanding of the documentation in the API.  But it doesn't alter the privacy state of my post.
What am I doing wrong?

A: Go to your facebook profile settings and click apps. Find your app in the list and delete it. Now go to your app again. When you are asked to authorize the app, make sure to choose the public scope for posts made by your app. If you want you can also edit the settings for your app (at developers.facebook.com) and make public the default option, look in the Auth Dialog section.


text:
Q: MinionPro semibold/medium After a day of struggle I managed to install the full family of MinionPro font on LaTeX.
After an hour of googling I cannot figure out how to use the medium (semibold) font. Ideally I would have something like a \sb command, eg., {\sb This is medium bold.}.

A: I assume you have set up the semibold variant like
   \DeclareFontShape{T1}{MinionPro}{sb}{n}{
      <-> T1--Adobe-Minion-Pro-Semibold
   }{}

in an .fd file.
Then you can define a user interface for it like
\newcommand*{\sbdefault}{sb}
\DeclareRobustCommand{\sbshape}{%
  \not@math@alphabet\sbshape\relax
  \fontshape\sbdefault\selectfont}

\DeclareTextFontCommand{\textsb}{\sbshape}

A good description of all that is the Font Installation Guide.

A: I'm a few years late, but your question came up in a search, it was a good one, and nobody really answered it.  You asked, "Ideally I would have something like a \sb command, eg., {\sb This is medium bold.}."
This should work with the OTF version of the fonts from the Minion Pro Complete Family Pack as of 2018, which have names like MinionPro-SemiboldIt.otf, but is untested.  You might need to modify this for the version of the fonts you have.  For example, if they're in a directory rather than installed as system fonts, add the  Path= key.
\documentclass{article}
\usepackage{fontspec}
\setmainfont[
   Scale=1.0,
   Ligatures={Common, Rare, TeX},
   Numbers={OldStyle, Proportional},
   Extension=.otf ,
   UprightFont=*-Regular ,
   BoldFont=*-Bold ,
   ItalicFont=*-It ,
   BoldItalicFont=*-BoldIt ,
   FontFace={sb}{n}{*-SemiBold},
   FontFace={sb}{it}{*-SemiBoldIt}
]{MinionPro}

\DefaultFontFeatures{Scale=MatchLowercase, Ligatures=TeX}

\DeclareRobustCommand\sbseries{\fontseries{sb}\selectfont}
\DeclareTextFontCommand{\textsb}{\sbseries}

\begin{document}
This is a \textsb{sample \textit{text}}
\textbf{and \textit{another}}.
\end{document}

If you have the full family with its optical and condensed variants, setting them all up with fontspec would be very complicated, and you'd probably want to move all that setup into a file named MinionPro.fontspec.  Then, your documents could simply load MinionPro.
It sets up NFSS-style \sbseries and \textsb{} commands.  If you really, truly want a \sb that works like \bf, you can add \DeclareOldFontCommand{\sb}{\fontseries{sb}\selectfont}{\mathbf}, but this is obsolete.
If you optionally want to add commands such as this for the entire family, the official¹ series and shape names for the fonts in the Minion Complete Family Pack are:

*

*Regular: {m}{n}

*Regular Italic: {m}{it}

*Semibold: {sb}{n}

*Semibold Italic: {sb}{it}

*Bold: {b}{n}

*Bold Italic: {b}{it}

*Condensed Regular/Medium Condensed: {mc}{n}

*Condensed Regular/Medium Condensed Italic: {mc}{it}

*Semibold Condensed: {sbc}{n}

*Semibold Condensed Italic: {sbc}{it}
The "LaTeX Font Installation Guide" adds two additional weights, mb for Medium (between Regular and Semibold) and db for Demibold (between Semibold and Bold).  Since there are separate Regular, Medium and Semibold weights, you'd want to use {mb}{n} for Medium and {mb}{it} for Medium Italic.  I'd recommend that, if there's only one weight in between Regular and Bold, you label it {sb}, as for example Computer Modern Demi does.
You would select caption, subhead and display either as separate font families or as size features. Condensed could also be its own set of font families, so that \textbf{} and so on don't uncondense the font.
Finally, be aware that many people recommend against using multiple weights of the same font within the same document, and would suggest that you instead choose either Minion Pro Bold or Minion Pro Semibold as your bold font.
¹ The fontspec manual and "LaTeX2e Font Selection" documentation both recommend using the schema from The Latex Companion, by Frank Mittelbach and Michel Goossens.  It is on page 414 of the second edition.

A: Here's a fontspec solution, which needs XeTeX or LuaTeX:
\documentclass[a6paper]{memoir}
\usepackage{fontspec}
\setmainfont[%
    Numbers=OldStyle,
    Kerning=Uppercase,
    SizeFeatures={%
        {Size={-9},Font=* Caption},
        {Size={9-14},Font=*},
        {Size={14-24},Font=* Subhead},
        {Size={24-},Font=* Display}
    },
]{Minion Pro}
\newfontfamily\semibold[%
    Numbers=OldStyle,
    Kerning=Uppercase,
    SizeFeatures={%
        {Size={-9},Font=* Caption},
        {Size={9-14},Font=*},
        {Size={14-24},Font=* Subhead},
        {Size={24-},Font=* Display}
    },
]{Minion Pro Semibold}
\newcommand{\blah}{Once upon a time,
    \textit{in a distant
    galaxy} called \textbf{Ööç},
    there lived a computer
    named {\bfseries\itshape R.~J. Drofnats.}\par}
\sloppypar
\begin{document}
\blah
\semibold
\blah
\end{document}

Notes:

*

*Text courtesy of Prof. Knuth.

*I've included the SizeFeatures just for illustration

*I should have (perhaps) used Minion Std Black for the bold version of semibold; "this is left as an exercise for the reader".

Here's the result (with XeLaTeX):

A: If you want to use mainly the semibold instead of the bold, use the following fontspec (in XeTeX or LuaTeX):
BoldFont={* Semibold}

A MWE:
\documentclass{article}
\usepackage{fontspec}
\setmainfont[
        BoldFont={* Semibold},
]{Minion Pro}
\begin{document}
This is a \textbf{sample}
\end{document}

However, it looks like fontspec automatically selects the semibold option. You can check the difference with
BoldFont={* Bold}


text:
Q: How can I use asyncio.Condition within a Task in Python < v3.10 Any reason why I can't use a asyncio.Condition within a Task?
c = asyncio.Condition()

async def a():
    print("A ..")
    # await asyncio.sleep(0.2) # This works
    async with c:
        # RuntimeError: Task <Task pending coro=<a() running at ..this file..:13>> got Future <Future pending> attached to a different loop
        await c.wait()   #

async def main():
    asyncio.get_event_loop().create_task(a())
    await asyncio.sleep(2)

Says: "Got Future  attached to a different loop"
I don't think I created a new loop.
Full example here:
import asyncio

c = asyncio.Condition()

async def a():
    print("A ..")
    # await asyncio.sleep(0.2) # This works
    async with c:
        # RuntimeError: Task <Task pending coro=<a() running at ..this file..:13>> got Future <Future pending> attached to a different loop
        await c.wait()   #
    print("A done")

async def b():
    await asyncio.sleep(2)
    print("B ..")
    async with c:
       c.notify_all()
    print("B done")
    await asyncio.sleep(1)

async def main():
    asyncio.get_event_loop().create_task(a())
    await b()

asyncio.run(main())

I see the same error using, Python 3.7. 3.8, 3.9.

A: The docs for asyncio.Condition.notify_all() states:

The lock must be acquired before this method is called and released shortly after. If called with an unlocked lock a RuntimeError error is raised.

The lock gets released in a on calling c.wait(), therefore the Lock inside c is unlocked when you call c.notify_all().
You need to hold the lock before calling notify_all(). Using
 async with c:
     c.notify_all()

makes your example work as expected.
UPDATE
I tested this only on Python 3.10.1 where it worked like this. In fact it fails when I run it on Python 3.8.5. But the problem here stems of the use of the Condition as a global variable. In your example the Condition is created before the event loop is created, so I assume it is not correctly attached to the event loop that is created later.
I updated your example in a way, that the Condition is created with a running loop. This makes the example work again in Python 3.8.5:
import asyncio

async def a(c):
    print("A ..")
    async with c:
        await c.wait()
    print("A done")

async def b(c):
    await asyncio.sleep(2)
    print("B ..")
    async with c:
        c.notify_all()
    print("B done")
    await asyncio.sleep(1)

async def main():
    c = asyncio.Condition() # loop already running
    asyncio.create_task(a(c)) # get_event_loop() also works but the use is discouraged in the docs
    await b(c)

asyncio.run(main())

A: As @JanWilamowski points out, this seems to be a bug with Python < v3.10. Works fine in 3.10.
Booo!
It also seems that you can't work around this bug by switching from Condition to Queue (see below) - I guess Queue uses Condition internally.
Simlarly ... this also failed:
async def main():
    loop.create_task(a())
    ...

loop = asyncio.new_event_loop()
loop.run_until_complete(main())
# asyncio.run(main())

However, for reasons unclear, this does work:
async def main():
    loop.create_task(a())
    ...

loop = asyncio.get_event_loop()   // @@@@
loop.run_until_complete(main())

Full working example below:
import asyncio
import time

USE_QUEUE = False

if not USE_QUEUE:
    c = asyncio.Condition()
else:
    q = asyncio.Queue()

async def a():
    print("A ..")
    # await asyncio.sleep(0.2) # This works
    if not USE_QUEUE:
        async with c:
           await c.wait()
    else:
        result = await q.get()
        q.task_done()
        print("result", result)
    print("A done", time.time())

async def b():
    await asyncio.sleep(1)
    print("B ..", time.time())
    if not USE_QUEUE:
        async with c:
            c.notify_all()
    else:
        result = await q.put(123)
    await asyncio.sleep(1)
    print("B done")

async def main():
    loop.create_task(a())
    # asyncio.get_event_loop().create_task(a())
    await b()

loop = asyncio.get_event_loop()
loop.run_until_complete(main())


text:
Q: Trying to get basic Http URL with querystring parameters processed in WCF service I'm trying to process a post by a third party server (Paypal) processed by my server through a WCF (.Net 3.5 SP1) service. All I need is to get and process the values with the query string. This sounds incredibly easy, but after a weekend, I'm still stumped.  Any help would be greatly appreciated.
Passing the following URL from my browser to the service causes a AddressFilter mismatch fault (below).
http://localhost:9409/PPInfo.svc/ReadResponse?RESULT=0&AUTHCODE=10001&RESPMSG=APROVED&PNREF=12345

produces
<Fault xmlns="http://schemas.microsoft.com/ws/2005/05/envelope/none">
- <Code>
  <Value>Sender</Value>
- <Subcode>
  <Value xmlns:a="http://schemas.microsoft.com/ws/2005/05/addressing/none">a:DestinationUnreachable</Value>
  </Subcode>
  </Code>
- <Reason>
  <Text xml:lang="en-US">The message with To 'http://localhost:9409/PPInfo.svc/ReadResponse?RESULT=0&AUTHCODE=10001&RESPMSG=APROVED&PNREF=12345' cannot be processed at the receiver, due to an AddressFilter mismatch at the EndpointDispatcher. Check that the sender and receiver's EndpointAddresses agree.</Text>
  </Reason>
  </Fault>

// web.config
 <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ASEEESPrivate.PPInfoBehavior">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <services>
      <service behaviorConfiguration="ASEEESPrivate.PPInfoBehavior" name="ASEEESPrivate.PPInfo">
        <endpoint address="" binding="webHttpBinding" contract="ASEEESPrivate.IPPInfo">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
  </system.serviceModel>
</configuration>

================================
[ServiceContract]
public interface IPPInfo
{
    // expecting RESULT = 0 and RESPMSG = APPROVED
    [OperationContract]
    [WebGet(UriTemplate = "Presponse?RESULT={result}&AUTHCODE={authcode}&RESPMSG={respmsg}&AVSDATA={avsdata}&PNREF={pnref}",
        BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Xml)]
    void ReadResponse();
}

=========================================
// write parameters of query string to tlkpOnlineMessage table
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, AddressFilterMode=AddressFilterMode.Any)]
    public class PPInfo : IPPInfo
    {

        public void ReadResponse()
        {
            var qString = HttpContext.Current.Request.QueryString;

            var ctx =
                new MembershipEntities();

            var log = new tlkpOnlineMessage();

            foreach (string s in qString)
            {
                log.LoginPageMsg = s;
                ctx.AddTotlkpOnlineMessages(log);
            }

            ctx.SaveChanges();
        }
    }

A: Besides the typo in your code, I believe you have two problems that are easily correctable:
1) For a RESTful service, you should define an endpoint behavior and enable the webHttp behavior.  You can do this by adding an <endpointBehavior> to your web.config as such:
<behaviors>
  <serviceBehaviors>
    <behavior name="ASEEESPrivate.PPInfoBehavior">
      <serviceMetadata httpGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="true" />
    </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
    <behavior name="ASEEESPrivate.PPInfoEndpointBehavior">
      <webHttp />
    </behavior>
  </endpointBehaviors>
</behaviors>

And then add this endpoint behavior to your service definition:
  <service behaviorConfiguration="ASEEESPrivate.PPInfoBehavior" name="WcfRestService1.PPInfo">
    <endpoint address="" binding="webHttpBinding" contract="WcfRestService1.IPPInfo"
              behaviorConfiguration="ASEEESPrivate.PPInfoEndpointBehavior">
      <identity>
        <dns value="localhost" />
      </identity>
    </endpoint>
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
  </service>

2) Secondly, you define a UriTemplate for your service with placeholders (result, authcode, etc.) but you don't define parameters for them in your interface.  If you're going to define a UriTemplate for your service definition with placeholders, then you need to have your service define those parameters accordingly.  You can do that as such:
[ServiceContract]
public interface IPPInfo
{
    // expecting RESULT = 0 and RESPMSG = APPROVED
    [OperationContract]
    [WebGet(UriTemplate = "ReadResponse?RESULT={result}&AUTHCODE={authcode}&RESPMSG={respmsg}&AVSDATA={avsdata}&PNREF={pnref}",
        BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Xml)]
    void ReadResponse(string result, string authcode, string respmsg, string avsdata, string pnref);
}

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, AddressFilterMode = AddressFilterMode.Any)]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class PPInfo : IPPInfo
{

    public void ReadResponse(string result, string authcode, string respmsg, string avsdata, string pnref)
    {
      ...
    }
}

By using a UriTemplate, you don't need to extract your querystring parameters out; or, if you want to extract parameters from your querystring, don't define a UriTemplate.
Once I made these two changes, I was able to get the service to run locally on my machine.
I hope this helps!


text:
Q: when to pass and return by reference to a function in c++ first I made a complex class in c++ which had two member datas -real and imaginary.(of the form a+ib).
when I tried to overload << operator for complex class object as follows-
friend ostream operator<<(ostream ,complex );  in .h file

ostream operator <<(ostream o,complex c){

    o<<"real part"<<c.real;
    o<<"imaginary part<<c.imaginary;
    return o;

}

in .cpp file,
 it does not work and rather opens an ios_base file and shows an error there.
but the same code overloads << perfectly when i pass by reference and return by reference as follows-
ostream& operator <<(ostream& o,complex& c)
{

      //same as before
};

i dont understand how passing and returning by reference helps?

A: std::ostream is not-copyable type type. You cannot do copy of o, so you must receive it by reference and return it by reference.

A: The rule for using a reference vs. not using a reference is simple: if you want to use the same object as in the caller, pass it by reference; if you want to make a copy of the object being passed, do not use reference.
In some cases you can pass an object only by reference. Specifically, when it is incorrect to copy an object, designers of its class can prohibit copying. Objects that represent input/output and synchronization resources are often non-copyable, meaning that you must pass them by reference or by pointer.


text:
Q: Select mysql com COUNT e GROUP BY MONTH Ola,
Estou tentando unir a informações de duas tabelas para gerar um gráfico, preciso contar o total de registro consultas1 e consultas2 e agrupar por mes:
Atualmente tenho essse retorno:
consultas1:
MariaDB [logview]> SELECT MONTH(data) as MES, COUNT(id_consulta) as TOTAL1 FROM consultas1 group by MONTH(data);
+------+--------+
| MES  | TOTAL1 |
+------+--------+
|    1 |    158 |
|    2 |    125 |
|    3 |     84 |
|    4 |    227 |
|    5 |    117 |
|    6 |    117 |
|    7 |    167 |
|    8 |    170 |
|    9 |     86 |
|   10 |    165 |
|   11 |    164 |
|   12 |    186 |
+------+--------+

consultas2
MariaDB [logview]> SELECT MONTH(data) as MES, COUNT(id_consulta) as TOTAL1 FROM consultas2 group by MONTH(data);
+------+--------+
| MES  | TOTAL1 |
+------+--------+
|    8 |      9 |
+------+--------+

Resultado esperado:
+------+--------+--------+
| MES  | TOTAL1 | TOTAL2 |
+------+--------+--------+
|    1 |    158 |    0   |
|    2 |    125 |    0   |
|    3 |     84 |    0   |
|    4 |    227 |    0   |
|    5 |    117 |    0   |
|    6 |    117 |    0   |
|    7 |    167 |    0   |
|    8 |    170 |    9   |
|    9 |     86 |    0   |
|   10 |    165 |    0   |
|   11 |    164 |    0   |
|   12 |    186 |    0   |
+------+--------+--------+

Alguém poderia me ajudar?

A: Tente com uma junção entre as tabelas:
SELECT  MONTH(COALESCE(consultas1.data, consultas2.data)) as MES,
            COALESCE(COUNT(consultas1.id_consulta), 0) as TOTAL1,
            COALESCE(COUNT(consultas2.id_consulta), 0) as TOTAL2
FROM consultas1 FULL OUTER JOIN consultas2 ON (MONTH(consultas1.data) = MONTH(consultas2.data))
GROUP BY 1;

Dependendo da particularidade de sua tabela consultas1 (se for ela que define quais meses considerar) você pode utilizar LEFT OUTER JOIN.


text:
Q: Is there a list of all tags used on Stack Overflow? I wondered if there is a list of all tags used on stackoverflow.com. I wanted to browse the whole list and had to open the tag search and scroll through every page. Is there a site which lists all the tags or do I have to go through all the search result pages?

A: Data Explorer is the way to go:
https://data.stackexchange.com/stackoverflow/query/1069131/get-all-tags
Note that since SEDE allows maximum of 50000 (50k) results per result set, and Stack Overflow got over 50k tags now, I had to split the query to return two result sets. To switch between the result sets, click the number in the header:

One downside though, the data in there is not live so it means you won't see new tags created since last Monday.


text:
Q: How to determine http 403 error substatus I am using thrid party Java library which communicates with Microsoft Exchange webservices. On executing a function with the library returns http 403 forbidden error when trying to connect to the EWS. So how do I determine the substatus of the http 403 error.I need the substatus to determine the cause of the error.

A: Which operation are you trying to use ?
403 generally isn't an EWS status code this will be more from IIS eg your not accessing the correct EWS endpoint. You might want to test EWS first using the EWSEditor https://ewseditor.codeplex.com/ to test the particular operation.
Cheers
Glen


text:
Q: Relationship between rxJava and promises I'm trying to relate rxJava to what I already know, particularly from JavaScript programming.  Is the core idea of rxJava like promises on observables?

A: As the comment explain, a promise will allow you to chain operation, but in the end, you'll get one result.
With RxJava, you can be notified multiple time and then get multiple result.
Promise can be seen as async operation, and Observable as async* operation.


text:
Q: como actualizar un jtable desde otro jframe ¿como puedo actualizar la tabla cuando modifico de otro jframe. es posible ?
tengo un formulario en java Netbeans en el cual  inserto datos y modifico, la acción de modificar la hago en una ventana emergente al hacer click en una fila de un jtable,hasta aquí todo bien pero cuando modifico en la ventana emergente actualizo con un método que se encuentra en la interfaz donde esta el  jtable pero no funciona. les dejo el codigo abajo

    //este metodo lo llamo del jframe
    public void datos(String opcion){
 DefaultTableModel modelo= new DefaultTableModel();
   modelo.addColumn("rut");
   modelo.addColumn("nombre");
   modelo.addColumn("A.materno");
   modelo.addColumn("A.paterno");
   modelo.addColumn("Fono");
   modelo.addColumn("Nro °casa");
   modelo.addColumn("Calle");
   modelo.addColumn("Sector");
   modelo.addColumn("Comuna");
   modelo.addColumn("T.zapato");
   modelo.addColumn("T.pantalon");
   modelo.addColumn("T.chaqueta");
   modelo.addColumn("Estado");
   modelo.addColumn("Paswword");
   modelo.addColumn("Cargo");
   modelo.addColumn("id_co");
   modelo.addColumn("id_e");
   modelo.addColumn("id_ca");

  ResultSet rs=null;

  try{
    if(opcion=="todo"){
  rs=obj.mostrar();
  }
   else if(opcion=="buscar"){

       obj.setNombre(txtbuscar.getText());
       obj.setRut(txtbuscar.getText());
       obj.setOpcion(buttonGroup1.getSelection().getActionCommand());
   rs=obj.buscar();
  }
    if(rs.next()){
  while(rs.next()){
    Object [] fila= new Object[18];
    fila[0]=rs.getString("RUT_TRABAJADOR");
    fila[1]=rs.getString("NOMBRE");
    fila[2]=rs.getString("APELLIDO_M");
    fila[3]=rs.getString("APELLIDO_P");
    fila[4]=rs.getInt("TELEFONO");
    fila[5]=rs.getInt("NRO_CALLE");
    fila[6]=rs.getString("CALLE");
    fila[7]=rs.getString("VILLA_POBLACION");
    fila[8]=rs.getString(9);
    fila[9]=rs.getInt("TALLA_CALZADO");
    fila[10]=rs.getInt("TALLA_PANTALON");
    fila[11]=rs.getInt("TALLA_CHAQUETA");
    fila[12]=rs.getString("NOMBRE_ESTADO");
    fila[13]=rs.getString("password");
    fila[14]=rs.getString("NOMBRE_CARGO");
    fila[15]=rs.getString("ID_COMUNA");
    fila[16]=rs.getString("ID_ESTADO");
    fila[17]=rs.getString("ID_CARGO");
    modelo.addRow(fila);
   }
  }

  }catch(Exception e){
      System.out.println(e.getMessage());
  }
tabla.setModel(modelo);

}

 //click del boton de la ventana emergente donde modifico y llamo a la funcion datos que esta en el jframe principal

private void btnmodificarMouseClicked(java.awt.event.MouseEvent evt) {
     Mantenedor_insumo m= new Mantenedor_insumo();
     //modificar datos del trabajador

    try{
        obj.setRut(txtrut.getText());
        obj.setNombre(txtnombre.getText());
        obj.setApellido_m(txtapellido_m.getText());
        obj.setApellido_p(txtapellido_p.getText());
        obj.setCalzado(Integer.parseInt(txtzapato.getText()));
        obj.setPantalon(Integer.parseInt(txtpantalon.getText()));
        obj.setChaqueta(Integer.parseInt(txtchaqueta.getText()));
        obj.setFono(Integer.parseInt(txtfono.getText()));
        obj.setNro_calle(Integer.parseInt(txtnro_casa.getText()));
        obj.setCalle(txtcalle.getText());
        obj.setSector(txtsector.getText());
        String  id=combocomuna.getSelectedItem().toString();
        String [] comuna= id.split("-");
        obj.setId_comuna(Integer.parseInt(comuna[0].trim()));
        String id_cargo=lst_cargo.getSelectedItem().toString();
        String [] cargo=id_cargo.split("-");
        obj.setId_cargo(Integer.parseInt(cargo[0].trim()));
        String id_estado=lst_estado.getSelectedItem().toString();
        String [] estado=id_estado.split("-");
        obj.setId_estado(Integer.parseInt(estado[0].trim()));
        obj.setPassword(txtpass.getText());
        obj.modificar();
        JOptionPane.showMessageDialog(null, "Datos del trabajador modificado correctamente","Confirmacion",JOptionPane.INFORMATION_MESSAGE);
        m.datos("todo");
    }catch(Exception e){
        System.out.println("problema en modificar : " + e.getMessage()+ " ");

    }

}

 //metodo modificar en clase trabajador funciona correctamente
 public void modificar () throws SQLException{
 String sql="UPDATE trabajador set        NOMBRE=?,APELLIDO_M=?,APELLIDO_P=?,TELEFONO=?,CALLE=?,NRO_CALLE=?,"
      + "VILLA_POBLACION=?,TALLA_CALZADO=?,TALLA_PANTALON=?,TALLA_CHAQUETA=?,password=?,"
      + "ID_COMUNA=?,ID_ESTADO=?,ID_CARGO=? WHERE RUT_TRABAJADOR=?";
Connection cn=datasource.getConnection();
PreparedStatement sentencia=cn.prepareStatement(sql);
sentencia.setString(1,getNombre());
sentencia.setString(2,getApellido_m());
sentencia.setString(3,getApellido_p());
sentencia.setInt(4,getFono());
sentencia.setString(5,getCalle());
sentencia.setInt(6,getNro_calle());
sentencia.setString(7,getSector());
sentencia.setInt(8,getCalzado());
sentencia.setInt(9,getPantalon());
sentencia.setInt(10,getChaqueta());
sentencia.setString(11,getPassword());
sentencia.setInt(12, getId_comuna());
sentencia.setInt(13, getId_estado());
sentencia.setInt(14, getId_cargo());
sentencia.setString(15, getRut());

sentencia.executeUpdate();

    System.out.println("sql modificar: "+ sentencia);

}

A: para el próximo que le pase contruye un boton actualizar  en el frame que recive la accion y desde el frame que hace la accion lo enlazamos con nombreframe.nombreboton.doClick(); detrno del boton metemos la tabla o l oque se valla a actualizar y ya


text:
Q: OpenCL kernel doesn't seem to get global id "globally" I am trying to convert a program I did to OpenCL, but I am not familiar enough with it yet. Still, I am having trouble with one of my (three) kernels. It is basically a complex matrix vector multiplication, but I am writing it so to fit better with my needs.
The problem is, I can't get the kernel to work on GPU. I have simplified it to the most (2 lines), debugged on CPU, and it works perfectly ok on a CPU. But when it comes to GPU, everything screws up. I'm working on a MacBook Pro, and on a NVIDIA GeForce 650M I get one result, while on the integrated Intel HD 4000, I get another. The kernel is
__kernel void Chmv_(__global float2 *H, const float alpha, __global float2 *vec,
                const int off/*in number of elements*/,
                __local float2 *vw,
                __global float2 *vout)
{
int gidx=get_global_id(0);
int gidy=get_global_id(1);
int gs=get_global_size(0);

    vout[gidx].x += alpha*(H[gidx+gidy*gs].x*vec[gidy].x-H[gidx+gidy*gs].y*vec[gidy].y);
    vout[gidx].y += alpha*(H[gidx+gidy*gs].y*vec[gidy].x+H[gidx+gidy*gs].x*vec[gidy].y);

}

For tests, I let the Matrix H be a 4x4 matrix, filled with (1.0f, 0.0f), while input vector vec is has x components (0.0, 1.0, 2.0, 3.0), and y components 0. alpha is set to 2.0f. So, I should have (12, 12, 12, 12) as x output, and I do, if I use CPU. NVIDIA gives me 6.0, while Intel gives me 4.0.
Now, closer inspection showed me that if the input vector is (0,1,2,0), NVIDIA gives me 0 as answer, and if it is (0,1,0,3), Intel gives 0 as well. By the way, changing vec[gidy] for vec[gidx] gives me just the vector doubled. From these, it seems to me that the kernel is executing well only in one dimension, x, while having only one value for get_global_id(1), which is clearly not ok.
I will add the test function which is calling this kernel inspection. Now, anyone has any idea of what can be going on?
void _test_(){
cl_mem mat,vec, out;
size_t gs[2]={4,4};
size_t ls[2]={1,4};
size_t cpuws[2]={1,1};
cl_float2 *A=(cl_float2*)calloc(gs[0]*gs[0], sizeof(cl_float2));
cl_float2 *v=(cl_float2*)calloc(gs[0], sizeof(cl_float2));
cl_float2 *w=(cl_float2*)calloc(gs[0], sizeof(cl_float2));
int i;

for (i=0; i<gs[0]; i++) {
    A[i*gs[0]].x=1.0;
    A[i*gs[0]+1].x= 1.0;//(i<ls-1)? 1.0f:0.0f;
    A[i*gs[0]+2].x=1.0;
    A[i*gs[0]+3].x=1.0;
    v[i].x=  (float)i;
    printf("%d %f %f %f %f\n%v2f\n",i, A[i*gs[0]].x, A[i*gs[0]+1].x, A[i*gs[0]+2].x, A[i*gs[0]+3].x, v[i]);
}
v[2].x=0.0f; //<--- set individually for debug

mat = clCreateBuffer(context, CL_MEM_READ_WRITE, gs[0]*gs[0]*sizeof(cl_float2), NULL, NULL);
vec = clCreateBuffer(context, CL_MEM_READ_WRITE, gs[0]*sizeof(cl_float2), NULL, NULL);
out = clCreateBuffer(context, CL_MEM_READ_WRITE, gs[0]*sizeof(cl_float2), NULL, NULL);

error = clEnqueueWriteBuffer(queue, mat, CL_TRUE, 0, gs[0]*gs[0]*sizeof(cl_float2), A, 0, NULL, NULL);
error = clEnqueueWriteBuffer(queue, vec, CL_TRUE, 0, gs[0]*sizeof(cl_float2), v, 0, NULL, NULL);
error = clEnqueueWriteBuffer(queue, out, CL_TRUE, 0, gs[0]*sizeof(cl_float2), w, 0, NULL, NULL);

int offset=0;
float alpha=2.0;
error  = clSetKernelArg(Chmv_, 0, sizeof(cl_mem),&mat);
error |= clSetKernelArg(Chmv_, 1, sizeof(float), &alpha);
error |= clSetKernelArg(Chmv_, 2, sizeof(cl_mem),&vec);
error |= clSetKernelArg(Chmv_, 3, sizeof(int), &offset);
error |= clSetKernelArg(Chmv_, 4, gs[0]*sizeof(cl_float2), NULL);
error |= clSetKernelArg(Chmv_, 5, sizeof(cl_mem), &out);
assert(error == CL_SUCCESS);

error = clEnqueueNDRangeKernel(queue, Chmv_, 2, NULL, gs, NULL, 0, NULL, &event);

error = clEnqueueReadBuffer(queue, out, CL_TRUE, 0, gs[0]*sizeof(cl_float2), w, 0, NULL, NULL);
clFinish(queue);

for (i=0; i<gs[0]; i++) {
    printf("%f %f\n", w[i].x, w[i].y);

}

clReleaseMemObject(mat);
clReleaseMemObject(vec);
clReleaseMemObject(out);
}

A: You are experiencing a typical problem of a multithreaded unsafe access to a common memory zone. (vout)
You have to think that all of the work-items will run concurrently. This means, they will read and write memory in any order.
When you execute in CPU, the problem does not show up since the execution is serially done by the HW.
However in the GPU, some work items read the memory of vout, increment it and write it. But others do also read the memory of vout before the new value is written by the previous work items.
Probably all your work items are running in parallel since your kernel size is small, that's why you only see one of them adding to the final result.
This is a typical parallel reduction problem. You can google it for more details. What you need to achieve is sync all the threads when accesing vout, either by an atomic_add() (slow) or by a proper reduction (hard to code). You can check this guide, it is for CUDA but is more or less the same basic idea : Reduction Guide


text:
Q: Is it possible to confuse EOF with a normal byte value when using fgetc? We often use fgetc like this:
int c;
while ((c = fgetc(file)) != EOF)
{
    // do stuff
}

Theoretically, if a byte in the file has the value of EOF, this code is buggy - it will break the loop early and fail to process the whole file. Is this situation possible?
As far as I understand, fgetc internally casts a byte read from the file to unsigned char and then to int, and returns it. This will work if the range of int is greater than that of unsigned char.
What happens if it's not (probably then sizeof(int)=1)?

*

*Will fgetc read a legitimate data equal to EOF from a file sometimes?

*Will it alter the data it read from the file to avoid the single value EOF?

*Will fgetc be an unimplemented function?

*Will EOF be of another type, like long?

I could make my code fool-proof by an extra check:
int c;
for (;;)
{
    c = fgetc(file);
    if (feof(file))
        break;
    // do stuff
}

It is necessary if I want maximum portability?

A: The C specification says that int must be able to hold values from -32767 to 32767 at a minimum. Any platform with a smaller int is nonstandard.
The C specification also says that EOF is a negative int constant and that fgetc returns "an unsigned char converted to an int" in the event of a successful read. Since unsigned char can't have a negative value, the value of EOF can be distinguished from anything read from the stream.*
*See below for a loophole case in which this fails to hold.

Relevant standard text (from C99):

*

*§5.2.4.2.1 Sizes of integer types <limits.h>:

[The] implementation-defined values shall be equal or greater in magnitude (absolute value) to those shown, with the same sign.
[...]

*

*minimum value for an object of type int

INT_MIN -32767

*maximum value for an object of type int

INT_MAX +32767

*§7.19.1 <stdio.h> - Introduction

EOF ... expands to an integer constant expression, with type int and a negative value, that is returned by several functions to indicate end-of-file, that is, no more input from a stream

*§7.19.7.1 The fgets function

If the end-of-file indicator for the input stream pointed to by stream is not set and a next character is present, the fgetc function obtains that character as an unsigned char converted to an int and advances the associated file position indicator for the stream (if defined)

If UCHAR_MAX ≤ INT_MAX, there is no problem: all unsigned char values will be converted to non-negative integers, so they will be distinct from EOF.
Now, there is a funny sort of loophole here: if a system has  UCHAR_MAX > INT_MAX, then a system is legally allowed to convert values greater than INT_MAX to negative integers (per §6.3.1.3, the result of converting a value to a signed type that cannot represent that value is implementation defined), making it possible for a character read from a stream to be converted to EOF.
Systems with CHAR_BIT > 8 do exist (e.g. the TI C4x DSP, which apparently uses 32-bit bytes), although I'm not sure if they are broken with respect to EOF and stream functions.

A: Yes, c = fgetc(file); if (feof(file)) does work for maximum portability.  It works in general and also when the unsigned char and int have the same number of unique values.  This occurs on rare platforms with char, signed char, unsigned char, short, unsigned short, int, unsigned all using the same bit width and width of range.
Note that feof(file)) is insufficient.  Code should also check for ferror(file).
int c;
for (;;)
{
    c = fgetc(file);
    if (c == EOF) {
      if (feof(file)) break;
      if (ferror(file)) break;
    }
    // do stuff
}

A: NOTE: chux's answer is the correct one in the most general case.  I'm leaving this answer up because I believe both the answer and the discussion in the comments are valuable in understanding the (rare) situations in which chux's approach is necessary.
EOF is guaranteed to have a negative value (C99 7.19.1), and as you mentioned, fgetc reads its input as an unsigned char before converting to int.  So those by themselves guarantee that EOF can't be read from a file.
As for your specific questions:

*

*fgetc can't read a legitimate datum equal to EOF.  In the file, there's no such thing as signed or unsigned; it's just bit sequences.  It's C that interprets 1000 1111 differently depending on whether it's being treated as signed or unsigned. fgetc is required to treat it as unsigned, so negative numbers (other than EOF) cannot be returned.
Addendum: It can't read EOF for the unsigned char part, but when it converts the unsigned char to an int, if the int is not capable of representing all values of the unsigned char, then the behavior is implementation-defined (6.3.1.3).

*fgetc is required by the standard for hosted implementations, but freestanding implementations are permitted to omit most of the standard library functions (some are apparently required, but I couldn't find the list.)

*EOF won't require a long, since fgetc needs to be able to return it and fgetc returns an int.

*As far as altering the data goes, it can't change the value exactly, but since fgetc is specified to read "characters" from the file as opposed to chars, it could potentially read in 8-bits at a time even if the system otherwise defines CHAR_BIT to be 16 (which is the minimum value it could have if sizeof(int) == 1, since INT_MIN <= -32767 and INT_MAX >= 32767 are required by 5.2.4.2).  In that case, the input character would be converted to a unsigned char that just always had its high bits 0.  Then it could make the conversion to int without losing precision.  (In practice, this just won't come up, since machines don't generally have 16-bit bytes)


text:
Q: How to change email address with Devise on rails3.1 I'd like to have an "edit profile" page, in which the user can change the email address registered when signing up.
I'd like to have the following process:

*

*the user has to input his password to confirm before he makes changes in the email field.

*after submitting that page, the user should receive a verification mail just like Devise's default sign up.

*the email change is completed as soon as the user clicks the verification token URL on the mail.

How would I do this?

A: I created this same flow for a site of mine.  Here's an example of what you can do:
add to config/routes.rb
(note that the routing could be better, but I did this a while ago)
scope :path => '/users', :controller => 'users' do
  match 'verify_email' => :verify_email, :as => 'verify_email'
  match 'edit_account_email' => :edit_account_email, :as => 'edit_account_email'
  match 'update_account_email' => :update_account_email, :as => 'update_account_email'
end

add to app/controllers/users_controller.rb
def edit_account_email
  @user=current_user
end

def update_account_email

  @user=current_user
  @user.password_not_needed=true
  @user.email=params[:address]

  if @user.save
    flash[:notice]="your login email has been successfully updated."
  else
    flash[:alert]="oops! we were unable to activate your new login email. #{@user.errors}"
  end
  redirect_to edit_user_path

end

def verify_email

  @user=current_user
  @address=params[:address]

  UserMailer.confirm_account_email(@user, @address).deliver

end

app/mailers/user_mailer.rb
class UserMailer < ActionMailer::Base

  def confirm_account_email(user, address)

    @user = user
    @address = address

    mail(
    :to=>"#{user.name} <#{@address}>",
    :from=>"your name <'your_email@domain.com'>",
    :subject=>"account email confirmation for #{user.name}"
    )

  end

end

app/views/user_mailer/confirm_account_email.html.erb

you can confirm that you'd like to use this email address to log in to your account by clicking the link below:

<%= link_to('update your email', update_account_email_url(@user, :address=>@address)) %>

if you choose not to confirm the new address, your current login email will remain active.


text:
Q: String to array after import in AngularJS I have an object with nested arrays which I:

*

*First turn into string using angular.toJSON() as ngCSV doesn't support nested arrays

*Then export as CSV file using ngCSV

*Then import and parse into JSON again using PapaParse.

The initial array looks like this:
filteredRecords [
{
date: '',
time: '',
comments: [
    {message: '',
    commenttime: ''},
    {message: '',
    commenttime: ''},
    {message: '',
    commenttime: ''}
],
arrival: '',
},
{
date: '',
time: '',
comments: [
    {message: '',
    commenttime: ''},
    {message: '',
    commenttime: ''},
    {message: '',
    commenttime: ''}
],
arrival: '',
}
]

After I've used angular.toJson() and done the export/import, the comment property looks like this:
filteredRecords [
{
date: '',
time: '',
comments: "[{"message":"wopwop","commenttime":"10.46"},{"message":"checkingin","commenttime":"10.46"},{"message":"tripletest","commenttime":"10.46"}]",
arrival: '',
}, ...
]

My problem is that I need to reverse the process and turn this string into an array after it's parsed, as my app needs to be able to read comment.message and comment.commenttime.
Any idea on how to proceed?
EDIT
I've managed to manually parse the string back into array using the solution from lex82, but I don't know how I could iterate into the main array and automatically do the same for all comments objects in every object from the array.
Any tips?

A: It looks like you need JSON.parse(). I think this should work:
var yourArray = JSON.parse(yourString);

You find a more elaborate answer here.


text:
Q: Why do MenuItem headers have underscores before them? If you're declaring MenuItems, I've always seen their Header properties declared like this:
<MenuItem Header="_Edit">
    <MenuItem Header="_Undo"/>
    <MenuItem Header="_Redo"/>
</MenuItem>

instead of like this:
<MenuItem Header="Edit">
    <MenuItem Header="Undo"/>
    <MenuItem Header="Redo"/>
</MenuItem>

Is there a reason for this or is it just a convention? In the designer it seems to affect nothing whether I have the underscore behind or not.

A: Its to designate the keyboard shortcut.
"_Edit" means that CTRL + E will activate that menu item, whereas
"E_dit" means that CTRL + D will work.
Also, the underscored letter will have an underline when in focus to clue the user in to the keyboard shortcut.
From MSDN


text:
Q: How to get a document from a collection based on a particular field in that document const docRef = firestore.collection("orders").document("")

I need to get the document "147OiRKFYKA3WAo5d5mk" if the field value is Admno:"11.11.1111"
here is my database

Thankyou for the help.

A: This case is mentioned in the official Firestore documentation:
db.collection("orders").where("Admno", "==", "11.11.1111")
    .get()
    .then(function(querySnapshot) {
        querySnapshot.forEach(function(doc) {
            console.log(doc.id, " => ", doc.data()); //here's your doc
        });
    })
    .catch(function(error) {
        console.log("Error getting documents: ", error);
    });

I strongly recommend reading the documentation if you're getting started with Firestore.


text:
Q: Event.observe() not working; ProtoytypeJS library I have this code.
<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/prototype.js">    </script>
        <script>
            Event.observe('clickme', 'click', function(event) {
                alert('clicked');
            });

            Event.observe('uploadme', 'change', function(event) {
                alert('hola');
            });

        </script>
    </head>
    <body>
        <form enctype="multipart/form-data" action="insertimage.php" method="post" name="changer">
            <input name="MAX_FILE_SIZE" value="10240000" type="hidden">
            <input id="uploadme"  type="file">
            <input type="button"  id="clickme" value="Upload Stuff!" />
            <input id="sub" type="submit" />
        </form>
    </body>
</html>

This is not working. I am unable to get alert for anything. Can anyone please suggest a solution?

A: Try adding the script just above body closing tag, like:
</head>
<body>
<form enctype="multipart/form-data" action="insertimage.php" method="post" name="changer">
<input name="MAX_FILE_SIZE" value="10240000" type="hidden">
<input id="uploadme"  type="file">
<input type="button"  id="clickme" value="Upload Stuff!" />
<input id="sub" type="submit" />
</form>
<script>
Event.observe('clickme', 'click', function(event) {
    alert('clicked');
});
Event.observe('uploadme', 'change', function(event) {
    alert('hola');
});
</script>
</body>

Demo: jsFiddle
Or, if you want to keep the script tag inside head,other option would be:
Event.observe(window, 'load', function() {
    Event.observe('clickme', 'click', function(event) {
        alert('clicked');
    });
    Event.observe('uploadme', 'change', function(event) {
        alert('hola');
    });
});


text:
Q: How to write and call an Oracle function in SQL I have two Oracle tables with a similar structure:

I'd like to write a function in Oracle which sum all values for each ID and returns a pair (ID,Text) where Text='ALERT' if the sum is greater than 100, 'OK' otherwise:

Then, I'd like to execute a query for each table, for example something like that:
SELECT MY_FUN() FROM TABLE_1
SELECT MY_FUN() FROM TABLE_2

Is this a right approach? How could I write this function?
Thanks

A: Generally it is considered bad practice to call a function in SQL which executes SQL. It creates all kinds of problems.
Here is one solution:
create or replace function my_fun
  ( p_sum in number) return varchar2 is
begin
    if p_sum > 100 then return 'ALERT';
    else return 'OK';
    end if;
end;
/

Run it like this:
select id, my_fun(sum(val)) as state
from your_table
group by id;

A: You can do this in sql like the following.  If you want to create a function to to this for different tables, you can wrap this in a function that takes the table name and run the query via dynamic SQL, but you are limited to the same columns.
-- begin test data
with test_data(id, value) as
  (select 1, 100 from dual union all
   select 1, 50 from dual union all
   select 2, 75 from dual union all
   select 3, 50 from dual union all
   select 3, 51 from dual)
-- end test data
select id, sum(value),
       case when sum(value) > 100 then 'ALERT'
       else 'OK' end AS alert
from test_data
group by id;


text:
Q: Declaring a javascript object literal in Script# I am trying to replicate a jquery ajax call in Script# and in the data option I am passing an object literal
{ id: target.data("id"), name: newName}

I am trying to reproduce this in Script#, but I am currently unsuccessful.  The first thing that came to mind was an anonymous object:
new { id = target.GetDataValue("id"), name = newName }

but that didn't seem to work.
Any ideas?

A: Try
new Dictionary("id", target.GetDataValue("id"), "name", newName)
or
Script.Literal("{ id: target.data(\"id\"), name: newName}")
Both should translate to your original code more or less.


text:
Q: Adding raster image to ArcGis Pro? It is said in manual, that

You can add pictures to your layout. The insert picture command can be
  found on the Insert tab in the Graphics group.

Unfortunately, I don't have any Graphics group in insert tab:

How to accomplish?

A: The menus in Pro are context driven, meaning depending what you have active or clicked on will you will see appropriate menus. As stated in the help topic you referenced, you need to have an active layout: You can add pictures to your **layout**. Your screen shot shows you're looking at a Scene.
Insert a new layout from the Insert menu. You'll then have the picture option.

A: You haven't opened a layout, only a scene. Click on New Layout, then under the graphics tab you'll have an option to add a picture.

After you click Picture, you will need to drag out a rectangle that indicates where on the page you want to place it, and then a file browser opens to let you choose your image.


text:
Q: Laravel mail attachment issue I haven't used Laravel's mail class before and i'm having a little trouble attaching files via a contact form. This is what I have:
public function mailer(){

    $fromEmail = Input::get('email');
    $fromName = Input::get('name');
    $phone = Input::get('phone');
    $subject = 'New Enquiry';
    $contactMessage = Input::get('message');
    $path = Input::get('files');

    $data = array('name'=>$fromName, 'email'=>$fromEmail, 'comment'=>$contactMessage, 'phone' => $phone);

    Mail::send('contactemail', $data, function($message) use ($fromEmail, $fromName, $subject, $path)
    {
        $message->to('stack-example@gmail.com', 'Enquiries');

        $message->from($fromEmail, $fromName);

        $message->subject($subject);
        $message->attach($path);
    });
}

It's throwing me the error:

fopen(stack-example-file.jpg): failed to open stream: No such file or directory

Mailer functions as it should without attachment. Any ideas as to where I am going wrong?

A: SOLVED
I had
Input::get('files');

instead of
Input::file('files');

Which resulted in a string rather than a file object. I had also moved from blade templating to vanilla html for the form tag and forgot to add
enctype="multipart/form-data"

to replace
'files' => true

File object was null as a result and therefore not attachable.


text:
Q: Is this WSDL valid? In running a WSDL2Java sample I wanted to inspect the generated WSDL because I was having problems with the client code Netbeans generated from a web service.  Is this WSDL valid or invalid?  If invalid, why is it "advertised", in the URL, as well as in the XML, as WSDL?
Running the WSDL2Java validator from the CLI shows it as invalid:
thufir@doge:~$
thufir@doge:~$ echo $JAVA_HOME
/usr/lib/jvm/java-8-openjdk-amd64/
thufir@doge:~$
thufir@doge:~$ jars/apache-cxf-3.1.11/bin/wsdlvalidator https://www.w3schools.com/xml/tempconvert.asmx?WSDL
WSIBP Validator found <{https://www.w3schools.com/xml/}TempConvertHttpPost> is NOT a SOAP binding
WSDLValidator Error :
line 127 column 66 of https://www.w3schools.com/xml/tempconvert.asmx?WSDL: cvc-complex-type.4: Attribute 'part' must appear on element 'mime:content'.

line 136 column 66 of https://www.w3schools.com/xml/tempconvert.asmx?WSDL: cvc-complex-type.4: Attribute 'part' must appear on element 'mime:content'.

thufir@doge:~$

However, that's, literally, the first time I've used the WSDL2Java API at all.  Perhaps there's an online validator which runs as a web service?
While I wasn't able to save the report, it seems to be valid, after downloading the page and then uploading it:
https://www.wsdl-analyzer.com/service/service/893784871?version=1

A: The aforementioned WSDL contains three different bindings: soap 1.1, soap 1.2 and http, meaning there are three different ways/protocols to call a temperaturte converter webservice as you can see here:
https://www.w3schools.com/xml/tempconvert.asmx?op=CelsiusToFahrenheit
But WSDL tooling and interoperability works best if you stick to just soap 1.1 binding. For learning purposes find a WSDL with just soap 1.1 binding.


text:
Q: Getting count of rows from every month of this year Now my question is simple I have many rows in mysql for instance
name    created_at
A       2017-05-1
B       2017-05-1
C       2017-06-2

Now I have ran this query
SELECT MONTH(created_at) , COUNT(created_at)
FROM invoices
WHERE created_at >= NOW() - INTERVAL 1 YEAR
GROUP BY MONTH(created_at)

This gives me correct result that is
5    2
6    1

But I also want statistics of previous months too like
1    0
2    0
3    0
4    0
5    2
6    1

How can I modify my querY?

A: The easiest way is to create a table of months 1 to 12:
CREATE TABLE months (month INT PRIMARY KEY);
INSERT INTO months (month)
VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9), (10), (11), (12);

Then use OUTER JOIN to join it to your result:
SELECT m.month, COALESCE(i.count, 0) AS count
FROM months AS m
LEFT OUTER JOIN (
    SELECT MONTH(created_at) AS month, COUNT(created_at) AS count
    FROM invoices
    WHERE created_at >= NOW() - INTERVAL 1 YEAR
    GROUP BY MONTH(created_at)
) AS i ON m.month = i.month


text:
Q: If I make holes to a pipe and make water flow through it, will water come out from all holes at the same flow rate once the whole pipe is filled? I am wondering because I want to set this up at a small scale (with a 5 V pump, 0.7 W, 120 L/h or what's the same... 0.33 L each 10 seconds) and an 8 mm diameter 1 m long flexible tube with a closed end.
And before buying things, I want to gain some insight.
My intuition says that once the tube is filled, the pressure that is "generated" by the pump, will make the water push against the pipe "walls" with the same force, everywhere. So... as long as all holes are the same, or very similar, water should flow out at the same rate from all holes.
I lack the deeper understanding of the laws that great people have found out along the recent centuries, that's why I ask here :-)

A: Good first thought, but some things can make a difference. Fluid dynamics can be complicated.
When water is still the situation is simpler. Pressure is higher at the bottom of a container. So if you hang a hose vertically, water will flow out of holes near the bottom faster than the top.
If water is flowing, pressure isn't the same everywhere. Suppose your hose made a sharp turn. Water would have to stop flowing forward and start flowing sideways. It takes a force to make water turn. The pressure would be higher there. The force comes from the walls of the hose pushing on the water. They push as hard as necessary to keep the water inside. You can see the same thing by pushing on a wall of your house. You can push hard or gently. Either way, the wall pushes back just hard enough to keep you from moving forward.
Friction matters. If you have a long hose, water will slow down as it goes. It will flow out the near holes faster than the far holes. The diameter of the pipe matters. In a narrow pipe, all the water is close to the walls so all the water is more affected by friction. Water speed matters too.
The size of the holes matters. More water will flow out of a big hole.
It is very hard to get an intuitive feel for how fluids behave. They often do surprising things.


text:
Q: Why is my neural network validation accuracy higher than my training accuracy and they both become constant? I have built a model and when I train it, my validation loss is smaller than my training one and the validation accuracy is higher than the training one. Is the model being overfitted? Am I doing something wrong? Can someone please look at my model and see if there is anything wrong with it? Thank you.
input_text = Input(shape=(200,), dtype='int32', name='input_text')
meta_input = Input(shape=(2,), name='meta_input')
embedding = Embedding(input_dim=len(tokenizer.word_index) + 1,
                  output_dim=300,
                  input_length=200)(input_text)

lstm = Bidirectional(LSTM(units=128,
                      dropout=0.5,
                      recurrent_dropout=0.5,
                      return_sequences=True),
                 merge_mode='concat')(embedding)
pool = GlobalMaxPooling1D()(lstm)
dropout = Dropout(0.5)(pool)
text_output = Dense(n_codes, activation='sigmoid', name='aux_output')(dropout)

output = concatenate([text_output, meta_input])
output = Dense(n_codes, activation='relu')(output)

main_output = Dense(n_codes, activation='softmax', name='main_output')(output)

model = Model(inputs=[input_text,meta_input], outputs=[output])
optimer = Adam(lr=.001)
model.compile(optimizer='adam',
          loss='binary_crossentropy',
          metrics=['accuracy'])

model.summary()
model.fit([X1_train, X2_train], [y_train],
      validation_data=([X1_valid,X2_valid], [y_valid]),
      batch_size=64, epochs=20, verbose=1)

Here is the output:
__________________________________________________________________________________________________
Layer (type)                    Output Shape         Param #     Connected to
==================================================================================================
input_text (InputLayer)         [(None, 200)]        0
__________________________________________________________________________________________________
embedding (Embedding)           (None, 200, 300)     889500      input_text[0][0]
__________________________________________________________________________________________________
bidirectional (Bidirectional)   (None, 200, 256)     439296      embedding[0][0]
__________________________________________________________________________________________________
global_max_pooling1d (GlobalMax (None, 256)          0           bidirectional[0][0]
__________________________________________________________________________________________________
dropout (Dropout)               (None, 256)          0           global_max_pooling1d[0][0]
__________________________________________________________________________________________________
aux_output (Dense)              (None, 545)          140065      dropout[0][0]
__________________________________________________________________________________________________
meta_input (InputLayer)         [(None, 2)]          0
__________________________________________________________________________________________________
concatenate (Concatenate)       (None, 547)          0           aux_output[0][0]
                                                             meta_input[0][0]
__________________________________________________________________________________________________
dense (Dense)                   (None, 545)          298660      concatenate[0][0]
==================================================================================================
Total params: 1,767,521
Trainable params: 1,767,521
Non-trainable params: 0
__________________________________________________________________________________________________
Train on 11416 samples, validate on 2035 samples
Epoch 1/20
11416/11416 [==============================] - 158s 14ms/sample - loss: 0.0955 - accuracy: 0.9929 -
val_loss: 0.0559 - val_accuracy: 0.9964
Epoch 2/20
11416/11416 [==============================] - 152s 13ms/sample - loss: 0.0562 - accuracy: 0.9963 -
val_loss: 0.0559 - val_accuracy: 0.9964
Epoch 3/20
11416/11416 [==============================] - 209s 18ms/sample - loss: 0.0562 - accuracy: 0.9963 -
val_loss: 0.0559 - val_accuracy: 0.9964
Epoch 4/20
11416/11416 [==============================] - 178s 16ms/sample - loss: 0.0562 - accuracy: 0.9963 -
val_loss: 0.0559 - val_accuracy: 0.9964
Epoch 5/20
11416/11416 [==============================] - 211s 18ms/sample - loss: 0.0562 - accuracy: 0.9963 -
val_loss: 0.0559 - val_accuracy: 0.9964
Epoch 6/20

A: The difference is marginal so I would not worry.
In general what might be happening is that by incident during the random splitting between train and validation sets the examples selected in the validation set are "easier" to guess than the ones in the training set.
You could overcome this by developing a cross validation strategy as following:

*

*Take 10% of the dataset out (holdout) and consider it you test set.

*With the remaining dataset make a 80%-20% split for training and validation sets.

*Repeat the 80-20 tranining validation split 5 times.

*Train 5 models on your 5 different train-valid datasets and see what the results are.

*You can even compare all 5 models on the test sets just to see what would be the "real" or "closer to reality" accuracy. That might help to see which model generalizes better.

In the end you might even consider to stack them together:
https://machinelearningmastery.com/stacking-ensemble-for-deep-learning-neural-networks/
The fact that both training and validation accuracy looks similar and do not change during the training indicates that the model might be stuck in a local minima.
It is worth to train for more epochs (at least 20) to see if the model can "jump" out of the local minimal with the current learning rate.
If this not solve the problem I would change the learning rate from .001 to .0001 or .00001. This should help the model to converge hopefully to a global minimal.
If this does not solve the problem, there many other parameters/hyperparameters in general which might be useful to check further: number of nodes in the layers, number of layers, optimizer strategy, size and distribution (generality and variance) of the training set...

A: Overfitting would be when acc is higher than val_acc and loss lower than val_loss.
However, it looks for me that your validation dataset is not representative for the overall distribution in the dataset. For whatever reason the results of your validation dataset is constant and even constantly higher.
You are doing a binary classification. Be aware of class imbalance!
E.g. if 99% of your sample is class 0 and 1% is class 1,
then, even if your model doesn't learn anything, it will have 99% accuracy if it always predicts 0 without ever once predicting a 1.
Imagine your (mostly random) split of data created a datset with 99.5% of the validation data will be class 0 and 0.5% class 1.
Imagine in worst case your model doesn't learn anything. And spits out ("predicts") always a 0. Then train acc will be constantly 0.99 and a certain loss. And val_acc will be constantly 0.995.
For me puzzling is that your performance measures are constant. That is ALWAYS bad. Because usually if the model learns sth and even if it overfits there will be stochastic noise always.
No book tells you the following - no beginner book. And I learned this by experience: You have to put shuffle=True in your model.fit().
Because for me it seems you are training in a way that you present the model first only samples of the one class and then the samples of another class. Mixing up samples of the one and the other class perturbs the model well enough and avoids it to get stuck in some local minima.
Or sometimes I got such constant results even when shuffling.
In that case, I just try to choose another random split which then works better. (So: try other splits!)

A: No, there is nothing wrong, this effect (validation metrics being better than training ones) is common with the use of Dropout, as your network uses.
Dropout adds noise during training, and this noise is not present during validation/testing, so it's natural that training metrics get a bit worse, but validation metrics do not have this noise, and are a bit better due to the improved generalization produced by Dropout.


text:
Q: How to solve this git merge issue with deleted files? This is what I want to do:
I have 2 branches: dev and prod
in dev I have a folder with .less files:
styles/less/myfile.less
So in dev I edit my styles by editing myfile.less, the .css file is automatically updated in styles/css/myfile.css
In prod branch I don't need to keep the /less/myfile.less or even the /less/ folder
So in prod branch I deleted it using
git rm styles/css/myfile.less
git commit -m "Deleted .less file"
Then:
git checkout dev
Done some more work in myfile.less
added and committed it to dev
Them:
git checkout prod
git merge dev
Now I see CONFLICT message, something like CONFLICT (modify/delete): styles/less/myfile.less deleted in HEAD and modified in dev. Version dev of styles/less/myfile.less left in tree.
This is not unexpected but what I really want to do is to NOT have myfile.less in prod and have myfile.less in dev and when I merge dev into prod I want git to automatically use "ours" merge strategy to accept that file is deleted so I don't have to resolve this conflict every time I merge dev into prod
Is this possible at all? Can this be done with some entry in .gitattributes file?


text:
Q: Send xml as part of URL request in Java This might be a trivial question but I'm trying to send web request to USPS to get a http post response (or email response depending on my request) containing the tracking information based on the tracking number that I send in. The documentation says the xml needs to appended as part of the url like below
http://secure.shippingapis.com/ShippingAPITest.dll?API=TrackV2&XML=<PTSEmailRequest USERID="xxxxx"><TrackId>xxxxx</TrackId><RequestType>EN</RequestType></PTSEmailRequest>

I saw there were 2 ways to make an xml request, one using HttpPost and the other URLConnection. I'm a bit thrown by how I go about this and I'm failing to appreciate what's the difference between appending xml in the url and a normal http request. Can someone please clear things up for me?
USPS documentation for tracking =>
https://www.usps.com/business/web-tools-apis/track-and-confirm.pdf
I read these related Stackoverflow posts
Java: How to send a XML request?
posting XML request in java
HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("http://secure.shippingapis.com/ShippingAPITest.dll");

List<String> params = new ArrayList<String>(2);
params.add(new BasicNameValuePair("API", "TrackV2"));
params.add(new BasicNameValuePair("XML", FuncTOGenerateXML()));
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();

if (entity != null) {
    InputStream instream = entity.getContent();
    //.....
    // .....
    instream.close();
}

A: An HTTP request can use one of several methods, like POST, GET, DELETE, PUT... Here we talk about POST and GET
Technical differences

*

*With GET, the data is retrieved from the parameters in the URL.

*With POST, the data is retrieved from the data transmitted inside the HTTP message.
Intended use differences

*

*GET is intended to be used when the request does not cause a change (v.g., searching in Google). Since you can repeat the request without side effects, the data is in the URL and can be stored in the browser history, favorites, etc.

*POST is intended to use when you are performing a change (v.g. sending an e-mail, doing a on-line purchase). The data related is not stored with the URL (it is then that, if you go back to a page that was obtained using POST, the browser many times will show you a pop-up asking for permission to send the data again.
In real usage, the distinction is not so clear cut, in particular POST is sometimes used when the data is too large (URLs have limited length). Also, sometimes GET is used with the meaning of POST so the data can be presented as an HTML link.
Finally, URLConnection is the basic API for opening a connection (which you can use as a POST or GET request, based in how you pass the data, or something else) and HttpPost is just a higher level API for creating a POST request. If you go the basic way, use HttpURLConnection better.


text:
Q: View pager Recycler view Fragment transition with shared element I am new to fragment transitions and i am trying to add an animation along with a shared element to an image item from a recyclerview from a fragment contained in a viewpager and i don't know what i'm missing.
The transition works, the next fragment opens, but the element that i want to share does not change. In fact it is invisible on the next fragment.
I have the next structure:

*

*a main activity that contains the tablayout and the viewpager

*pagercontroller

*recyclerview adapter.

*2 main fragments + another one that i want to open when i click an
image item from the recyclerview
This is the onclick code in the recyclerview adapter's OnBindViewHolder :
holder.postimage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Activity_Feed fragment1 = new Activity_Feed();
                Post fragment2 = new Post();

                Transition changeTransform = TransitionInflater.from((Activity)context).
                        inflateTransition(R.transition.change_image_transform);
                Transition explodeTransform = TransitionInflater.from((Activity)context).
                        inflateTransition(android.R.transition.explode);

                fragment1.setSharedElementReturnTransition(changeTransform);
                fragment1.setExitTransition(explodeTransform);

                fragment2.setSharedElementEnterTransition(changeTransform);
                fragment2.setEnterTransition(explodeTransform);

                FragmentManager manager = ((AppCompatActivity)context).getSupportFragmentManager();

                FragmentTransaction transaction = manager.beginTransaction();

                transaction.addSharedElement(holder.postimage, "imagetransition");
                transaction.setReorderingAllowed(true);

                transaction.replace(R.id.container, fragment2).addToBackStack(null);

                transaction.commit();
            }

        });

And the transition resource change_image_transform :
<?xml version="1.0" encoding="utf-8"?>
<transitionSet xmlns:android="http://schemas.android.com/apk/res/android">
    <changeImageTransform />
</transitionSet>

I also set the transitionName on both fragments' images to "imagetransition".
I'm sure i'm missing something but i really don't know what.
Thank you for your help!


text:
Q: C++/CLI windows label form I need help getting label1 to display the string that the user inputs.
I know that std::string and System::string are two different types, so I casted the inputted string to String^.
The textbox:
private: System::Void text_box_1(System::Object^  sender, System::EventArgs^  e) {
                 cin >> name;
                 String^ something = gcnew String(name.c_str());
                 label1->Text = "Name->" + something;

Function that returns string:
string getName()
    {
        return name;
    }

The problem is, label1 always outputs "Name-> blank".
What am I doing wrong?


text:
Q: Apache Solr Boolean Search 100% Match I have 2 docs in my apache solr with following values of field
custom_value: haris mehmood

custom_value: hari mehmood

I am trying to do a boolean search and using dismax and my query is +haris, I do the following:
defType=dismax & mm=100% & ps=0 & q=+haris & wt=json

P.S: I added spaces myself in query string for better understanding
I just want 1 result in response that should be the first one i.e. haris mehmood and not the one with hari mehmood
I want to know what is it that I am doing wrong and if not, is there a way to achieve what I want.

A: if you want to handle non English text in that query/field, then use a different analysis, not doing any English language stuff.
text_en does probably some stemming and the s in 'haris' is being removed, so it matches your query.

A: You are using fieldType text_en. It has a filter Porter Stem Filter which stemming your word and remove the trailing s.
Create a new fieldType without the Porter Stem Filter
<fieldType name="text_simple" class="solr.TextField" positionIncrementGap="100">
  <analyzer type="index">
    <tokenizer class="solr.StandardTokenizerFactory"/>
    <!-- in this example, we will only use synonyms at query time
    <filter class="solr.SynonymFilterFactory" synonyms="index_synonyms.txt" ignoreCase="true" expand="false"/>
    -->
    <!-- Case insensitive stop word removal.
    -->
    <filter class="solr.StopFilterFactory"
            ignoreCase="true"
            words="lang/stopwords_en.txt"
        />
    <filter class="solr.LowerCaseFilterFactory"/>
    <filter class="solr.EnglishPossessiveFilterFactory"/>
    <filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>
  </analyzer>
  <analyzer type="query">
    <tokenizer class="solr.StandardTokenizerFactory"/>
    <filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true"/>
    <filter class="solr.StopFilterFactory"
            ignoreCase="true"
            words="lang/stopwords_en.txt"
    />
    <filter class="solr.LowerCaseFilterFactory"/>
    <filter class="solr.EnglishPossessiveFilterFactory"/>
    <filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>
  </analyzer>
</fieldType>

And change your fieldType to text_simple and reload the core and reindex data


text:
Q: getaddrinfo unable to resolve host I'm having a weird problem. I have this Python application and when I try to open a url in the application, for instance urllib2.urlopen("http://google.com", None) I get the following error:
IOError: [Errno socket error] [Errno 8] nodename nor servname provided, or not known

However when I do the same thing on the python command line interpreter it works fine. The same python executable is being used for both the application and the command line.
nslookup google.com seems to work fine. I opened up wireshark and it looks like when the application tries to open google.com only a mDNS query goes out for "My-Name-MacBook-Pro.local". However, when the command line tries to open google.com a regular DNS query goes out for "google.com" I found if I hardcoded Google's IP in /etc/hosts then the request from the application finally started working.
It seems something weird must be altering how the application resolves domain names, but I have no idea what could be doing this.
I'm running Mac OSX 10.6.7 and Python 2.6.
Edit: I am not using a proxy to access the internet

A: Just see that you don't have HTTP_PROXY environment variable set which is preventing this. (In which case, that would be a bad error message. Given the proper directory and try again, like
import urllib
r = urlib.urlopen('http://www.google.com')
print r.read()


text:
Q: how we can use split function with multiple _ data = ['test_function']

If we want to split 'test_function' we use following command (what is learn)
test = data['test_function'].str.split('_', expand = True)

then it will create two row 'test' and 'function'
what if
data = ['test_function_practice']

and we only want to separate only 'test' and 'function' how we can do this

A: You can pass n to change the limit for the number of splits.
try:
test = data['test_function'].str.split('_', n = 1, expand = True)

output:
      0                  1
0  test  function_practice


text:
Q: Change UITableViewController's style How can I subsequently change the style of a UITableView?
Edit: Hi, i know how i set the style with the init-method, but can is change the style after initialization?
Like:
[Self.Style = "Grouped"];

I guess there is no way to do this, isnt it?

A: Okay nobody seems to really read the question :D
But to answer it:
No, it can't be done, you have to re-create it

A: myTVContoller = [[UITableViewController alloc] initWithStyle:UITableViewStyleGrouped];

or
UITableView *myTable = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];

A: I suppose you want to change the style of the whole tableview. YOu can do this by following line.
    UITableView *yourTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];

A: To change a table view style, there are two possibilities: plain or grouped.
You can set these style when you initialize the table view or when you create it on Interface Builder.
You can use something like this:
// Plain Style
MyTableController *controller = [[MyTableController alloc] initWithStyle:UITableViewStylePlain];
// Grouped Style
MyTableController *controller = [[MyTableController alloc] initWithStyle:UITableViewStyleGrouped];

Or in IB, you can select your table view and set its style from Attribute Inspector.


text:
Q: После клонировании: cannot load module file После клонирования проекта с github получил эту ошибку:

2 modules cannot be loaded. You can remove them from the project (no files will be deleted).
Xolostyak20. Cannot load module 'file .../Xolostyak20.iml':
  File .../Xolostyak20.iml does not exist
app. Cannot load module 'file .../app.iml':
  File .../app.iml does not exist

как исправить?

A: Нажмите Remove Selected и Сделайте Re-build - (Build > Rebuild) проекта.
У человека которого вы скачали этот репозиторий проект находился в другом месте. И Android Studio говорит -  я не могу найти эти файлы.
Доп. ком. от  A. Shakhov: добавить настройки среды .idea и личные файлы в .gitignore (по умолчанию он скрыт)


text:
Q: Помогите с sql запросом в ActiveDataProvider и временной таблицей Мне нужно такой Sql запрос вставить в ActiveDataProvider, подскажите как?
SELECT * FROM (
  SELECT id, username, text, sender_id
  FROM pm
  WHERE user_id =2
  ORDER BY created_at DESC
) AS tmp_table GROUP BY sender_id

Дошел до этого
$subQuery = (new \yii\db\Query())->select('id, username, text, sender_id')->from('pm')->where('user_id =2 ORDER BY created_at DESC');
    $query = self::find();
    $query->from(['AS tmp_table GROUP BY sender_id' => $subQuery]);
    $query->with(['profile']);

Но этот код генерит такой запрос
SELECT *
FROM (
      SELECT `id`
             ,`username`
             ,`text`
             ,`sender_id`
      FROM `pm`
      WHERE user_id =2
      ORDER BY created_at DESC
     ) `AS tmp_table
GROUP BY sender_id`
LIMIT 10

Не работает из-за того что он ставит апотоф перед AS AS tmp_table GROUP.

вот весь код, тут где-то есть ошибка, может кто увидит
$subQuery = (new \yii\db\Query())
->from('pm')
->where('user_id = :user_id AND sender_id != :user_id AND status != :status ORDER BY created_at DESC', [
    'user_id' => Yii::$app->user->id, 'status' => Pm::STATUS_DELETE]);
$query = self::find()->select('id, text, created_at, username, sender_id');
$query->from(['AS `tmp_table` GROUP BY `sender_id` ORDER BY `created_at` DESC' => $subQuery]);
$query->with(['profile']);

$dataProvider = new ActiveDataProvider([
    'query' => $query,
    'pagination' => [
        'pageSize' => 10,
    ],
]);

$this->load($params);
// grid filtering conditions
$query->andFilterWhere([
    'FROM_UNIXTIME(created_at, "%d.%m.%Y")' => $this->created_at,
]);

// $query->andFilterWhere(['like', 'text', $this->text])
//     ->andFilterWhere(['like', 'username', $this->username]);

return $dataProvider;