text:
Q: Erro na utilização dos filter_input no PHP Olá, pessoal. Tenho um  e estou tentando tratar os dados dele no arquivo php. (Estou utilizando AJAX para enviar para o arquivo PHP).
A consulta era realizada normalmente antes de eu colocar os filter_input. Porém, após colocá-los, a consulta não é mais realizada.
Vocês conseguem apontar um erro que eu esteja cometendo na utilização dos filtros.
Imagem do form abaixo:

Código HTML

<form id="formulario-consulta">

Filtrar por atividade :

      <select name="prioridade" id="prioridade" class="input-sm form-control">
        <option value="Todos" selected>TODOS</option>
        <option value="Comum">COMUM</option>
        <option value="Extra">EXTRA</option>
        <option value="Urgente">URGENTE</option>
      </select>

Filtrar por data de:

      <select name="data" id="data" class="input-sm form-control">
        <option value="inicio">INÍCIO</option>
        <option value="finalizacao">FINALIZAÇÃO</option>
        <option value="vencimento" selected>VENCIMENTO</option>
      </select>

De:

    <input type="date" name="dataInicial" id="dataInicial" class="col-xs-12 input-sm form-control ">

Até:

    <input type="date" name="dataFinal" id="dataFinal" class="col-xs-12 input-sm form-control">

Código

      <select name="cod" id="cod" class="input-sm form-control">
        <option></option>
        <?php
          while($linha_cod = mysqli_fetch_assoc($lista_cod))
          {
         ?>
          <option id="<?php echo $linha_cod['EMPRESAS'];?>" value="<?php echo $linha_cod[" COD "];?>">
            <?php echo $linha_cod["COD"]; ?>
          </option>
          <?php
          }
         ?>
      </select>

Cliente

      <select name="empresas" id="empresas" class="input-sm form-control">
        <option></option>
        <?php
         while($linha_empresas = mysqli_fetch_assoc($lista_empresas))
         {
         ?>
          <option id="<?php echo $linha_empresas['COD'];?>" value="<?php echo $linha_empresas[" EMPRESAS "];?>">
            <?php echo $linha_empresas["EMPRESAS"];?>
          </option>

          <?php
          }
         ?>
      </select>

Tributação

    <select name="tributacao" id="tributacao" class="input-sm form-control">
      <option></option>
      <?php
         while($linha_tributacao = mysqli_fetch_assoc($lista_tributacao))
         {
        ?>
        <option value="<?php echo $linha_tributacao[" TRIBUTACAO "];?>">
          <?php echo $linha_tributacao["TRIBUTACAO"];?>
        </option>

        <?php
         }
        ?>
    </select>

Atividade

      <select name="atividade" id="atividade" class="input-sm form-control">
        <option></option>
        <?php
          while($linha_atividade = mysqli_fetch_assoc($lista_atividade))
          {
         ?>
          <option value="<?php echo $linha_atividade[" TIPO_ATIVIDADE "];?>">
            <?php echo $linha_atividade["TIPO_ATIVIDADE"]; ?>
          </option>

          <?php
          }
         ?>
      </select>

Status

    <select name="status" id="status" class="input-sm form-control">
      <option></option>
      <?php
          while($linha_status = mysqli_fetch_assoc($lista_status))
          {
         ?>
        <option value="<?php echo $linha_status[" STATUS "];?>">
          <?php echo $linha_status["STATUS"]; ?>
        </option>

        <?php
          }
         ?>
    </select>

    <input type="hidden" name="botao-click-dashboard" id="botao-click-dashboard">

Pesquisar

    <input name="enviar" id="enviar" class="btn btn-sm btn-primary  btn-block  form-control" type="submit" value="Buscar">

</form>

Código dos filtros:

<?php

//PREENCHE AS VARIÁVEIS COM OS DADOS VINDOS DOS CAMPOS DO FORMULÁRIO

filter_input(INPUT_POST, 'dataInicial', FILTER_SANITIZE_STRING);

$pegaropcao   = filter_input(INPUT_POST, 'prioridade', FILTER_SANITIZE_STRING);
$tipodedata = filter_input(INPUT_POST, 'data', FILTER_SANITIZE_STRING);
//$dataInicial = !empty($_POST["dataInicial"]) ? $_POST["dataInicial"] : null;
$dataInicial = !empty($_POST["dataInicial"]) ? filter_input(INPUT_POST, 'dataInicial', FILTER_SANITIZE_STRING) : null;
//$dataFinal  = !empty($_POST["dataFinal"]) ? $_POST["dataFinal"] : null;
$dataFinal = !empty($_POST["dataFinal"]) ? filter_input(INPUT_POST, 'dataFinal', FILTER_SANITIZE_STRING) : null;
$cod = filter_input(INPUT_POST, 'cod', FILTER_SANITIZE_STRING);
//$empresas   = !empty($_POST["empresas"]) ? $_POST["empresas"] : "";
$empresas   = !empty($_POST["empresas"]) ? filter_input(INPUT_POST, 'empresas', FILTER_SANITIZE_STRING) : "";
//$tributacao = !empty($_POST["tributacao"]) ? $_POST["tributacao"] : "";
$tributacao = !empty($_POST["tributacao"]) ? filter_input(INPUT_POST, 'tributacao', FILTER_SANITIZE_STRING) : "";
//$atividade  = !empty($_POST["atividade"]) ? $_POST["atividade"] : "";
$atividade = !empty($_POST["atividade"]) ? filter_input(INPUT_POST, 'atividade', FILTER_SANITIZE_STRING) : "";

$status = filter_input(INPUT_POST, 'status', FILTER_SANITIZE_STRING);
$condicao = filter_input(INPUT_POST, 'botao-click-dashboard', FILTER_SANITIZE_STRING);
if(is_string($_SESSION["nome"])){
 $responsavel = $_SESSION["nome"];
}else{
 die("A SESSION[nome] não tem caracter String");
 exit;
}
?>

A: Existe um filter_input solto, sem objetivo na primeira linha do seu código.
Qual o objetivo do: filter_input(INPUT_POST, 'dataInicial', FILTER_SANITIZE_STRING); Ele deve ser removido do código.
Depois, tire o filter_input que está dentro da condição ternária. Faça o tratamento antes, ficando assim:
 $dataInicial = filter_input(INPUT_POST, 'dataInicial', FILTER_SANITIZE_STRING);

 $dataInicial = (!empty($_POST["dataInicial"])) ? $dataInicial : null;

Depois verifique também os campos que são numérico e estão sendo tratados como string, veja alguns filtros em: https://www.php.net/manual/en/filter.filters.sanitize.php
Fora os filtros, vc pod eutilizar as flags de cada tipo de filtro:
O filtro FILTER_SANITIZE_STRING remove tags e remove ou codifica caracteres especiais de uma string.
Possíveis opções e flags:

FILTER_FLAG_NO_ENCODE_QUOTES - Não codifica aspas
FILTER_FLAG_STRIP_LOW - Remove caracteres com valor ASCII < 32
FILTER_FLAG_STRIP_HIGH - Remove caracteres com valor ASCII > 127
FILTER_FLAG_ENCODE_LOW - Codifica caracteres com valor ASCII < 32
FILTER_FLAG_ENCODE_HIGH - Codifica caracteres com valor ASCII > 127
FILTER_FLAG_ENCODE_AMP - Encode o caractere "&" para &

Ex:
filter_var($str, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);


