text:
Q: Converting certain index values in list to int I have searched for a solution to this, but I have not been able to find one, weirdly.
I am opening a file with the following contents in it.
Alex,10,0,6,3,7,4
Bob, 6,3,7,2,1,8

I want to convert all the values in score_list from 1-4 index value to an integer. I have tried to do so with this following but it just doesn't work.
    score_list = []
    def opening_file():
         counter = 0
         with open('scores.txt', newline='') as infile:
             reader = csv.reader(infile)
             for row in reader:
                score_list.append(row[0:5])

             counter = 0
             while counter != 5:
               counter +=1
               row[counter] = int(row[counter])
             print (score_list)

    opening_file()

but it doesn't work and just produces
[['Alex', '10', '0', '6', '3'], ['Bob', ' 6', '3', '7', '2']]

instead of [['Alex', 10, 0, 6, 3], ['Bob', 6, 3, 7, 2]]

A: You are converting the items within row which is just a throwaway variable. Also you don't need to that redundant works, you can simply unpack your row to name and scores parts and use a list comprehension in order to convert the digits to integer.
with open('scores.txt', newline='') as infile:
    reader = csv.reader(infile)
    for row in reader:
        name, *scores = row
        score_list.append([name] + [int(i) for i in scores])

A: Your while loop transforming the values in row happens too late. Each row's values have already been copied (by a slice operation) into a new list which has been appended to score_list. And you only run the loop on the last row anyway (assuming your indentation in the question is correct).
Try something like this:
with open('scores.txt', newline='') as infile:
    reader = csv.reader(infile)
    for row in reader:
        for i in range(1,5):
            row[i] = int(row[i])
        score_list.append(row[0:5])

I'm using a for loop on a range, rather than a while loop, just because it's more convenient (a while loop version could work just fine, it just requires more lines). The key thing is to change row inside the loop on reader and before we slice the row to append to score_list.

A: First of all, the code converts items in the row array, but you print the score_list array. Second, as it alters the row variable outside the reader for loop, it only alters the last row. You could do something like this:
import csv

def opening_file():
  with open('scores.txt', newline='') as infile:
    return [[row[0]] + [int(x) for x in row[1:]] for row in csv.reader(infile)]
score_list = opening_file()
print(str(score_list))


text:
Q: Slick carousel. Дергаются слайды при переключении Когда выбираю следующий слайд, он сначала уходит немного влево, а потом становится нормально, по центру. Как можно избавиться от такого "дёрганья"?
Если убрать variableWidth, то этот эффект исчезает, но тогда не устраивает то, как отображается слайдер.
Пример кода

$(document).ready(function(){
  $("a").click(function(e){
    e.preventDefault();
  })
  $('#adventage_tabs_nav').slick({
    slidesToScroll: 1,
    arrows: false,
    centerMode: true,
    variableWidth: true,
    focusOnSelect: true,
    infinite: false,
    draggable: false,
  });
})
.adventage_tabs_nav{
  display: block;
}

.adventage_tabs_nav_item_wrap{
  margin: 0;
  padding: 0 40px;
}

.adventage_tabs_nav_item{
  margin: auto;
  width: 97px;
  height: 96px;
  margin-top: 42px;
  padding: 8px;
  transition: .3s;
  padding: 13px;
  background-color: rgba(207,232,252,.6);
  border-radius: 10px;
  position: relative;
}

.adventage_tabs_item{
  padding: 0 20px;
}

.adventage_tabs_nav_title{
  display: none;
}

.adventage_tabs_nav_item.active{
  background-color: rgba(207,232,252,.6);
}

.adventage_tabs_nav_item.active a{
  background-color: rgba(207,232,252,1);
}

.slick-current .adventage_tabs_nav_item{
  width: 138px;
  height: 138px;
  margin-top: 0;
}

.slick-current .adventage_tabs_nav_title{
  display: block;
}

.slick-current .adventage_tabs_nav_item{
  background-color: rgba(26,80,142,.6);
}

.slick-current .adventage_tabs_nav_item a{
  background-color: rgba(26,80,142,1);
}
<link href="https://cdn.jsdelivr.net/jquery.slick/1.6.0/slick.css" rel="stylesheet"/>

гарантия
качества

выгодные
цены

опытный
персонал

несем
ответственность

проекты
от эконом до VIP

расчет
по ГОСТ и СанПин

A: Вы меняете ширину центрального слайда после анимации, после получения класса центральный слайд. А смещение сначала происходит исходя из его изначальной ширины, а потом дергается, обновляясь до новой ширины. Можно убрать дергание за счет изменения паддинга центрального слайда, тогда по мнению слайдера ширина не меняется, дергания не происходит:

$(document).ready(function() {
  $("a").click(function(e) {
    e.preventDefault();
  })
  $('#adventage_tabs_nav').slick({
    slidesToScroll: 1,
    arrows: false,
    centerMode: true,
    variableWidth: true,
    focusOnSelect: true,
    infinite: false,
    draggable: false,
  });
})
.adventage_tabs_nav{
  display: block;
}

.adventage_tabs_nav_item_wrap{
  margin: 0;
  padding: 0 40px;
}

.adventage_tabs_nav_item{
  margin: auto;
  width: 97px;
  height: 96px;
  margin-top: 42px;
  padding: 8px;
  transition: .3s;
  padding: 13px;
  background-color: rgba(207,232,252,.6);
  border-radius: 10px;
  position: relative;
}

.adventage_tabs_item{
  padding: 0 20px;
}

.adventage_tabs_nav_title{
  display: none;
}

.adventage_tabs_nav_item.active{
  background-color: rgba(207,232,252,.6);
}

.adventage_tabs_nav_item.active a{
  background-color: rgba(207,232,252,1);
}

.slick-current .adventage_tabs_nav_item{
  width: 138px;
  height: 138px;
  margin-top: 0;
}

.slick-current .adventage_tabs_nav_title{
  display: block;
}

.slick-current .adventage_tabs_nav_item{
  background-color: rgba(26,80,142,.6);
}

.slick-current .adventage_tabs_nav_item a{
  background-color: rgba(26,80,142,1);
}

.adventage_tabs_nav_item_wrap.slick-slide.slick-current.slick-center{
  padding: 0 19.5px;
}
<link href="https://cdn.jsdelivr.net/jquery.slick/1.6.0/slick.css" rel="stylesheet" />

гарантия
качества

выгодные
цены

опытный
персонал

несем
ответственность

проекты
от эконом до VIP

расчет
по ГОСТ и СанПин

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I check to see if a Dialog is closed? Is there a way to tell if a Dialog has been closed  in java, here is bear minimum code:
JFrame jframe = new JFrame();
Dialog dialog = new Dialog(jframe);
JButton jbutton = new JButton("Press to stuff");

jframe.add(jbutton);

jbutton.addActionListener((e)->{

    methodStuff(dialog);
    //stuff to do after dialog has been closed
}

And somewhere in this so called "methodStuff"
...
dialog.dispose();
...

How can I check that this line: "dialog.dispose();" happened?  Is that possible?

A: You need to add a listener to the dialog and put the code you want to execute inside the override method...
Example:
JFrame jframe = new JFrame();
Dialog dialog = new Dialog(jframe);
JButton jbutton = new JButton("Press to stuff");
dialog .addWindowListener(new java.awt.event.WindowAdapter() {
    @Override
    public void windowClosing(java.awt.event.WindowEvent windowEvent) {
            //your code here!!!
    }
});

A: Add window listener and window adapter for tracking this

A: In a simple way, just keep a boolean in the parent class and just change its status(true or false) for the dialog.
Eg- Change the value to true when dialog appears and change the value back to false just before the dispose();.


text:
Q: How to e-mail an offline webpage? I was wondering if there is a way to upload an offline webpage (css, html and some images) into an email. Then send a link to the index.html for the user to click on.
I work for a television production company so the content is not allowed to actually go online. This is part of a pitch so online a small file size.
Thanks!


text:
Q: How to replace repeating characters with the same number of asterisks? I want to replace the repeated characters with the same number of asterisks (*).
For example:
replaceLetters("keviin");

Should return:

kev**n

And:
replaceLetters("haaa");

Should return:

h***

How can I go about doing this?
If I use the following code it does replace the repeating characters, but it replaces the whole repetition with one asterisk instead of the same number of asterisks as repeating characters.
function replaceLetters(s) {
    s.replace(/([^])\1+/g, '*');
}

A: .replace() allows a function to be passed as the second argument. The argument for the callback function passed will be the matched string. Once you have access to the matched string, there are any number of ways you can replace the matched string with the same number of asterisks.
For example, you could turn the string into an array, use map to replace each array item with an asterisk and join the array back together as a string.
function replaceLetters(s) {
    return s.replace(/([^])\1+/g,function(m) {
        return m.split('').map(function(){ return '*' }).join('');
    });
}

Or you could replace every character in the matched string with an asterisk.
function replaceLetters(s) {
    return s.replace(/([^])\1+/g,function(m) {
        return m.replace(/[^]/g,'*');
    });
}

There are many ways you could go about this, it all depends on how you want to accomplish the task.


text:
Q: Dynamic Table with HTML and PHP I show you my following problem .. I basically have the following database .. to understand it I think a practical example is the best way ..
I have a building site where N entrusters can intervene, these N trustees can in turn delegate N Sub-Affidiates.
then pulling the sums I have some relationships between the three tables (which in my language are "Cantiere" "Affidataria" "SubAffidataria")
Building site 1 ------> N Reliable
Relater 1 -----> N Sub-Affidiates
Having said that my problem is the following I have to do a control panel in which for each construction site I have to show the carers and the sub-contractors.
I would like to point out that the Sub-Affiliates do not have "direct" links with the Shipyards, but they have the FK of the Affilatories
It must be structured as follows ...
Under Each Relevant ("Affidataria") the results of the $ sql1 query must be placed
Under each Subsidiary ("SubAffidatari") the results of the $ sql2 query must be placed.
The question is how do I divide everything by columns?
I tried creating a dynamic HTML table .. but it does not work ..
I am attaching my proof ...
<!DOCTYPE html>
<?php
    session_start();
    if(!isset($_SESSION["username"])){
        header('location: ../index.php');
    }else
    {

?>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "my_progettocantiere";

$idCantiere = $_GET["idCantiere"];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT idCantiere,nomeCantiere,codiceCommessa,indirizzoCantiere FROM Cantiere WHERE idCantiere = '$idCantiere'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {

    echo'
' . $row["codiceCommessa"] . '-' . $row["nomeCantiere"] . '
';
    }

} else {
    echo "0 results";
}
$conn1 = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn1->connect_error) {
    die("Connection failed: " . $conn1->connect_error);
}

$sql1 = "SELECT idAffidataria,nomeCantiere FROM Affidataria WHERE fkIDCantiere = '$idCantiere'";
$result1 = $conn1->query($sql1);

//echo "";

