text:
Q: Union/intersection of two Jordan measurable sets is Jordan measurable.
Problem: Let $A,B\subset \mathbb{R}^{n}$ be bounded and Jordan measurable, and let $R\supset A,B$ be a rectangle. Then $A\cup B$ and $A\cap B$ are Jordan measurable and $$c(A\cup B)+c(A\cap B)=c(A)+c(B).$$

Our definition is that a set $A$ is Jordan measurable if the numbers
$$\underline{c}(A)=\sup_{P\in\mathcal{P}}\left\{\underline{J}(P,A)\right\}$$
$$\overline{c}(A)=\inf_{P\in\mathcal{P}}\left\{\overline{J}(P,A)\right\}$$
coincide, where
$$\underline{J}(P,A)=\sum\left\{m(I_{k})\ \vert\ I_{k} \mathrm{\ interval\ of\ }P\mathrm{\ contained\ in \ int}(A)\right\}$$
$$\overline{J}(P,A)=\sum\left\{m(I_{k})\ \vert\ I_{k} \mathrm{\ interval\ of\ }P\mathrm{\ intersecting\ } \overline{A}=A\cup \partial A\right\}$$
and $\mathcal{P}$ is the set of finite partitions of $R$.
I am not sure if I am approaching this the correct way. I wanted to use the fact that if $C, D$ are Jordan measurable with $D\subset C$, then $C\setminus D$ is Jordan measurable with $c(C\setminus D)=c(C)-c(D)$ and apply this to $\partial (A\cup B)\subset \partial A\cup \partial B$ since $\partial A=\partial B=0$, but I realized that I cannot assume that $\partial A\cup \partial B$ is Jordan measurable with $c(\partial A\cup \partial B)=0$.
The only other thing I considered is to take four different collections of intervals in $P$ intersecting $\mathrm{int}(A)$, $A\cup\partial A$, $\mathrm{int}(B)$, and $B\cup \partial B$ respectively, and try to come up with an equality to show $\underline{J}(P,A\cup B)=\overline{J}(P,A\cup B)$ and $\underline{J}(P,A\cap B)=\overline{J}(P,A\cap B)$, but I thought that this may be an overly complicated approach.
I appreciate any suggestions!

A: I think your idea using $\partial(A \cup B) \subseteq \partial(A) \cup \partial(B)$ is a good one. It will be easier to show that a union of two sets with content zero has content zero than showing the general proposition. Once you know that a union of two measurable sets or a difference of two comparable measurable sets is measurable, and that areas are additive in the case of a disjoint union, the rest of the problem can be done with formal manipulations only.


text:
Q: Why shouldn't "responsive" web design be a consideration? This might seem like more of a graphic design question than a programming question, but I think it has much more technical/programming merit than actual graphic design.
The concept of "responsive" web design revolves around using media queries in CSS3 to detect the size of the viewing device and adjust the CSS rules accordingly - essentially, dynamic CSS. This fills the void on a lot of deployment cases - mobile, in particular.
I think use of media queries is surfacing slowly (I've found that many people don't really know about it), but I'm wondering if there is a reason for slow adoption. Is it impractical for web applications? Is there something I'm missing that might be a fundamental pitfall?

A: You have to jump through hoops to get it to actually work. For a site I'm developing I used @media (max-width:800px) to define a stylesheet for phones and other smaller screens. But it wasn't being used by e.g. iPhone.
Turns out that phone browser developers assume that people won't take small screens into account so they lie to the rendering engine (iPhone claims to be more than 900px wide, for example) unless you put in an extra meta-tag to tell it not to lie. When it gets to the point that you're fighting the browser implementers you start to wonder whether it's worth the effort.