text:
Q: What is the (co)limit of a Quiver? Given that a Quiver (also known as directed multigraphs) is so important in category theory, being that every Quiver produces a free Category, and every Category has an underlying Quiver, I was wondering what a limit of a Quiver is. (See also the nice overview of Quivers and Diagrams in the answer on finding the limits of a diagram)
So if I take a category with two objects E and V and two functions s,t: E → V which given the start and end edges of vertices, then I should be able to have a functor from that to sets, which determines a quiver. Then all I need is to add a constant functor to some object of set say $L$ - the putative limit - and then find the real one. So for each vertex of the diagram, $v$, we have an arrow $p_v:L\to D(v)$. In this case it would be  have the equations $p_V = s \circ p_E$,  $p_V = t \circ p_E$. Which leads to $s \circ p_E = t \circ p_E$.
What would the co-version be? I suppose we turn the arrows around
$p_v: D(v) \to L$ giving us $p_E = p_V \circ s$ and $p_E = p_V \circ t$, and so $p_V \circ s = p_V \circ t$
(I'd like to also ask what Monad one could build with the Free and Underlying Functors, but I guess that should be a different question).

A: (Co)limits of this form are called (co)equalizers.  In sets, an equalizer of a functor $D$ from your category is just given by the set $L=\{x\in D(E): D(s)(x)=D(t)(x)\}$ with its inclusion map to $D(E)$.  (So, in terms of quivers, it is just the set of loops.)  Coequalizers are a bit more complicated, but a coequalizer can be constructed as the quotient of $D(V)$ by the smallest equivalence relation $\sim$ such that $D(s)(x)\sim D(t)(x)$ for all $x\in D(E)$.  (In terms of quivers, this quotient is the set of connected components of the quiver.)
Note that colloquially, one typically just speaks of the (co)equalizer of a pair of morphisms $f,g:A\to B$ in some category, without talking about a functor explicitly.  This refers to the (co)limit of the functor from your category which sends $E$ to $A$, $V$ to $B$, and $s$ and $t$ to $f$ and $g$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I avoid NullPointerException warning in this Java lambda expression code? How can I avoid NullPointerException warning in this Java code?
I am working with IntelliJ and I am getting this warning:

Method Invocation 'getChartController()' may produce
  'java.Lang.NullPointerException'"

chartControlButtons.add(
    new JButton("Zoom In") {{
        addActionListener(
            (ActionEvent e) -> getChartController().zoomIn()
        );
    }}
);

A: You can use optional to avoid NullPointerExceptions.
Following is a kind of optional use this case.
     chartControlButtons.add(
        new JButton("Zoom In") {{
          addActionListener(
              (ActionEvent e) -> Optional.ofNullable(getChartController()).ifPresent(s -> s.zoomIn())
          );
        }}
    );


text:
Q: Free video converter where I can choose video/audio codec? I'm looking for free (or < 10$) video converter on mac with following features:
Another features which are welcome:

*

*option to choose file format (.mpg, .avi etc)

*option to choose video/audio encoding (xvid, h264, acc etc)

*option to always save output to the same directory the source is in

*batch processing of many files

*possibility to set created/modified time of created file to the same as source has

A: Have you checked out HandBrake? Looks to have what you are looking for...

A:
Free and OpenSource VLC media player supports video encoding

A: Miro Video Converter:
Convert almost any video to MP4, WebM (vp8), Ogg Theora, or for Android, iPhone, and iPad. Batch conversion, custom sizing, and more.
Available for Linux, OS X & Windows


text:
Q: Fail to publish GP as a service I have no idea what the issue is here, I created this scripting tool which works fine when I run it through ArcGIS desktop. However, for some reason, I am unable to publish the tool as a service.The following is the error (00178) that I keep receiving:
"Data: \, used by script cannot be copied to the server". The script is very simple as it is just doing a simple calculation derived from a feature class which is currently stored on the SDE geodatabase. I've already looked through the documentation and none of the solution seems to resolve my issue.
    import arcpy, csv, datetime

    output = arcpy.GetParameterAsText(0)
    DATA = r'C:\!PROD_Connections_SDE\PROD@ABC.sde\ABC.PROD.S2_testbuild\ABC.PROD.ABC_testline'

    #table = arcpy.MakeFeatureLayer_management(DATA,"data")

    # Map of UTM Zone WKIDs, modify as needed
    utmZones = {10: 32610,
        11: 32611,
        12: 32612,
        13: 32613}

        pLength = 0.0
        hLength = 0.0

       def getUTMZone(geometry):
       #http://gis.stackexchange.com/questions/13291/computing-utm-zone-from-lat-long-point
           from math import floor
           geo = geometry.projectAs(arcpy.SpatialReference(4326))
           lon = geo.trueCentroid.X
           return int(floor((lon + 180)/6) + 1)

       with arcpy.da.SearchCursor(DATA,["SHAPE@","Activity"]) as cur:
           for row in cur:
               utmZone = getUTMZone(row[0])
               sr = arcpy.SpatialReference(utmZones[utmZone])

               # Project line to correct UTM zone and add its length to the correct sum
               geom = row[0].projectAs(sr)
               if row[1] == "HDD":
                   hLength += geom.length
               else:
                   pLength += geom.length

       # Write data to CSV
       with open(output,'wb') as outFile:
           date = datetime.datetime.today()
           headers = ("Date","P Total Length (m)","H Total Length (m)")
           record = (str(date),str(plength),str(hlength))
           writer = csv.writer(outFile)
           writer.writerow(headers)
           writer.writerow(record)

A: The analyser likes to pick out random items and claim the script is using them, for example this post on Geonet.
I got round the problem by putting the SDE connection file on a network share that the server could also see and referencing it with a full UNC path:
INWorkspace = r"\\store\UTILITIES\SDE Connections\xxx_geodb.sde"


text:
Q: segmentation fault in ONP Here is my code for the problem id-4 in spoj, it is running perfectly in ideone.com but in spoj its showing segmentation fault, I am unable to find out the bug.Please help. I have used stacks to implement it.Thanks in advance.
exp is the input string, and out is the output string, int l keeps track of the index of output string
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//declarations
int top = 0;
void push(char ch);
char pop();
int prec(char c);
char stack[20];
char out[20];
int l = 0;

int main() {
    char exp[20];
    int x, t;
    char temp;
    int i = 0;
    scanf("%d", &t);      //no. of test cases
    while (t--) {
      l=0;
        scanf("%s", exp);
        stack[0] = '(';   //initially pushing '('
        x = strlen(exp);
        exp[x] = ')';     //for completion of statement

        for (i = 0; i < x + 1; i++) {
            if (exp[i] == '+' || exp[i] == '-' ||
                exp[i] == '/' || exp[i] == '*' || exp[i] == '^') {   //operators
                while (prec(exp[i]) < prec(stack[top])) { //checking precedence
                    out[l] = pop();
                    l++;
                }
                push(exp[i]);
            } else
            if (exp[i] == '(') {
                push(exp[i]);
            } else
            if (exp[i] == ')') {
                while (stack[top] != '(') {
                    out[l] = pop();
                    l++;
                }
                temp = pop();     //to throw out '('
            } else {
                out[l] = exp[i];  //variables
                l++;
            }
        }
        for (i = 0; i < l; i++) {
            printf("%c", out[i]);         //output
        }
    }
    return 0;
}

void push(char c) {            //push operation on stack
    if (top >= 19) {
    } else {
        top++;
        stack[top] = c;
    }
    return;
}

char pop() {              //pop operation on stack
    char t;
    if (top <= -1) {
        return 0;
    } else {
        t = stack[top];
        top--;
        return t;
    }
}

int prec(char c) {                           //precedence check
    if (c == 94) { return 5; }
    else if (c == 47) { return 4; }
    else if (c == 42) { return 3; }
    else if (c == 43) { return 2; }
    else if (c == 45) { return 1; }
    else { return 0; }
}

A: You have to check if top is greater or equal 0:
while( top >= 0 && prec(exp[i])<prec(stack[top])){
//     ^^^^^^^^
....
while( top >= 0 && stack[top]!='('){
//     ^^^^^^^^

The segmentation fault occurs, because you access to stack[top] and top is less than 0. Apart form this I recommend to increase the size of arrays exp and out coherently.

A: The buffer to read the expression is very small: char exp[20]; and you do not protect scanf for buffer overflow.
Sphere Online Judge specifies:

Input

t [the number of expressions <= 100]
    expression [length <= 400]
    [other expressions]

You should use a larger stack, at least 100, a larger buffer and use:
char exp[402];
...
scanf("%400s", exp);

Also test the return value from scanf("%d", &t), just in case they give you purposely erroneous input.


text:
Q: JavaScript - Binding a function to an Event to an element returns an error? I don't know what's wrong here, but what do you think is wrong?
I have this very simple JavaScript function, which, when executed directly to
the Inspect Element console works perfectly, but when I bind it to an event, then
it returns the error "Uncaught TypeError: object is not a function". What do you think is
wrong here?
Here's the function.
var pass_sh_busy = 0;
var pass_sh = function(y) {
if(pass_sh_busy) {
        document.getElementById('pass_sh').type = 'password';
        document.getElementById('pass_sh').placeholder = '********';
        pass_sh_busy = 0;
    } else {
        pass_sh_busy = 1;
        document.getElementById('pass_sh').type = 'text';
        document.getElementById('pass_sh').placeholder = 'password';
    }
}

pass_sh is this...
<input name="rass" id="pass_sh" placeholder="*********" type="password">

Here's my binded element.
<input style="width:5%" type="button" onclick="pass_sh()">

This is a very weird error I think. What do you think is wrong here?

A: The problem is that you have an element with ID pass_sh. Elements with IDs will create global variables with the ID referring to that element. So pass_sh inside the HTML attribute seems to refer to the DOM element instead of your function.
Either give the element a different ID or your function a different name.

FYI, there are more flexible ways to bind event handlers.


text:
Q: SSlv3 open.urllib handshake failure so I have some software who uses webscraping, but for some reason it doesn't seem to work. It's bizarre because when I run it in Google Colab, the code works fine and the url's can open and be scraped, but when I run it in my web application (and run it on my console using python3 run.py) it doesn't work.
Here is the code that is returning errors :
      b = searchgoogle(query, num)
      c = []
      print(b)
      for i in b:
          extractor = extractors.ArticleExtractor()
          headers = {
              'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) '
                            'Chrome/50.0.2661.102 Safari/537.36'
          }
          extractor = extractors.ArticleExtractor()
          req = Request(url=i, headers=headers)
          d = urlopen(req)
          try:
            if d.info()['content-type'].startswith('text/html'):
                  print ('its html')
                  resp = requests.get(i, headers=headers)
                  if resp.ok:
                      doc = extractor.get_content(resp.text)
                      c.append(comparetexts(text,doc,i))
                  else:
                      print(f'Failed to get URL: {resp.status_code}')
            else:
                    print ('its not html')
          except KeyError:
            print( 'its not html')
          print(i)
  return c

The code returning errors is the "d = urlopen(req)"
There is code above the section I just put here but it has nothing to do with the errors. Anyways, thanks for your time!
(By the way, I checked my OPEN SSL version on python3 and it says : 'OpenSSL 1.1.1m  14 Dec 2021' so I think it's up to date)

A: This happens because your web application does not have SSL certification, so you should tell your script to ignore SSL verification when making the request, as specified here:
Python 3 urllib ignore SSL certificate verification


text:
Q: How can I display all the data from a table? How can I display all the data from a table inside a table tag using loops?
Here is my code:

                     <?php echo $left_bread['recipe'];?>
                     <?php echo $left_bread['name'];?>
                     <?php echo $left_bread['scale_date'];?>

A: i think your code is lacking..from what i see it lacks a foreach(). maybe you should try this,
<?php foreach($your_variable as $your_alias):?>

    <?php echo $your_alias['recipe'];?>
    <?php echo $your_alias['name'];?>
    <?php echo $your_alias['scale_date'];?>

<?php endforeach;?>

I think that's it, if what you want is display data dynamically from a query, then this will do, knowing that $your_variable contains a query which will get recipe,name and scale_date. :)

A: you need to use foreach  to acces your data ..
//$data for example contains your fetched results from the database

// this will lopp until it contains results
<?php
foreach( $data as $left_bread ) {

 <?php echo $left_bread['recipe'];?>
<?php echo $left_bread['name'];?>
<?php echo $left_bread['scale_date'];?>

}

  ?>


text:
Q: User form has cells that need autocomplete for common values I need to have a list that autocomplete values into a cell. With the way the form is setup I can't list and hide them at the bottom because the comments cell is empty until the end.
Is there a way to make a dynamic list within a cell that makes autocomplete work within an adjacent cell?
One cell example is Name. If someone enters their name and it has been entered before it should autocomplete. If it is a new name, it should store it for the next time.
I made a macro to do this and put spaces in all the empty cells in the column to make them "not empty". Unfortunately the form will have things that aren't filled out already that create an empty cell.
Sub WhiteRabbit()
'
'Macro WhiteRabbit

'
    'Turn off screen updating and unprotect worksheet
    Application.ScreenUpdating = False
    Sheets("Entry Form").Select
    ActiveSheet.Unprotect
'**********++++++++++============BEGIN GRABBING INFO============++++++++++**********
'COLUMN B COLUMN B COLUMN B COLUMN B COLUMN B COLUMN B COLUMN B COLUMN B COLUMN B COLUMN B COLUMN B
'----------------COLUMN B Grab info----------------
    Sheets("Entry Form").Select
    Range("B7").Select '(Grab B7 Tech Name)
    Selection.Copy
'Add to Auto List Column B
    Sheets("Entry Form").Select
    Range("B25").Select
    Selection.End(xlDown).Select 'Go to last item
        ActiveCell.Offset(1, 0).Range("A1").Select 'then one more to the next blank spot
    'Paste value with invisible formatting
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    ActiveCell.Offset(0, 1).Range("A1").Select
        'Selection.NumberFormat = ";;;"
'----------------END COLUMN B Grab info-------------

'============Remove Duplicates from Column B============
Range("B25").End(xlDown).Select
ActiveSheet.Range("B25", Range("B25").End(xlDown)).RemoveDuplicates Columns:=1, Header:=xlNo

'Add color back to Any that had it removed
Range(Selection, Selection.End(xlUp)).Select
    'Range(Selection, Selection.End(xlUp)).Select
    With Selection.Interior
        .PatternColorIndex = xlAutomatic
        .ThemeColor = xlThemeColorAccent1
        .TintAndShade = 0.799981688894314
        .PatternTintAndShade = 0
    End With
    Selection.NumberFormat = ";;;"
'============End Remove Duplicates from Column B=========
'COLUMN B COLUMN B COLUMN B COLUMN B COLUMN B COLUMN B COLUMN B COLUMN B COLUMN B COLUMN B COLUMN B

'COLUMN D COLUMN D COLUMN D COLUMN D COLUMN D COLUMN D COLUMN D COLUMN D COLUMN D COLUMN D COLUMN D
'----------------COLUMN D Grab info----------------
    Sheets("Entry Form").Select
    Range("D13").Select '(Grab D13 UNIT)
    Selection.Copy
'Add to Auto List Column D
    Sheets("Entry Form").Select
    Range("D25").Select
    Selection.End(xlDown).Select 'Go to last item
        ActiveCell.Offset(1, 0).Range("A1").Select 'then one more to the next blank spot
    'Paste value with invisible formatting
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    ActiveCell.Offset(0, 1).Range("A1").Select
        'Selection.NumberFormat = ";;;"
'----------------END COLUMN D Grab info-------------

'============Remove Duplicates from Column D============
Range("D25").End(xlDown).Select
ActiveSheet.Range("D25", Range("D25").End(xlDown)).RemoveDuplicates Columns:=1, Header:=xlNo

'Add color back to Any that had it removed
Range(Selection, Selection.End(xlUp)).Select
    'Range(Selection, Selection.End(xlUp)).Select
    With Selection.Interior
        .PatternColorIndex = xlAutomatic
        .ThemeColor = xlThemeColorAccent1
        .TintAndShade = 0.799981688894314
        .PatternTintAndShade = 0
    End With
    Selection.NumberFormat = ";;;"
'============End Remove Duplicates from Column D=========
'COLUMN D COLUMN D COLUMN D COLUMN D COLUMN D COLUMN D COLUMN D COLUMN D COLUMN D COLUMN D COLUMN D

'COLUMN F COLUMN F COLUMN F COLUMN F COLUMN F COLUMN F COLUMN F COLUMN F COLUMN F COLUMN F COLUMN F
'----------------COLUMN F Grab info----------------
    Sheets("Entry Form").Select
    Range("F9").Select '(Grab F MODEL)
    Selection.Copy
'Add to Auto List Column F
    Sheets("Entry Form").Select
    Range("F25").Select
    Selection.End(xlDown).Select 'Go to last item
        ActiveCell.Offset(1, 0).Range("A1").Select 'then one more to the next blank spot
    'Paste value with invisible formatting
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    ActiveCell.Offset(0, 1).Range("A1").Select
        'Selection.NumberFormat = ";;;"
'----------------END COLUMN F Grab info-------------

'============Remove Duplicates from Column F============
Range("F25").End(xlDown).Select
ActiveSheet.Range("F25", Range("F25").End(xlDown)).RemoveDuplicates Columns:=1, Header:=xlNo

'Add color back to Any that had it removed
Range(Selection, Selection.End(xlUp)).Select
    'Range(Selection, Selection.End(xlUp)).Select
    With Selection.Interior
        .PatternColorIndex = xlAutomatic
        .ThemeColor = xlThemeColorAccent1
        .TintAndShade = 0.799981688894314
        .PatternTintAndShade = 0
    End With
    Selection.NumberFormat = ";;;"
'============End Remove Duplicates from Column D=========
'COLUMN F COLUMN F COLUMN F COLUMN F COLUMN F COLUMN F COLUMN F COLUMN F COLUMN F COLUMN F COLUMN F

'**********++++++++++============END GRABBING INFO============++++++++++**********
'Reprotect Sheet
ActiveSheet.Protect DrawingObjects:=False, Contents:=True, Scenarios:= _
        False
Range("B7").Select
ActiveWorkbook.Save
    Application.ScreenUpdating = True
End Sub

Thank you for your response @DisplayName.
I have almost no experience with activex combo boxes.
I like where your code is going though.
Your code is great, I just need it to work with tabbing.

A: If I'm correctly guessing what you want to do, then I'd say you call for an "on-the-fly" ActiveX ComboBox
what follows assumes that:

*

*you don't have any ActiveX combobox in your sheet already
actually you must not have any ActiveX control or any linked or embedded OLE object in the sheet

*you don't have a Worksheet_Change event handling in your sheet code pane
then you may try putting the following code in the "Entry Form" sheet code pane (explanations in comments)
Option Explicit

Private Sub Worksheet_SelectionChange(ByVal target As Range)
    If OLEObjects.Count > 0 Then 'check for any existing activeX combobox already in the sheet
        With OLEObjects("myDD") ' if so, then reference the combobox you must have put through this code (see below)
            If .Object.ListIndex = 0 Then ' if no elements selected in the combobox list
                Range(.LinkedCell).ClearContents ' then clear the content of the cell you linked to the combobox through this code (see below)
            Else 'otherwise
                Range(.LinkedCell).Value = .Object.Value ' fill the content of the cell linked to the combobox with this latter selected value
                ListUpdate Range(.LinkedCell) 'try and update the range from which combobox will be filled with
            End If
            .Delete ' delete the combobox and leave underneath cell visible
        End With
    End If

    If target.Count <> 1 Then Exit Sub ' if selection is not a single cell then exit
    If Intersect(target, Range("B7, D13, F9")) Is Nothing Then Exit Sub ' if selection is not one of the form entry cells then exit

    With target 'reference selected cell
        If IsEmpty(Cells(25, .Column).Value) Then Exit Sub ' if no values available fot the current entry cell then exit sub

        With ActiveSheet.OLEObjects.Add(ClassType:="Forms.ComboBox.1", Link:=False, DisplayAsIcon:=False, _
                                        Left:=.Left, Top:=.Top, Width:=.Width, Height:=.Height) ' add and reference a new ActiveX combobox
            .Name = "myDD" 'name it as "myDD"
            .ListFillRange = Range(Cells(25, target.Column), Cells(Rows.Count, target.Column).End(xlUp)).Address ' fill its range with already available values
            .LinkedCell = target.Address ' link it to the selected cell
        End With
    End With
End Sub

Sub ListUpdate(target As Range)
    If IsEmpty(Cells(25, target.Column).Value) Then Exit Sub ' if no values available fot the current entry cell then exit sub
    With Range(Cells(25, target.Column), Cells(Rows.Count, target.Column).End(xlUp)) ' reference values already available
        If .Find(what:=target.Value, lookat:=xlWhole, LookIn:=xlValues) Is Nothing Then .Offset(.Rows.Count).Resize(1).Value = target.Value ' if new entered value not in the referenced values range already, then add it at the bottom of the list
    End With
End Sub


text:
Q: How to use 'apt' to get source code and then do separate compile I want to get the source code for a project and then build it the same way that apt would.  E.g. I want the working source code and be able to run 'make' or similar command on the source.
How can I do that?
Specifically I want to get this source 'icedtea-6-jre-jamvm'

A: to just compile the package use the debian/rules script which is provided in each debain package:
sudo apt-get build-dep <package>
apt-get source <package>
cd <package>_<version>
./debian/rules binary

this just does the configure and the compile part.

A: You can use the follwing :
apt-get source <package>

you need to make sure you install the build dependencies :
sudo apt-get build-dep <package>

for more info run :
man apt-get

Alternative option :First you need to know the location of the package.
then download the tar file using :
sudo wget <url>

You can then untar it and compile it using make
if your not sure about the specific command look inside of the folder, there should be a README file or INSTALL which will tell you the appropriate command .

A: For this example I'll use icedtea-6-jre-jamvm as the package you want to rebuild.
First install all the dependencies and build essential:
sudo apt-get build-dep icedtea-6-jre-jamvm
sudo apt-get install build-essential

Then grab the source:
apt-get source icedtea-6-jre-jamvm

Then cd in the openjdk directory directory and build the deb, the -us and -uc here skip the GPG checks if you're just rebuilding it for yourself:
cd openjdk-6-6b24-1.11.5
dpkg-buildpackage -us -uc

Then go up a directory and you should have .deb files.
Sources:

*

*http://www.debian.org/doc/manuals/maint-guide/build.en.html


text:
Q: Why does my adt emulator does not show the activity using menu? I don't see any errors in my code, and I did what the tutorial taught me. I'm quite new to android and new member here(please be gentle).
Sorry guys for not clearing up my question.
The thing is when i click the menu button on the right side of the emulator the menu shows.. yes it shows the inflate  but every time i choose one of those menu nothing happens , it doesnt do anything at all.
Anyway here's the code for the java :
 public boolean onCreateOptionsMenu(Menu menu) {
 super.onCreateOptionsMenu(menu);
 //inflates the menu
 MenuInflater awesome = getMenuInflater();
awesome.inflate(R.menu.main, menu);

return true;
 }

  public boolean onOptionItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuSweet:
    startActivity(new Intent("Sweet"));
    return true;

case R.id.menuToast:
    Toast andEggs = Toast.makeText(MainActivity.this,
    "This is a toast", Toast.LENGTH_LONG);
    andEggs.show();
    return true;

}
return false;

   }`

Heres the xml in res/menu :
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

 <item
 android:id="@+id/menuSweet"
 android:alphabeticShortcut="s"
 android:title="Open Sweet Activity"
 android:onClick="@layout/about" />

 <item
 android:id="@+id/menuToast"
 android:alphabeticShortcut="t"
 android:title="Open Toast Activity" />

 </menu>

Heres the manifest :
    <activity
        android:name=".Sweet"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.Dialog"

         >
        <intent-filter>
            <action android:name="Sweet" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
      </activity>

A: You probably need to add the default case in your switch tatement i.e.
default:  return super.onOptionsItemSelected(item);

And I don't think there is any need of return false; ..   Remove it also .

A: The second method should be called:
onOptionsItemSelected

instead of:
onOptionItemSelected

There is a missing "s" in method's name.


text:
Q: VSCode Flutter refuses to indent with 4 spaces I find it incredibly distracting to code with 2 spaces indentation, so I always set my indentation size to 4 spaces, however, on this flutter project, the indentation stays at 2 spaces, no matter what I change, it refuses to be 4 spaces... (this applies to all files, not just the main.dart file)

I've tried setting indentation spaces to 4 from 2 (https://stackoverflow.com/a/37077167/15586166 and https://stackoverflow.com/a/51398290/15586166) but even when it is set to 4 spaces for Dart specific projects (the json file), workspace settings (assuming frontend for json file) and in the VSCode user settings tab, it goes back to 2 spaces on format (or rather the settings stays at 4 spaces, but it still formats at 2 spaces). I do not have a .editorconfig, so I couldn't change it there. I've also disabled detect indentations (https://stackoverflow.com/a/43809036/15586166) on all the levels I did with the indentations sizes.

Could it be that dart_style (which I am assuming is formatting the code), enforces 2 spaces indentations? If it is, is it possible to change it?

Although, taking a look through its code, it shouldn't be enforcing 2 spaces, like this function. (see image)

I also only have these 2 extensions for Dart/Flutter, and only Prettier formatter (only other formatter), but disabling it does not fix the issue...


text:
Q: How to run or load .po/.mo files for localization in php I have installed poedit and running my file through it, it creates .po and .mo files for them. But I have a problem to load and use these files for translating my text. I don't know how to load or open the translated files and to show the translated content.
Can anyone help me about this. I tried every possible source but not succeeded.

A: First of all you need to inform PHP which locale and domain you are using.
putenv("LANG=da_DK");
setlocale('LC_ALL', "da_DK");
bindtextdomain("mycatalog", "./locale/");
textdomain("mycatalog");

In this case I'm having a Danish translation and a file called mycatalog.mo (and .po). These files are placed (from your root) here: locale/da_DK/LC_MESSAGES/mycatalog.mo/po
In order to show your translation, you will do this:
echo _("Hello world");   // Which would become "Hej verden"

_(); is an alias of gettext(); The smart thing about gettexts is that if there's no translation you will not have an ugly language code like "MSG_HELLO_WORLD" in your UI, but instead a better alternative: Simply the plain English text.
In the messages.po file you must have all the messages (case-sensitive and also with respect to used commas, dots, colons, etc.) on this form:
msgid "Hello world!"
msgstr "Hej verden!"

When you have added this to your .po file, you open this file in poedit, hit "Save" and it will generate a .mo file. This file is uploaded to the same directory as the .po file (typically something like \locale\da_DK\LC_MESSAGES\ from the script root)
To translate dynamic/variable content you can use - among other things - sprintf, in this manner:
echo sprintf(_("My name is %s"), $name);

In this case the %s will occur in the .po file; When you have the translated string (which contains the %s), sprintf will make sure to replace the %s with the variable content. IF the variable must be translated too, you can do this:
echo sprintf(_("The color of my house is %s"), _($color));

Then you don't need a full sentence for every color, but you still get the colors translated.
It is important to note that the first time a .mo is run on the server it is cached - and there is no way of removing this file from the cache without restarting (Apache or the like itself should be enough). This means that any changes you make to the .mo after the first time it is used, will not be effective. There are a number of hacks to work around this, but honestly, they are mostly not very pretty (they include copying the .mo, add the time() behind it and then import and cache it again). This last paragraph is only of importance if you aren't going to translate the whole thing at once, but in chunks.
If you want to create your own translation tool at some point, this tool helps you convert .po to .mo using PHP:
http://www.josscrowcroft.com/2011/code/php-mo-convert-gettext-po-file-to-binary-mo-file-php/

A: See (and explore) http://php.net/manual/en/book.gettext.php. There are user-comments on that page that should give you an idea on how to procede.
Also, your question is a duplicate of Get translations from .po or .mo file


text:
Q: Can I override MaterialBanner widget to change its height? I was dealing with the ScaffoldMessenger.of(context).showMaterialBanner method and it needs a MaterialBanner widget as parameter.
Goal
In my case I need to put an empty MaterialBanner widget but with a custom height (less than default).
In few words override the original MaterialBanner build method.
What I tried
so I thought that I had to extend a StatefulWidget implementing MaterialBanner:
class MiniBanner extends StatefulWidget implements MaterialBanner {
  const MiniBanner({Key? key}) : super(key: key);

  @override
  List<Widget> get actions => [const SizedBox()];

  @override
  Animation<double>? get animation => null;

  @override
  Color? get backgroundColor => Colors.amber;

  @override
  Widget get content => const SizedBox();

  @override
  TextStyle? get contentTextStyle => null;

  @override
  double? get elevation => 0;

  @override
  bool get forceActionsBelow => false;

  @override
  Widget? get leading => null;

  @override
  EdgeInsetsGeometry? get leadingPadding => EdgeInsets.zero;

  @override
  VoidCallback? get onVisible => null;

  @override
  OverflowBarAlignment get overflowAlignment => OverflowBarAlignment.end;

  @override
  EdgeInsetsGeometry? get padding => EdgeInsets.zero;

  @override
  MaterialBanner withAnimation(Animation<double> newAnimation, {Key? fallbackKey}) {
    return MaterialBanner(
      key: key ?? fallbackKey,
      content: content,
      contentTextStyle: contentTextStyle,
      actions: actions,
      elevation: elevation,
      leading: leading,
      backgroundColor: backgroundColor,
      padding: padding,
      leadingPadding: leadingPadding,
      forceActionsBelow: forceActionsBelow,
      overflowAlignment: overflowAlignment,
      animation: newAnimation,
      onVisible: onVisible,
    );
  }

  @override
  State<MiniBanner> createState() => _MiniBannerState();
}

class _MiniBannerState extends State<MiniBanner> {
  @override
  Widget build(BuildContext context) {
    // I want the code to go here to build a smaller MaterialBanner
    return Container(
      color: widget.backgroundColor,
      height: 10,
    );
  }
}

But my code keep going to the original MaterialBanner method.
Maybe I'm missing some knowledge about extending stateful widgets.

A: Solved
The main issue was the return type of the "withAnimation" method. It has to be the same type of your custom widget.
So:
class MiniBanner extends StatefulWidget implements MaterialBanner {
  const MiniBanner({
    Key key,
    this.content = const SizedBox(),
    this.contentTextStyle,
    this.actions = const [SizedBox()],
    this.elevation = 0,
    this.leading,
    this.backgroundColor = Colors.red, //custom default color
    this.padding = EdgeInsets.zero,
    this.leadingPadding = EdgeInsets.zero,
    this.forceActionsBelow = false,
    this.overflowAlignment = OverflowBarAlignment.end,
    this.animation,
    this.onVisible,
  })  : assert(elevation == null || elevation >= 0.0),
        assert(content != null),
        assert(actions != null),
        assert(forceActionsBelow != null),
        super(key: key);

  @override
  final List<Widget> actions;

  @override
  final Animation<double> animation;

  @override
  final Color backgroundColor;

  @override
  final Widget content;

  @override
  final TextStyle contentTextStyle;

  @override
  final double elevation;

  @override
  final bool forceActionsBelow;

  @override
  final Widget leading;

  @override
  final EdgeInsetsGeometry leadingPadding;

  @override
  final VoidCallback onVisible;

  @override
  final OverflowBarAlignment overflowAlignment;

  @override
  final EdgeInsetsGeometry padding;

  @override
  MiniBanner withAnimation(Animation<double> newAnimation, {Key fallbackKey}) {
    return MiniBanner(
      key: key ?? fallbackKey,
      content: content,
      contentTextStyle: contentTextStyle,
      actions: actions,
      elevation: elevation,
      leading: leading,
      backgroundColor: backgroundColor,
      padding: padding,
      leadingPadding: leadingPadding,
      forceActionsBelow: forceActionsBelow,
      overflowAlignment: overflowAlignment,
      animation: newAnimation,
      onVisible: onVisible,
    );
  }

  @override
  State<MiniBanner> createState() => MiniBannerState();
}

class MiniBannerState extends State<MiniBanner> {
  @override
  Widget build(BuildContext context) {
    // Now our MiniBanner correctly build this method
    return Container(
      color: widget.backgroundColor,
      height: 10,
    );
  }
}

Important note
This code is not null sound safety so if you have a Flutter application with null sound safety enabled you have to change some syntax, like adding ? after the nullable properties and so on.
UPDATE
If you want to really emulate the original MaterialBanner with all the animations, you have to copy almost the entire original "build" method.
Then, to custom your widget, you just have to edit the assignment of materialBanner variable, example:
// other parts of code copied from original build method above

Widget materialBanner = Container(
  color: widget.backgroundColor,
  height: 10,
);

// other parts of code copied from original build method below


text:
Q: How to derive exterior and/or interior Schwarzschild solution using Feynman excess radius equation? Feynman excess radius equation for a uniformly dense spherical body is
$R-\sqrt{\frac{A}{4\pi } } = \frac{G}{3c^{2}} M$
Where $R$ is the radius directly measured by digging a hole in the body, $ A $ is the surface area of the body and $M$ is its mass.
I tried to use this equation, coupled with the fact that exterior gravitation due to a uniformly dense spherical body does not depend upon the radius of the body, to derive schwarzschild solution.
This is what I did:
$R-x = M$ (where $ x= \sqrt{\frac{A}{4\pi } }$  ($x$ is the predicted radius); and $\frac{G}{3c^{2}}=1$.)
$\Rightarrow R-x=g\int 4\pi x^{2} dR,$ (where $g$ is the density of the body)
$\Rightarrow 1-\frac{dx}{dR} =4\pi gx^{2}$
$ \Rightarrow \frac{dR}{dx} =\frac{1}{1-4\pi gx^{2}} $
My idea was to calculate, for every value of $x$, the value of  $\frac{dR}{dx}$, for different values of density $g$, such that for every value of $x=a$, $ g.\int ^{a}_{0}4\pi x^{2}dR=M=constant $. So i would get  $\frac{dR}{dx}$ in the form of $x$ for every value of $x=a$, and integrate it to get the solution.
But many disasters happened in this scheme. Let me summarize by saying that, according to my understanding of Feynman excess radius equation, one needs infinite mass to create an event horizon around a uniformly dense spherical body. In other words,  $\frac{dx}{dR}=0$ if and only if $R=\infty$. Which does not makes sense.
So, the question is, how will you derive the exterior and/or interior schwarzschild solution using excess radius equation?

A: In addition to my comments and the answer of @Raja. There is actually a way to derive parts of the Schwarzschild solution using the exact expression for the excess:
$$S=a \arcsin(\frac ar).$$
If you think of the excess as a distance measured instant in time and radially inward ($\Rightarrow 0=dt=d\theta=d\phi$) the equation for $S$ in general becomes:
$$S=\int_0^R \frac {dr}{g_{rr}}.$$
This means if you take the derivative of the exact expression for $S$ you can extract $g_{rr}$ of the interior Schwarzschild solution:
$$\frac{dS}{dr}\equiv\frac{1}{g_{rr}}=\frac{1}{\sqrt{1-r^2/a^2}}.$$
This only works with the exact expression and only gives you one metric potential, since $g_{tt}$ has nothing to do with the excess you can not extract it form it.
That all being said I am not to happy with this "derivation": I mean you get back to the interior Schwarzschild solution but only to one part of it and by using a very special equation.
I derived the interior Schwarzschild solution recently because I needed it to benchmark numerical code, which solves the TOV equation. One can derive the TOV equation without the Schwarzschild solution because of that I think a nice way to derive the exterior and interior Schwarzschild solution is to do it starting from the TOV equation. Getting the exterior solution is trivial and getting the interior solution can be done by integrating the remaing equation for $dP/dr$, once one puts in $M(r)=4\pi/3\rho_c r^3$. Or one could follow Schwarzschild's original way, which does not use the TOV equation at all. However the original derivation is much more involved then just integrating the TOV equation.
Personally I see the exterior and interior Schwarzschild solution as special, analytical solutions of the underling TOV equation anyway.

A: I found a solution to this question. Feynman's excess radius equation is wrong. I found the proof of this in Hartle's book 'gravity' (example 7.6, page no.147).
This example in Hartle's book describes the spacetime curvature of a uniformly dense star using following polar equation:
$ dS^{2}=\frac{{dr}^{2}}{1-\frac{{r}^{2}}{{a} ^{2}}} +r^{2}\left( d\theta ^{2}+\sin \nolimits^{2}\theta d\phi ^{2}\right) $
Where $a$ is a constant depending only on the density of the star.
Now, following this, the book gives the formula of the actual radius $S$ of the star, measured directly by digging a hole to the its center:
$S=a\arcsin (\frac{r}{a} )$
Also, volume of the star is given in the book by:
$ V=2\pi a^{2}[a\arcsin (\frac{r}{a} )-r\frac{(a^{2}-r^{2})}{a} ^{\frac{1}{2} }] $
$\Rightarrow V\propto [S-r\frac{(a^{2}-r^{2})}{a} ^{\frac{1}{2} }]$
Now for a star of constant density, $Volume\propto Mass$
$\Rightarrow Mass\propto [S-r\frac{(a^{2}-r^{2})}{a} ^{\frac{1}{2} }] $          ...(1)
Now, according to feynman's excess radius equation:
$Mass\propto S-r$          ...(2)
We notice that (1) and (2) cannot both be right.
This suggests that Feynman's excess radius equation is wrong. But actually it is not, as explained by M. J. Steil in the comments to this answer...


text:
Q: Usage for global.jelly and config.jelly in Jenkins plugin I am working on a Jenkins plugin using Maven 3 see two default .jelly files: global.jelly and config.jelly. What is the difference between the two, and can you give me examples of what goes in each file?
This is a result of a project created by:
mvn hpi:create

Thanks in advance for any help!

A: *

*global.jelly is for global configuration (i.e per Jenkins instance - the values you can configure at http://<your_jenkins_server>/configure )
examples can be - SMTP server address  if this is a mailer plugin,  or some tool location if your plugin calls that tool

*config.jelly is for the job configuration - defining plugin parameters for a specific job.
examples: mail recipients for that job reports, specific execution parameters, output file locations, etc.


text:
Q: Undefined references on run, SSL Trying out Kemal in a VM, fresh install of Arch-Linux with gc, openssl, crystal, and shard packages. Ran through steps on Kemal guide for simple web app, but errors upon crystal run src/test_app.cr:

_main.o: In function '__crystal_main':
  /usr/lib/crystal/openssl/lib_ssl.cr:213: undefined reference to 'SSL_Library_init'

...followed by a lot of similar error messages, undefined references etc.
Am I missing a dependency?

A: Install the base-devel package group using pacman -S base-devel.
On Arch Linux, Crystal is a compiler package so it assumes you have base-devel installed. Without the pkg-config package, Crystal can't find out which version of OpenSSL you have installed and can't link to it.


text:
Q: Gradle zip: how to include and rename one file easily? Create a zip adding file "hello/world.xml" under directory "foo/bar" as "hello/universe.xml"
task myZip(type: Zip) {
     from ("foo/bar") {
         include "hello/world.xml"
         filesMatching("hello/*") {
             it.path = "hello/universe.xml"
         }
     }
}

filesMatching(...) will impact performance obviously.
What is a better way? like:
task myZip(type: Zip) {
     from ("foo/bar") {
         include ("hello/world.xml") {
              rename "hello/universe.xml"
         }
     }
}

But rename is not supported with include.

A: I don't get why you are using filesMatching at all. You are only including one single file in your child CopySpec. Simply rename it and everything is fine:
task myZip(type: Zip) {
    from ('foo/bar') {
        include 'hello/world.xml'
        rename { 'hello/universe.xml' }
    }
}

If you want to include multiple files (or even copy all), but only want to rename one of them, specify which file(s) to rename with a regular expression as first argument:
task myZip(type: Zip) {
    from 'foo/bar'
    rename 'hello/world.xml' 'hello/universe.xml'
}

A: If the last one did not work, try:
rename ('a.java', 'b.java')


text:
Q: Azure webapp, web.config. Don´t redirect if specific URL Hay all I´m having a doubt over here and not sure if possible with web.config.
I have a web app in azure . Domain foo.bar.com is pointing to this webapp.
On the other had I have a CDN as well in azure with a sub domain which is www.foo.bar.com is pointing to this CDN .
the idea is that foo.bar.com redirects to www.foo.bar.com so to use this CDN.
Right now the picture is:
foo.bar.com > WEBAPP > redirect > www.foo.bar.com > DNS > CDN > webapp  which is causing like to many redirects and sort of endless loop.
Is there a way with web.config to have some rule say something like:
if URL is www.foo.bar.com  don´t redirect, stay on webapp. to have something like:
foo.bar.com > WEBAPP > redirect > www.foo.bar.com  and that´s it stay on webapp.

Tried something like this but is not working:
<rule name="www" stopProcessing="true">
                    <match url="https://foo.bar.com" ignoreCase="true" />
                    <conditions>
                        <add input="{HTTP_HOST}" pattern="https://foo.bar.com" />
                    </conditions>
                    <action type="Redirect" url="https://www.foo.bar.com/{R:0}" redirectType="Permanent" />
                </rule>


text:
Q: Project gets unloaded when opening with Visual Studio 2019 I am trying to open a solution using Visual studio 2019 and visual studio 2017. All the projects in the solution are loading except for one. When trying to load the unloaded project i get an error in the output window as

TakstMVC.csproj : error  : The imported project
"....build\MSBuild.Community.Tasks.targets" was not found. Confirm
that the expression in the Import declaration
"TakstMVC\.....build\MSBuild.Community.Tasks.targets" is correct,
and that the file exists on disk.  TakstMVC\FluentMigrator.targets

When i tried to open using VS 2017 i saw a migration report which said

TakstMVC.csproj: The application which this project type is based on
was not found. Please try this link for further information:
http://go.microsoft.com/fwlink/?LinkID=299083&projecttype=E3E379DF-F4C6-4180-9B81-6769533ABE47

Part of the .csproj of the project is as below:
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProductVersion>
    </ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{A4354F5C-ECF5-4621-AA9E-B91FE543F096}</ProjectGuid>
    <ProjectTypeGuids>{E3E379DF-F4C6-4180-9B81-6769533ABE47};{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
    <OutputType>Library</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>TakstMVC</RootNamespace>
    <AssemblyName>TakstMVC</AssemblyName>
    <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
    <MvcBuildViews>false</MvcBuildViews>
    <UseIISExpress>true</UseIISExpress>
    <SccProjectName>SAK</SccProjectName>
    <SccLocalPath>SAK</SccLocalPath>
    <SccAuxPath>SAK</SccAuxPath>
    <SccProvider>SAK</SccProvider>
    <FileUpgradeFlags>
    </FileUpgradeFlags>
    <UpgradeBackupLocation>
    </UpgradeBackupLocation>
    <OldToolsVersion>4.0</OldToolsVersion>
    <IISExpressSSLPort />
    <IISExpressAnonymousAuthentication />
    <IISExpressWindowsAuthentication />
    <IISExpressUseClassicPipelineMode />
    <MvcProjectUpgradeChecked>true</MvcProjectUpgradeChecked>
    <NuGetPackageImportStamp>
    </NuGetPackageImportStamp>
  </PropertyGroup>

I have the following installed in my computer

*

*Microsoft .NET Framework 4.7.1 SDK

*Microsoft .NET Framework 4.7.1 SDK Targeting Pack (ENU)

*Microsoft .NET Core 3.1.1 - Windowsserver hosting

*Microsoft .NET Core SDK 3.1.101 (x64)

*Microsoft .NET Core SDK 2.2.207 (x64)

*Microsoft .NET Core Runtime - 3.1.1

*Microsoft .NET Core Runtime - 2.2.8

I tried to install dotnetfx35.exe but it doesnt even run when executed (not even a message or error).
The windows feature are as below:

How can I identify the target framework of the project and load it in visual studio successfully ? appreciate some advise on this.

A: The error is clear that you did not import the MSBuild.Community.Tasks.targets correctly on your local area. The reason is that you did not install MSBuild.Community.Tasks.targets on your PC or the import path from csproj file is incorrect.
You should check this document to install the right target.
First, remove xml node under csproj file like these:
 <Import Project="..\build\MSBuild.Community.Tasks.targets" Condition="Exists('..\build\MSBuild.Community.Tasks.targets')" />

 <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
    <PropertyGroup>
      <ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
    </PropertyGroup>
    <Error Condition="!Exists('..\build\MSBuild.Community.Tasks.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\build\MSBuild.Community.Tasks.targets'))" />
  </Target>

Second, install the msi file.
then, add these under the csproj file:
<Import Project="C:\Program Files (x86)\MSBuild\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets"/>

Besides, you could also use nuget function. First, uninstall the nuget package if you have a old version on the project. Then, use the first suggestion to remove any previous import projects="xxx\MSBuildTasks.targets". After that, install the MSBuildTasks nuget package. That is the same.
Update
Try to You should change ..\..\ to ..\. Use the right path.
Or use this command under Tools-->Nuget Package Manager-->Package Manager Console
update-package -reinstall

Answer from the Customer
embarrassingly enough the whole issue was with the solution path where my solution was located in my local computer. I had a long path including a folder having two words as well. After trying everything else I moved the solution folder to C:\temp folder and the issue was no longer there. The error showed in VS was quite misleading. What a waist of time. Thank you for your efforts !


text:
Q: Giving a variable a value of 1 or 0 based on whether another variable appears in query results I have a query $sqlStr4 that "selects" these fields from a MySQL database:
loginid
username
created

The query $sqlStr4 is limited to 10 rows / results.
I also have the following variable:
$u = $_SESSION['username'];

I would like to assign another variable $topten a value of 1 if $u equals any of the ten username fields returned by the query $sqlStr4, and a value of 0 if it does not.
How can I do this?
Thanks in advance,
John

A: If you had pasted the query, we'd be able to provide a fixed version.  You can do this multiple ways, but one would be to add a column to your query and use a CASE statement.
select *, CASE WHEN username = '$u' THEN 1 ELSE 0 END as topten
from ...

This is just an example.. obviously to prevent SQL injection you should parameterize it, or use mysql_real_escape_string(), or a stored procedure, etc etc...
EDIT:  I see you want the variable to be in PHP... so you would need to loop through the array to check each one.  What is the problem you're having?...
$topten = 0;
if ($result) {
   while ($record = mysql_fetch_array($result)) {
      if ($record['username'] == $u) $topten = 1;
   }
}

A: Use:
<?php

$u = $_SESSION['username'];
$topten = 0;

$result = mysql_query($sqlStr4);

while ($row = mysql_fetch_assoc($result)) {
  if ($row['username'] == $u) {
    $topten = 1;
    break;
  }
}

mysql_free_result($result);
?>

A: Could try something like this...
while ($row = mysql_fetch_assoc($sqlStr4))
{
    $topten = ($u == $row['username']) ? 1 : 0;
    // the rest of your processing code here
}

There may well be better solutions for your situation. Would be easier if you posted some code!


text:
Q: Deleting with a trigger I am importing a spreadsheet once a week that is filled with all the training that we do as a company, some of which is mandatory some of which is not. Am i able to make a trigger to get rid of the mandatory training.
delete from [import training]
where module not in ('Mandatory Training 1','Mandatory Training 2' etc...)

As an example of what the code would look like, but will it work as a trigger when I have the correct syntax around it?

A: Why delete the mandatory training?
Instead, create a view:
create view optional_training as
    select t.*
    from [import training] t
    where t.module not in ('Mandatory Training 1','Mandatory Training 2' etc...);

Then, someone can query the view to get the optional training.  They can query the base table to get all training.

A: Yes, it will work, but first consider the following options:

*

*Filter the data before doing the insert.

*Implement a CHECK constraint with the accepted values only. This will force all non-valid values to be rejected with the whole insert/update.

*Keep all data but filter when you access it, with a condition on a WHERE or a view.

If the previous options are not appropriate, then you can create an INSTEAD OF trigger like Jeroen mentioned, which will rewrite the insert operation just with the valid values. You will also need to consider updates of this field.
CREATE TRIGGER OnlyMandatoryTrainings ON [import training]
    INSTEAD OF INSERT
AS
BEGIN

    SET NOCOUNT ON

    INSERT INTO [import training] (
        module
        -- All remaining columns
        )
    SELECT
        module
        -- All remaining columns
    FROM
        inserted AS I
    WHERE
        I.module IN ('valid value 1', 'valid value 2')

END

Using triggers to implement business logic isn't a good practice, although there might be a few exceptions every now and then. I would try to avoid them as much as possible, if not then problems such as "my rows aren't being inserted but the insert doesn't fail" arises.


text:
Q: Sass::SyntaxError: Undefined mixin 'transition' I am getting error

Sass::SyntaxError: Undefined mixin 'transition'
   while doing assets pre-compile.

I have following things in my code:
application.css.scss
/*
 *= require_tree .
 *= require_self
 */

custom.css.scss
@import "bootstrap";
@import "bootstrap-sprockets";

@import "font-awesome";
@import "font-awesome-sprockets";

Please let me know in case I am doing anything wrong here.


text:
Q: Let $R$ be a UFD, and let $f(X) \in R[X]$ be a primitive polynomial. Prove that if $g(X) | f(X)$, then $g(X)$ is primitive. Let $R$ be a UFD, and let $f(X) \in R[X]$ be a primitive polynomial. Prove that if $g(X) | f(X) \in R[X]$, then $g(X)$ is primitive.
Attempted Proof:
Since $f(x)$ is primitive, its coefficients do not have a gcd, hence, f(x) cannot be expressed as $f(x) = c \times h(x)$ where c is a constant. Assume that g(x) is not primitive, then g(x) can be expressed as $d \cdot k(x)$. Since $g(x) | f(x)$, $f(x) = g(x) h(x) = d \cdot k(x) h(x)$. Contradiction.
I don't know why I just have a feeling that it is not quite right. Or is there any more elegant way of doing it? Thanks

A: This is quite right. The only problem is that its coefficients has a gcd w/c is 1 (Definition of a primitive polynomial). But the rest of the proof is correct.


text:
Q: AWS Api-Gateway incorrect region I'm not entirely sure what is wrong with my aws api-gateway setup. I have two regions I use, one for my staging (eu-west-1) environment and another for my live (us-east-1) environment.
When I build and run my api in staging, all works fine. However when I try to run my api on live, I get the following error:
{"message": "Internal server error"}
To try and debug this I ran the API using the 'test' functionality in the aws console and performed a GET request. To my surprise I noticed that the region in the request header was wrong (eu-west-1 instead of us-east-1). Also the test returned the following message with a 502 response:
{"Message":"Functions from 'us-east-1' are not reachable in this region ('eu-west-1')","Type":"User"}
Does this mean that my api is being run in the eu-west-1 region?
If I check my region in the console I am clearly in us-east-1 when running the test. Also the region in my api-gateway uri is us-east-1.
https://.execute-api.us-east-1.amazonaws.com/prod
I can see that my request header has: Host=lambda.eu-west-1.amazonaws.com
and in the output I have the following property:
Endpoint request URI: https://lambda.eu-west-1.amazonaws.com/2015-03-31/functions/arn:aws:lambda:us-east-1::function:/invocations
I have no idea why my regions are mixed up! I thought it might have something to do with my build process, but after double checking everything I am not able to see what could be causing it. I am hoping a fresh set of eyes could pick something up!
To build my api I use a combination of a swagger.yaml file and a cloudformation.json file.
SWAGGER:
I have placeholders in this file which I replace running a node script before sending the file to aws.
---
swagger: 2.0
info:
  title: ServerlessExpress
basePath: /YOUR_API_GATEWAY_STAGE
schemes:
- https
paths:
  /:
    x-amazon-apigateway-any-method:
      produces:
      - application/json
      responses:
        200:
          description: 200 response
          schema:
            $ref: "#/definitions/Empty"
      x-amazon-apigateway-integration:
        responses:
          default:
            statusCode: 200
        uri: arn:aws:apigateway:YOUR_AWS_REGION:lambda:path/2015-03-31/functions/arn:aws:lambda:YOUR_AWS_REGION:YOUR_ACCOUNT_ID:function:api-gateway-service/invocations
        passthroughBehavior: when_no_match
        httpMethod: POST
        type: aws_proxy
    options:
      consumes:
      - application/json
      produces:
      - application/json
      responses:
        200:
          description: 200 response
          schema:
            $ref: "#/definitions/Empty"
          headers:
            Access-Control-Allow-Origin:
              type: string
            Access-Control-Allow-Methods:
              type: string
            Access-Control-Allow-Headers:
              type: string
      x-amazon-apigateway-integration:
        responses:
          default:
            statusCode: 200
            responseParameters:
              method.response.header.Access-Control-Allow-Methods: "'GET,OPTIONS,POST'"
              method.response.header.Access-Control-Allow-Headers: "'Content-Type,Authorization,X-Amz-Date,X-Api-Key,X-Amz-Security-Token'"
              method.response.header.Access-Control-Allow-Origin: "'*'"
        passthroughBehavior: when_no_match
        requestTemplates:
          application/json: "{\"statusCode\": 200}"
        type: mock
  /{proxy+}:
    x-amazon-apigateway-any-method:
      produces:
      - application/json
      parameters:
      - name: proxy
        in: path
        required: true
        type: string
      responses: {}
      x-amazon-apigateway-integration:
        uri: arn:aws:apigateway:YOUR_AWS_REGION:lambda:path/2015-03-31/functions/arn:aws:lambda:YOUR_AWS_REGION:YOUR_ACCOUNT_ID:function:api-gateway-service/invocations
        httpMethod: POST
        type: aws_proxy
    options:
      consumes:
      - application/json
      produces:
      - application/json
      responses:
        200:
          description: 200 response
          schema:
            $ref: "#/definitions/Empty"
          headers:
            Access-Control-Allow-Origin:
              type: string
            Access-Control-Allow-Methods:
              type: string
            Access-Control-Allow-Headers:
              type: string
      x-amazon-apigateway-integration:
        responses:
          default:
            statusCode: 200
            responseParameters:
              method.response.header.Access-Control-Allow-Methods: "'GET,OPTIONS,POST'"
              method.response.header.Access-Control-Allow-Headers: "'Content-Type,Authorization,X-Amz-Date,X-Api-Key,X-Amz-Security-Token'"
              method.response.header.Access-Control-Allow-Origin: "'*'"
        passthroughBehavior: when_no_match
        requestTemplates:
          application/json: "{\"statusCode\": 200}"
        type: mock
definitions:
  Empty:
    type: object
    title: Empty Schema

CLOUDFORMATION:
{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Description": "AWS Serverless Express.",
    "Parameters": {
        "AwsServerlessExpressS3Bucket": {
            "Type": "String",
            "Description": "The S3 bucket in which the lambda function code is stored. Bucket names are region-unique, so you must change this."
        },
        "LambdaFunctionS3Key": {
            "Type": "String",
            "AllowedPattern": ".*\\.zip",
            "Description": "The S3 object for the lambda function code package.",
            "Default": "lambda-function.zip"
        },
        "ApiGatewaySwaggerS3Key": {
            "Type": "String",
            "AllowedPattern": ".*\\.yaml",
            "Description": "The S3 object for the swagger definition of the API Gateway API.",
            "Default": "simple-proxy-api.yaml"
        }
    },

    "Resources": {
        "ApiGatewayApi": {
            "Type": "AWS::ApiGateway::RestApi",
            "Properties": {
                "Description": "AWS Serverless Express API",
                "BodyS3Location": {
                    "Bucket": {
                        "Ref": "ServerlessExpressBucket"
                    },
                    "Key": {
                        "Ref": "ApiGatewaySwaggerS3Key"
                    }
                }
            }
        },

        "ApiGatewayApiDeployment": {
            "Type": "AWS::ApiGateway::Deployment",
            "Properties": {
                "RestApiId": {
                    "Ref": "ApiGatewayApi"
                },
                "StageName": "YOUR_API_GATEWAY_STAGE"
            }
        },

        "LambdaApiGatewayExecutionPermission": {
            "Type": "AWS::Lambda::Permission",
            "Properties": {
                "Action": "lambda:InvokeFunction",
                "FunctionName": {
                    "Fn::GetAtt": ["LambdaFunction", "Arn"]
                },
                "Principal": "apigateway.amazonaws.com",
                "SourceArn": {
                    "Fn::Join": ["", ["arn:aws:execute-api:", {
                        "Ref": "AWS::Region"
                    }, ":", {
                        "Ref": "AWS::AccountId"
                    }, ":", {
                        "Ref": "ApiGatewayApi"
                    }, "/*/*"]]
                }
            }
        },

        "LambdaFunction": {
            "Type": "AWS::Lambda::Function",
            "Properties": {
                "Code": {
                    "S3Bucket": {
                        "Ref": "ServerlessExpressBucket"
                    },
                    "S3Key": {
                        "Ref": "LambdaFunctionS3Key"
                    }
                },
                "FunctionName": "api-gateway-service",
                "Handler": "lambda.serverlessExpress",
                "Description": "Service running on api-gateway",
                "MemorySize": 128,
                "Role": {
                    "Fn::Join": ["", ["arn:aws:iam::", {
                        "Ref": "AWS::AccountId"
                    }, ":role/service-lambda"]]
                },
                "Runtime": "nodejs4.3",
                "Timeout": 30
            }
        }
    },

    "Outputs": {
        "LambdaFunctionConsoleUrl": {
            "Description": "Console URL for the Lambda Function.",
            "Value": {
                "Fn::Join": ["", ["https://", {
                    "Ref": "AWS::Region"
                }, ".console.aws.amazon.com/lambda/home?region=", {
                    "Ref": "AWS::Region"
                }, "#/functions/", {
                    "Ref": "LambdaFunction"
                }]]
            }
        },
        "ApiGatewayApiConsoleUrl": {
            "Description": "Console URL for the API Gateway API's Stage.",
            "Value": {
                "Fn::Join": ["", ["https://", {
                    "Ref": "AWS::Region"
                }, ".console.aws.amazon.com/apigateway/home?region=", {
                    "Ref": "AWS::Region"
                }, "#/apis/", {
                    "Ref": "ApiGatewayApi"
                }, "/stages/YOUR_API_GATEWAY_STAGE"]]
            }
        },
        "ApiUrl": {
            "Description": "Invoke URL for your API. Clicking this link will perform a GET request on the root resource of your API.",
            "Value": {
                "Fn::Join": ["", ["https://", {
                    "Ref": "ApiGatewayApi"
                }, ".execute-api.", {
                    "Ref": "AWS::Region"
                }, ".amazonaws.com/YOUR_API_GATEWAY_STAGE/"]]
            }
        }
    }
}

A: Turns out I had manually created the lambda function that api-gateway calls. Although cloudformation updated this code, there seemed to be a region mix-up going on behind the scenes.
So in short, simply deleting the stack in cloudformation and the lambda function I had manually created, re-running the build and letting cloudformation to build the lambda function solves the problem!


text:
Q: Double elements in a list if values are over certain threshold Trying to double elements of a list that are greater than 5 for example.
to double every element in a list i would do this
doubleAll n = [2*x| x <-n]

now i want to double all elements in list that are greater than 5 using list comprehensions.
So if i do this
doubleAll n = [2*x| x <-n, x>5]

My list [1,2,3,4,5] would  result in to [10]. But i want my list to show [1,2,3,4,10]
Can anyone explain what i did wrong and how can this be fixed?

A: An interpretation of [2*x| x <-n, x>5] is:

*

*Take the next element from n and call it x

*Proceed if x>5, otherwise go to step 1

*Return the value 2*x as the next element of the list.

*Repeat

From this it is clear that the x>5 filters out elements of n. The expression is equivalent to:
map (\x -> 2*x) ( filter (\x -> x>5) n )

As Arthur mentioned, you want something like:
[ if x > 5 then 2*x else x | x <- n ]

It's interpretation is:

*

*Take the next value of n and call it x

*Return the value if x > 5 then 2*x else x as then next value of the list.

A: This is clearer to understand if you don't use list comprehensions and use the map and filter operations instead:
-- Apply a function to every element of the list.
map :: (a -> b) -> [a] -> [b]

-- Throw out list elements that don't pass the test.
filter :: (a -> Bool) -> [a] -> [a]

Your original doubleAll is equivalent this:
-- Multiply every element of the list by two.
doubleAll xs = map (*2) xs

The version where you double only if x > 5 would be this:
-- Apply the `step` function to every element of the list.  This step function
-- multiplies by two if x >= 5, otherwise it just returns its argument.
doubleAll xs = map step xs
    where step x | x >= 5    = 2*x
                 | otherwise = x

The problem with the list comprehension version that you wrote is that it's instead equivalent to this:
-- Filter out list elements that are smaller than 5, then double the remaining ones.
doubleAll xs = map (*2) (filter (>=5) xs)

The list comprehension solution that produces the result you want would instead be this:
doubleAll xs = [if x >= 5 then x*2 else x | x <- xs]

As a more general remark, I always recommend to newcomers to stay away from list comprehensions and learn the higher-order list functions, which are more general and less magical.


text:
Q: Swipe carousel responsiveness I'm using Swipe carousel, I need it to make responsive (decrease image height and width while resizing browser), but not sure why, the .swiper-slide width remaining larger, though it's width is auto. Did anybody meet such problem? Also after browser maximize, image widths are not updated. See in screenshots.

HTML

        <?= HTML::image('/assets/images/tmp/carousel/img1.jpg') ?>

        <?= HTML::image('/assets/images/tmp/carousel/img2.jpg') ?>

        <?= HTML::image('/assets/images/tmp/carousel/img1.jpg') ?>

        <?= HTML::image('/assets/images/tmp/carousel/img1.jpg') ?>

        <?= HTML::image('/assets/images/tmp/carousel/img1.jpg') ?>

        <?= HTML::image('/assets/images/tmp/carousel/img1.jpg') ?>

        <?= HTML::image('/assets/images/tmp/carousel/img2.jpg') ?>

        <?= HTML::image('/assets/images/tmp/carousel/img1.jpg') ?>

JS
$(document).ready(function(){
  var swiper = new Swiper('.swiper-container', {
    slidesPerView: 'auto',
    nextButton: '.swiper-next',
    prevButton: '.swiper-prev',
    paginationClickable: true
  });

  var imgHeight = $(window).width()/2;
  $('.swiper-slide').each(function(){
    var width = $(this).children('img').width();
    $(this).css('width', width + 'px');
  });

  $('.block-carousel').css('height', imgHeight + 'px');
});

$(window).resize(function() {
  var imgHeight = $(window).width()/2;

  $('.swiper-slide').each(function(){
    var width = $(this).children('img').width();
    $(this).css('width', width + 'px');
  });

  $('.block-carousel').css('height', imgHeight + 'px');
});

CSS
.swiper-container .swiper-slide {
  max-width: 700px;
  margin-left: 3px;
  margin-right: 0!important;
  display: inline-block;
  width: auto;
  overflow: hidden;
}
.swiper-container .swiper-slide img {
  width: auto;
}
.swiper-container .swiper-slide:first-child {
  margin-left: 0;
}
.swiper-wrapper * {
  height: 100%;
}
.swiper-container {
  height: 100%;
}
.swiper-container-horizontal > .swiper-pagination {
  bottom: auto;
  top: 50%;
  margin-top: -60px;
}
.swiper-prev,
.swiper-next {
  width: 60px;
  height: 120px;
  background: rgba(0, 0, 0, 0.2);
  line-height: 150px;
  cursor: pointer;
  border-radius: 3px;
  -webkit-transition: all 0.2s;
  -moz-transition: all 0.2s;
  -o-transition: all 0.2s;
  transition: all 0.2s;
}
.swiper-prev {
  margin-left: 45px;
  float: left;
}
.swiper-next {
  margin-right: 45px;
  float: right;
}

Code is in fiddle, but for some reasons it's not working.
Note: I just want to make the carousel responsive (resize images height/width during browser resize)


text:
Q: Two kinds of search on a field? I work on a project that uses elasticsearch 5.2. The code is in java and I use elasticsearch java client 5.2.
In this project, I have a field called hash, a 7-character code containing uppercase letters, lowercase letters, and numbers (in English language).
I want to do two searches on this field:

*

*check the existence of a hash "ErTg1Qh" (case sensitive)

*find hashes that sub string s contains in them (for example, sub string "tg" exist in the hash "ErTg1Qh").
For the hash field, I chose the keyword datatype.
I used matchQuery function for first search as below:
String hash = "ErTg1Qh";
QueryBuilders.matchQuery("hash", hash)

and queryStringQuery function for the second search as below:
queryString = "hash:*" + subString + "*";
QueryBuilders.queryStringQuery(queryString)

but, the second one does not work properly.
How can I handle these two kinds of search on a field?

A: One of your query requires to be case sensitive while the second one is case insensitive. So I'll suggest you to use sub field for the hash field. Your main field will be analyzed with lowercase analyzer and one will store raw data i.e. the exact hash. So your index will look like below:
PUT /test
{
  "settings": {
    "number_of_shards": "1",
    "number_of_replicas": "0",
    "analysis": {
      "analyzer": {
        "custom_lowercase": {
          "filter": [
            "lowercase"
          ],
          "type": "custom",
          "tokenizer": "keyword"
        }
      }
    }
  },
  "mappings": {
    "_doc": {
      "properties": {
        "hash": {
          "type": "text",
          "analyzer": "custom_lowercase",
          "fields": {
            "keyword": {
              "type": "keyword"
            }
          }
        }
      }
    }
  }
}

Query to check the existence of a hash "ErTg1Qh" (case sensitive)
POST /test/_doc/_search
{
  "query": {
    "match": {
      "hash.keyword": "ErTg1Qh"
    }
  }
}

Query to find hashes that sub string s contains in them
POST /test/_doc/_search
{
  "query": {
    "query_string": {
      "query": "*tg*"
    }
  }
}


text:
Q: Hive - Can one extract common options for reuse in other scripts? I have two Hive scripts which look like this:
Script A:

SET hive.exec.dynamic.partition=true;
SET hive.exec.dynamic.partition.mode=non-strict;
SET hive.exec.parallel=true;

... do something ...

Script B:

  SET hive.exec.dynamic.partition=true;
  SET hive.exec.dynamic.partition.mode=non-strict;
  SET hive.exec.parallel=true;

... do something else ...

The options that we set at the beginning of each script are the same. Is it possible somehow to extract them out to a common place (for example, into a commonoptions.sql) so that our scripts look like this:
Script A:

 <run commonoptions.sql>

... do something ...

Script B:

 <run commonoptions.sql>

... do something else ...

Ideally I would like to extract out table defintions as well, so that I have:
Script A:

 <run commonoptions.sql>
 <run defineExternalTableXYZ.sql>
... do something with Table XYZ ...

Script B:

 <run commonoptions.sql>
 <run defineExternalTableXYZ.sql>
... do something else with Table XYZ ...

That way I can manage the TableXYZ definition at a single spot. I am not using the Hive CLI. I am using Amazon EMR with Hive Steps.

A: You can store these configuration parameters in common file and load in each of your scripts using source command:
source /tmp/common_init.hql;

Also you can generate this file for each workflow from the database.

A: You should be able to use hive -i config.hql -f script_A.hql, where config.hql would contain your dynamic settings.  The -i flag allows you to pass an initialization script that will be executed before the actual hive file passed to -f.  I'm not super familiar with how AWS kicks off hive jobs in steps, but presumably you edit the submission arguments.


text:
Q: Webserver not listening to ports Problem
I've recently found out that PHP has a built-in webserver which can be used for development purposes. Starting the server with the address "127.0.0.1" and the port "8080" works without any problems and my requests are handled properly. However, if I dare to use the address "localhost" with the same port, the webserver doesn't handle any requests.
Specs

*

*Windows 10 64-Bit

*Php 64-Bit Thread-Safe installed

*MongoDB installed (Not running)

*IIS Server installed and running

*MariaDB installed (Not running)

A: Name resolution for localhost is handled by your DNS server which is likely resolving it to the IPv6 address ::1.
If you run:
php -S 127.0.0.1:8080

The webserver is running on the IPv4 address but localhost resolves to the IPv6 address.
So you can either use 127.0.0.1:8080 in the browser address bar.
Or force the address by un-commenting the following line from C:\Windows\System32\drivers\etc\hosts:
#   127.0.0.1       localhost

Or bind the webserver to the IPv6 address (this is what I do):
php -S localhost:8080


text:
Q: Stubborn bit won't be set to one. I have this code I use for getting the mantissa, or value, of an IEEE binary number.
iFloat_t floatGetVal (iFloat_t x) {
  iFloat_t mantissa = (BITS == 16) ? (x & 0x03FF)
                      : (x & 0x007FFFFF);
    debug("%s: getVal before implicit 1", getBinary(mantissa));
    //mantissa = (BITS == 16) ? (mantissa | 0x04)
    //                : (mantissa | 0x008);
    mantissa = x | 0000010000000000;
    debug("%s: getVal after implicit 1", getBinary(mantissa));
    mantissa = (BITS == 16) ? (mantissa & 0x07FF)
                      : (mantissa & 0x00FFFFFF);
    if(floatGetSign(x) == 1) {
        mantissa = ~mantissa + 1;
    }
    return mantissa;
}

My issue is when I try to get the value from the number 63.125, here is the corresponding output:
DEBUG iFloat.c[31] floatGetVal() 0000-0011-1110-0100: getVal before implicit 1
DEBUG iFloat.c[35] floatGetVal() 0101-0011-1110-0100: getVal after implicit 1
DEBUG iFloat.c[81] floatAdd() 0000-0011-1110-0100: bits of val_y after assignment

This is my expected output:
DEBUG iFloat.c[31] floatGetVal() 0000-0011-1110-0100: getVal before implicit 1
DEBUG iFloat.c[35] floatGetVal() 0101-0111-1110-0100: getVal after implicit 1
DEBUG iFloat.c[81] floatAdd() 0000-0111-1110-0100: bits of val_y after assignment

Here is my full code:
https://pastebin.com/w4UVzmUe

A: 0000010000000000 is an octal literal, not a binary one, use hexadecimal 0x0400.

A: There are no binary constants in standard C. So you cannot have something like 0b0000010000000000. But GCC has an extension to support them with 0b or 0B prefixes.
If you are not using GCC, then better go with the suggestion provided by @zch.


text:
Q: Timeouts in Xamarin HTTP requests Good evening!
I was trying to clean/refine some code and ended up finding issues with timeouts in Xamarin HTTP requests (as described in my original thread: Async Download and Deserialize).
Issue found (only tested with Xamarin.Android; don't know about iOS):
When a host cannot be reached (e.g., an offline local server), GetAsync throws a System.Net.WebException after roughly 3 minutes with the message Error: ConnectFailure (Connection timed out). The Inner exception is System.Net.Sockets.SocketsException (full log here: http://pastebin.com/MzHyp2FM).
Code:
internal static class WebUtilities
{
    /// <summary>
    /// Downloads the page of the given url
    /// </summary>
    /// <param name="url">url to download the page from</param>
    /// <param name="cancellationToken">token to cancel the download</param>
    /// <returns>the page content or null when impossible</returns>
    internal static async Task<string> DownloadStringAsync(string url, CancellationToken cancellationToken)
    {
        try
        {
            // create Http Client and dispose of it even if exceptions are thrown (same as using finally statement)
            using (var client = new HttpClient() { Timeout = TimeSpan.FromSeconds(5) })
            {
                // should I always do this?
                client.CancelPendingRequests();

                // Issue here; Timeout of roughly 3 minutes
                using (var response = await client.GetAsync(url, cancellationToken).ConfigureAwait(false))
                {
                    // if response was successful (otherwise return null)
                    if (response.IsSuccessStatusCode)
                    {
                        // return its content
                        return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                    }
                }
            }
        }
        // TODO: split exceptions?
        catch (Exception ex) when (ex is System.Net.Sockets.SocketException ||
                                    ex is InvalidOperationException ||
                                    ex is OperationCanceledException ||
                                    ex is System.Net.Http.HttpRequestException)
        {
            WriteLine("DownloadStringAsync task has been cancelled.");
            WriteLine(ex.Message);
            return null;
        }

        // return null if response was unsuccessful
        return null;
    }
}

Calling Method:
internal static async Task CallAsync(string url)
    {
        using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)))
        {
            var token = cts.Token;
            token.ThrowIfCancellationRequested();

            string result = await WebUtilities.DownloadStringAsync(url, token).ConfigureAwait(false);
        }
    }

Setting client.Timeout doesn't seem to work.
Either way, shouldn't cancellationToken cancel automatically after 10 seconds?
This timeout issue happens when:

*

*An offline/unreachable IP address (in my case an offline local server
such as 192.168.1.101:8080) is requested (i.e., using GetAsync, SendAsync,
GetResponseAsync)

The code works well when:

*

*The request is made from a desktop client (e.g., WPF). If the
IP is offline/unreachable it throws 4 exceptions really fast (No connection could be made because the target machine actively refused it).

Conclusions
Xamarin seems to have some bugs in Http requests (with Timeouts at least?), as they do not give the expected results. And from what I have read, it could be something that has been around for few a years (since 2012 or 2013).
Xamarin unit testing doesn't really help either: https://github.com/xamarin/xamarin-android/blob/1b3a76c6874853049e89bbc113b22bc632ed5ca4/src/Mono.Android/Test/Xamarin.Android.Net/HttpClientIntegrationTests.cs
Edit

*

*Timeout = TimeSpan.FromMilliseconds(1000) - works

*Timeout = Timeout = TimeSpan.FromSeconds(1) - doesn't work (?????)

*Timeout = TimeSpan.FromMilliseconds(2000) (and above) - doesn't
work

Any ideas? Thanks!

A: I found that that changing the http client settings for Android resolved my issue.
To solve the issue:

*

*from HttpClient implementation to AndroidClientHandler

*from SSL/TLS implementation to Native TLS 1.2+
In Xamarin Android project options. "Default" values were using Mono's own client which caused the problem.
I posted more details here.


text:
Q: PHP Single page submission fails with no error php single submission fails and page remains the same, data is not added to the database as well. When i click the cancel button, am redirected to a new form as it should work.
How do i get the submission to work and add the form data to the database? Below is the php and form html code and attached is the form picture

                First name *
                <input type="text" class="form-control" placeholder="First name">
                Last name *
                <input type="text" class="form-control" placeholder="Last name">
                Middle name
                <input type="text" class="form-control" placeholder="Middle name">
                Date of Birth *
                <input type="text" class="form-control" placeholder="DD/MM/YYYY">
                Phone Number *
                <input type="text" class="form-control" placeholder="Phone number">
                Email *
                <input type="text" class="form-control" placeholder="Email address">
                Entry level *
                <input type="text" class="form-control" placeholder="Entry level">

                <input type="submit" name="submit" value="Save" class="btn btn-default" />
                &nbsp
                <button type="button" class="btn btn-default" aria-label="Left Align">Cancel</button>

<?php
if (isset($_POST['submit'])) {
    # process the form

    $s_fname = $_POST["s_fname"];
    $s_lname = $_POST["s_lname"];
    $s_mname = $_POST["s_mname"];
    $s_dob = $_POST["s_dob"];
    $g_phone = $_POST["g_phone"];
    $g_email = $_POST["g_email"];
    $entry_year = $_POST["entry_year"];

    $query  = "insert into students (s_fname, s_lname, s_mname, s_dob, g_phone, g_email, entry_year) ";
    $query .= "values ('{$s_fname}', '{$s_lname}', '{$s_mname}', {$s_dob}, {$g_phone}, {$g_email}, {$entry_year})";

    $result = mysqli_query($connection, $query);

    if ($result) {
        # successful
        redirect_to("student.php");
    } else {
        # failure
        redirect_to("new_student.php");
    }
}
?>

A: *

*Add names to your elements.

*Make sure the form method is "post" not "get".

A: Mena -
I see a few problems with this code:

*

*You do not have this HTML in a  element. You will want to wrap that entire  in a  element and ensure that it is submitted as POST instead of GET. See the W3C documentation on forms here: http://www.w3schools.com/html/html_forms.asp

*As Don't Panic mentions, your form input fields do not have names, and therefore won't be submitted with the form. See the link above about the name attribute for input fields.

*Unless you emitted it for security reasons (if you did, good call!), you will need a valid mysqli connection. See the PHP manual for instructions on how to create a connection: http://php.net/manual/en/function.mysqli-connect.php

*Lastly, your php code to redirect back to the student.php or new_student.php pages will not work unless you specifically created those functions somewhere else as they are not build into PHP. See the PHP manual for the header function here to correctly redirect your users: http://php.net/manual/en/function.header.php
Otherwise, everything else looks like it should work!

A: The problem seems to lie in your HTML. The inputs in the form are not named. And further, if that's the whole code, then some very crucial part is amiss. You did not enclose the form controls in the    <form>    tag. You need to do this and define the form action as SELF shown. Your code should therefore look like below:
<form name="myform" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">

</form>

That should work if its the php code that wasn't being reached by the form submission.


text:
Q: Jquery .hide() and .show() are slowing down on firefox but work great on chrome I made a tree with child elements and for hide and show them on user click, I use the .show('fast') and .hide('fast') jquery functions.
But I noticed that on firefox the transition between the two state are slowing down but on Chrome it works like a charm.
I have the latest version of firefox.
You should also know that I use different libraries into my website such as bootstrap , datatable.js . I tell you because I see that the slowdown is less pronounced on codepen.io that on my site.
this is the codepen.io with my tree
And that's my javascript code :
$('.tree li.parent_li > span').on('click', function(e) {
    var child = $(this).parent('li.parent_li').find(' > ul > li');
    if (child.is(":visible")) {
        child.hide('fast');
        $(this).find('>i').addClass('glyphicon-chevron-right').removeClass('glyphicon-chevron-down');
    } else {
        child.show('fast');
        $(this).find('>i').addClass('glyphicon-chevron-down').removeClass('glyphicon-chevron-right');
    }
    e.preventDefault();
    e.stopPropagation();
});

Thanks.

A: This was my attempt:

$(function(){
  $('.tree li.parent_li > span').on('click', function(e) {
    var parent = $(this).closest('li.parent_li');
    parent.toggleClass("open");
    e.preventDefault();
    e.stopPropagation();
  });
});
.administrationRowTab {
  background-color: #ffffff;
  border: 1px solid rgba(0, 0, 0, 0.12);
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.05);
}

.tab-pane,
.active {
  color: inherit;
}

/*TREE STYLE*/

.tree ul {
  list-style: none;
}

.tree .parent_li > span {
  cursor: pointer;
}

.tree i {
  margin-right: 5px;
}

.parent_li .glyphicon-chevron-down,
.parent_li.open .glyphicon-chevron-right {
  display: none;
}

.parent_li.open .glyphicon-chevron-down {
  display: inline-block;
}

.parent_li ul {
  height: 0;
  overflow: hidden;
  -webkit-transition: all 500ms linear;
  -moz-transition: all 500ms linear;
  -o-transition: all 500ms linear;
  transition: all 500ms linear;
}

.parent_li.open ul {
  height: 60px;
  overflow: auto;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />

Test

                  Parent 1

Child 1

Child 2

Child 3

                  Parent 2

Child 1

Child 2

Child 3

A: This is pure CSS.
I added two classes: .chiled-hide and .chiled-show to the css, and updated your js script:
Here is a link to codepen example

$(function(){
        $('.tree li.parent_li > span').on('click', function(e){
            var test = $(this).parent('li.parent_li').hasClass('chiled-hide');
            if(test)
            {
                $(this).parent('li.parent_li').removeClass('chiled-hide').addClass('chiled-show');
                $(this).find('>i').addClass('glyphicon-chevron-down').removeClass('glyphicon-chevron-right');
            }
            else
            {
                $(this).parent('li.parent_li').removeClass('chiled-show').addClass('chiled-hide');
                $(this).find('>i').addClass('glyphicon-chevron-right').removeClass('glyphicon-chevron-down');
            }
            e.preventDefault();
            e.stopPropagation();
        });
    });
.administrationRowTab{
    background-color: #ffffff;
    border: 1px solid rgba(0, 0, 0, 0.12);
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.05);
}

.tab-pane, .active{
    color : inherit;
}

/*TREE STYLE*/
.tree ul{
    list-style: none;
}

.tree .parent_li > span { cursor: pointer;}

.tree i {margin-right: 5px;}

.chiled-hide > ul {
  display:none;
  opacity:0;
  transition:opacity 0.5s linear;
}
.chiled-show > ul {
  display:block;
  opacity:1;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>

Test

                                        Parent 1

Child 1

Child 2

Child 3

                                        Parent 2

Child 1

Child 2

Child 3


text:
Q: How can I make a Jenkins build fail only for specific tests? I have an application which has unit and integration tests. Inside Jenkins, only unit tests are being called, and if any of them fail, the build will fail as well. Integration tests are not being called because some of them depend on external servers, which can be offline in the moment of a new build, thus making the build fail. Is it possible to run these tests on Jenkins without failing the build? If so, how should I configure it?
Just to make clear, the expected behavior is:

*

*Build App

*Run Unit Tests

*

*Build Failure (if any unit tests fail)

*Run Integration Tests

*Build Success

A: If you are using pipeline you can use try-catch block:
node {
    stage('Unit') {
        // run unit tests
    }

    stage('Integration') {
        try {
            // run integration tests
        } catch (e) {
            // ignore
        } finally {
            // archive test results
        }
    }

}

A: one very simple way is to put "exit 0" at the end of the tests relying on external servers.
for example using a unix shell script you may write:
#!/bin/bash
# If remote check fails, exit with rc=0
./my_remote_server_check1 || exit 0


text:
Q: how to remove the whole array with commas and change option will return to the first option Used jade with node.js for routes.js and Jquery
  .filter
     select.selectFilter
       option(value="") #{list}

JQuery
 var options = $('.selectFilter');
          console.log("1 " + options);
          if(options.length){
            var split = options.text().split(',');
            console.log("2 " + split);
            options.empty();
            if(split.length > 1){
              for (var i = 0; i < split.length; i++) {
               options.append('<option value=?list=' + split[i] + '>' + split[i] + '</option>');
              }
            }
          }
          $(options).on('change', function(e){
            var url = $(this).val();
            window.location = url;
          });

routes.js
var list = ['a','b','c']

I tried to use options.empty() which shows A, B, C in one line while others are split as expected.
For example:
A, B, C
A
B
C
When reloading the page, it would still show A, B, C (jumpy) before showing the first option "A". Also when select any of the options, it still shows the first option "A". Couldn't figure how to remove "A, B, C" totally.
Also not sure why change option will return to the first option, not selected option? How to set option selected?
Help appreciated.
Updates
JSFIDDLE

A: I think you have mistake here:
options.append('<option value=?list=' + split[i] + '>' + split[i] + '</option>');

Change it to:
options.append('<option value="?list=' + split[i] + '">' + split[i] + '</option>');