if ($result1->num_rows > 0)
    {
    // output data of each row
    while($row1 = $result1->fetch_assoc())
    {

        echo'

';
        echo '
 Affidataria
';
       echo '' . $row1["nomeCantiere"] . '';
       echo '
 SubAffidatario
';
        $idAffidataria = $row1["idAffidataria"];

        $conn2 = new mysqli($servername, $username, $password, $dbname);
// Check connection
    if ($conn2->connect_error)
        {
    die("Connection failed: " . $conn2->connect_error);
        }

    $sql2 = "SELECT * FROM SubAffidatario WHERE fkIdAffidataria = '$idAffidataria'";
    $result2 = $conn2->query($sql2);
    if ($result2->num_rows > 0)
        {
    // output data of each row
        while($row2 = $result2->fetch_assoc())
        {

      //  echo '' . $row1["nomeCantiere"] . '';
        echo'

';
        echo '' . $row2["ragioneSocialeSubAffidatario"] . '';
        }
    //echo'

';
    //echo 'Nuovo Cantiere +';

        }
        else {
        echo "0 results";
        }

    }
    //echo'

';
    //echo 'Nuovo Cantiere +';

    }
    else
    {
    echo "0 results";
    }

$conn->close();

$conn1->close();

$conn2->close();

?>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
   <title>Progetto Cantiere</title>

    <link href="../paginaIniziale/css/bootstrap-4.0.0.css" rel="stylesheet">

<?php } ?>

and this is the result I got:

A: Try with the following code ..
<!DOCTYPE html>
<?php
    session_start();
    if(!isset($_SESSION["username"])){
        header('location: ../index.php');
    }else
    {

?>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "my_progettocantiere";

$idCantiere = $_GET["idCantiere"];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT idCantiere,nomeCantiere,codiceCommessa,indirizzoCantiere FROM Cantiere WHERE idCantiere = '$idCantiere'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {

    echo'
' . $row["codiceCommessa"] . '-' . $row["nomeCantiere"] . '
';
    }

} else {
    echo "0 results";
}
$conn1 = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn1->connect_error) {
    die("Connection failed: " . $conn1->connect_error);
}

$sql1 = "SELECT * FROM Affidataria WHERE fkIDCantiere = '$idCantiere'";
$result1 = $conn1->query($sql1);

//echo "";

if ($result1->num_rows > 0)
    {
    // output data of each row
    while($row1 = $result1->fetch_assoc())
    {

        echo '
';

    echo '
';
        echo '
Anagrafica
';
        echo '
 Affidataria
	';
        echo '
 SubAffidatario

';
        echo '
Anagrafica	';
        echo '' . $row1["nomeCantiere"] . '
';

        $idAffidataria = $row1["idAffidataria"];

        $conn2 = new mysqli($servername, $username, $password, $dbname);
// Check connection
    if ($conn2->connect_error)
        {
    die("Connection failed: " . $conn2->connect_error);
        }

    $sql2 = "SELECT * FROM SubAffidatario WHERE fkIdAffidataria = '$idAffidataria'";
    $result2 = $conn2->query($sql2);
    if ($result2->num_rows > 0)
        {
    // output data of each row
        while($row2 = $result2->fetch_assoc())
        {

      //  echo '' . $row1["nomeCantiere"] . '';
        echo'

';
        echo '
';
        echo '	';
        echo '	';
        echo '' . $row2["ragioneSocialeSubAffidatario"] . '	';
        }
    //echo'

';
    //echo 'Nuovo Cantiere +';

        }
        else {
        echo "0 results";
        }

    }
    //echo'

';
    //echo 'Nuovo Cantiere +';

    }
    else
    {
    echo "0 results";
    }
    echo'
';
    echo '
';

$conn->close();

$conn1->close();

$conn2->close();

?>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
   <title>Progetto Cantiere</title>

    <link href="../paginaIniziale/css/bootstrap-4.0.0.css" rel="stylesheet">

<?php } ?>

A: Try this, but I'm not sure if it's what you asked for, because I did not understand what you wanted.
    <?php

    session_start();

    if(!isset($_SESSION["username"])){
        header('location: ../index.php');
    }

    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "my_progettocantiere";

    $idCantiere = $_GET["idCantiere"];

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);

    // Check connection
    if ($conn->connect_error)
    {
        die("Connection failed: " . $conn->connect_error);
    }

?>

<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Progetto Cantiere</title>

        <link href="../paginaIniziale/css/bootstrap-4.0.0.css" rel="stylesheet">
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">

                <?php

                    $sql = "SELECT idCantiere,nomeCantiere,codiceCommessa,indirizzoCantiere FROM Cantiere WHERE idCantiere = '$idCantiere'";

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

                    if ($result->num_rows > 0) {

                        while($row = $result->fetch_assoc())
                        {

                            ?>

 <?php echo $row["codiceCommessa"] . '-' . $row["nomeCantiere"] ?>

                            <?php
                        }

                    } else {

                        echo "0 results";

                    }

            ?>

                <?php
                    $sql1 = "SELECT idAffidataria,nomeCantiere FROM Affidataria WHERE fkIDCantiere = '$idCantiere'";
                    $result1 = $conn->query($sql1);

                    if ($result1->num_rows > 0)
                    {
                        // output data of each row
                        while($row1 = $result1->fetch_assoc())
                        {

                            ?>

Affidataria

                                    <a class="myButton" href="../../pagineHtml/visualizza/visualizzazione/affidatario.php?idAffidataria= <?php echo $row1["idAffidataria"] ?>">
                                        <?php echo $row1["nomeCantiere"] ?>

SubAffidatario

                                    <?php

                                        $idAffidataria = $row1["idAffidataria"];

                                        $sql2 = "SELECT * FROM SubAffidatario WHERE fkIdAffidataria = '$idAffidataria'";
                                        $result2 = $conn->query($sql2);

                                        if ($result2->num_rows > 0)
                                        {
                                            // output data of each row
                                            while($row2 = $result2->fetch_assoc())
                                            {
                                                ?>

                                                        <a class="myButton" href="../../pagineHtml/visualizza/visualizzazione/affidatario.php?idAffidataria=<?php echo $row2["ragioneSocialeSubAffidatario"]  ?>">
                                                            <?php echo $row2["ragioneSocialeSubAffidatario"]  ?>

                                                <?php
                                            }

                                        }else {
                                            echo "0 results";
                                        }

                        }

                            ?>

                            <?php

                    }else{

                        echo "0 results";

                    }

                    $conn->close();

                ?>


text:
Q: FLASK_APP variable don't work even it's in .env I have installed python-dotenv==0.6.5
And I put FLASK_APP in .env file
DEBUG=True
FLASK_ENV=development
FLASK_APP=flasky.py

But it shows this error when I run flask run
Usage: flask run [OPTIONS]

Error: Could not locate Flask application. You did not provide the FLASK_APP environment variable.

For more information see http://flask.pocoo.org/docs/latest/quickstart/

But if I export FLASK_APP=flasky.py , it works well.
I also tried to put FLASK_APP=flasky.py in .flaskenv file, but I didn't work :(
All other env variables are loaded well. Thanks

A: The problem was FLASK version.
I updated it using pip install --upgrade Flask
Thanks!


text:
Q: Extracting tokens from a text file? I want to be able to extract text from text files as tokens - for example, say I have a text file that contains the sentence:
It's a good restaurant,
believe me!
I want to extract the contents of this as 'tokens' - for example, one token would be "It's", the next token would be " ", the one after that would be "a", then " ", then "good", then "restaurant", then "," and "\n", then "believe", " ", "me", "!". So I guess one way of putting it is that tokens are either words or not words.
Here is what I have so far (I check to see if the token is a word or not elsewhere in the program, this method just returns the next token):
public Token next() {
  if (c == -1) {
        throw new NoSuchElementException();
    }

  Writer sw=new CharArrayWriter();
  try {
        while ( c != -1 && Character.isLetter(c) ) {
            sw.write(c);
            c = r.read();
        }
        while ( c != -1 && !Character.isLetter(c)) {
            c = r.read();
        }
    } catch (IOException e) {
        c = -1;
        return null;
    }
    return null;
}

Right now I have the return values as 'null' because I'm not sure how to use the writer to export it as tokens. Does anyone have any tips for this? Thank you!

A: Take a look at the Scanner class it might suit your needs.
http://docs.oracle.com/javase/6/docs/api/java/util/Scanner.html
If you build a Scanner from your file, you can use the next() method to get your tokens.

A: I guess that a solution using Matcher class could solve your issue.
Matcher m = Pattern.compile("\\p{Alpha}+|\\p{Digit}+|\\p{Punct}+|\\p{Space}+").matcher("It's a good restaurant, believe me!");
while(m.find())
    System.out.println(">"+m.group()+"<");

Maybe this regex could not be the right one, but you can build a better one. See the Pattern documentation in:
http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html


text:
Q: Один post обработчик для нескольких форм. Jquery Здравствуйте, подскажите как приучить код к нескольким формам на странице.
Обработчик:
$(document).ready(function(){
    /* Следующий код выполняется только после загрузки DOM */

    /* Данный флаг предотвращает отправку нескольких комментариев: */
    var working = false;

    /* Ловим событие отправки формы: */
    $('#addCommentForm').submit(function(e){

        e.preventDefault();
        if(working) return false;

        working = true;
        $('#submit').val('Занято...');
        $('span.error').remove();

        /* Отправляем поля формы в comment.php: */
        $.post('comment.php',$(this).serialize(),function(msg){

            working = false;
            $('#submit').val('Отправить');

            if(msg.status){

                /*
                /   Если вставка была успешной, добавляем комментарий
                /   ниже последнего на странице с эффектом slideDown
                /*/

                $(msg.html).hide().insertBefore('#addCommentContainer').slideDown();
                $('#body').val('');
            }
            else {

                /*
                /   Если есть ошибки, проходим циклом по объекту
                /   msg.errors и выводим их на страницу
                /*/

                $.each(msg.errors,function(k,v){
                    $('label[for='+k+']').append(''+v+'');
                });
            }
        },'json');

    });

});

Форма:

Добавить комментарий

<form id="addCommentForm" method="post" action="">

Имя
<input type="text" name="name" id="name" />

Email
<input type="text" name="email" id="email" />

Вебсайт (не обязательно)
<input type="text" name="url" id="url" />

Содержание комментария
<textarea name="body" id="body" cols="20" rows="5"></textarea>

<input type="submit" id="submit" value="Отправить" />

</form>