A: I can't speak for everyone, but from my own experience time and money has been the deciding factor. My colleagues and I are always looking at the latest stuff, but designing and implementing different layouts for differently sized devices is a big deal. Especially considering that on my 3 year old nokia 5800 all our websites look fine - bar that I have to scroll to get the sidebar content. We design and implement websites for small companies and self-employed folk.
Another reason that may be valid is that serving a completely separate website for mobile versions, with its own separate sitemap ( http://www.google.com/support/webmasters/bin/answer.py?hl=en&answer=34648 ), is an easy and entry-level way to maintain the site.

A: If you can guarantee to reliably recover the data, it's all fine.
But imagine, someone loads a webpage in a windowed browser of a desktop computer. Do you force them to open fullscreen to read everything, or do you accomodate the size to the reduced window and present lots of blank space as they maximize it? You serve the CSS once, at page load!
What about a phone browser that switches landscape/portrait modes as you rotate the phone?
What about a browser that simply has too small resolution and people normally use zoom-in, but you have already adapted to the reported, way too small resolution and the page becomes unreadable?
Just follow the standard guidelines of making a decent universal, scalable CSS and let the browser handle scaling the page to the right resolution.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Segmentation fault while executing with  I'm trying to execute a program that establishes a SFTP connection, a really simple one, based on the documentation presented in https://api.libssh.org/master/libssh_tutor_sftp.html#sftp_subsystem. The .c file is next:
#define LIBSSH_STATIC 1

#include <stdio.h>
#include <libssh/sftp.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/stat.h>

//int sftp_session(ssh_session session);
//int sftp_directory(ssh_session session, sftp_session sftp_conn);

ssh_session session_1;

int sftp_connection(ssh_session session)
{
    sftp_session sftp_conn;
    int conn_check;

    sftp_conn = sftp_new(session);
    if(sftp_conn == NULL)//If there is not a SFTP connection
    {
        fprintf(stderr, "Error opening SFTP session: %s\n", ssh_get_error(session));
        return SSH_ERROR;
    }

    conn_check = sftp_init(sftp_conn);//Initializes a SFTP connection
    if(conn_check != SSH_OK)
    {
        //fprintf(stderr, "Error establishing connection: %s\n", sftp_get_error(sftp_conn));
        sftp_free(sftp_conn);//Frees the connection
        return conn_check;
    }

    sftp_free(sftp_conn);
    return SSH_OK;
}

int main()
{
    sftp_connection(session_1);

    return 0;
}

When I compile it, I do the following, in order to statically link the libssh library:
gcc -Wall sftp.c -o sftp -lssh -DLIB_STATIC
The sftp executable is generated, but I get a Segmentation fault error. How could I solve it?


text:
Q: Selenium: find part of identifier The next command does not work
wd.findElement(By.id("post_message_*"));

The goal is to find id's with post_message_3456346, post_message_01548 and so on. How to fix it?
Actulay there is only one id on page which starts with "post_message_".

A: Try to locate required element by XPath as below:
wd.findElement(By.xpath("//*[starts-with(@id, 'post_message_')]"));

or by CSS selector
wd.findElement(By.cssSelector("*[id^='post_message_']"));

A: Try using a css Selector
wd.findElement(By.cssSelector("[id^='post_message_']"));


text:
Q: How to use PDF.JS with React? I would like to parse a pdf file in a React app. The pdf will be provided through a html input.
I used pdf-parse - a wrapper around pdf.js in node - without any problem. But when it comes to React, I only receive this error:

MissingPDFException {message: 'Missing PDF "http://localhost:3000/myfile.pdf".', name: 'MissingPDFException'}

I upload the file like this:

export default function Home() {
  const [data, setData] = useState();

  const handleFile = (e) => {
    const file = e.target.files[0];
    const fileReader = new FileReader();
    fileReader.onload = (d) => {
      setData(new Uint32Array(d.target.result));
    };
  };
  return (
    <>

hello!

      <input
        type="file"
        accept="application/pdf"
        placeholder="insert PDF here"
        onChange={(e) => handleFile(e)}
      />
      <PDFViewer pdfFile={data} />
    </>
  );
}

And The file is supposed to be read here:

import * as PDFJS from "pdfjs-dist/build/pdf";
import * as pdfjsWorker from "pdfjs-dist/build/pdf.worker.entry";

window.PDFJS = PDFJS;

export default function PDFViewer({ pdfFile }) {
  PDFJS.GlobalWorkerOptions.workerSrc = pdfjsWorker;

  const getPDFDoc = useCallback(async () => {
    const doc = await PDFJS.getDocument(pdfFile);
    doc.promise.then(
      (loadedPdf) => {
        setPdfRef(loadedPdf);
      },
      function (reason) {
        console.error(reason);
      }
    );
  }, []);

  useEffect(() => {
    getPDFDoc();
  }, [getPDFDoc]);

I doesn't seem to work at all. I have a custom config with webpack, typescript and SWC-loader. I have read all the related stackoverflow threads.
How to properly parse a PDF with PDF.js in React? If there is a better library, I'm open to any suggestions. My goal is not to display the pdf, but to get its content.

A: Your component only runs getPDFDoc on mount since pdfFile is missing in the usecallback deps, so when the file changes, it probably doesn't even notice as your effect won't re-run since getPDFDoc is referentially stable when it shouldn't be.
Try
import * as PDFJS from "pdfjs-dist/build/pdf";
import * as pdfjsWorker from "pdfjs-dist/build/pdf.worker.entry";

window.PDFJS = PDFJS;

export default function PDFViewer({ pdfFile }) {
  PDFJS.GlobalWorkerOptions.workerSrc = pdfjsWorker;

  const getPDFDoc = useCallback(async () => {
    if (!pdfFile) return
    const doc = await PDFJS.getDocument(pdfFile);
    doc.promise.then(
      (loadedPdf) => {
        setPdfRef(loadedPdf);
      },
      function (reason) {
        console.error(reason);
      }
    );
  }, [pdfFile]);

  useEffect(() => {
    getPDFDoc();
  }, [getPDFDoc]);

I think the reason for the weird "myfile.pdf" thing is probably because when it first runs pdfFile is not defined and this might be some internal library default. So I also added a guard to not do anything when it's not set.


text:
Q: How to merge predicted values back to original DataFrame in Pandas and sklearn first tip toe into using sklearn with pandas so apologies if this may be a basic question. This is my code:
import pandas as pd
from sklearn.linear_model import LogisticRegression

X = df[predictors]
y = df['Plc']

X_train = X[:int(X.shape[0]*0.7)]
X_test = X[int(X.shape[0]*0.7):]
y_train = y[:int(X.shape[0]*0.7)]
y_test = y[int(X.shape[0]*0.7):]

model = LogisticRegression(max_iter=1000)
model.fit(X_train, y_train)
result = model.score(X_test, y_test)
print("Accuracy: %.3f%%" % (result*100.0))

Now what I am hoping to do is get the predicted values back into the original df so i can have a look at the difference between the actual df['Plc'] column and the predicted values for the y_test.
I have tried this but feel its a) probably not the best way and b) the index numbers aren't lining up as expected.
y_pred = pd.DataFrame()
y_pred['preds'] = model.predict(X_test)
y_test = pd.DataFrame(y_test)
y_test['index1'] = y_test.index
y_test = y_test.reset_index()
y_test = pd.concat([y_test,y_pred],axis=1)
y_test.set_index('index1')
df = df.reset_index()
df_out = pd.merge(df,y_test,how = 'inner',left_index = True, right_index = True)

Any ideas on what I should be doing instead? Thanks!

A: You can define the preds column in df "on the fly", without creating other dataframes:
import pandas as pd
import numpy as np
from sklearn.linear_model import LogisticRegression

# Generate fake data
df = pd.DataFrame(np.random.rand(1000, 4),
                  columns = list('abcd'))
df['Plc'] = np.random.randint(0,2,1000)

# Split X and y
predictors = list('abcd')
X = df[predictors]
y = df['Plc']

# Split train and test
train_size = int(X.shape[0]*0.7)
X_train = X[:train_size]
X_test = X[train_size:]
y_train = y[:train_size]
y_test = y[train_size:]

# Train the model
model = LogisticRegression(max_iter=1000)
model.fit(X_train, y_train)

# Predict train and test
y_pred_train = model.predict(X_train)
y_pred_test = model.predict(X_test)

Now you have at least two options:

*

*Stack the prediction and create the column based on the stacked array:

df['preds'] = np.hstack([y_pred_train, y_pred_test])

*

*Initialize the column and then assign predictions:

df['preds'] = np.nan
df.loc[:train_size-1, 'pred'] = y_pred_train
df.loc[train_size:, 'pred'] = y_pred_test

They yield the same result.

A: I believe what you want is to merge X_test, y_test and y_pred into the same dataframe (as there's no use to have X_train) here. I think it's easy to use train_test_split with Pandas to keep the indices (though there's a way to use numpy too Scikit-learn train_test_split with indices). I'm going to use iris as toy data here but you get the idea.
from sklearn.datasets import load_iris
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
X, y = load_iris(return_X_y=True)
X = pd.DataFrame(X)
y = pd.Series(y)
### you can use shuffle = False instead of random if it's needed
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.3,random_state=42)

model = LogisticRegression(max_iter=1000)
model.fit(X_train, y_train)
df = X_test.copy()
df['Plc']= y_test
df.reset_index(inplace=True)
df['pred'] = model.predict(X_test)

## then print df, you can remove the index of the original df if you like

if you really want to merge X_train,y_train and have NaN in the pred column, you can merge X_train and y_train the same fashion and use pd.concat to make a single dataframe
df2 = X_train.copy()
df2['Plc'] = y_train
df2.reset_index(inplace=True)
pd.concat([df,df2])

index   0   1   2   3   Plc pred
0   73  6.1 2.8 4.7 1.2 1   1.0
1   18  5.7 3.8 1.7 0.3 0   0.0
2   118 7.7 2.6 6.9 2.3 2   2.0
3   78  6.0 2.9 4.5 1.5 1   1.0
4   76  6.8 2.8 4.8 1.4 1   1.0
... ... ... ... ... ... ... ...
100 71  6.1 2.8 4.0 1.3 1   NaN
101 106 4.9 2.5 4.5 1.7 2   NaN
102 14  5.8 4.0 1.2 0.2 0   NaN
103 92  5.8 2.6 4.0 1.2 1   NaN
104 102 7.1 3.0 5.9 2.1 2   NaN
150 rows × 7 columns

A: Becase your X_test corresponds to X_test = X[int(X.shape[0]*0.7):], which is the last 30% of your samples, you can add your prediction results at the lower 30% part of your original dataframe:
Z=model.predict(X_test)
df.loc[int(X.shape[0]*0.7):,'predictions']=Z

Here we have a new column called 'prediction's in df.
An example if your dataframe is:
df=pd.DataFrame({'predictor1':[0.1,0.3,0.3,0.3,0.5,0.9,0.02,0.8,0.8,0.75],
             'predictor2':[0.1,0.4,0.4,0.5,0.5,0.9,0.02,0.8,0.8,0.75],
        'Plc':np.array([0,1,1,1,1,1,1,0,1,1])})
predictor=['predictor1','predictor2']

It gives you the result:
   predictor1  predictor2  Plc  predictions
0        0.10        0.10    0          NaN
1        0.30        0.40    1          NaN
2        0.30        0.40    1          NaN
3        0.30        0.50    1          NaN
4        0.50        0.50    1          NaN
5        0.90        0.90    1          NaN
6        0.02        0.02    1          NaN
7        0.80        0.80    0          1.0
8        0.80        0.80    1          1.0
9        0.75        0.75    1          1.0

Where Z=[1,1,1] is added to the last 3 samples.


text:
Q: Convert MYSQL query to PHP Query I have been trying to get this to work for some time. I'm just stumped.  Here is the original MYSQL and then the PHP Ive been working on.
MYSQL:
SET @COD_PAIS = 3;
SET @F_HASTACORTE = '2012-03-31 01:00:00';

SELECT mcarteras.DES_CARTERA_CC                 AS 'Short Name of Fund'
     , mcarterasflias.DES_CARTERAFLIA           AS 'I/C'
     , msociedades.DES_SOCIEDAD_CORTO           AS 'Fund Manager Company'
     , mcarteras_clases.DES_CARTERACLASE        AS 'Class'
     , mcarteras_clasesesp.DES_CARTERACLASE_ESP AS 'Special Class'
     , dr_rentmovil_carteras.POR_RENTCARTERA    AS 'TTR year-to-date %'
     , dficha_mes.POR_REMUNERA_COBRADA          AS 'Mgmt Fee Effectively Charged'
     , dficha_mes.POR_GASTOS_TOTALESC           AS 'Total Expenses %'
     , dficha_mes.VR_CARTERA_FCORTE             AS 'Fund Size'
     , dr_rentmovil_carteras.F_HASTACORTE             AS 'Date'
  FROM mcarteras
INNER
  JOIN mcarterasflias
    ON mcarterasflias.ID_CARTERAFLIA           = mcarteras.ID_CARTERAFLIA
INNER
  JOIN msociedades
    ON msociedades.ID_SOCIEDAD                 = mcarteras.ID_SOCIEDADADM
INNER
  JOIN mcarteras_clases
    ON mcarteras_clases.ID_CARTERACLASE        = mcarteras.ID_CARTERACLASE
INNER
  JOIN mcarteras_clasesesp
    ON mcarteras_clasesesp.ID_CARTERACLASE_ESP = mcarteras.ID_CARTERACLASE_ESP
INNER
  JOIN dr_rentmovil_carteras
    ON dr_rentmovil_carteras.ID_CARTERA        = mcarteras.ID_CARTERA
   AND dr_rentmovil_carteras.COD_PAIS                                       = @COD_PAIS
   AND dr_rentmovil_carteras.F_HASTACORTE                                =@F_HASTACORTE
   AND dr_rentmovil_carteras.ID_FORMATO = 1
   AND dr_rentmovil_carteras. ID_COLUMNA = 5
INNER
  JOIN dficha_mes
    ON dficha_mes.ID_CARTERA                   = mcarteras.ID_CARTERA
   AND dficha_mes.COD_PAIS                                                  = @COD_PAIS
   AND dficha_mes.F_CORTE                                              = @F_HASTACORTE

 WHERE mcarteras.COD_PAIS                                                   = @COD_PAIS
   AND mcarteras.ID_CARTERATIPO = 4
   AND mcarteras.ID_CARTERAFLIA IN ( 3,4 )
   AND mcarteras.IND_PUBLICACION = 1
   AND mcarteras.COD_ESTADO= 1

PHP:
<?php
$con = mysql_connect("localhost","root","");
 if (!$con)
   {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("bdcarterascv2", $con);
$COD_PAIS = '3';
$F_HASTACORTE = '2012-03-31 01:00:00';

$result = mysql_query("SELECT DES_CARTERA_CC               AS 'Short Name of Fund'
     , mcarterasflias.DES_CARTERAFLIA           AS 'I/C'
     , msociedades.DES_SOCIEDAD_CORTO           AS 'Fund Manager Company'
     , mcarteras_clases.DES_CARTERACLASE        AS 'Class'
     , mcarteras_clasesesp.DES_CARTERACLASE_ESP AS 'Special Class'
     , dr_rentmovil_carteras.POR_RENTCARTERA    AS 'TTR year-to-date %'
     , dficha_mes.POR_REMUNERA_COBRADA          AS 'Mgmt Fee Effectively Charged'
     , dficha_mes.POR_GASTOS_TOTALESC           AS 'Total Expenses %'
     , dficha_mes.VR_CARTERA_FCORTE             AS 'Fund Size'
     ,dr_rentmovil_carteras.F_HASTACORTE        AS'Date'
  FROM mcarteras
INNER
  JOIN mcarterasflias
    ON mcarterasflias.ID_CARTERAFLIA           = mcarteras.ID_CARTERAFLIA
INNER
  JOIN msociedades
    ON msociedades.ID_SOCIEDAD                 = mcarteras.ID_SOCIEDADADM
INNER
  JOIN mcarteras_clases
    ON mcarteras_clases.ID_CARTERACLASE        = mcarteras.ID_CARTERACLASE
INNER
  JOIN mcarteras_clasesesp
    ON mcarteras_clasesesp.ID_CARTERACLASE_ESP = mcarteras.ID_CARTERACLASE_ESP
INNER
  JOIN dr_rentmovil_carteras
    ON dr_rentmovil_carteras.ID_CARTERA        = mcarteras.ID_CARTERA
  AND dr_rentmovil_carteras.COD_PAIS                                       =  $COD_PAIS
   AND dr_rentmovil_carteras.F_HASTACORTE                          =      $F_HASTACORTE
   AND dr_rentmovil_carteras.ID_FORMATO = 1
   AND dr_rentmovil_carteras. ID_COLUMNA = 5
INNER
  JOIN dficha_mes
    ON dficha_mes.ID_CARTERA                   = mcarteras.ID_CARTERA
   AND dficha_mes.COD_PAIS                                            =      $COD_PAIS
   AND dficha_mes.F_CORTE                                             =  $F_HASTACORTE

 WHERE mcarteras.COD_PAIS                                                =  $COD_PAIS
   AND mcarteras.ID_CARTERATIPO = 4
   AND mcarteras.ID_CARTERAFLIA IN ( 3,4 )
   AND mcarteras.IND_PUBLICACION = 1
   AND mcarteras.COD_ESTADO= 1
")
or die(mysql_error());

// HTML ... Aliases from Mysql
echo "

Short Name of Fund
I/C
Fund Manager Company
Class
Special Class
TTR year-to-date %
Mgmt Fee Effectively Charged
Total Expenses %
Fund Size
Date

";

//
 specifies table row. for each  (table data) will specify a new column.  The     $row specifies the mysql column name (in this case using an alias)
while($row = mysql_fetch_array($result))
  {
  echo "
";
  echo "" . $row['Short Name of Fund'] . "	";
 echo "" . $row['I/C'] . "	";
  echo "" . $row['Fund Manager Company'] . "	";
  echo "" . $row['Class'] . "	";
  echo "" . $row['Special Class'] . "	";
  echo "" . $row['TTR year-to-date %'] . "	";
  echo "" . $row['Mgmt Fee Effectively Charged'] . "	";
  echo "" . $row['Total Expenses %'] . "	";
  echo "" . $row['Fund Size'] . "	";
   echo "" . $row['Date'] . "	";
  echo "
";
  }
echo "
";

mysql_close($con);
?>

Here is the current error:
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 '01:00:00 AND dr_rentmovil_carteras.ID_FORMATO = 1 AND dr_rentmovil_carte' at line 28
Any help would be greatly appreciated.

A: You need to wrap the datetime string in quotes:
='$F_HASTACORTE'

Otherwise it is evaluating 2012-03-31 01:00:00 as a number, not a datetime.

A: you probably want to put quotes around your '$VARIABLES'. And escape them if you didn't.

A: Try:
AND dr_rentmovil_carteras.F_HASTACORTE                          =      '$F_HASTACORTE'

If your variables aren't integers, you should quote them - there are a few other places where you should do that, too.
You should also look at using PDO instead of the mysql_* functions, too - if you use bound parameters, you can sidestep a lot of this sort of problem very neatly.


text:
Q: Erro no captcha Estou com o seguinte erro no captcha:

Notice: Undefined index: captcha in C:\xampp\htdocs\darknetwork\index.php on >line 7

e também ele só esta me retornando o else mesmo se der um F5 na page, o session_start(); já esta no config.php

*

*index.php
<?php
require 'config.php';
require 'classes/usuarios.class.php';
$ip = $_SERVER["REMOTE_ADDR"];

$u = new Usuarios;
if($_SESSION['captcha'] == $_POST['captcha']) {

  if(isset($_POST['email']) and !empty($_POST['email'])) {
    $email = addslashes($_POST['email']);
    $senha = addslashes($_POST['senha']);

  if($u->login($email, $senha)) {

    header("Location: central.php");

  } else {
  ?>

  E-mail e/ou Senha incorretos, tente novamente !

  <?php
          }
      }
  } else {
  ?>

  Captcha esta incorreto !

  <?php
  }
   ?>

<!DOCTYPE html>

    <title>Dark Network</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" href="assets/css/style.css">

      ÁREA DE LOGIN - DARK NETWORK

    <form class="login-form" method="post">

      <input type="email" name="email" placeholder="E-mail" required=""/>
      <input type="password" name="senha" placeholder="Senha" required=""/>

      <input type="text" name="captcha" placeholder="Digite o código" required=""/>

      <button type="submit">Entrar</button>

Não é registrado ? Cadastre-se aqui.

Desenvolvido por: Weltec

    </form>

`

*captcha.php
<?php
session_start();

$codigoCaptcha = substr(md5(time().rand(0,999)), 0, 9);

$_SESSION['captcha'] = $codigoCaptcha;

$imagemCaptcha = imagecreatefrompng("fundocaptch.png");
$fonteCaptcha = imageloadfont("anonymous.gdf");
$corCaptcha = imagecolorallocate($imagemCaptcha, 0, 115, 50);

imagestring($imagemCaptcha, $fonteCaptcha, 15, 5, $codigoCaptcha, $corCaptcha);
imagepng($imagemCaptcha);
imagedestroy($imagemCaptcha);
?>

A: Isso é um notice e não um bem erro para saber a diferença veja o link citado pelo @Everson:

Qual a diferença entre "notice" e "warning" no PHP?

No entanto, mesmo sendo um notice o ideal é checar se o envio foi feito por POST, pode usar isset, empty ou filter_input, note que o seu if/else estão sendo executados a todo momento.
Detalhes importantes:

*

*Se usa isset ou empty

*isset pode ser usado com mais de um campo

um exemplo simples seria isto:
<?php
require 'config.php';
require 'classes/usuarios.class.php';
$ip = $_SERVER["REMOTE_ADDR"];

//Uma variavel para o erro
$erro = null;

$u = new Usuarios;

//Checa se todos campos vieram do form
if (isset($_POST['captcha'], $_POST['captcha'], $_POST['email'], $_POST['senha'])) {
    if ($_SESSION['captcha'] == $_POST['captcha']) {
        $email = addslashes($_POST['email']);
        $senha = addslashes($_POST['senha']);

        if($u->login($email, $senha)) {

            header("Location: central.php");
            exit; //Isso impede de "baixar" o resto

        } else {
            $erro = 'E-mail e/ou Senha incorretos, tente novamente !';
        }
    } else {
        $erro = 'Captcha esta incorreto !';
    }
}

<!DOCTYPE html>

    <title>Dark Network</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" href="assets/css/style.css">

<?php if ($erro) { /*se $erro não for null então é exibido */ ?>

<?php $erro; ?>

<?php } ?>


text:
Q: MVC accessing model of view at layout page I do not know the right approach to do it but I have one strange requirement in Razor
Scenario
I have a layout page being shared in 40 views, the layout pages also contain some label fields.
I have made a base class in Model which contains properties need to be displayed on Layout page, this class gets inherited in each and every model.
So basically when Model is passed to View it contain some properties to be displayed on layout.
Query
Is this is a right approach ? (If no then what is the right approach to do it?)
How to access the properties of model at view in layout page.

A: Partial View can be alternate but why not to make a Base class which contains Layout Properties and all the Model inherits Base Class
Check out this for more
Pass data to layout that are common to all pages


text:
Q: MySQL: Perform join on all rows of a table I have a view where I combine some normalized tables. Based on a "master" table, I join connected tables (e.g. JOIN child ON master.child_fk = child.pk). This is pretty straight forward. Now, I'd like to extend this query to perform a join on ALL child rows in some special cases, for example if the master.child_fk equals to -1.
I managed to get a working query by creating a view where I duplicate all rows and set the pk to -1 in the duplicates, but this is incredibly slow (I have quite a lot of data). The same result could be produced by iterating over all the child.pks and performing a separate join for each, but I can't imagine that being faster.
What would be the best way to go about this using MySQL? Please ask questions if something is not clear.
edit: I can add that it seems the reason why my attempt was slow was because of poor index utliziation. See attached EXPLAIN output here https://i.imgur.com/8zfT0HM.png

A: Replace your join condition as JOIN child ON CASE WHEN master.child_fk != -1 THEN master.child_fk = child.pk ELSE 1 END)


text:
Q: SQL Server date conversion from string value In my table, I have a string-represented date column in the following format: {^2013/05/29}.
How do I convert this to standard datetime format in SQL Server? This contains string characters that are not part of what a datetime string usually has.

A: That format is recognizable as a strict format by VFP only. Is that stored in SQL Server as text? If so:
Select cast(substring(myColumn, 3, 10) as date) as myDate from myTable;

would do the conversion.
If you mean it is stored like that in a VFP table and you want to convert a date then:
select ctod(myColumn) as myDate from myTable;

A: SELECT CAST(REPLACE('^2018/05/29','^','') AS DATETIME2)

A: If the data is always in the format {^yyyy/MM/dd} then you could use:
CONVERT(date,REPLACE(SUBSTRING(YourDateColumn,3,10),'/',''))

Ideally, however, you should be fixing your column to be the correct datatype:
CREATE TABLE Test (DateColumn varchar(13));
INSERT INTO Test VALUES ('{^2013/05/29}');
GO

SELECT *
FROM Test;

UPDATE Test
SET DateColumn = CONVERT(date,REPLACE(SUBSTRING(DateColumn,3,10),'/',''));

SELECT *
FROM Test;

ALTER TABLE test ALTER COLUMN DateColumn date;

SELECT *
FROM Test;
GO

DROP TABLE Test;


text:
Q: How to call an array by button I have an array and I want to call the array by button, Also I wanted it keep calling the array every time when I click on button. Please correct the array if it has any issue.
my array is :
array (

"name" => __('name1','vbegy'),
"id" => $this->shortname."_menu_1",
"desc" => __('name2)','vbegy'),
"type" =>  "text",
"std" => __('name3','vbegy'),

),

array (

"name" => __('name4','vbegy'),
"id" => $this->shortname."_menu_1_url",
"desc" => __('name5)','vbegy'),
"type" =>  "text",

),

A: I think first thing you should do is to learn how to use HTML forms/buttons and use PHP to process them. Below is a simple form example.
In your HTML file, add
<form method="post" action="your-php-file.php">
<input type="text" name="text-name" value="">
<input type="submit" name="button-name" value="Submit">
</form>

In your PHP file (your-php-file.php), add
    $array1 = array(
        "name" => array('name1' => 'vbegy'),
        "id" => $this->shortname."_menu_1",
        "desc" => array('name2' => 'vbegy'),
        "type" =>  "text",
        "std" => array('name3','vbegy')
    );

    $array2 = array (
        "name" => array('name4' => 'vbegy'),
        "id" => $this->shortname."_menu_1_url",
        "desc" => array('name5' => 'vbegy'),
        "type" =>  "text"
    );

    if (isset($_POST['button-name'])) {
        //use php to process your array data as you want
        echo $array1['name']['name1']; //print vbegy
        echo $array1['type']; //print text
        echo $array2['desc']['name5']; //print vbegy

        $std = $array1['std']['name3'];
        echo $std; //print vbegy

        echo "You clicked submit button!";
    }

For detailed explanation, please use following links.
http://www.w3schools.com/php/php_forms.asp
http://www.w3schools.com/php/php_form_complete.asp
Hope this will help.


text:
Q: Simple Form Validation in Ruby not working correctly I have a couple of forms in my Ruby on Rails project that all need validation. For one for, that creates users, the f.error_notification method works quite well for displaying errors, I believe because it's working with the user model. However I have another form for editing passwords that isn't working the right way. I'm trying to use all the same methods so that all of the error messages display the same everywhere on the website. The problem I'm having is that if the passwords don't match (or there's any other kind of problem), the f.error_notification displays in red at the top: Please review the problems below. As it should. But it doesn't actually display any problems below.
This is the form:

Change your password

<%= simple_form_for(resource, :as => resource_name, :url => password_path(resource_name),  :html => { :method => :put }) do |f| %>
  <%= f.error_notification %>
  <%= f.hidden_field :reset_password_token %>

<%= f.label :password, "New password" %>

  <%= f.password_field :password, :autofocus => true, required: true %>

<%= f.label :password_confirmation, "Confirm new password" %>

  <%= f.password_field :password_confirmation, required: true %>

  <%= button_tag(type: 'submit', class: "btn doc-action-btn btn-success") do %>
       Change my password
  <% end %>
<% end %>

I'm not sure what else to post code wise to help make this clearer but I'm happy to update my post if there's something else I can add. I should also note that the form above was generated by Devise. I switched from Devise error messages to the Rails ones for consistency's sake because we use the Rails ones elsewhere in our custom forms. Thank you!

A: you have to use devise_error_messages! method. it is special devise method which take care of displaying errors. You can't flip back and forth unless you fully customise it.
if case you want to customize it, you can check this https://github.com/plataformatec/devise/wiki/Override-devise_error_messages!-for-views


text:
Q: Linux: memory is free but swap is used. Why? Here are Munin's diagrams.
Memory usage:
http://koryagin.com/w/q/memory-day.png
Swap in/out:
http://koryagin.com/w/q/swap-day.png
Why does Linux decide to increase cache and use swap when the RAM size is much bigger than the memory used by programs?

A: Your server probably has some memory-eating and/or inactive processes having many inactive pages. Linux kernel prefers to swap out inactive portions of programs to swap since most likely the memory is better used as cache.
If you wish to change this behaviour, play with vm.swappiness sysctl tunable but be warned, outsmarting the kernel developers / distro maintainers is not that easy. :-)
Are you having performance problems on your server during that swap spike or did you ask out of curiosity?

A: You should try to play with swappiness parameter. As you can see your system started to swap when it tried to increase file cache size, this is normal if swappines is not 0.


text:
Q: Why is iOS Xcode project giving error for missing OSX framework AVKit? So my iOS project was working fine, then all of a sudden I am getting the following error when I try to run in simulator:
ld: framework not found AVKit for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)

And when I try to archive I get this error:
ld: framework not found AVKit for architecture armv7
clang: error: linker command failed with exit code 1 (use -v to see invocation)

From what I can tell, AVKit is an OSX framework and not an iOS framework.
So why is my project suddenly confused and wanting an OSX framework, and do I convince it that it does not need it?

A: Well apparently AVKit is available in the iOS 8 SDK so I need to upgrade Xcode to version 6 in order to add it.
See this question: Need help: 'Wrong Architecture' causing app to crash when launching in iOS 7 but works fine in iOS 8
And it should be set as an Optional framework if you want to support iOS 7 and below as well.


text:
Q: convert svg to Highcharts Map I have an SVG and just want to convert it, So it can be used in Highmaps.
for example this SVG
https://www.highcharts.com/maps/maps/Germany.svg

Highcharts site recommended this guideline:
https://www.highcharts.com/docs/maps/create-custom-maps-for-highmaps

I created SVG with inkspace software, but when trying to convert it to highcharts map data using this link:
https://www.highcharts.com/studies/map-from-svg.htm

It got error. any idea how to do it?

A: It seems that it was a bug which has been already fixed but the documentation doesn't include the new URL yet.
GitHub issue channel: https://github.com/highcharts/highcharts/issues/6654
Please try to use the new link: https://highcharts.github.io/map-from-svg/


text:
Q: Capture HTML Form Arrays in PHP Email I have an HTML form with a few arrays as defined by their name tags having [] after them. I am trying to send all of those array values in a single PHP email. I know var_dump will show those array values on screen, but var_dump doesn't seem to work to send the values in the email. Any guidance is greatly appreciated. Thank you, below is what I have.
In the html form the fields name and email are arrays with '[]' after their name tags, up to 15 can be submitted on a single form. Below is the PHP code I have trying to capture the values.
$to = "$Eemail";
$subject = "Credential Request";
$message = var_dump($name, $email);
$from = "EmailAddres@email.com";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);

The email is sending fine, but as I've tried many options in the $message, I either get an empty email or a NULL response.

A: var_dump is just a function to print arrays, very similar to print_r in your case you will need to assign a string to your $message variable
I suppose $name and $email are both array with same number of values, you can just use a for loop
for($i=0; $i<count($name); $i++)
{
    $to = "$Eemail";
    $subject = "Credential Request";
    $message = 'name: ' . $name[$i] . ' email: ' . $email[$i];
    $from = "EmailAddres@email.com";
    $headers = "From:" . $from;
    mail($to,$subject,$message,$headers);
}

As pointed out it seems you need to send one email with all your arrays value so simply loop and concatenate all arrays value
$to = "$Eemail";
$subject = "Credential Request";
$message = '';
for($i=0; $i<count($name); $i++)
{
     $message .= 'name: ' . $name[$i] . ' email: ' . $email[$i] . "\n";
}
$from = "EmailAddres@email.com";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);

A: var_dump doesn't return anything. Therefor assigning its result to $message will result in an empty variable, which in turn causes your mail to be empty.
Instead if you want to have the result as a string, you could use the following code:
$message = print_r($name, true) . "\n" . print_r($email, true);

A: var_dump only outputs something to the output buffer. You're probably looking for something like this:
$message = implode(" ", $name) . " " . implode(" ", $email);

A: I found what I was looking for. A foreach loop with multiple arrays.
$to = "$Eemail";
$subject = "Credential Request";
$message = '';
$message .= '';
        $message .= "
Credential Requests
";
        $message .= '
';

foreach($_POST['name'] as $key => $something) {
$email = $_POST['email'][$key];
$position = $_POST['position'][$key];
        $message .= "
 $something	 $email 	 $position
";
}
        $message .= "
";
$from = "Credentials@UHSAA.org";
$headers = "From: " . $from . "\r\n";
        $headers .= "Reply-To: ". strip_tags($_POST['req-email']) . "\r\n";
        $headers .= "MIME-Version: 1.0\r\n";
        $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
mail($to,$subject,$message,$headers);


text:
Q: Tomcat connector failed to start but port is bound I get the following error when I try to initiate Tomcat connector on port 443 :
16-Jul-2018 09:30:08.394 SEVERE [main] org.apache.catalina.core.StandardService.initInternal Failed to initialize connector [Connector[HTTP/1.1-443]]
 org.apache.catalina.LifecycleException: Failed to initialize component [Connector[HTTP/1.1-443]]
        at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:112)
        at org.apache.catalina.core.StandardService.initInternal(StandardService.java:549)
        at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:107)
        at org.apache.catalina.core.StandardServer.initInternal(StandardServer.java:875)
        at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:107)
        at org.apache.catalina.startup.Catalina.load(Catalina.java:632)
        at org.apache.catalina.startup.Catalina.load(Catalina.java:655)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.apache.catalina.startup.Bootstrap.load(Bootstrap.java:309)
        at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:492)

I expect this error and knows why it occurred.
The issue is that although the connector has failed to start, it seems that Tomcat is still listing on port 443 and every message sent to this port hangs until I get read timeout.
How can i configure Tomcat not to listen when connector failed to start ?

A: I can't comment... but still, the configuration related to the ports ins't in the server.xml file?
Something like this?
<!-- Define a non-SSL HTTP/1.1 Connector on port 8180 -->
<Connector port="8180" maxHttpHeaderSize="8192"
           maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
           enableLookups="false" redirectPort="8443" acceptCount="100"
           connectionTimeout="20000" disableUploadTimeout="true" />

Look up for the 443 port and modify it?


text:
Q: change wordpress image directory with sql I've changed my wordpress default upload directory from:
mysite.com/files/year/month/upload
to
mysite.com/images/upload
I'm a bit stumped on the proper sql syntax to replace /files/year/month/ with /images/.
Using phpmyadmin, I selected the correct db, selected the correct table, and searched/found what needs to be changed using this sql:
SELECT *
FROM  `wp_postmeta`
WHERE  `meta_value`
LIKE  '%/files/%/%/%'

Now I need to REPLACE everything FROM wp_postmeta WHERE meta_value LIKE %/files/%/%/ WITH /images/

A: To modify the entries for the uploaded media files you need to run the queries found in this article:
http://www.dezzain.com/wordpress-tutorials/how-to-move-wordpress-uploads-path-to-subdomain/
Mainly these two queries:
UPDATE wp_posts SET post_content = REPLACE(post_content,'http://www.domain.com/wp-content/uploads','http://img1.domain.com/uploads')

and:
UPDATE wp_posts SET guid = REPLACE(guid,'http://www.domain.com/wp-content/uploads','http://img1.domain.com/uploads')

The problem with the other answers is that although the upload path will be fixed for new files, the source path for media that has already been inserted into posts is still pointing to the old directory since the paths are stored in the database.

A: Rather than doing it that way, WordPress provides the facility to change the upload folder using the wp-config.php file.
Basically you set WP_CONTENT_DIR for the server location and WP_CONTENT_URL for the URI's to be based on.

A: Another option is to use the following settings:
    update_option('uploads_use_yearmonth_folders', 0);
    update_option('upload_path', 'images');

A: I'd recommend the plugin WP Migrate DB for this. That's the easy way.
If your stuck on doing it the hard way, you could either run a query using REPLACE() for each path you want to replace (the function does not allow wildcards) or try something like this.


text:
Q: DropDown bind to property names; based on first set second DropDown binding I have one ObservableCollection<M> fooBar {get;set;}. The class M.cs looks like this:
public class M{
    private int _ID;
    public int ID {
        get {return this._ID;}
        set {this._ID = value;}
    }

    private string _number;
    public int Number {
        get {return this._number;}
        set {this._number = value;}
    }

    private string _power;
    public int Power {
        get {return this._power;}
        set {this._power = value;}
    }

    /*
       ...
    */
}

Now I want to bind the names of these 3 propertys to a ComboBox. I don't want to do it like this:
<ComboBox>
    <ComboBoxItem>ID</ComboBoxItem>
    <ComboBoxItem>Number</ComboBoxItem>
    <ComboBoxItem>Power</ComboBoxItem>
</ComboBox>

Is there a more comfortable way?
Based on the choose of the first ComboBox I want to fill the second ComboBox. As example I choose in the first ComboBox the property Numberthen the second ComboBox should look like this
<ComboBox
    SelectedValue="{Binding ???}"
    ItemsSource="{Binding fooBar}"
    SelectedValuePath="Number"
    DisplayMemberPath="Number"
    />

Maybe someone of you can help me, because I have no idea how to connect both comboboxes.

A: For the 1st ComboBox: Use Reflection to get the names of all the properties of class M and put those into the ComboBox.
For the 2nd ComboBox: When selection changes in the 1st one, you get the property name. Now set the SelectedValue binding to the property that was selected in the 1st ComboBox.

A: This is how I would do it:

*

*Make a property on the view model which exposes the properties on the model (class M) which can be selected. This way you explicitly control which properties can be selected.

*Make a property to hold the selected value of each combo box.

*DisplayMemberPath/SelectedValuePath in ComboBox2 binds to the SelectedValue of ComboBox1.
ViewModel:
        // ComboBox 1
        public Dictionary<string, string> SelectableProperties = new Dictionary<string, string>()
        {
            { nameof (M.ID), "ID" }
            { nameof (M.Number), "Nummer" }
            { nameof (M.Power), "Potenz" }
        }

        // Selection in combobox 1 (not strictly necessary as it can be handled in view, but you may need to know what SelectedValue represents)
        private string _selectedValueMember = String.Empty;
        public string SelectedValueMember
        {
            get { return _selectedValueMember; }
            set { _selectedValueMember = value; }
        }

        // Selection in combobox 2 (object just in case there could be other values than int)
        private object _selectedValue = null;
        public object SelectedValue
        {
            get { return _selectedValue; }
            set { _selectedValue = value; }
        }

        public ObservableCollection<M> FooBar{ get; set; }

View:
<ComboBox x:Name="ComboBox1"
                  Width="100"
                  Margin="5"
                  SelectedValuePath="Key"
                  DisplayMemberPath="Value"
                  SelectedValue="{Binding SelectedValueMember}"
                  ItemsSource="{Binding SelectableProperties}">

        </ComboBox>
        <ComboBox Width="100"
                  Margin="5"
                  DisplayMemberPath="{Binding ElementName=ComboBox1, Path=SelectedValue}"
                  SelectedValuePath="{Binding ElementName=ComboBox1, Path=SelectedValue}"
                  SelectedValue="{Binding SelectedValue}"
                  ItemsSource="{Binding FooBar}">

        </ComboBox>


text:
Q: Creating composite COLUMNS (not keys) with CQL 3 This article discusses possible ways CQL 3 could be used for creating composite columns in Cassandra 1.1. They are just ideas. Nothing is official, and the Datastax documentation doesn't cover this (only composite keys).
As I understand it, composite columns are a number of columns that together have only one value.
How do you create them with CQL?
EDIT
I will be using C# to interface into Cassandra. CQL looks straightforward to use, which is why I want to use it.

A: You've got a couple concepts confused, I think. Quite possibly this is the fault of the Datastax documentation; if you have any good suggestions for making it clearer after you have a better picture, I'll be glad to send them on.
The "composite keys" stuff in the Datastax docs is actually talking about composite Cassandra columns. The reason for the confusion is that rows in CQL 3 do not map directly to storage engine rows (what you work with when you use the thrift interface). "Composite key" in the context of a CQL table just means a primary key which consists of multiple columns, which is implemented by composite columns at the storage layer.
This article is one of the better explanations as to how the mapping happens and why the CQL model is generally easier to think about.
With this sort of use, the first CQL column becomes being the storage engine partition key.
As of Cassandra 1.2 (in development), it's also possible to create composite storage engine keys using CQL, by putting extra parentheses in the PRIMARY KEY definition around the CQL columns that will be stored in the partition key (see CASSANDRA-4179), but that's probably going to be the exception, not the rule.

A: With Cassandra, you store data in rows.  Each row has a row key and some number of columns.  Each column has a name and a value.  Usually the column name and value (and row key, for that matter) are single values (int, long, UTF8, etc), but you can use composite values in row keys, column names and column values.  A composite value is just some number of values that have been serialized together in some way.
Over time a number of language-specific API's have been developed.  These API's start with the understanding I describe above and provide access to a Column Family accordingly.  Hector, the java client API, is the one I'm most familiar with, but there are others.
CQL was introduced as a means to use Cassandra tables in an SQL/JDBC fashion.  Not all Cassandra capabilities were supported through CQL at first, although CQL is getting more and more functional as time goes on.
I don't doubt your need for composite column names and values (I believe that's what your asking for).  The problem is that CQL has yet to evolve (as I understand it) to that level of native support.  Whether or not it ever will is not known to me.
I suggest that you complete the definition of your desired column family schemas, complete with composite values if necessary.  Once you've done that, look at the various API's available to access Cassandra column families and choose the one that best supports your desired schema.
You haven't said what language you're using.  If you were coding in java then I'd recommend Hector and not CQL.

A: Are you sure you want to create them with CQL?  What is your use case?


text:
Q: headers are not being set into AXIOS post request I am working on react-redux App. When i am making Api Post request to Rest Api(on CORS). Headers are not being set. But when i try this in postman it work perfectly.
this is the code:
I want to send TOKEN(for testing).
post: (endPoint, data) => {
        return axios({
            method: 'post',
            url: `${apiPath}/${endPoint}`,
            data: data,
            headers: { "Content-Type": "application/json", 'TOKEN': 1111}
        }).then((res) =>{
            return res;
        })
    }


text:
Q: Devices networking on C++ I have the need to access the network interfaces on my device. I have the below code that does that but I am missing the ones that are active but with no IP address associated to them. Any idea on how programmatically I could gather the information from those?
The code posted has the functions to get the information from the interface, function to list all interfaces and a main to test.
Thanks
struct iface {
    std::string name;
    std::string address;
    std::string netmask;
    std::string broadcast;
    std::string hwaddr;
    int mtu;
};

void print_iface(iface s) {
    std::cout << s.name << ": <UP, RUNNING>" << std::endl;
    std::cout << "  mtu: " << s.mtu << std::endl;
    std::cout << "  hwaddr: " << s.hwaddr << " " << std::endl;
    std::cout << "  inet: " << s.address << " " << std::endl;
    std::cout << "  netmask: " << s.netmask << " " << std::endl;
    std::cout << "  broadcast: " << s.broadcast << std::endl;
}

std::tuple<char*, int> get_active_interfaces() {
    int socketfd;
    struct ifconf conf;
    char data[4096];

    socketfd = socket(AF_INET, SOCK_DGRAM, 0);
    conf.ifc_len = sizeof(data);
    conf.ifc_buf = (caddr_t) data;
    if (ioctl(socketfd, SIOCGIFCONF, &conf) < 0) {
        fprintf(stderr, "ioctl error: %s", std::strerror(errno));
        return std::make_tuple(nullptr, 0);
    } else {
        return std::make_tuple(data, conf.ifc_len);
    }
}

std::string get_ifname(struct ifreq *ifr) {
    return ifr->ifr_name;
}

std::string get_ipv4_addr(struct ifreq *ifr) {
    std::string addr(45, 0);
    inet_ntop(ifr->ifr_addr.sa_family,
            &((struct sockaddr_in*) &ifr->ifr_addr)->sin_addr, &addr[0],
            addr.size());
    return addr;
}

#define MAC_TEMPLATE "%02X:%02X:%02X:%02X:%02X:%02X"
#define LOOPBACK_TEMPLATE "LOOPBAK INTERFACE"

std::string get_mac_addr(struct ifreq *ifr) {
    std::string addr;

    u_int8_t hd[6];
    struct ifreq ifl;
    int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
    if (sock >= 0) {
        strcpy(ifl.ifr_name, ifr->ifr_name);
        if (ioctl(sock, SIOCGIFFLAGS, &ifl) == 0) {
            if (!(ifl.ifr_flags & IFF_LOOPBACK)) {
                if (ioctl(sock, SIOCGIFHWADDR, &ifl) == 0) {
                    memcpy(hd, ifl.ifr_hwaddr.sa_data, sizeof(hd));
                    size_t n = snprintf(nullptr, 0, MAC_TEMPLATE, hd[0], hd[1],
                            hd[2], hd[3], hd[4], hd[5]);
                    addr.resize(n + 1, 0);
                    sprintf(&addr[0], MAC_TEMPLATE, hd[0], hd[1], hd[2], hd[3],
                            hd[4], hd[5]);
                }
            } else {
                addr = LOOPBACK_TEMPLATE;
            }
        }
    }

    return addr;
}

std::string get_netmask(struct ifreq *ifr) {
    std::string addr(45, 0);

    struct ifreq ifl;
    int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
    if (sock >= 0) {
        strcpy(ifl.ifr_name, ifr->ifr_name);
        if (ioctl(sock, SIOCGIFNETMASK, &ifl) == 0) {
            inet_ntop(ifl.ifr_addr.sa_family,
                    &((struct sockaddr_in*) &ifl.ifr_addr)->sin_addr, &addr[0],
                    addr.size());
        }
    }
    return addr;
}

std::string get_broadcast(struct ifreq *ifr) {
    std::string addr(45, 0);

    struct ifreq ifl;
    int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
    if (sock >= 0) {
        strcpy(ifl.ifr_name, ifr->ifr_name);
        if (ioctl(sock, SIOCGIFFLAGS, &ifl) == 0) {
            if (!(ifl.ifr_flags & IFF_LOOPBACK)) {
                if (ioctl(sock, SIOCGIFBRDADDR, &ifl) == 0) {
                    inet_ntop(ifl.ifr_addr.sa_family,
                            &((struct sockaddr_in*) &ifl.ifr_addr)->sin_addr,
                            &addr[0], addr.size());
                }
            } else {
                addr = LOOPBACK_TEMPLATE;
            }
        }
    }
    return addr;
}

int get_mtu(struct ifreq *ifr) {
    int mtu = 0;

    struct ifreq ifl;
    int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
    if (sock >= 0) {
        strcpy(ifl.ifr_name, ifr->ifr_name);
        if (ioctl(sock, SIOCGIFMTU, &ifl) == 0) {
            mtu = ifl.ifr_mtu;
        }
    }
    return mtu;
}

/**
 *  Return a list of interface (network layer) addresses.
 *  Accept or return only AF_INET socket addresses are
 *  IP-specific and perhaps should rather be documented in ip(7).
 *  [https://www.man7.org/linux/man-pages/man7/ip.7.html]
 *  This currently means only addresses of the AF_INET (IPv4)
 *  family for compatibility.
 *  The names of interfaces with no addresses or that don't have the
 *  IFF_RUNNING flag set can be found via /proc/net/dev.
 */
std::vector<iface> get_ifce_list() {
    std::vector<iface> ifaces;
    int socketfd;

    printf("Opening socket...");
    socketfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (socketfd >= 0) {
        printf(" OK\n");
        printf("Discovering interfaces...\n");
        auto data = get_active_interfaces();

        for (struct ifreq *ifr = (struct ifreq*) std::get<0>(data);
                (char*) ifr < std::get<0>(data) + std::get<1>(data); ifr++) {
            switch (ifr->ifr_addr.sa_family) {
            case AF_INET: {
                iface ifc;
                ifc.name = get_ifname(ifr);
                ifc.address = get_ipv4_addr(ifr);
                ifc.netmask = get_netmask(ifr);
                ifc.broadcast = get_broadcast(ifr);
                ifc.hwaddr = get_mac_addr(ifr);
                ifc.mtu = get_mtu(ifr);

                ifaces.emplace_back(ifc);

                break;
            }
#if USE_IPV6
                case AF_INET6:

                    break;
    #endif
            }
        }
        close(socketfd);
    } else {
        printf(" Failed!\n");
    }

    return ifaces;
}

// This is the main function

int main() {
    std::time_t start = std::time(nullptr), stop;
    std::vector<iface> _ifaces = get_ifce_list();
    for (auto &_iface : _ifaces) {
        print_iface(_iface);
    }
    stop = std::time(nullptr);

    std::cout << "End of code. ran for: " << stop - start << " seconds. "
            << std::endl;
    return 0;
}

A: This code is problematic in a few ways:
std::tuple<char*, int> get_active_interfaces() {
    int socketfd;
    struct ifconf conf;
    char data[4096];

    socketfd = socket(AF_INET, SOCK_DGRAM, 0);
    conf.ifc_len = sizeof(data);
    conf.ifc_buf = (caddr_t) data;
    if (ioctl(socketfd, SIOCGIFCONF, &conf) < 0) {
        fprintf(stderr, "ioctl error: %s", std::strerror(errno));
        return std::make_tuple(nullptr, 0);
    } else {
        return std::make_tuple(data, conf.ifc_len);
    }
}

The basic problem is that the tuple you return contains a pointer to data, which is a local variable. Any use of that pointer outside the function is an error.
What you want to do, IIUC, is iterate over ifc_req, which is defined as a list of interfaces no more than ifc_len bytes long.
The most general approach, according to my Ubuntu man page, is first to make one call with ifc_req == NULL, in which case the system will populate ifc_len with the required size.  Compute the number of elements and allocate from the free store with
size_t N = ifc_len / sizeof(ifc_req[0]);
conf.ifc_req = new ifreq(N);

I would redefine the function to return std::tuple<struct ifreq *, size_t>, and change the meaning of second to be the number of elements, not the number of bytes.  That way, the caller can be organized around an array of structures, and you're done mucking about with bytes and casts.  Since you're working in C++, that would let you iterate over the array with std::for_each quite neatly.


text:
Q: How can I selectively validate a form in WPF? I'm currently using the validation code listed here in an application. I'd like to selectively validate a page. What I mean by that is this: I have a form that's databound with validation rules attached. I also have a checkbox that, when checked, disables and clears the values of several bound textboxes. Is there a property I can set on these textboxes to tell the validation engine not to include these when validating?

A: Perhaps if you wrote an attached property for your Validator class, and checked for it first thing in your IsValid method.
static class Validator
{
    public static readonly DependencyProperty SkipValidationProperty =
        DependencyProperty.RegisterAttached("SkipValidation", typeof(bool), typeof(Validator),
        new UIPropertyMetadata(false));
    public static bool GetSkipValidation(DependencyObject obj)
    {
        return (bool)obj.GetValue(SkipValidationProperty);
    }
    public static void SetSkipValidation(DependencyObject obj, bool value)
    {
        obj.SetValue(SkipValidationProperty, value);
    }

    public static bool IsValid(DependencyObject parent)
    {
        if (Validator.GetSkipValidation(parent)) return true;
       //Rest of the validation code
    }

}

Then you could do something as simple as:
<StackPanel>
 <TextBox x:Name="txt" local:Validator.SkipValidation="{Binding IsChecked, ElementName=cbx}" />
 <CheckBox x:Name="cbx" >Skip Validate?</CheckBox>
</StackPanel>

A: Possibly, you could have triggers that would switch the bindings. Meaning the Setter-s would rebind the property using another bindings with different validation rules.
But that would only(?) work if all those validation rules are in a ControlTemplate or DataTemplate.


text:
Q: Why this sprintf statement crashing? char filebuf[256];
path current = current_path();
std::cout<<"CurrentWorking "<<current<<endl;
string _UserDir = "TTiTraceLogs";
sprintf(filebuf,"%s/%s",current,_UserDir); ///crashing here

If I format only current, then it is ok.
sprintf(filebuf,"%s",current);

Output:
CurrentWorking D:/working/eclipse_projects/sadftp/CollectTTiTraceSept10_1009_174
_higher/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/Release

A: Is string actually std::string? And path a boost::filesystem::path? In that case, you should know that C library functions (like sprintf and printf) don't support C++ classes like std::string. That's only natural.
What you need to do is:
sprintf(filebuf, "%s%s", current.c_str(), _UserDir.c_str());

But a more elegant solution, if you're already using C++, is to either use std::stringstream or boost::format. As a bonus won't have to mess with allocating buffers on the stack and worrying that the result might be longer than the buffer (which may lead to buffer overruns and security exploits - sprintf() is probably the culprit behind many of those...).
std::stringstream
std::stringstream filebuf;
filebuf << current_path().c_str() << _UserDir;
std::string filename = filebuf.str();

boost::format
std::string filename = "%s%s" % current_path().c_str() % _UserDir;

By the way, if you just want to concatenate directories, the 'proper' way to do that with boost::filesystem::path would be:
boost::filesystem::path fullPath = current_path() / _UserDir;

Yes, the / operator is used for adding path components. They are separated by slashes after all, aren't they?
That being said, if you still choose, against all good advice, to use the old C library functions, please, for all that's good in the world, don't use sprintf(). Use the slightly-safer snprintf(), which takes the maximum buffer size as an argument.

A: In the standard sprintf() function (and the other printf()-like functions), the %s specifier doesn't work with C++ stringss; it only works with C-style strings. Try _UserDir.c_str(), which gives you a const char * that points to the internal array of the string and can therefore be used with many C functions.
If current_path() returns something that is not a (possibly const) pointer to char or unsigned char, you need to convert that value too.

A: Some of your code is unclear (e.g., what on earth is a path type?), but it looks like you're trying to print a std::string via a C-style string formatter (sprintf %s), which is totally invalid.
Look at std::stringstream.  Also, for simple concatenation, std::string provides a + operator overload.  So you could be doing simply:
current + "/" + whatever

A: sprintf only works with char*, you cannot use it with strings. Try _UserDir.c_str() and you should be fine.

A: What I don't understand is why your compiler doesn't complain.  You can't pass non-POD types like std::string or boost::filepath as varargs; my compiler says that this will abort at runtime, and any compiler will know here that you're passing class types to a vararg.  (Formally, it's undefined behavior, but unless the compiler defines it somehow as an extention, then there's no reason for it not to at least warn.)

A: current is not a char* pointer, it is a path so it might lead to complication
also, sprintf can't print to string variables like you are trying to do.

A: How long is current_path? Maybe strlen(current_path)+strlen(_UserDir)+2 > 256.

A: Since _UserDir is a C++ string, you'll need to get its C string to call sprintf(), which is a C function.
sprintf(filebuf,"%s/%s",current,_UserDir.c_str());  // gets C string

Also, what is a path? If it isn't like a typedef for char*, then you can't just sprintf() that either. It may be that operator<<() is overloaded for path, which is why the std::cout works.

A: %s indicates a C string. You have a C++ string. You need to call .c_str()

A: The reason of the crash has already been explained - I can only add one piece of advice - just ditch sprintf if possible and use string streams. It will make your code better. You will not have to worry about the length of the buffer or other errors like the one you encountered.


text:
Q: How to find the main function's entry point of elf executable file without any symbolic information? I developed a small cpp program on platform of Ubuntu-Linux 11.10.
Now I want to reverse engineer it. I am beginner. I use such tools: GDB 7.0, hte editor, hexeditor.
For the first time I made it pretty easy. With help of symbolic information I founded the address of main function and made everything I needed.
Then I striped (--strip-all) executable elf-file and I have some problems.
I know that main function starts from 0x8960 in this program.
But I haven't any idea how should I find this point without this knowledge.
I tried debug my program step by step with gdb but it goes into  __libc_start_main
then into the ld-linux.so.3 (so, it finds and loads the shared libraries needed by a program). I debugged it about 10 minutes. Of course, may be in 20 minutes I can reach the main function's entry point, but, it seems, that more easy way has to exist.
What should I do to find the main function's entry point without any symbolic info?
Could you advise me some good books/sites/other_sources from reverse engineering of elf-files with help of gdb?
Any help would be appreciated.

A: As far as I know, once a program has been stripped, there is no straightforward way to locate the function that the symbol main would have otherwise referenced.
The value of the symbol main is not required for program start-up: in the ELF format, the start of the program is specified by the e_entry field of the ELF executable header.  This field normally points to the C library's initialization code, and not directly to main.
While the C library's initialization code does call main() after it has set up the C run time environment, this call is a normal function call that gets fully resolved at link time.
In some cases, implementation-specific heuristics (i.e., the specific knowledge of the internals of the C runtime) could be used to determine the location of main in a stripped executable.  However, I am not aware of a portable way to do so.

A: Locating main() in a stripped Linux ELF binary is straightforward. No symbol information is required.
The prototype for __libc_start_main is
int __libc_start_main(int (*main) (int, char**, char**),
                      int argc,
                      char *__unbounded *__unbounded ubp_av,
                      void (*init) (void),
                      void (*fini) (void),
                      void (*rtld_fini) (void),
                      void (*__unbounded stack_end));

The runtime memory address of main() is the argument corresponding to the first parameter, int (*main) (int, char**, char**). This means that the last memory address saved on the runtime stack prior to calling __libc_start_main is the memory address of main(), since arguments are pushed onto the runtime stack in the reverse order of their corresponding parameters in the function definition.
One can enter main() in gdb in 4 steps:

*

*Find the program entry point

*Find where __libc_start_main is called

*Set a break point to the address last saved on stack prior to the call to _libc_start_main

*Let program execution continue until the break point for main() is hit

The process is the same for both 32-bit and 64-bit ELF binaries.
Entering main() in an example stripped 32-bit ELF binary called "test_32":
$ gdb -q -nh test_32
Reading symbols from test_32...(no debugging symbols found)...done.
(gdb) info file                                  #step 1
Symbols from "/home/c/test_32".
Local exec file:
    `/home/c/test_32', file type elf32-i386.
    Entry point: 0x8048310
    < output snipped >
(gdb) break *0x8048310
Breakpoint 1 at 0x8048310
(gdb) run
Starting program: /home/c/test_32

Breakpoint 1, 0x08048310 in ?? ()
(gdb) x/13i $eip                                 #step 2
=> 0x8048310:   xor    %ebp,%ebp
   0x8048312:   pop    %esi
   0x8048313:   mov    %esp,%ecx
   0x8048315:   and    $0xfffffff0,%esp
   0x8048318:   push   %eax
   0x8048319:   push   %esp
   0x804831a:   push   %edx
   0x804831b:   push   $0x80484a0
   0x8048320:   push   $0x8048440
   0x8048325:   push   %ecx
   0x8048326:   push   %esi
   0x8048327:   push   $0x804840b                # address of main()
   0x804832c:   call   0x80482f0 <__libc_start_main@plt>
(gdb) break *0x804840b                           # step 3
Breakpoint 2 at 0x804840b
(gdb) continue                                   # step 4
Continuing.

Breakpoint 2, 0x0804840b in ?? ()                # now in main()
(gdb) x/x $esp+4
0xffffd110: 0x00000001                           # argc = 1
(gdb) x/s **(char ***) ($esp+8)
0xffffd35c: "/home/c/test_32"                    # argv[0]
(gdb)

Entering main() in an example stripped 64-bit ELF binary called "test_64":
$ gdb -q -nh test_64
Reading symbols from test_64...(no debugging symbols found)...done.
(gdb) info file                                  # step 1
Symbols from "/home/c/test_64".
Local exec file:
    `/home/c/test_64', file type elf64-x86-64.
    Entry point: 0x400430
    < output snipped >
(gdb) break *0x400430
Breakpoint 1 at 0x400430
(gdb) run
Starting program: /home/c/test_64

Breakpoint 1, 0x0000000000400430 in ?? ()
(gdb) x/11i $rip                                 # step 2
=> 0x400430:    xor    %ebp,%ebp
   0x400432:    mov    %rdx,%r9
   0x400435:    pop    %rsi
   0x400436:    mov    %rsp,%rdx
   0x400439:    and    $0xfffffffffffffff0,%rsp
   0x40043d:    push   %rax
   0x40043e:    push   %rsp
   0x40043f:    mov    $0x4005c0,%r8
   0x400446:    mov    $0x400550,%rcx
   0x40044d:    mov    $0x400526,%rdi            # address of main()
   0x400454:    callq  0x400410 <__libc_start_main@plt>
(gdb) break *0x400526                            # step 3
Breakpoint 2 at 0x400526
(gdb) continue                                   # step 4
Continuing.

Breakpoint 2, 0x0000000000400526 in ?? ()        # now in main()
(gdb) print $rdi
$3 = 1                                           # argc = 1
(gdb) x/s **(char ***) ($rsp+16)
0x7fffffffe35c: "/home/c/test_64"                # argv[0]
(gdb)

A detailed treatment of program initialization and what occurs before main() is called and how to get to main() can be found be found in Patrick Horgan's tutorial "Linux x86 Program Start Up
or - How the heck do we get to main()?"

A: If you have a very stripped version, or even a binary that is packed, as using UPX, you can gdb on it in the tough way as:
$ readelf -h echo | grep Entry
Entry point address:               0x103120

And then you can break at it in GDB as:
$ gdb mybinary
(gdb) break * 0x103120
Breakpoint 1 at 0x103120gdb)
(gdb) r
Starting program: mybinary
Breakpoint 1, 0x0000000000103120 in ?? ()

and then, you can see the entry instructions:
(gdb) x/10i 0x0000000000103120
=> 0x103120:    bl      0x103394
  0x103124: dcbtst  0,r5
  0x103128: mflr    r13
  0x10312c: cmplwi  r7,2
  0x103130: bne     0x103214
  0x103134: stw     r5,0(r6)
  0x103138: add     r4,r4,r3
  0x10313c: lis     r0,-32768
  0x103140: lis     r9,-32768
  0x103144: addi    r3,r3,-1

I hope it helps


text:
Q: Should you include the word "the" inside a quoted/emphasized words? I'm having a bit of trouble regarding whether to include the word "the" inside a quoted words.
For example:
None was known when the Great Cataclysm had happened on the other hand.
Should I emphasize it like this:
None was known when the "Great Cataclysm" had happened on the other hand.
or
None was known when "The Great Cataclysm" had happened on the other hand.
Other than that, I have one more extra question regarding emphasizing.
Sometime I see a lot of emphasizing with italic and quotation.
I know that the one with quotation are words that's unfamiliar and weird without being quoted.
As for the one with italic, it is oftentimes used in simple word being emphasized like to-be, adverb, and many other.
But is it always been the case like this?
Any help is appreciated.

A: At Grammarbook com, https://data.grammarbook.com/blog/quotation-marks/italics-vs-quotation-marks/,

Nori K. says: August 24, 2014, at 5:07 pm My understanding was that, the first time you use, say, a term of art [edit: i.e. a specialised word/phrase, name, etc., or one that has a meaning or significance different from the usual one], you set it off in quotation marks. For example, you might write that a "record of survey" is a document in which a surveyor records material discrepancies with earlier surveys. When you use the term after that, my understanding is that you don't keep using the quotation marks.

To which the response is

"... the Oxford Guide to Style, which is more useful, says, "Use quotation marks to enclose an unfamiliar word or phrase, or one to be used in a technical sense. The effect is similar to that of highlighting the term through italics …
Most often quotation marks should be used only at the first occurrence of the word or phrase in a work; thereafter it may be considered to be fully assimilated."

Thus, in your case, there should be a sentence explaining the Great Catalclysm, e.g. In 20,000 BC, the "Great Cataclysm" occurred: the Great Cataclysm was the event that destroyed Atlantis.
Following this statement, and in your example, it will therefore be "None was known when the Great Cataclysm had happened on the other hand."
The the is not capitalised unless it is the first word of the title (or, obviously, the sentence.) This is because the the is simply a required determiner:
"I have told you about the Great Cataclysm and why I do not think that there will be another Great Cataclysm" <- Note how unnatural "there will be Another Great Cataclysm" looks.


text:
Q: KQL - Ignoring items with property not equal to value I have to configure the site search so that it does not include items wich have a property of ModerationStatus != 1. I found out that using a query like ModerationStatus <> 1 can probably solve my problem, but I am not sure if it will work in my environment since not all possible search items have this property of ModerationStatus. Can someone show me an example query that might work in such case? I am kinda new to KQL.

A: So I think I figured it out. I'd have to white two queries combined like this:
(ContentTypeId: 'ContentType that has ModerationStatus' ModerationStatus <> 1) OR (ContentTypeId <> 'ContentType that has ModerationStatus')
I apologize for the dumb question.


text:
Q: Javascript - How to move focus from one textbox to another in Javascript after the previous text box is filled? I am writing one Javascript code
Please see the images. There are 4 text boxes where only one character can be entered .
The rightmost field's id is first and the leftmost id is fourth
4 conditions are to be fulfilled
The last text box - the rightmost/first textbox will be input first, then the second one will be filled , then the third and at last the fourth
Then the rightmost/first textbox value will shift (left shift) to the second and in this way values will shift until all 4 fields are filled  - See screenshot Insert
If we place the cursor on any other element except the first/rightmost it will move the cursor to the rightmost because we will only enter input in the rightmost
There will be backspace function which will delete the rightmost/first , ie. the the first field will be deleted the fourth field value will move to third, third to second , like this , a right shift will occur in this way all elements are to be deleted  - see Screenshot Delete
In delete the cursor is not staying in rightmost position , I have place the cursor again & again to delete  - Please again refer Screenshot Delete
During insertion - When the value will move to second from first the second one should remain focus ,right now the first one/rightmost is always remaining focused , i mean during insertion the cursor will always stay in the first but the focus should move from right to left one by one
The entire solution should be in Javascript , no JQuery can be used
Screenshot Insert
Screenshot Delete

var myInputs = document.getElementsByTagName("input");
var myEditable = document.getElementById("first");

for (var i = 0; i < myInputs.length; i++) {
  myInputs[i].addEventListener("click", function() {
    document.getElementById("first").focus();
  })
}

myEditable.addEventListener("keydown", function(evt) {
  /****
   *  A few things are handled here: we can check if
   *  the input is a numeric, and we can check if the input
   *  is a backspace. Nothing else is allowed.
   ****/
  if (evt.which == 8) {
    // If a backspace has been pressed, move all the input
    //  values one field UP.
    myEditable.blur();
    for (var i = myInputs.length - 1; i >= 1; i--) {
      myInputs[i].value = myInputs[i - 1].value;
    }
    myInputs[0].value = "";
  } else if (evt.which >= 48 && evt.which <= 59) {
    // Here, we have a number. Everything gets shifted to the LEFT

    if (myInputs[0].value == "") {
      for (var i = 0; i < myInputs.length - 1; i++) {
        myInputs[i].value = myInputs[i + 1].value;
      }
      myEditable.value = String.fromCharCode(evt.which);
    }
  } else {
    console.log("Sorry");
  }
});
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>

<body>
  <form>
    <input type="text" id="fourth" size="1" maxlength="1" />
    <input type="text" id="third" size="1" maxlength="1" />
    <input type="text" id="second" size="1" maxlength="1" />
    <input type="text" id="first" size="1" maxlength="1" />
  </form>
</body>

</html>

A: Have  look to this.
HTML:
<input type="text" id="input3" onfocus="HandleFocus(this)" onkeypress="return HandleKeys(event, this)" value="" style="width:40px">
<input type="text" id="input2" onfocus="HandleFocus(this)" onkeypress="return HandleKeys(event, this)" value="" style="width:40px">
<input type="text" id="input1" onfocus="HandleFocus(this)" onkeypress="return HandleKeys(event, this)" value="" style="width:40px">
<input type="text" id="input0" onfocus="HandleFocus(this)" onkeypress="return HandleKeys(event, this)" value="" style="width:40px">

Javascript:
function HandleFocus(obj)
{
    if (obj.id.indexOf("0")==-1) {
    document.getElementById("input0").focus();
  }
}

var content = "";
function HandleKeys(e, obj)
{
    if (obj.id.indexOf("0")!=-1)
  {
    var c = e.which;
    if ( (c==8)&&(content.length>0) ) {
        content = content.substr(0, content.length -1);
    } else if ( (c>=48)&&(c<=57)&&(content.length<4) ) {
        content += String.fromCharCode(c);
    }
    for (var i=0; i<4; i++)
        document.getElementById("input" + i.toString()).value = (i>=content.length) ? "" : content[content.length-1-i];
  }
   return false;
}

You can run it in JSfiddle


text:
Q: UWP navigation memory leak We have noticed that our UWP apps have memory leaks. I have investigated it and found out that when navigating to new pages, the memory gets higher and doesn't seem to go down by much even when GC runs.
I have put together a small repro that consists of two pages:

*

*MainPage

<Page>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="70" />
            <RowDefinition  />
        </Grid.RowDefinitions>

        <Button x:Name="navigateButton" Content="Navigate" HorizontalAlignment="Center"
                    Click="NavigateButton_Click" />

        <Frame x:Name="mainFrame" IsNavigationStackEnabled="False"
               Padding="10" Grid.Row="1" />
    </Grid>
</Page>

    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }

        private void NavigateButton_Click(object sender, RoutedEventArgs e)
        {
            mainFrame.Navigate(typeof(Page1), null, new Windows.UI.Xaml.Media.Animation.DrillInNavigationTransitionInfo());
        }
    }

*Page1:

<Page>
    <VariableSizedWrapGrid ItemWidth="100" ItemHeight="60">
        <Button Padding="20, 10" Content="Hello!"/>
        <Button Padding="20, 10" Content="Hello!"/>
        <Button Padding="20, 10" Content="Hello!"/>
        <Button Padding="20, 10" Content="Hello!"/>
        <Button Padding="20, 10" Content="Hello!"/>

        <!-- And 25 more buttons here -->
    </VariableSizedWrapGrid>
</Page>

    public sealed partial class Page1 : Page
    {
        public Page1()
        {
            this.InitializeComponent();
        }

        ~Page1()
        {
            Debug.WriteLine("Page dead :(");
        }
    }

The full source code is available on GitHub.
And you can see a video of the repro.
I have also tried out setting Frame.IsNavigationStackEnabled to false, it doesn't help.
What am I doing wrong here?

A: I am using Windows 1803 because I have not the latest 1809 but I think it works the same,
In the code of Page 1:
 protected override void OnNavigatedFrom(NavigationEventArgs e)
    {
        base.OnNavigatedFrom(e);

        System.GC.Collect();
    }

It is another way to check if the App has to dispose the Pages. and it works.


text:
Q: How to import JavaScript into RoR project with Rubymine? I am having an issue using JQuery in my RoR project in Rubymine. I am new to Ruby on Rails and want bootstrap-sass in my project.
I followed the instructions from here, which is the Github bootstrap repository. I am using rails6.0.0.
And I have the following snippet in my application.html.erb:

      <button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#main-nav-collapse">
        Toggle navigation

      </button>
      <%= link_to 'SaaS', root_path, class: 'navbar-brand' %>

<%= link_to "Login", '#' %>

A navbar-button is generated when the width drops below about 600px, however, when I click it, it does not give me the collapsed list. So I am assuming the problem is with the JQuery support.
These are the gems I imported for the JQuery support.
gem 'jquery-rails'
gem 'bootstrap-sass', '~> 3.4.1'
gem 'sassc-rails', '>= 2.1.0'

And the imports in my application.scss:
@import "bootstrap-sprockets";
@import "bootstrap";

My require statements for my application.js:
require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
//= require jquery
//= require bootstrap-sprockets

I have restarted my server several times and ran bundle install. I, also, do not get any error when running the server or while clicking the button.
Edit:
When adding the require statements to application.js, the directory stated  here is different from my application.js directory.
Directory in instruction app/assets/javascripts/application.js.
My directory app/javascript/packs/application.js.
I created the directory asked for in the instructions and put the the require statements there.

A: Apart from adding the jquery-rails and bootstrap-sass gems to the Gemfile and adding the imports to the application.scss file, you need to include the javascripts for jquery and bootstrap in the application.js file. These steps are also mentioned in the docs if you go through them clearly.
application.js
//= require jquery
//= require bootstrap-sprockets

If you are using sass make sure you delete the default application.css file generated in a new rails project.

A: ok so in rails 6 you will notice the use of the javascript folder app/javascript this means that anything you do with JS should be done from there. The reliance on gems for these is now minimal and replaced by yarn.
what you are missing is the yarn install.
this is a process I like to use which I have modified from something i read on medium a while back
# app/javascript/packs/application.js
import '../stylesheets/application'

# app/views/layouts/application.html.erb
<%= stylesheet_pack_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>

in the console run
yarn add bootstrap@4.3.1 jquery popper.js

then
# config/webpack/environment.js
...
const webpack = require('webpack')
environment.plugins.append(
  'Provide',
  new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery',
    Popper: ['popper.js', 'default']
  })
)
...

then
# app/javascript/packs/bootstrap_custom.js
import 'bootstrap/js/dist/alert'
import 'bootstrap/js/dist/button'
import 'bootstrap/js/dist/carousel'
import 'bootstrap/js/dist/collapse'
import 'bootstrap/js/dist/dropdown'
import 'bootstrap/js/dist/index'
import 'bootstrap/js/dist/modal'
import 'bootstrap/js/dist/popover'
import 'bootstrap/js/dist/scrollspy'
import 'bootstrap/js/dist/tab'
import 'bootstrap/js/dist/toast'
import 'bootstrap/js/dist/tooltip'
import 'bootstrap/js/dist/util'

And link it in your app/javascript/packs/application.js file.
# app/javascript/packs/application.js
import './bootstrap_custom.js'

then
# app/javascript/stylesheets/application.scss
@import './bootstrap_custom.scss'

then
# app/javascript/stylesheets/bootstrap_custom.scss
@import '~bootstrap/scss/_functions.scss';
@import '~bootstrap/scss/_variables.scss';
@import '~bootstrap/scss/_mixins.scss';
@import '~bootstrap/scss/_root.scss';
@import '~bootstrap/scss/_reboot.scss';
@import '~bootstrap/scss/_type.scss';
@import '~bootstrap/scss/_alert.scss';
@import '~bootstrap/scss/_badge';
@import '~bootstrap/scss/_breadcrumb';
@import '~bootstrap/scss/_button-group';
@import '~bootstrap/scss/_buttons';
@import '~bootstrap/scss/_buttons.scss';
@import '~bootstrap/scss/_card.scss';
@import '~bootstrap/scss/_carousel.scss';
@import '~bootstrap/scss/_close.scss';
@import '~bootstrap/scss/_code.scss';
@import '~bootstrap/scss/_custom-forms.scss';
@import '~bootstrap/scss/_dropdown.scss';
@import '~bootstrap/scss/_forms.scss';
@import '~bootstrap/scss/_grid.scss';
@import '~bootstrap/scss/_images.scss';
@import '~bootstrap/scss/_input-group.scss';
@import '~bootstrap/scss/_jumbotron.scss';
@import '~bootstrap/scss/_list-group.scss';
@import '~bootstrap/scss/_media.scss';
@import '~bootstrap/scss/_modal.scss';
@import '~bootstrap/scss/_nav.scss';
@import '~bootstrap/scss/_navbar.scss';
@import '~bootstrap/scss/_pagination.scss';
@import '~bootstrap/scss/_popover.scss';
@import '~bootstrap/scss/_print.scss';
@import '~bootstrap/scss/_progress.scss';
@import '~bootstrap/scss/_spinners.scss';
@import '~bootstrap/scss/_tables.scss';
@import '~bootstrap/scss/_toasts.scss';
@import '~bootstrap/scss/_tooltip.scss';
@import '~bootstrap/scss/_transitions.scss';
@import '~bootstrap/scss/_utilities.scss';

If you choose to follow this follow it precisely, do not change the scss lines etc it will mess it up


text:
Q: Error in Hive Command Prompt while executing DESC FORMATTED Command I have a requirement where I need to get the CREATE TABLE statements for all the External table.
I used the script provided by other developers on StackOverflow and made changes for getting CREATE TABLE Statement
#Command to Execute sh ScriptName.sh <Hive_database_name>
#Create external table list for a schema
SCHEMA=$1

#define filenames
alltableslist=tables_$SCHEMA
exttablelist=ext_tables_$SCHEMA

#Get all tables Line 12
 hive -S -e " set hive.cli.print.header=false; use $SCHEMA; show tables;" 1> $alltableslist

sed -i '/WARN:/d' $alltableslist
#For each table check its type:
for table in $(cat $alltableslist)
 do

     #Describe table- line no 20
     describe=$(hive -S -e "use $SCHEMA; DESCRIBE FORMATTED $table")

     #Get type
     table_type=$(echo "${describe}" | egrep -o 'Table Type:[^,]+' | cut -f2)
     # echo $table "-" $table_type
     #Check table type, get create table statement
      if [ $table_type == EXTERNAL_TABLE ]; then
         echo Processing table $table ...
         #get CREATE TABLE SCRIPT and save results
         hive -e "use $1;show create table $SCHEMA.$table" >> $exttablelist
         echo  -e ";\n" >> $exttablelist
      fi

done; #tables loop
sed -i '/WARN:/d' $exttablelist

The script working fine till line no 12, and I got the list of all the tables in the Hive Database.
But the script fails at line no 20, giving below error.
Logging initialized using configuration in file:/etc/hive/2.6.5.3016-3/0/hive-log4j.properties
OK
Time taken: 1.871 seconds
NoViableAltException(13@[1453:5: ( ( KW_DATABASE | KW_SCHEMA )=> ( KW_DATABASE | KW_SCHEMA ) ( KW_EXTENDED )? (dbName= identifier ) -> ^( TOK_DESCDATABASE $dbName ( KW_EXTENDED )? ) | ( KW_FUNCTION )=> KW_FUNCTION ( KW_EXTENDED )? (name= descFuncNames ) -> ^( TOK_DESCFUNCTION $name ( KW_EXTENDED )? ) | ( KW_FORMATTED | KW_EXTENDED | KW_PRETTY )=> ( (descOptions= KW_FORMATTED |descOptions= KW_EXTENDED |descOptions= KW_PRETTY ) parttype= partTypeExpr ) -> ^( TOK_DESCTABLE $parttype $descOptions) |parttype= partTypeExpr -> ^( TOK_DESCTABLE $parttype) )])
        at org.antlr.runtime.DFA.noViableAlt(DFA.java:158)
        at org.antlr.runtime.DFA.predict(DFA.java:144)
        at org.apache.hadoop.hive.ql.parse.HiveParser.descStatement(HiveParser.java:18250)
        at org.apache.hadoop.hive.ql.parse.HiveParser.ddlStatement(HiveParser.java:4182)
        at org.apache.hadoop.hive.ql.parse.HiveParser.execStatement(HiveParser.java:1786)
        at org.apache.hadoop.hive.ql.parse.HiveParser.statement(HiveParser.java:1152)
        at org.apache.hadoop.hive.ql.parse.ParseDriver.parse(ParseDriver.java:211)
        at org.apache.hadoop.hive.ql.parse.ParseDriver.parse(ParseDriver.java:171)
        at org.apache.hadoop.hive.ql.Driver.compile(Driver.java:447)
        at org.apache.hadoop.hive.ql.Driver.compile(Driver.java:330)
        at org.apache.hadoop.hive.ql.Driver.compileInternal(Driver.java:1233)
        at org.apache.hadoop.hive.ql.Driver.runInternal(Driver.java:1274)
        at org.apache.hadoop.hive.ql.Driver.run(Driver.java:1170)
        at org.apache.hadoop.hive.ql.Driver.run(Driver.java:1160)
        at org.apache.hadoop.hive.cli.CliDriver.processLocalCmd(CliDriver.java:217)
        at org.apache.hadoop.hive.cli.CliDriver.processCmd(CliDriver.java:169)
        at org.apache.hadoop.hive.cli.CliDriver.processLine(CliDriver.java:380)
        at org.apache.hadoop.hive.cli.CliDriver.processLine(CliDriver.java:315)
        at org.apache.hadoop.hive.cli.CliDriver.executeDriver(CliDriver.java:712)
        at org.apache.hadoop.hive.cli.CliDriver.run(CliDriver.java:685)
        at org.apache.hadoop.hive.cli.CliDriver.main(CliDriver.java:625)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.apache.hadoop.util.RunJar.run(RunJar.java:243)
        at org.apache.hadoop.util.RunJar.main(RunJar.java:158)
FAILED: ParseException line 1:15 cannot recognize input near 'FORMATTED' '_1xy_abcde00005' '<EOF>' in describe statement

I have total 75000 tables in the database, and around 1000 tables like _1xy_abcde00005
Can you please help?


text:
Q: What is the mysql function to show 5 most frequent records in a specific time frame? Using 3 tables My database tables and fields:
table author
AuthorID pk
AuthorFirstName
AuthorLastName
AuthorNationality

table book
bookid pk
booktitle
bookauthor fk from author.authorid
genre

table borrower
borrowid
clientid pk
bookid fk from book.bookid
borrowdate

table client
clientid fk from borrower.clientid
clientfirstname
clientlastname
clientdob
occupation

I am trying to get the First and Last names of the top 5 authors from the books that clients most borrowed during 2017. So I would think that I would select the author first and last name, inner join the author table with the book table focusing on the author id, and then inner joining the book table with the borrower table, focusing on the bookid which could lead to bookauthor and identify the name of the author. I am not sure if I am wrong in this.
So this is what I tried, to get the top 5 most popular authors among all the borrowed books.
select Author.AuthorFirstName, Author.AuthorLastName, Borrower.Bookid, Count(Borrower.BorrowId) as numberofborrows
from Author
inner join Book
on  Author.AuthorId = Book.BookAuthor
inner join Borrower
on Book.BookId = Borrower.BookId
where BorrowDate between '2017-01-01' and '2017-12-31'
limit 5

This gives me an error, error code 1140. But I am not sure if this is the correct way.
This is what I tried to get all the author names between the year of 2017, I did not include the code for top 5 authors from the books that were most borrowed:
select Author.AuthorFirstName, Author.AuthorLastName
from Author inner join Book on  Author.AuthorId = Book.BookAuthor
inner join Borrower on Book.BookId = Borrower.BookId
where BorrowDate between '2017-01-01' and '2017-12-31'

This code did work and gave me the names of the Authors from borrows that ocurred during 2017. How do I mix the between function with a function that could display names of the 5 authors that had most borrows from their written books during 2017?

A: Starting from your working query you of course need to join the book ids to. However in your attempt you simply joined the borrows without any further means; then trying to count the borrow ids, if it did work, would yield 1 (one) for any column anyway. What you instead need to do is grouping the results to appropriate sub-sets:
GROUP BY Author.AuthorFirstName, Author.AuthorLastName, Book.Bookid

Now all books are collected in sub-sets on which you can count the borrower.borrowid.
However these sets might appear in any order and you might get any first five books; limit 5 will only be of use if you sort the results by the count of borrows:
ORDER BY numberofborrows DESC

So the whole query might look as follows (note: untested; if you find a bug, please fix yourself):
select
  Author.AuthorFirstName, Author.AuthorLastName, Book.Bookid,
  Count(Borrower.BorrowId) as numberofborrows
from Author
  inner join Book on Author.AuthorId = Book.BookAuthor
  inner join Borrower on Book.BookId = Borrower.BookId
where BorrowDate between '2017-01-01' and '2017-12-31'
GROUP BY Author.AuthorFirstName, Author.AuthorLastName, Book.Bookid
ORDER BY numberofborrows DESC
limit 5


text:
Q: How to remove author or commiter in git how can I prevent of adding two author and commiter in github when make a commit. I have the same author and the same commiter person. I checked my global .config file and there are person info. How to remove from git commits one of them.

A: I apologize if I misunderstand your question - as I'm sure you realize, the phrasing is a bit unclear.
I think you're saying that the committer is always the same person as the author, and so you don't want to have the commit store both pieces of information.  That is impossible; a commit always stores both an author and a committer.  They can be, and often are, the same; but that's fine, and they still both have to be specified.
I'm not sure why this would be a problem.  No meaningful amount of space is used, and it's handled automatically.  Even if it doesn't help in any way for your repo today, if the project ever has multiple contributors then it can be important (e.g. if one contributor rebases another's commits); and, again, in the meantime it doesn't hurt anything.
If you need help configuring the two values so that they are the same / both correct, please refer to the git config documentation


text:
Q: How to translate these kind of phrases? I am confused in translating some kind of phrases such as below :
Which one of the pairs is true? If both, What is the difference? and what is the meaning of the phrase? (I mean if I want to explain the phrase what I must say?)

*

*Security function requirement interfering actions

*Security function requirement interfered actions

*Security function requirement enforcing actions

*Security function requirement enforced actions

Update :
I want to translate the below paragraph in persian. But I don't understant the ...ing words in the bold phrases return to which one of the words in back!
Note : SFR = Sequrity Function Requirement

The purpose of this work unit is to supplement the details about the
  SFR-enforcing actions (provided in work unit ADV_FSP.3-6) with a
  summary of the remaining actions (i.e., those that are not
  SFR-enforcing). This covers all SFR-supporting and SFR-non-interfering
  actions, whether invokable through SFR-enforcing TSFI or through
  SFR-supporting or SFR-non-interfering TSFI. Such a summary about all
  SFR-supporting and SFR-non-interfering actions helps to provide a more
  complete picture of the functions provided by the TSF, and is to be
  used by the evaluator in determining whether an action or TSFI may
  have been mis-categorised.

A: The -ing forms of enforce, interfere, and support are used here to create adjectives. For example,

SFR-enforcing actions

refers to actions which enforce the SFR. Two simple and more familiar examples for this construction are the adjectives "ground-breaking" (derived from "to break ground"), and "breath-taking".
All four variants given in your question are in principle correct. However,
an

SFR-enforced action

is an action that has been enforced by the SFR, as compared to an action that enforces the SFR (which would be an SFR-enforcing action).
Note that the hyphen is quite useful because it indicates that "SFR" and "enforcing" are joined together to form the adjective "SFR-enforcing". Finally, using the abbreviation SFR also makes the expression much easier to understand.


text:
Q: How to set a DTO's property value directly in LINQ select statement Deal all,
Assume I have a XML file and I need to parse it to objects (DTOs). Example:
<Root>
  <Item>
    <X>1</X>
    <Y>2</Y>
  <Item>
</Root>

And I have a DTO object:
public class Item
{
  public int X{get;set;}
  public int Y{get;set;}
  public int Z{get;set;}
}

To create a Item object, I need to know X and Y, and I will set Z = X*Y
I use LINQ to parse XML to objects:
XDocument reportDoc = XDocument.Load(@"Report.xml");
var query = from item in reportDoc.Element("Root").Descendants()
select new Item()
{
   X = Convert.ToInt32(item.Element("X").Value),
   Y = Convert.ToInt32(item.Element("Y").Value)
   // Z = X*Y -> I can't do this by this statement
};

Please help me how to set value to Z property directly in LINQ select statement. Thanks.

A: You can use the let clause to declare intermediate variables:
XDocument reportDoc = XDocument.Load(@"Report.xml");
var query = from item in reportDoc.Element("Root").Descendants()
let x = Convert.ToInt32(ticket.Element("X").Value)
let y = Convert.ToInt32(ticket.Element("Y").Value)
select new Item()
{
   X = x,
   Y = y
   Z = x * y
};


text:
Q: Do I need 2 NIC cards to forward public IP to private IP? To use NAT do I need 2 nic cards? I want to use my server for my own business (I don't require VPN) and simply need to forward my public IP to the private IP so that websites show up as www.upnorthsound.co.uk and not the private IP of the machine.
I'm new to this and thank you in advance for your patience towards newbies like myself!
Regards, Jay.

A: How many NICs you need depends on the structure and number of networks which you want to be connected to. That's independent of NAT. You don't need an additional NIC for NAT, not even for routing.
It's generally not useful to ask something like that without any information about the configuration. Have a look at the FAQ so that you can improve this and future questions.

A: No you don't need 2 nic's.
But you do need a router to do the NAT and to separate your LAN from the internet.
You are obviously not familiar enough with the concepts.
That makes putting your server onto the Wild-West of the Internet very risky.
The best advice I can give is that you get a professional to look at your situation and advice on the best (security wise) approach for your business.