Нужно чтобы было несколько таких форм на странице и обработчик мог работать с ними по отдельности. Т.е определял с какой формы именно отправлен post, обрабатывал данные и писал ответ.
А в данный момент он работает только с одной.
Можно по идее поменять на id="addCommentForm" на class="addCommentForm" и привешать на каждую форму разный id... Но я не знаю, как потом его выловить через jquery. :(

A: Используй класс вместо id, тогда твой обработчик привяжется ко всем формам, а не первой найденной по id.

A: Можно повешать класс на форму и будем обращаться к классу
$('.addCommentForm').submit(function(e){...

или просто обрабатывать ВСЕ формы
$('form').submit(function(e){...

как вам больше нравится...
а потом определять id формы и передавать его в пост
$id = $(this).attr("id");

или у каждой формы сделать хиден поле в котором будет указан тип формы. В посте будем получать тип и в зависимости от типа по разному обрабатывать


text:
Q: compile and run c++ code runtime Does anyone know how to compile your c++ code wich you write while your program is already running?
And later i would like to run that code.
I want to do this because I am trying to make a game that woul teach you programing and so the user would have to write the code while the game is running and test it.
Thanks for any help

A: You'd have an easier time if you chose a language that was designed with embedding in mind - like LUA or python. For C++, you'd have to go for something extremely clumsy and fragile like invoking an external compiler (which is also a logistics nightmare when shipping your game), or something as complex as integrating a compiler in your game (probably doable with llvm components, but...)
Also, for "teaching programming", C++ probably isn't the best language :)

A: You have to call the compiler to compile and link the user-entered code. This has to be made either into an executable that is then run from another process you create, or as a library that you dynamically load and call.
How this is done is different on POSIX platforms (like Linux and OSX) and Windows.


text:
Q: Debugging modified OpenSSL I would like to modify OpenSSL code and then debug it in my IDE (QTCreator).
I have downloaded the OpenSSL source code, built it according to ./config with debugging symbols, and deployed it in non-system folder. Still, when I make modifications to the library, the changes are not effective in the debugged program.
For instance, I attempt to modify handshake process and test the results using the s_client app. Nevertheless, the s_client app points to the system version of OpenSSL. Namely, s_client includes <openssl/...> (which is located in /usr/local/...).
I would like it to point to the just installed/modified version of openssl in different folder. There's a catch though. I have figured only one way how to do it, by modifying the original OpenSSL makefile, which is just huge and the task seems overwhelming.
Does anyone has any idea how to approach this issue? Please note that I would like to keep the system version of the OpenSSL operational (symbolic link not suitable).
I run the Ubuntu 16.04 LTS. The output of ldd /my/version/of/openssl is
linux-vdso.so.1 =>  (0x00007ffd9a3d6000)
    libssl.so.1.1 => /usr/local/lib/libssl.so.1.1 (0x00007f04523f8000)
    libcrypto.so.1.1 => /usr/local/lib/libcrypto.so.1.1 (0x00007f0451f6a000)
    libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f0451d4d000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f0451983000)
    libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f045177f000)
    /lib64/ld-linux-x86-64.so.2 (0x00007f0452668000)

A: With the help of the two guys (see comments), I was able to figure out the problem. First, make sure you compile OpenSSL with --prefix and --openssl directories properly set.
Once OpenSSL installed, you need your code (apps of OpenSSL) to be calling/linking your new version of OpenSSL. In QtCreator you can achieve this by setting the LD_LIBRARY_PATH to the directory with the library files libcrypto.so.1 and libssl.so.1. The setting is done in Projects -> Run environment -> (add LD_LIBRARY_PATH into system environment).
Moreover, you can check what libraries are called by the binary manually, by entering the directory with the binary and calling command ldd ./openssl from the terminal. This way, you will see what libraries are called (it should be your own version, not the system libraries). Further, you can set LD_LIBRARY_PATH from terminal, optionally with export command in front of it, to achieve permanent effect (lasting whole terminal session). In total, you could call
export LD_LIBRARY_PATH=/path/to/your/lib.


text:
Q: Using where clause with not-equal condition after join I am trying to use WHERE with not-equal condition after joining two tables but it does not work.
Example: I have a table with data on famous people and a separate table with their works. Some works can have several authors. So I want a table listing authors with their co-authors:
CREATE TABLE famous_people (id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT,
    profession TEXT,
    birth_year INTEGER);

INSERT INTO famous_people (name, profession, birth_year)
    VALUES ("Landau", "physicist", 1908);
INSERT INTO famous_people (name, profession, birth_year)
    VALUES ("Lifshitz", "physicist", 1908);
INSERT INTO famous_people (name, profession, birth_year)
    VALUES ("Fisher", "statistician", 1908);
INSERT INTO famous_people (name, profession, birth_year)
    VALUES ("Ginzburg", "physicist", 1916);
INSERT INTO famous_people (name, profession, birth_year)
    VALUES ("A. Strugatsky", "writer", 1925);
INSERT INTO famous_people (name, profession, birth_year)
    VALUES ("B. Strugatsky", "writer", 1933);

CREATE TABLE works (id INTEGER PRIMARY KEY AUTOINCREMENT,
    person_id INTEGER,
    work TEXT);
INSERT INTO works (person_id, work)
    VALUES (1, "Theoretical Physics");
INSERT INTO works (person_id, work)
    VALUES (2, "Theoretical Physics");
INSERT INTO works (person_id, work)
    VALUES (1, "Theory of Superconductivity");
INSERT INTO works (person_id, work)
    VALUES (4, "Theory of Superconductivity");
INSERT INTO works (person_id, work)
    VALUES (3, "Fisher test");
INSERT INTO works (person_id, work)
    VALUES (5, "Roadside Picnic");
INSERT INTO works (person_id, work)
    VALUES (6, "Roadside Picnic");
INSERT INTO works (person_id, work)
    VALUES (5, "Hard to Be a God");
INSERT INTO works (person_id, work)
    VALUES (6, "Hard to Be a God");

/* Co-authors */
SELECT a.name AS author, b.name AS coauthor FROM works
    JOIN famous_people a
    ON works.person_id = a.id
    JOIN famous_people b
    ON works.person_id = b.id;

It is Ok, except each author also has themselves as their own co-author, so I am trying to filter it out by adding WHERE author <> coauthor as the last line. But what I get is a table with two columns: work and name. Same weird result with WHERE a.name <> b.name
Funny enough, WHERE author = coauthor works fine but this is not what I want.
Expected result: a table with 2 columns:
author      co-author
Landau        Lipshitz
A. Strugatsky B. Strugatsky
Fisher        NULL

A: Find all works that have two authors (using inner join on same work but different authors) and find all works that have one author (using not exists). Then combine the results:
SELECT w1.work, p1.name AS author, p2.name AS coauthor
FROM works AS w1
JOIN works AS w2 ON w1.work = w2.work AND w1.person_id < w2.person_id
JOIN famous_people AS p1 ON w1.person_id = p1.id
JOIN famous_people AS p2 ON w2.person_id = p2.id

UNION ALL

SELECT w1.work, p1.name, null
FROM works AS w1
JOIN famous_people AS p1 ON w1.person_id = p1.id
WHERE NOT EXISTS (
    SELECT 1
    FROM works AS w2
    WHERE w2.work = w1.work AND w2.person_id <> w1.person_id
)

Demo on DB<>Fiddle

A: Your query cannot work. Keep in mind that a join works on rows. So there is one works row with one person ID that you look at at a time in your where clause. Then you join the person to the works row and then you join the person to the works row. That is the same person twice of course, because one works row only refers to one person.
This shows another, minor, problem. You call this table works. I would consider "Theoretical Physics" a work. You do so too; you named the column work. But then, why is the same work twice in the works table? This must not be. A works table shall store works, i.e. one work per row. What you have is a work_author table actually, and a work is uniquely identified by its title. This kind of makes sense; a title may uniquely identify a work - as long as no other  author happens to name their work "Theoretical Physics", too :-( And as long as there are no typos in the table either.
This would be a better model:

*

*person (person_id, name, birth_year, ...)

*work (work_id, title, year, ...)

*work_author (work_id, person_id)

If you have a typo in a title in this model, there is one row where you correct it and the data stays intact.
Now you want to get the authors of a work. This is easily done with aggregation:
select w.*, group_concat(p.name) as authors
from work_author wa
join person p on p.person_id = wa.person_id
join work w on w.work_id = wa.work_id
group by w.work_id
order by w.work_id;

You forgot to tell us your DBMS. As you are using double quotes where it must be single quotes according to the SQL standard, and your DBMS doesn't complain, this may be MySQL. (You should still always use single quotes for string literals.) For MySQL the string aggregation function is GROUP_CONCAT, so guessing MySQL, I used that in my query. Other DBMS use STRING_AGG, LISTAGG or something else.
If you just want to show up to two authors per work, you can take the minimum and maximum name (and compare the two in order not to show the same author twice):
select
  w.*,
  min(p.name) as author1,
  case when min(p.name) <> max(p.name) then max(p.name) end as author2
from ...

UPDATE
In the comments you say that for every author you want to know all authors who worked with them. For this you need to join authors to authors based on their works. Still assuming MySQL:
select p1.name, group_concat(distinct p2.name) as others
from work_author wa1
join work_author wa2 on wa2.work_id = wa1.work_id
                     and wa2.person_id <> wa1.person_id
join person p1 on p1.person_id = wa1.person_id
join person p2 on p2.person_id = wa2.person_id
group by p1.name
order by p1.name;

Or not aggregated:
select distinct p1.name as person1, p2.name as person2
from work_author wa1
join work_author wa2 on wa2.work_id = wa1.work_id
                     and wa2.person_id <> wa1.person_id
join person p1 on p1.person_id = wa1.person_id
join person p2 on p2.person_id = wa2.person_id
order by p1.name, p2.name;

A: I changed the model as proposed by Thorsten Kettner and solved the task of matching authors with their co-authors as follows:
CREATE TABLE famous_people (id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT,
    profession TEXT,
    birth_year INTEGER);

INSERT INTO famous_people (name, profession, birth_year)
    VALUES ("Landau", "physicist", 1908);
INSERT INTO famous_people (name, profession, birth_year)
    VALUES ("Lifshitz", "physicist", 1908);
INSERT INTO famous_people (name, profession, birth_year)
    VALUES ("Fisher", "statistician", 1908);
INSERT INTO famous_people (name, profession, birth_year)
    VALUES ("Ginzburg", "physicist", 1916);
INSERT INTO famous_people (name, profession, birth_year)
    VALUES ("A. Strugatsky", "writer", 1925);
INSERT INTO famous_people (name, profession, birth_year)
    VALUES ("B. Strugatsky", "writer", 1933);

CREATE TABLE works (id INTEGER PRIMARY KEY AUTOINCREMENT,
    work TEXT,
    subject TEXT);
INSERT INTO works (work, subject)
    VALUES ("Theoretical Physics", "physics");
INSERT INTO works (work, subject)
    VALUES ("Theory of Superconductivity", "physics");
INSERT INTO works (work, subject)
    VALUES ("Fisher test", "statistics");
INSERT INTO works (work, subject)
    VALUES ("Roadside Picnic", "scifi");
INSERT INTO works (work, subject)
    VALUES ("Hard to Be a God", "scifi");

CREATE TABLE author_works (id INTEGER PRIMARY KEY AUTOINCREMENT,
    work_id INTEGER,
    author_id INTEGER);
INSERT INTO author_works (work_id, author_id) VALUES (1, 1);
INSERT INTO author_works (work_id, author_id) VALUES (1, 2);
INSERT INTO author_works (work_id, author_id) VALUES (2, 1);
INSERT INTO author_works (work_id, author_id) VALUES (2, 4);
INSERT INTO author_works (work_id, author_id) VALUES (3, 3);
INSERT INTO author_works (work_id, author_id) VALUES (4, 5);
INSERT INTO author_works (work_id, author_id) VALUES (4, 6);
INSERT INTO author_works (work_id, author_id) VALUES (5, 5);
INSERT INTO author_works (work_id, author_id) VALUES (5, 6);

/* List of authors and their works */
SELECT famous_people.name, works.work FROM author_works
    JOIN famous_people
    ON author_works.author_id = famous_people.id
    JOIN works
    ON works.id = author_works.work_id;

/* Authors and co-authors ids*/
SELECT DISTINCT a.name, b.name
    FROM author_works aw1
    JOIN author_works aw2
    ON aw1.work_id = aw2.work_id
    JOIN famous_people a
    ON aw1.author_id = a.id
    JOIN famous_people b
    ON aw2.author_id = b.id
    WHERE aw1.author_id <> aw2.author_id;


text:
Q: Toggle all layers in Leaflet I am using CSS buttons to toggle map layers in a leaflet.js environment. I have 25 layers. I would like to add 1 more button that will toggle ALL layers on/off. Here is the code I use for toggling the layers.

 1
 2
 3
 4
 5
 6
7
25


text:
Q: Build (and Debug) ASP.NET Web Application in a non-default folder location I have a Visual Studio 2008 solution with an ASP.NET Web Application project.  I want to change the default output folder, of said project, to $(SolutionDir)\WebApps\$(ProjectName)\bin.  This I can do and when I build I get the expected assembly files in this folder.  It doesn't copy the content files (aspx, etc.) to the parent folder but I have managed to fix this by hacking the project.csproj file with a custom build target.
The problem is I want to be able to debug this application using the ASP.NET Development Server, by pressing F5 in VS2008.  Unfortunately the ASP.NET Dev server starts, has a "Physical Path", in the project directory rather than the parent of the output directory.
Is there any way to build my web application to a different output folder but still run the asp.net dev server to debug my site?
Thanks.

A: Short answer is yes, but it isn't pretty.  The process I used is given below.

*

*Unloaded the project in VS.

*Manually edited the .csproj file to include a post build action that basically copies the content files (aspx, etc.) to the parent of the output folder.

*For the debug options I set the project to launch an external executable.  The Asp.Net Development server.  Also manually set the url to launch.

What I learnt?  I wouldn't do this, I'd just stick with the default and create an install/web deployment project instead.


text:
Q: Creating a Label via a method in a class I am slowly developing a custom button (while learning how to implement classes etc).
I have a ViewController, which imports a SuperButton.h (UIControl) and then creates an instance of the SuperButton. (This works, as proved by a NSLog.)
But I cannot get the method in SuperButton to display a Label.
I think this might have something to with the '.center' value or the 'addSubview' command?
I would really appreciate your help. Thanks.
Here is my SuperButton.m code:
#import "SuperButton.h"

@implementation SuperButton
@synthesize firstTitle;
@synthesize myLabel;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}
- (void) shoutName{
    NSLog(@"My name is %@", firstTitle);

    self.backgroundColor = [UIColor blueColor];
    CGRect labelFrame = CGRectMake(0.0f, 0.0f, 100.0f, 50.0f);
    self.myLabel = [[UILabel alloc] initWithFrame:labelFrame];
    self.myLabel.text = @"Come on, don't be shy.";
    self.myLabel.font = [UIFont italicSystemFontOfSize:14.0f];
    self.myLabel.textColor = [UIColor grayColor];
    self.myLabel.center = self.center;
    [self addSubview:self.myLabel];
}

Here is the code in my ViewController:
- (void) makeButton{
    SuperButton *button1 = [[SuperButton alloc] init];
    button1.firstTitle = @"Mr. Ploppy";
    [button1 shoutName];
}

(EDIT:) Just in case, here's the SuperButton.h code:
#import <UIKit/UIKit.h>
@interface SuperButton : UIControl

@property (nonatomic, strong) NSString *firstTitle;
@property (nonatomic, strong) UILabel *myLabel;

- (void) shoutName;

@end

A: I found an answer elsewhere.
I needed to addSubview the 'button'. My working code now looks like this:
- (void) makeButton{
    SuperButton *button1 = [[SuperButton alloc] init];
    button1.firstTitle = @"Mr. Ploppy";
    [button1 shoutName];
    [self.view addSubview:button1.myLabel];
    [self.view sendSubviewToBack:button1.myLabel];
}

A: You are initializing your button not with initWithFrame: method, but with simple init. This makes the button of CGRectZero size. Change this line:
SuperButton *button1 = [[SuperButton alloc] init];

to this:
SuperButton *button1 = [[SuperButton alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 100.0f, 50.0f)];

or add a call to setFrame: after initializing your button.


text:
Q: Is the universe linear? If so, why? I'm trying to build a quantum memory system that uses the superposition principle to model specific phenomenon I am trying to predict.
Is the universe linear? The superposition principle would apply in all cases if the universe is linear, which would make sense as the quantum theory is the most accurate theory so far.
If the universe is linear, why is it? Why not semi or non linear?

A: This question is very hard to answer at a fundamental level, because quantum mechanics seems to be exact so far, yet one cannot be sure in the scientific sense without confirmation that nontrivial quantum computation is possible. If this is so, then one would have to renounce any classical descriptions, at least within the bounds of scientific reason, and it is likely that quantum mechanics is the final word. If this is not so, then of course, all bets are off.
One should say at first that any system can be converted to an exactly linear system by making probability distributions. Suppose you have a nonlinear equation, for example:
$$ {dx\over dt} = {1\over x^2 + 1} $$
Now you have a nonlinear relation between $x(0)$ and $x(t)$. Suppose you say "I don't know $x(0)$, but I have an idea that it is described by a probability distribution $\rho(x_0)$". Then you can say, knowing how x is changing, how the probability distribution $\rho$ is changing. The equation for $\rho$ is always linear, even if the underlying dynamics for x is nonlinear.
The reason is simple--- if you have a probability distribution which is a linear combination of two others:
$$ \rho(x_0) = \alpha \rho_1(x_0) + (1-\alpha)\rho_2(x_0) $$
you can interpret this distribution by the following process: flip a coin which has probability $\alpha$ of landing heads, then pick $x_0$ according to $\rho_1$ if you got heads, and according to $\rho_2$ if you got tails. Then evolve $x_0$ according to the nonlinear equation.
You can also pick an $x_0$ from $\rho_1$ and pick and $x_0'$ from $\rho_2$ and evolve both of these, and then choose one of the outcomes using the same coin. Clearly (meaning it is equivalent to the axioms of probability) flipping the coin at the beginning to find $x_0$ is the same as evolving a pick from $\rho_1$ and $\rho_2$ without knowing which is which, and flipping the coin at the end. The reason is that we know there is a secret $x_0$ underneath, and the probability of the $x_0$ being what it is doesn't care when we find out the answer as to which it was, so long as we find out the answer eventually.
This tells you that the time evolution operator for probability distributions obeys:
$$ T\rho =  \alpha T \rho_1 + (1-\alpha)T \rho_2 $$
This is the fundamental linearity of probability theory.
Similarly, for GR, and you consider probability distributions on metrics, the equation for the probability distribution is always linear. This doesn't make solving the equations any easier, because the linear space is so much more enormous--- the difficulty of solving for the evolution of probability distributions on classical systems, is by Monte-Carlo roughly the same as solving the classical equations many times.
The thing about quantum mechanics is that it is like probability, in that the equation of motion is always linear. It is also like probability in that it is formulated over the space of all configurations, so the number of real numbers you use grows exponentially with the size of the system.
But Quantum mechanics is not like probability in that it has interference. This means that you can't use the ignorance justification for the perfect linearity--- you can't say "the reason the wavefunction evolves perfectly linearly is because it is representing the ignorance of coin-tosses at the beginning", because the only reasonable calculus for ignorance is probability.
It also means that it is not possible to use Monte-Carlo in general to simulate quantum mechanics with multiple samples (although it is amazing to what extent you can do quantum monte-carlo, you need to do an impossible analytic continuation to turn it into general real space results). This is almost a theorem, since Monte Carlo can't have exponential speed-up for classical computation. So the existence of Shor factoring and other exponential speed-ups means you can't simulate a quantum computer efficiently with a stochastic classical one.
But quantum mechanics is still mixed up with probability, because the probabilities are the square of the wavefunction values. In general, the diagonal elements of the density matrix are probabilities when you measure, and need to obey exact classical linearity of probability theory when you have multiple measurements.
This restriction means that you have a very hard time imagining quantum mechanics having a slight nonlinearity, since it is difficult or impossible to make sure that the probability theory included in the classical limit is going to be exactly linear (in the limit of classical measurements) if the underlying quantum dynamics is not exactly linear. There are attempts from time to time to collapse the wavefunction using nonlinearity, but these are generally misguided. If you do a nonlinear interaction on a probability like entity like the wavefunction, you get interaction between different possible worlds, or Everett branches, not a sensible collapse to one of the possible worlds.
So yes, with scientific standards of knowledge, if quantum mechanics is exact, it is linear. If quantum mechanics fails, it is likely because it is a stochastic description of some underlying variables, but what this could be is very difficult to imagine.


text:
Q: Json response using django 1.8 I need help in generating json response in the following way using Django 1.8 pl help thanks in advance.
{"files": [
  {
    "name": "picture1.jpg",
    "size": 902604,
    "url": "http:\/\/example.org\/files\/picture1.jpg",
    "thumbnailUrl": "http:\/\/example.org\/files\/thumbnail\/picture1.jpg",
    "deleteUrl": "http:\/\/example.org\/files\/picture1.jpg",
    "deleteType": "DELETE"
  },
  {
    "name": "picture2.jpg",
    "size": 841946,
    "url": "http:\/\/example.org\/files\/picture2.jpg",
    "thumbnailUrl": "http:\/\/example.org\/files\/thumbnail\/picture2.jpg",
    "deleteUrl": "http:\/\/example.org\/files\/picture2.jpg",
    "deleteType": "DELETE"
  }
]}

A: Hm, do it like described in the documentation
from django.http import JsonResponse
data = {"files": [
  {
    "name": "picture1.jpg",
    "size": 902604,
    "url": "http:\/\/example.org\/files\/picture1.jpg",
    "thumbnailUrl": "http:\/\/example.org\/files\/thumbnail\/picture1.jpg",
    "deleteUrl": "http:\/\/example.org\/files\/picture1.jpg",
    "deleteType": "DELETE"
  },
  {
    "name": "picture2.jpg",
    "size": 841946,
    "url": "http:\/\/example.org\/files\/picture2.jpg",
    "thumbnailUrl": "http:\/\/example.org\/files\/thumbnail\/picture2.jpg",
    "deleteUrl": "http:\/\/example.org\/files\/picture2.jpg",
    "deleteType": "DELETE"
  }
]}
return JsonResponse(data)


text:
Q: geometry of the node from dae file is nil I've made 3d model with blender and I want to use it in scene kit.
var platform = SCNNode();
let dae = SCNScene(named:"platform.dae");
platform = dae!.rootNode;
platform.position = SCNVector3(x: 0,y: 0,z:0);
if platform.geometry == nil {
    print("geo is nil.")
}
platform.geometry?.firstMaterial?.diffuse.contents = "wood.png";
platform.geometry?.firstMaterial?.diffuse.wrapS = SCNWrapMode.Repeat
platform.geometry?.firstMaterial?.diffuse.wrapT = SCNWrapMode.Repeat
platform.physicsBody = SCNPhysicsBody(type: SCNPhysicsBodyType.Static, shape: SCNPhysicsShape(node: platform, options: nil));
scene.rootNode.addChildNode(platform);

It always prints out "geo is nil". So I can't make a physics body for the model. Can anyone tell me why does this happen?

A: The DAE file, when loaded, returns a full node tree. If the Blender file has a light and a camera (which it almost certainly does), so does the DAE's node tree. The root SCNNode doesn't have a geometry (and there's no requirement that an SCNNode have one). But you can find the children that do.
print (platform)
platform.childNodes.map {
    print($0.name, $0.geometry)
}

produces
<SCNNode: 0x7fe008e938d0 | 3 children>
Optional("Camera") nil
Optional("Lamp") nil
Optional("Cube") Optional(<SCNGeometry: 0x7fe00ab08930 'Cube'>)

You can use childNodeWithName() or childNodesPassingTest() to pick out the object you want and add it to your scene.


text:
Q: Minimize all windows on the active monitor I'm looking for a way to use a keyboard shortcut to minimize all the windows on the monitor that currently has my mouse on it. I found this page: http://vbcity.com/forums/t/163339.aspx but that appears to be hardcoded to minimize windows on a specific monitor, rather than the active monitor. Plus, I have no idea how to compile that code (not a VB coder). Anybody know a way that I can make this happen? I'm on Windows 7 ultimate, 3 monitors.

A: Under Windows 7, here is the list of the keyboard shortcuts that manage multiple windows :
Win+d
Minimize all windows on all Monitors. Press again to restore previous state
Win+m
Minimize all windows on all Monitors.
Win+Shift+m
Restore previously minimized windows on current Monitor
Win+Home
Set all windows to Minimized on current Monitor except active
Win+Space
Preview Desktop / make windows transparent (May not work with all Settings)
Source : 127 useful Keyboard Shortcuts for Windows 7.
The OP notes that Actual Multiple Monitors has an option for "Minimize All command affects only the monitor with mouse".

A: The other answer, although superior, is not as fun as mine. Take one active window and shake it. All other windows will be minimized. Then minimize that window

A: I found another way to resolve this problem. I write autohotkey script to make all program minimize except some program. I often move Xshell and git command to another monitor, so I make them maximize again. The script like following, hope can help you.
#d::get()
get(){
    WinMinimizeAll
    WinGet, active_id, ID, ahk_exe Xshell.exe
    WinMaximize, ahk_id %active_id%

    WinGet, active_id, ID, ahk_exe mintty.exe
    WinMaximize, ahk_id %active_id%
}

You can replace "Xshell.exe" and "mintyy.exe" with another program and move them to another monitor then press Win+d to make all program minimize exclude
you specified.
How to run autohotkey you can click here.


text:
Q: Multiple dns suffix/search base on Windows DHCP I am trying to find out how can I give out more than one DNS suffix on a DC with the Windows DHCP server.
  Is it possible somehow? (Win 2K8 with XP, Win7 and Linux clients)

A: You can use DHCP option 119 for a domain search list.  It's format is a String which is semi-colon delimited (e.g. mydomain.com;dev.mydomain.com)
Related:
Which DHCP Client OS Support DHCP Option 119 Domain Suffix Search?

A: Some DHCP servers have the ability to assign a DNS suffix search list to DHCP clients through the use of DHCP option 119; however, Windows Server does not support this functionality by default. Furthermore, Windows DHCP clients do not support option 119 at all. Option 119 can be created manually on a Windows DHCP server using the procedure listed in DHCP Search Options, but this will only provide a DNS suffix search list to non-Windows clients that support it. In short, there is no way to assign a DNS suffix search list to a Windows client using DHCP.
A DNS suffix search list can be assigned to domain-joined Windows machines via Group Policy by following the procedure in Configure the DNS Suffix Search List for a Disjoint Namespace.
Information source - Unable to configure DNS suffix search list via DHCP @ Dell Knowledge base

A: If you have linux clients (and Macs) you can use DHCP option 119 Domain-search-list.  If you have a WIndows DHCP server then in the windows DHCP snap-in you'll find it in the server scope pre-defined options.  You have to add option 119 there.  You have to choose byte array and you have to enter the bytes of the search domains in a kind of weird pascal string format.  It's easier to enter them backwards in windows DHCP snap-in.
ex.com,am.com would be in hex:
02 0x065 0x78 03 0x63 0x6f 0x6d 0x00 0x02 0x61 0x6d 0x03 0x63 0x6f 0x6d 0x00
2bytes e x 3bytes c o m 0null 2bytes a m 3bytes c o m 0null

Windows clients will ignore this though.  For them you have to use a GPO.
It's much simpler with a linux DHCP server.


text:
Q: Custom arrow shapes in tikzcd The tikz-cd package comes with plenty of arrow head and tail options, but there are some more adventurous applications that are harder to implement. In my particular case, I would like to replace the arrow with a long triangle, as illustrated in this mock-up:

There are dedicated chemistry notation packages with this kind of arrow/bond packages available, but I want the output to be consistent with the other diagrams I have in my work, so a tikz-cd-based option would be preferred. A solid triangle would also be acceptable if that is easier for whatever reason.
MWE (outputs dashed line where I would like the triangle to be):
\documentclass[11pt]{article}
\usepackage{tikz-cd}

\begin{document}

\begin{tikzcd}
K \ar[dr,dashed, no head] & & \\
& A \ar[dr,two heads] & \\
& & X
\end{tikzcd}

\end{document}

A: So, here's a solution that involves remember picture and to draw afterwards your tikz-cd, but I think it could be enough for your purpose.

\documentclass[11pt]{article}
\usepackage{tikz-cd}
\usetikzlibrary{calc}

\newcommand{\triar}[2]{
    \draw[orange] ($(#2)!0.2!(#1)$) -- ($ (#2)!0.8! 10:(#1) $) -- ($ (#2)!0.8! -10:(#1) $)  --cycle;
    }

\begin{document}

    \begin{tikzcd}[remember picture]
        |[alias=K]|K  & & \\
        & |[alias=A]|A \ar[dr,two heads] & \\
        & & X
    \end{tikzcd}

    \begin{tikzpicture}[overlay,remember picture]
        \triar{K}{A};
    \end{tikzpicture}

\end{document}

If you're not familiar with the calc library, when you type ($ (#2)!0.8! 10:(#1) $), it means the point between arg2 and arg1 (here between A and K), but with an additional turn by 10°. The triangle is made with this. You can change the value of the angle like you want.
Of course, the orange colour is only here to emphasize the new arrow.
EDIT
Here's a little variation, letting you pass the angle as a parameter, because on more complex diagrams, it could be interesting to customize that point.
\documentclass[11pt]{article}
\usepackage{tikz-cd}
\usetikzlibrary{calc}

\newcommand{\triar}[3]{
    \draw[orange] ($(#2)!0.1!(#1)$) -- ($ (#2)!0.9! #3:(#1) $) -- ($ (#2)!0.9! -#3:(#1) $)  --cycle;
    }

\begin{document}
    \begin{tikzcd}[remember picture]
        |[alias=A]|A \arrow{d} \arrow{r}[near start]{\phi}[near end]{\psi}
        & |[alias=B]|B  & |[alias=E]| E\\
        |[alias=C]|C \arrow[red]{r}[blue,below]{\eta}
        & |[alias=D]|D \arrow[purple]{r}[green,below]{\nu} & |[alias=F]| F
    \end{tikzcd}

    \begin{tikzpicture}[overlay,remember picture]
        \triar{E}{C}{2};
    \end{tikzpicture}

\end{document}

I also changed the percentage to .1 and .9 for start and end of the triangle, it seems better to me like this.

And of course, I know this commutative diagram is absurd, it's just to show the new arrow properties.


text:
Q: How i can solve NULL value problem when selectingfrom a table? I have students TABLE with 4 3 columns:

*

*first which has the first name

*middle which has the middle name and NULL VALUES

*last the last name

*house the name of the house

*birth the date of birth of each person

I want to SELECT all records WHERE house is Gryffindor including records which has middle value is NULL.
SELECT first || " " || middle || " " || last || "," || " " || "born" || " " || birth AS birth
FROM students
WHERE house LIKE "Gryffindor"
ORDER BY last, first;

A: One quick and dirty workaround here would be to use COALESCE against all the name components:
SELECT COALESCE(first, '') || ' ' ||
       COALESCE(middle || ' ', '') ||
       COALESCE(last, '') || ', born ' || birth AS birth
FROM students
WHERE house = 'Gryffindor'  -- assuming you want a specific house
ORDER BY last, first;


text:
Q: Best way to version control T-SQL?
Possible Duplicate:
Stored procedures/DB schema in source control

What's the best way to version control my tables, views, sprocs, etc? Preferably automated or at least semi-automated :)
Thanks

A: I asked this one yesterday and got some nice responses:
Stored procedures/DB schema in source control

A: The articles from K Scott Allen say it all:
http://odetocode.com/Blogs/scott/archive/2008/01/31/11710.aspx

A: Write migration scripts for all db changes and keep them in a repository. Enforce a policy of making all changes to the db only by running a script; that way there is a record of what has been done, and a way to revert it. Investigate whether there's a migrations framework available for your favorite language/db combination.

A: I use Visual Studio 2008 Pro create Database projects (Other project types -> Database).  We already use SVN as a code repository, so a project with a bunch of .sql files representing your stored procedures is just another thing to put in the repository - you can see diffs/history etc.  This works the same with VSS or any other repository you use.
The nice thing about Database projects is that your project will remember your connection string, and all you have to do is right click on a .sql file (or select all of them at once!) and select run to update it in the db.  This makes it easy to update your .sql files from the repository and run them all to update all your stored procedures, verifying your database is updated in seconds.
You can also select create a LINQ project (Visual C# -> Database) and store all your LINQ code in your repository.
Hope that helps!

A: If you were super lazy you could use the SMO (SQL Server Management Objects) or if using SQL Server prior to 2005 the DMO (distributed managmeent objects) to script out all tables/views/stored procedures daily and then compare the script to the script in source control and if there are any changes check the new version in.  You won't be able to necessarily have as pretty of a script as if you just created all db changes in scripts, but at least you can recreate all tables/stored procedures/views.  For example, in my table creation scripts there are often comments.
Here is an article to get you started on scripting: http://www.sqlteam.com/article/scripting-database-objects-using-smo-updated.
Again, this is mainly if you are too lazy to bother with version control and it won't help if you change something twice in one day.  Also any data migration scripts still have to be saved and checked in because this won't pick up ad hoc SQL, only database objects.

A: I'm using Visual Studio Database edition which can export the schema from SQL Server in to a Visual Studio project.  This is then stored in Source Control and can be deployed where ever needed.  The VS Database project is just a bunch of scripts though and it's a clunky way of working.
A more robust method would be to use a database migration framework and if you're working with .Net check out this blog post for a good description http://flux88.com/NETDatabaseMigrationToolRoundup.aspx.
Update
As mentioned in the comments, this page is no more. So here is the last known snapshot from wayback machine http://web.archive.org/web/20080828232742/http://flux88.com/NETDatabaseMigrationToolRoundup.aspx

A: Try Randolph, One of the best SQL Version control tools I know.

A: I have written a DDL trigger which logs all the changes done to the definition of SQL objects (triggers, tables, SP, view etc). I could very well invoke extended SP from the trigger and store the details in another Database and use that as repository.
But if your team is really disciplined any source control should do the trick. The trigger is used as an audit mechanism and it's ideal for teams which are geographically scattered.


text:
Q: How to align an element in case of multiple elements in SwiftUI? I am trying to alight my text Final Context below Hello World and after Text1 but I am unable to do so, here is my code. I am new to SwiftUI.

           VStack {
               HStack{
                   Text("Text1")
                   Toggle(isOn: binding){
                    Text("Hello World")
                   }.padding()
               }
               Text("Final Context")
           }

        }

A: What about this:
 struct align: View {
     @State private var binding = false
     var body: some View {
        HStack(alignment: .top){
              VStack{
                 Text("Text")
              }
              .padding(.top, 5)

              VStack(alignment: .leading){

                 Toggle(isOn: $binding){
                    Text("Hello World")
                 }

                 Text("Final Context")
              }
        }
     }
  }

A: Try adding alignment: .leading to the VStack:
VStack(alignment: .leading) {
    HStack {
        Text("Text")
        Toggle(isOn: binding) {
            Text("Hello World")
        }.padding()
    }
    Text("Final Context")
}

A: You have to align your vStack to leading. Your code should look like this:
import SwiftUI
struct ContentView: View {

    @State private var binding = false

    var body: some View {
        VStack(alignment: .leading) {
           HStack{
               Text("Text")
               Toggle(isOn: $binding){
                Text("Hello World")
               }.padding()
           }
           Text("Final Context")
       }
    }
}

Then you get the alignment, like this:

A: Use a VStack inside HStack.
var body: some View {
    VStack {
      HStack{
        Text("Text")
        VStack(alignment:.leading){
          Toggle(isOn: $toggle){
            Text("Hello World")
          }
          Text("Final Context")
        }
      }
    }
  }


text:
Q: Is there a realiable way to troubleshoot wake up from sleep in Windows? Is there a reliable way to troubleshoot laptop wakes? I've seen "heuristics" posted here and there but isn't there really a simple and deterministic way to tell what's causing a problem?
Specifically, my laptop wakes up about every hour for about 2 minutes. Exported event log entries are here: http://www.mediafire.com/?abcqb00v5wyo6pj.
I've tried:
powercfg -devicequery wake_armed

Empty result set.
Scheduled tasks - the main ones are not scheduled to run every hour. When go through a long list of all possible tasks, there are some that are set to be triggered every hour (e.g., MS "RacTask" whatever it is). But when I go to power options, Advanced settings, Sleep, Allow wake timers it is set to "Disable". Also, the specific task is not set to wake the computer if necessary.
Power options for my Ethernet card don't enable it to wake the computer - the cable is disconnected anyway. There are no other HW devices attached - no USB disks, no keyboards / mice etc. I am really clueless and quite unhappy that it's so hard to troubleshoot this situation.

A: Resume is tough to troubleshoot sometimes, usually it is a 3rd party driver or software that is causing the problem, not a windows system driver, task or software. Use msconfig to disable Non microsoft items under startup and services tabs, see if it cures it. If it does re-enable them one at a time until the problem comes back, then you have the culprit.
You can also check device manager under network, check the properties of each network adapter, go to the power management tab and be sure the box "allow this device to wake the computer" is Unticked. Do this for all adapters present.
.

A: There are (generally) three locations that configure WOL capability.

*

*BIOS. Depending on your BIOS you may have advanced options beyond a simple enable/disable option.

*Windows power management options.

*Power management options of the device itself.
If you are trying to completely disable WOL, verify that it's disabled in the BIOS.


text:
Q: Enumerating and Switching Wireless Profiles in WM6 without using OpenNetCF I'm trying to enumerate and switch wireless profiles under Windows Mobile 6. The unit that I'm using is the SocketMobile 650. I've pretty much ruled out using OpenNetCF to accomplish this, since the GetAllNetworkInterfaces() call returns a wifi network interface that doesn't appear to advertise itself as WirelessZeroConfigNetworkInterface (or even WirelessNetworkInterface, for that matter).
So, I'm back to looking at API calls. My question is: How can I use c# to enumerate and switch wireless profiles without using OpenNetCF?

A: sorry, looks like SO "insert code" does not handle long code listings well, so codes look bad. Please copy/paste them into your editor, and do reformatting.
items (1), (2), (3) are quite trivial - they are just definitions of classes/structs/export functions. Item (4) is where all magic happens - but i was not able to insert it here  (too long), so I copied it to PasteBin (link is below). Please let me know if you have any questions - i will try to help you - but idea is to use DeviceIoControl low-level function to communicate with the adapter.

please take a look at the codes. I don't think you will be able to compile them, however they should give you an idea what's going on under the hood. Disclaimer - i wrote them 5-6 years ago, and now i would do it quite different :)

*

*C# wrapper for C++ dll:
public class WiFiDllWrapper
{
    private class DllFunctions
    {
        [DllImport("ewf.dll")]
        internal static extern bool TurnWlanOn();
    [DllImport("ewf.dll")]
    internal static extern bool FindWirelessAdapter();

    [DllImport("ewf.dll")]
    internal static extern bool ConnectToAdapter();

    [DllImport("ewf.dll")]
    internal static extern bool DisconnectFromAdapter();

    [DllImport("ewf.dll")]
    internal static extern bool StartScan();

    // gets a list of APs from NIC
    [DllImport("ewf.dll")]
    internal static extern bool GetAPsList([In, Out] APInfo[] pAPs, int maxAPs, ref int foundAPs);

    // connects to a selected AP
    [DllImport("ewf.dll")]
    internal static extern bool ConnectToAP(int maxWaitTimeSeconds, string ssid, bool isWepEnabled, string wepKey);

    [DllImport("ewf.dll")]
    internal static extern bool RenewIPAddress(int maxWaitTimeSeconds);

}

public static bool TurnWlanOn()
{
    return DllFunctions.TurnWlanOn();
}

public static bool FindWirelessAdapter()
{
    return DllFunctions.FindWirelessAdapter();
}

public static bool ConnectToNdis()
{
    bool bDisableWzcViaDriver = (Settings.GetOSVersion() != OSVersion.WM2003);

    bool bRes = DllFunctions.ConnectToAdapter();

    return bRes;
}

public static bool DisconnectFromNdis()
{
    return DllFunctions.DisconnectFromAdapter();
}

public static void StartScan()
{
    DllFunctions.StartScan();
}

public static bool ConnectToAP(int maxWaitTimeSeconds, string ssid, bool isWepEnabled, string wepKey)
{
    DllFunctions.ConnectToAP(maxWaitTimeSeconds, ssid, isWepEnabled, wepKey);
    return true;
}

public static bool RenewIPAddress(int maxWaitTimeSeconds)
{
    return DllFunctions.RenewIPAddress(maxWaitTimeSeconds);
}

public static List<AccessPoint> GetAPsList()
{
    int numberOfItems = 0;  // gets a number of actually found devices
    APInfo[] OutputList = new APInfo[30];

    if (DllFunctions.GetAPsList(OutputList, OutputList.Length, ref numberOfItems) == false)
        throw new Exception("AP scan failed!");

    List<AccessPoint> lst = new List<AccessPoint>();
    for (int i = 0; i < numberOfItems; i++)
        lst.Add(new AccessPoint(OutputList[i]));

    return lst;
}

}

*AccessPoint model definition:
// just took enums from NTDDNDIS.H file...

enum NDIS_802_11_WEP_STATUS
{
    Ndis802_11WEPEnabled,
    Ndis802_11Encryption1Enabled = Ndis802_11WEPEnabled,
    Ndis802_11WEPDisabled,
    Ndis802_11EncryptionDisabled = Ndis802_11WEPDisabled,
    Ndis802_11WEPKeyAbsent,
    Ndis802_11Encryption1KeyAbsent = Ndis802_11WEPKeyAbsent,
    Ndis802_11WEPNotSupported,
    Ndis802_11EncryptionNotSupported = Ndis802_11WEPNotSupported,
    Ndis802_11Encryption2Enabled,
    Ndis802_11Encryption2KeyAbsent,
    Ndis802_11Encryption3Enabled,
    Ndis802_11Encryption3KeyAbsent
};
enum NDIS_802_11_NETWORK_INFRASTRUCTURE
{
    Ndis802_11IBSS,
    Ndis802_11Infrastructure,
    Ndis802_11AutoUnknown,
    Ndis802_11InfrastructureMax         // Not a real value, defined as upper bound
};
enum NDIS_802_11_NETWORK_TYPE
{
    Ndis802_11FH,
    Ndis802_11DS,
    Ndis802_11OFDM5,            // Added new types for OFDM 5G and 2.4G
    Ndis802_11OFDM24,
    Ndis802_11NetworkTypeMax    // not a real type, defined as an upper bound
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
struct APInfo
{
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 40)]
    public string _ssid;    // SSID of the AP
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)]
public string _mac; // MAC address of the AP

//[MarshalAs(UnmanagedType.U4)]
public int _rssi;   // signal strength in dB
//[MarshalAs(UnmanagedType.U4)]
public uint _wepStatus;

[MarshalAs(UnmanagedType.I4)]
public NDIS_802_11_NETWORK_INFRASTRUCTURE _networkInfrastructure;
[MarshalAs(UnmanagedType.I4)]
public NDIS_802_11_NETWORK_TYPE _networkType;

[MarshalAs(UnmanagedType.U4)]
public uint BeaconPeriod;       // units are Kusec

[MarshalAs(UnmanagedType.U4)]
public uint DSConfig;           // Frequency, units are kHz

[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
public byte[] _rates;          // MSDN: Each byte describes a single rate in units of 0.5 Mbps

}
public class AccessPoint
{
    //  if the power level (in dBm) lower that this, then the signal is weak
    const int STRONG_WEEK_dBm_THRESHOLD = -70;
public static bool IsSignalWeak(int SignalStrengthdBm)
{
    return SignalStrengthdBm < STRONG_WEEK_dBm_THRESHOLD;
}

internal AccessPoint(APInfo apInfo)
{
    _ssid = apInfo._ssid;
    _mac = apInfo._mac;
    _rssi = apInfo._rssi;
    _wepStatus = apInfo._wepStatus;

    _networkInfrastructure = apInfo._networkInfrastructure;
    _networkType = apInfo._networkType;
    BeaconPeriod = apInfo.BeaconPeriod;
    DSConfig = apInfo.DSConfig;
    _rates = apInfo._rates;
}

private string _ssid;   // SSID of the AP
private string _mac;    // MAC address of the AP

private int _rssi;  // signal strength in dB
private uint _wepStatus;
private NDIS_802_11_NETWORK_INFRASTRUCTURE _networkInfrastructure;
private NDIS_802_11_NETWORK_TYPE _networkType;

private uint BeaconPeriod;      // units are Kusec

private uint DSConfig;          // Frequency, units are kHz

private byte[] _rates;          // MSDN: Each byte describes a single rate in units of 0.5 Mbps

public bool IsEncrypted
{
    get
    {
        return _wepStatus != 0;
    }
}

/// <summary>
/// Beacon Interval in ms
/// </summary>
public ulong BeaconInterval
{
    get { return BeaconPeriod; }
}

/// <summary>
/// Frequency in MHz
/// </summary>
public ulong Frequency
{
    get { return (DSConfig / 1000); }
}

/// <summary>
/// Supported Rates by AP. Part of them belongs to Basic Rate Set.
/// </summary>
public string Rates
{
    get
    {

        Array.Sort(_rates);

        string basicRateSet = "", notBasicRateSet = "";
        for (int i = 0; i < _rates.Length; i++)
        {
            if (_rates[i] == 0)
                continue;

            // Each supported rate from the BSSBasicRateSet is encoded as a byte with the most significant bit (bit 7) set to 1.
            if ((_rates[i] & (1 << 7)) > 0)
                basicRateSet += ((_rates[i] - 128) / 2).ToString() + "; ";
            // Rates that are not included in the BSSBasicRateSet are encoded with the most significant bit set to zero.
            else
                notBasicRateSet += (_rates[i] / 2).ToString() + "; ";
        }

        return "BSSBasicRateSet: {" + basicRateSet + "}. other: {" + notBasicRateSet + "}";
    }
}

/// <summary>
/// Number of wireless channel
/// </summary>
public ulong Channel
{
    get
    {
        ulong centralFreqMHz = DSConfig / 1000;

        if (centralFreqMHz > 2400 && centralFreqMHz < 2500)      // then this is 802.11b/g
        {
            /*
            Regional allocated use of 802.11b/g channels
                1 to 11 -- North America (USA and Canada)
                1 to 13 -- Austria, Belgium, Denmark, Finland, France, Germany, Greece, Iceland, Ireland, Italy, Liechtenstein, Luxembourg,  Netherlands, Norway, Portugal, Spain, Sweden, Switzerland, United Kingdom.
                1 to 14 -- Japan, China, Hong Kong, Philippines, Taiwan, Thailand, Singapore, South Korea
            */

            switch (centralFreqMHz)
            {
                case 2412:
                    return 1;
                case 2417:
                    return 2;
                case 2422:
                    return 3;
                case 2427:
                    return 4;
                case 2432:
                    return 5;
                case 2437:
                    return 6;
                case 2442:
                    return 7;
                case 2447:
                    return 8;
                case 2452:
                    return 9;
                case 2457:
                    return 10;
                case 2462:
                    return 11;
                case 2467:
                    return 12;
                case 2472:
                    return 13;
                case 2484:
                    return 14;

                default:
                    return 0;
            }
        }
        else if (centralFreqMHz > 5100 && centralFreqMHz < 5900)       // this is 802.11a
        {
            switch (centralFreqMHz)
            {
                case 5170:
                    return 34;
                case 5180:
                    return 36;
                case 5190:
                    return 38;
                case 5200:
                    return 40;
                case 5210:
                    return 42;
                case 5220:
                    return 44;
                case 5230:
                    return 46;
                case 5240:
                    return 48;
                case 5260:
                    return 52;
                case 5280:
                    return 56;
                case 5300:
                    return 60;
                case 5320:
                    return 64;
                case 5500:
                    return 100;
                case 5520:
                    return 104;
                case 5540:
                    return 108;
                case 5560:
                    return 112;
                case 5580:
                    return 116;
                case 5600:
                    return 120;
                case 5620:
                    return 124;
                case 5640:
                    return 128;
                case 5660:
                    return 132;
                case 5680:
                    return 136;
                case 5700:
                    return 140;
                case 5745:
                    return 149;
                case 5765:
                    return 153;
                case 5785:
                    return 157;
                case 5805:
                    return 161;

                default:
                    return 0;
            }
        }
        else
            return 0;
    }
}

/// <summary>
/// SSID of the AP
/// </summary>
public string SSID
{
    get { return _ssid; }
}

/// <summary>
///  MAC address "XX-XX-XX-XX-XX-XX"
/// </summary>
public string MAC
{
    get { return _mac; }
}

/// <summary>
/// Signal strength in dB
/// </summary>
public int SignalStrength
{
    get { return (int)_rssi; }
}

/// <summary>
/// MSDN:
/// Specifies a WEP/WPA/WPA2 encryption requirement. A value of 0 indicates that privacy is disabled.
/// A value of 1 indicates that privacy is enabled.
/// </summary>
public string WEP
{
    get { return (_wepStatus == 0 ? "WEP disabled" : "WEP enabled"); }
}

/// <summary>
/// Indicates the physical layer for the AP
/// </summary>
public string NetworkType
{
    get
    {
        if (_networkType == NDIS_802_11_NETWORK_TYPE.Ndis802_11FH)
            return "frequency-hopping spread-spectrum PHY";
        else if (_networkType == NDIS_802_11_NETWORK_TYPE.Ndis802_11DS)
            return "direct-sequence spread-spectrum PHY";
        else if (_networkType == NDIS_802_11_NETWORK_TYPE.Ndis802_11OFDM24)
            return "OFDM 2.4 GHz";
        else if (_networkType == NDIS_802_11_NETWORK_TYPE.Ndis802_11OFDM5)
            return "OFDM 5 GHz";
        else
            return "PHY is not FH, nor DS";
    }
}

/// <summary>
/// Indicates current network mode for AP
/// </summary>
public string NetworkMode
{
    get
    {
        if (_networkInfrastructure == NDIS_802_11_NETWORK_INFRASTRUCTURE.Ndis802_11IBSS)
            return "IBSS (ad hoc) mode";
        else if (_networkInfrastructure == NDIS_802_11_NETWORK_INFRASTRUCTURE.Ndis802_11Infrastructure)
            return "Infrastructure (ESS) mode";
        else if (_networkInfrastructure == NDIS_802_11_NETWORK_INFRASTRUCTURE.Ndis802_11AutoUnknown)
            return "Automatic network mode";
        else
            return "not specified";
    }

}

}

*C++ file #1 - exportable functions:
include "stdafx.h"
include "ewf.h"
include "NdisConnect.h"
include
NdisConnect g_NdisAdapter(L"ewf_log.txt");
extern HANDLE g_NdisConnectedEvent;
extern "C" EWF_API BOOL WINAPI FindWirelessAdapter()
{
    ENTER;
try
{
    return g_NdisAdapter.FindWirelessAdapter();
}
catch (NdisException* e)
{
    LOG_EXCEPTION(e);
    return FALSE;
}

LEAVE;
return TRUE;

}
// 1. init adapter: CreateFile(NDISUIO_DEVICE_NAME, - done at g_NdisAdapter ctor
// 2. disable WZC
// 3. rebind adapter
// 4. open adapter
extern "C" EWF_API BOOL WINAPI ConnectToAdapter()
{
    ENTER;
try
{
    if (FALSE == g_NdisAdapter.FindWirelessAdapter())
        return FALSE;

    if (false == g_NdisAdapter.DisableWZC_Driver())
        g_NdisAdapter.DisableWZC_API();

    g_NdisAdapter.RebindAdapter();
    g_NdisAdapter.OpenDevice();
}
catch (NdisException* e)
{
    LOG_EXCEPTION(e);
    return FALSE;
}

LEAVE;
return TRUE;

}
extern "C" EWF_API BOOL WINAPI TurnWlanOn()
{
    return g_NdisAdapter.TurnWlanOn();
}
extern "C" EWF_API BOOL WINAPI DisconnectFromAdapter()
{
    ENTER;
    try
    {
        g_NdisAdapter.Disassociate();
    }
    catch (NdisException* e)
    {
        LOG_EXCEPTION(e);
        return FALSE;
    }
LEAVE;
return TRUE;

}
extern "C" EWF_API BOOL StartScan()
{
    ENTER;
    g_NdisAdapter.ScanForAPs();
return TRUE;

}
extern "C" EWF_API BOOL GetAPsList(APInfo* pAPs, int maxAPs, int* foundAPs)
{
    ENTER;
    BOOL res = FALSE;
try
{
    res = g_NdisAdapter.GetAPList(pAPs, maxAPs, foundAPs);
}
catch (NdisException* e)
{
    LOG_EXCEPTION(e);
    return FALSE;
}

LEAVE;
return TRUE;

}
extern "C" EWF_API BOOL ConnectToAP(int maxWaitTimeSeconds, const wchar_t* ssid, bool isWepEnabled, const wchar_t* wepKey)
{
    char cSSID[33], cWepKey[30];
    localFunctionCT2A(ssid, cSSID, sizeof(cSSID));
    localFunctionCT2A(wepKey, cWepKey, sizeof(cWepKey));
ENTER_FUNC("SSID = " << cSSID << ", wep enabled = " << isWepEnabled << ", wep key = '" << cWepKey << "'");

g_NdisAdapter.Disassociate();

Sleep(2000);

ResetEvent(g_NdisConnectedEvent);
g_NdisAdapter.ConnectToAP(cSSID, isWepEnabled, cWepKey);

if (WAIT_OBJECT_0 != WaitForSingleObject(g_NdisConnectedEvent, maxWaitTimeSeconds*1000))
{
    LOG("Did not get CONNECTED event from NDIS...");
    return FALSE;
}

LEAVE;
return TRUE;

}

*

*NdisConnect class - all NDIS magic happens here:

<< when i pasted code here, i went well over 30k limit for the post, so I created PasteBin file>> - http://pastebin.com/wMBZAYCQ


text:
Q: Python: mmap module's offset argument Exception I'm working with a 1.5 GB File on a 32-Bit windows (and python) and using the mmap module.
As you can see I'm using the parameter offset=0x5E2030AA to get the starting point of the data I'm interested in. Since the offset of the mmap.mmap module must be a multiple of mmap.ALLOCATIONGRANULARITY, I'm using the following function to get the nearest offset:
def getNearestOffset(offset):
    nearest = offset
    nearest -= (offset % mmap.ALLOCATIONGRANULARITY)
    return nearest

I then seek to the remaining offset by subtracting the passed attribute offset=0x5E2030AA from the nearestOffset.
def readRIFF(fileno, bufLength=1024**3, offset=0x5E2030AA):
    partialData = False
    previousRIFF = None
    while True:
        nearestOffset = getNearestOffset(offset)
        with contextlib.closing(mmap.mmap(fileno, bufLength, offset=nearestOffset, access=mmap.ACCESS_READ)) as mm:
            if not partialData:
                mm.seek(offset - nearestOffset)
                startOffset = mm.tell()
                riffID = mm.read(4)
                assert riffID == "RIFF"
                riffSize = toLittleEndianInt(mm.read(4))
                riffType = mm.read(4)
                riffData = mm.read(riffSize - 4)
                # Check for partialData
                if len(riffData) != riffSize - 4:
                    print "DEBUG: Current RIFF blobs trunkated."
                    partialData = True
                    previousRIFF = riffBlob.RiffBlob(riffID, riffSize, riffType, riffData, startOffset)
                    break

But when I try to instanciate a new mmap object (in the readRIFF function), I get the following exception:
Traceback (most recent call last):
  File "testRead.py", line 57, in <module>
    readRIFF(f.fileno())
  File "testRead.py", line 28, in readRIFF
    with contextlib.closing(mmap.mmap(fileno, bufLength, offset=nearestOffset, access=mmap.ACCESS_READ)) as mm:
WindowsError: [Error 8] Not enough storage is available to process this command

I'm confused, why does this exception occur?
Is there a different way to access my desired offset?
Do I have to modify the length parameter because I try to read more than the file is in size?

A: Okay seems like I found the answer on my own.
The contextmanager contextlib.closing doesn't actually remove the created memory map from memory (?) and thus my memory is slowly filled with it on each new call.
I fixed the issue by simply deleting the memorymap with del(mm) after I'm done extracting relevant data from the blob.


text:
Q: How to correctly introduce HTML tag with 2 and more classes in Idea IntelliJ? I'm using IntelliJ autocomplete for HTML feature and it is cool!. As for example when I'm trying to create a button with id and class:
div#myId.myClass

And after pressing "tab" I'm getting:

And this is OK. But is it possible to add more than one class and than after pressing "tab" have two off them as div attribute?
ex.

A: Simply write
div#myId.myClass.myClass2

and press "tab". I've tested it in PhpStorm from IntelliJ

A: Standard Emmet syntax for creating several classes at once is
div#id.class1.class2.class3

See https://docs.emmet.io/abbreviations/syntax/#id-and-class


text:
Q: Uploaded SPFx app not deploying - unable to add to site I created a simple SPFx web part, bundled and created the solution package using the following commands.
gulp clean
gulp bundle --ship
gulp package-solution --ship
Then uploaded the .sppkg to my app catalog (https://.sharepoint.com/sites/apps). But after uploading the .sppkg file it doesn't seem to get deployed and the "Deploy" button stays enabled. When the "Deploy" button is clicked, I get the deploy confirmation dialog but the deploy button says enabled - seems like the deployment didn't happen successfully. When I try add the app from another site's Site Contents, the app doesn't even show up.
Toolchain and versions:
node: 16.18.0
npm: 8.19.2
gulp: 2.3.0 (CLI), 4.0.2 (Local)
@microsoft/generator-sharepoint: 8.19.2

A: Something that might help to confirm if the package has been deployed would be to go to your client side assets folder in the app catalog and see if there is a folder with your solution id as the folder name. Inside that all the bundled js files should exist.
eg https://[tenant].sharepoint.com/sites/apps/ClientSideAssets/[solutionid]
Also as Ganesh mentioned, with tenant-wide deployment you can just try adding the web part without installing the app to a specific site.

A: From the screenshots you attached with your question, your SPFx solution is already deployed successfully:

Also, from your 2nd screenshot, it seems that you are using tenant wide deployment and not site collection specific deployment:

As you are using tenant wide deployment, your web part will be available to use in all site collections in your tenant automatically. In this case, you don't have to add the SPFx solution to individual sites from Site Contents manually.
You can directly add & use this web part on site pages like any other out of the box or SPFx web parts:

*

*Go to SharePoint site page

*Edit the page using "Edit" option at top right corner

*Click on circled + to add web part

*Search your web part and add it to the page.

Follow detailed steps at: Using web parts on SharePoint pages

Related Microsoft documentations:

*

*Tenant-scoped solution deployment for SharePoint Framework solutions

*Use the site collection app catalog - This can be used only when you want to deploy the solution for specific site collection only.


text:
Q: Having function as argument in setInterval I'm simply trying to pass a function to a setInterval function. Doesn't seem to be working with my code. Right now the code below works at first, but how would I pass my function parameters when calling the setInterval function?
//Works here

ajaxUpdateOne(function(countOne,countTwo) {
    var itemCount = countOne;
    var totalCount = countTwo;
    console.log(itemCount);
    console.log(totalCount);
});

//Does not work here.

var myVar = ajaxUpdateOne(function(countOne,countTwo) {
    var itemCount = countOne;
    var totalCount = countTwo;
    console.log(itemCount);
    console.log(totalCount);
});

setInterval(myVar,8000);

A: Currently you are calling ajaxUpdateOne() with anonymous function as an argument. myVar is not a function.
Change Your code as
var myVar = function () {
    ajaxUpdateOne(function (countOne, countTwo) {
        var itemCount = countOne;
        var totalCount = countTwo;
        console.log(itemCount);
        console.log(totalCount);
    });
}
setInterval(myVar, 8000);

A: While the code you posted is partial, and it is not clear what ajaxUpdateOne() does, I am assuming it calls $.ajax() and updates the page based on the response results. However, to be able to pass parameters into the function called later in setInterval(), following construct can be used:
var deferredUpdate = function(countOne, countTwo) {
  return function() { ajaxUpdateOne(countOne, countTwo); }
}

setInterval(deferredUpdate(42,3), 8000);
setInterval(deferredUpdate(1,2), 2000);

The trick here is that your deferredUpdate() returns a function itself, not a value. However the parameters for this resulting function are bound in the particular closure. This is one of the basic techniques in functional programming.


text:
Q: What url masking method worked in Javascript disabled browser? I have tried iframing but it doesn't worked in Javascript disabled browser. Anyone please tell me how can I mask an url and still worked in Javascript disabled situation, thanks in advance.

A: Use POST, rather than GET. Something like this early in the page:
    <form action="nextpage" method="post">
<input type="hidden" name="parameter1" value="value1" />
...etc...

This page
</form>
<form action="otherpage" method="post">
<input type="hidden" name="parameter1" value="value1" />
...etc...

That page
</form>

Bit more longwinded, but it will work.


text:
Q: Datagridcombobox value not displaying I have a DataGridView (called DataGridViewSecurity) in VB.net (Visual Studio 2010) which is bound to a DataTable (called DataTableSecurity) in a DataSet (called DataSetSecurity).  I have added a nonbound column (called nSecurityComboBox) that I set based on an integer field (called nSecLevel) in the DataTable.  After setting the combobox, it doesn't display anything in the combobox, but when you select the combobox, the 5 values in it's items collection show.
Here's the code I'm using to add a record to the DataTable and then to set the combobox:
Sub Foo()
.
.
.
    DataSetSecurity.Tables(0).Rows.Add(New Object() {sName, sID, sSec})
    ComboCell_Select(nRow, 3, DataGridViewSecurity, sSecRecs.nSecLevel)
    MessageBox.Show("Value for the combo set at " + DataGridViewSecurity.Rows(nRow).Cells(3).Value.ToString)
.
.
.
End Sub

Private Sub ComboCell_Select(ByVal dgvRow As Integer, _
                             ByVal dgvCol As Integer, _
                             ByRef DGV As DataGridView,
                             ByRef nComboBoxRow As Int16)

    Try
        Dim CBox As DataGridViewComboBoxCell = CType(DGV.Rows(dgvRow).Cells(dgvCol), DataGridViewComboBoxCell)
        Dim CCol As DataGridViewComboBoxColumn = CType(DGV.Columns(dgvCol), DataGridViewComboBoxColumn)

        CBox.Value = CCol.Items(nComboBoxRow)
        DGV.UpdateCellValue(dgvCol, dgvRow)

        'MessageBox.Show("New value in the combo box = " + CBox.Value.ToString)
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
End Sub

The messagebox.show in Foo shows the correct value for the combobox, but nothing is displayed.
Anyone see what I'm doing wrong?
Thanks.
-NCGrimbo

A: In the end, I found some C# code that I converted to VB.net to fix the issue.  Here's the code:
Private Sub DataGridViewSecurity_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridViewSecurity.EditingControlShowing
    Dim cellComboBox As ComboBox = TryCast(e.Control, ComboBox)
    If cellComboBox IsNot Nothing Then
        ' make sure the handler doen't get registered twice
        RemoveHandler cellComboBox.SelectionChangeCommitted, AddressOf Me.CellComboBoxOnSelectionChangeCommitted
        AddHandler cellComboBox.SelectionChangeCommitted, AddressOf Me.CellComboBoxOnSelectionChangeCommitted
    End If
End Sub

Private Sub CellComboBoxOnSelectionChangeCommitted(ByVal sender As Object, ByVal e As EventArgs)
    Dim comboBox As DataGridViewComboBoxEditingControl = TryCast(sender, DataGridViewComboBoxEditingControl)
    If sender Is Nothing Then
        Return
    End If
    If comboBox.SelectedItem Is Nothing Then
        Return
    End If
    If Me.DataGridViewSecurity.CurrentCell.Value = comboBox.SelectedItem Then
        Return
    End If

    Me.DataGridViewSecurity.CurrentCell.Value = comboBox.SelectedItem

End Sub

A: If I understand the question right, all values are in the combobox just not being selected by default properly?  I think I just had this problem a few days ago, here's what I have now.
'Create the combobox column
Dim comboBox As New DataGridViewComboBoxColumn()

'Add some stuff to the combobox
comboBox.Items.Add("FirstItem")
comboBox.Items.Add("SecondItem")

'Select the first item
comboBox.DefaultCellStyle.NullValue = comboBox.Items(0)

'Now add the whole combobox to the DataGridView
dgvItems.Columns.Add(comboBox)

Hope this helps!


text:
Q: input element displays something else than it has in value I'm trying to make myself a little jQuery plugin based on jQueryUI's Autocomplete, because I have a lot of different autocomplete fields which I want to treat differently.
Although every other part of my plugin is working fine, it does one thing that I don't understand.
Despite that the onSelect function clearly defines this:
box.val(ui.item.nazev); // item name
boxID.val(ui.item.value);

which I can confirm by listing those elements values after it's been done, for the user the box element somehow shows ui.item.value
I tried every possibility I can think of, none of them worked ... I'm quite desperate.
Plugin is included here: http://jsfiddle.net/meridius/AVA6M/

Edit:
OK, it's quick and dirty, but I managed to make it work in jsfiddle.net without AJAX. It's not perfect (results aren't filtered as typing), but you can see what I mean when you select some result.

A:
Using Chrome (F12) to debug your fiddle I found your problem at line Line 2257 o jquery-1.9.1.js. It was a matter of event propagation so the following code should solve your problem.
select: function (event, ui) {
            o.onSelect(event, ui, box, boxID);
            return false; //This line stops event propagation solving the problem.
},

Note: see this post for details on how to stop event propagation. event.preventDefault() vs. return false


text:
Q: org.hibernate.MappingException: Repeated column in mapping for entity: AGVDock I have an entity class AGVDock which has the following 3 WarehouseCoords attributes:
@Entity
public class AGVDock implements ValueObject, Comparable<AGVDock>, Serializable, AggregateRoot<AGVDock> {

    @Id
    private Long pk;
    @SerializedName(value = "id", alternate = {"Id", "ID", "iD"})
    private String id;

    @Embedded
    private WarehouseCoords begin;
    @Embedded
    private WarehouseCoords end;
    @Embedded
    private WarehouseCoords depth;
    ...

These 3 attributes share the same WarehouseCoords 'embedded' class which basically represent X and Y coordinates in a 2D grid:
@Embeddable
public class WarehouseCoords {

    private final int lSquare;
    private final int wSquare;

    /**
     * WarehouseCoords constructor
     *
     * @param lSquare the X axis square coordinate
     * @param wSquare the Y axis square coordinate
     */
    private WarehouseCoords(int lSquare, int wSquare) {
        this.lSquare = lSquare;
        this.wSquare = wSquare;
    }

but I am getting the following error:
Repeated column in mapping for entity: eapli.base.warehousemanagement.domain.AGVDock column: lSquare (should be mapped with insert="false" update="false")

If I remove end and depth attributes from AGVDock, it works.
Is it possible to have the 3 attributes of AGVDock share the same embedded class type of objects?