text:
Q: What is wrong with this class for getting connection from database pool I wrote a class to get connections from a database pool (HikariCP). I searched for error and it means that connection is closed. But, I am not able to figure out the problem. I am certain I did something wrong in the code, may be not closing the connection properly or whatever because after some time I start to get errors as below:
11:27:58.843 [http-apr-8080-exec-10] WARN  c.z.h.u.ConcurrentBag -
**Attempt to remove an object from the bag that does not exist: com.mysql.jdbc.JDBC4Connection@5f3145e5, created Oct 21, 11:27:12.734, last release 0ms ago, NOT_IN_USE 11:27:58.861 [http-apr-8080-exec-10] ERROR c.p.d.DAOConnectionFactory - Error while closing connection.** java.sql.SQLException: Connection is closed   at com.zaxxer.hikari.proxy.ClosedConnection$1.invoke(ClosedConnection.java:51) ~[HikariCP-2.4.1.jar:na]     at com.sun.proxy.$Proxy4.clearWarnings(Unknown Source) ~[na:na]     at com.zaxxer.hikari.proxy.ConnectionProxy.close(ConnectionProxy.java:197) ~[HikariCP-2.4.1.jar:na]     at com.presence.dao.DAOConnectionFactory.closeConnection(DAOConnectionFactory.java:73)
**~[DAOConnectionFactory.class:na]   11:28:01.133 [http-apr-8080-exec-9] WARN  c.z.h.p.ConnectionProxy - HikariPool-0 - Connection com.mysql.jdbc.JDBC4Connection@46fb3f92, created Oct 21, 11:27:12.781, last release 28ms ago, IN_USE marked as broken because of SQLSTATE(08003), ErrorCode(0) com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after statement closed.   at** sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_45]   at

Below is the class:
public class DAOConnectionFactory {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(DAOConnectionFactory.class);
    private static final String databaseJNDI = "jdbc/presencedb";
    private static DataSource dataSource = null;
    private static Context context = null;
    private static Connection conn = null;

    private DAOConnectionFactory() {
        System.out.println("Initialized");
    }

    private static DataSource getDataSource() {
        if (dataSource != null) {
            return dataSource;
        }
        try {
            context = new InitialContext();

            if (context == null) {
                context = new InitialContext();
            }

            dataSource = (DataSource) context.lookup("java:comp/env/" + databaseJNDI);
        } catch (NamingException e) {
            logger.error("Error while creating datasource.", e);
        }
        return dataSource;
    }

    protected static Connection getConnection() {
        try {
            conn = getDataSource().getConnection();
        } catch (SQLException e) {
            logger.error("Error while getting database connection.", e);
        }
        return conn;
    }

    protected static void closeConnection(Connection connection, Statement statement, ResultSet resultSet) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                logger.error("Error while closing resultset.", e);
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                logger.error("Error while closing statement.", e);
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                logger.error("Error while closing connection.", e);
            }
        }
    }
}

hikaricp properties:
cachePrepStmts="true"
defaultAutoCommit="true"
description="Presence database."
driverClassName="com.mysql.jdbc.Driver"
factory="com.zaxxer.hikari.HikariJNDIFactory"
global="jdbc/presencedb"
jdbcUrl="jdbc:mysql://192.168.254.167/presence"
maxWaitMillis="10000" maximumPoolSize="30"
name="jdbc/presencedb"
password=""
prepStmtCacheSize="50"
prepStmtCacheSqlLimit="512"
removeAbandoned="true"
removeAbandonedTimeout="300"
type="javax.sql.DataSource"
idleTimeout="25200000"
maxLifetime="25200000"
username="root"

Add this is how I obtain the connection
Connection connection = null;
PreparedStatement preparedStatement = null;
connection = DAOConnectionFactory.getConnection();
preparedStatement = connection.prepareStatement(SQL_UPDATE);

DAOConnectionFactory.closeConnection(connection, preparedStatement, null);

This happens always when I perform load testing otherwise for few random queries I have not noticed this.
HikariCP version is 2.4.1.

A: Don't declare Connection static, they will cause a collision in your stress tests or distributed environments, your final code that look like
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import com.itextpdf.text.log.LoggerFactory;

public class DAOConnectionFactory {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(DAOConnectionFactory.class);
    private static final String databaseJNDI = "jdbc/presencedb";
    private static DataSource dataSource = null;
    private static Context context = null;
    private Connection conn = null;

    public DAOConnectionFactory() {
        System.out.println("Initialized");
    }

    static {
        if (dataSource == null) {
            try {
                context = new InitialContext();

                if (context == null) {
                    context = new InitialContext();
                }

                dataSource = (DataSource) context.lookup("java:comp/env/" + databaseJNDI);
            } catch (NamingException e) {
                logger.error("Error while creating datasource.", e);
            }
        }
    }

    public Connection getConnection() {
        try {
            conn = dataSource.getConnection();
        } catch (SQLException e) {
            logger.error("Error while getting database connection.", e);
        }
        return conn;
    }

    protected static void closeConnection(Connection connection, Statement statement, ResultSet resultSet) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                logger.error("Error while closing resultset.", e);
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                logger.error("Error while closing statement.", e);
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                logger.error("Error while closing connection.", e);
            }
        }
    }
}

And the call like
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class Main {

    public static String SQL_UPDATE = "query";

    public DAOConnectionFactory factory = new DAOConnectionFactory();

    public static void main(String args[]){
        Main instanceppl = new Main();
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        connection = instanceppl.factory.getConnection();
        try {
            preparedStatement = connection.prepareStatement(SQL_UPDATE);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        instanceppl.factory.closeConnection(connection, preparedStatement, null);

    }

}


text:
Q: Building a block user functionality: how to force user to logout or terminate their existing session I am working on an ASP.NET MVC website, it's an e-commerce website. I am using ASP.NET Identity.
I have added a new functionality to block users when they create spam advertisements. I have added a IsBlocked flag to user table and if the flag is set, that user can no longer login to website.
But if the user is already logged in and have a valid session/cookie, then they can continue using the website until they logout or their session is expired. Is it possible to invalidate their existing session (if any) when they are blocked?

A: From here:
When you set IsBlocked update the SecurityStamp of the user as well via:
await userManager.UpdateSecurityStampAsync(user);

So the next time the SecurityStamp of the user is validated against the principal that results from the cookie the validation will fail and the user will be signed out.
You control the length of the interval the security stamp is validated via:
services.Configure<SecurityStampValidatorOptions>(options =>
{
    options.ValidationInterval = TimeSpan.FromMinutes(30); // 30 minutes is default
});

Be sure to call it after AddIdentity.
You could set the ValidationInterval to zero but that would cause a validation and consequentially a database request for every request the user is making.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error installing scrapy 0.22 (on Ubuntu 12.04): 'gcc' failed with exit status 1 When trying to install Scrapy from the command line using pip

sudo pip install scrapy
I get the following error:

error: command 'gcc' failed with exit status 1
Looking a few lines up in the error output, I see that the error occurs while trying to install the 'cryptography' package which seems to be a dependency of pyOpenSSL
I tried installing pyOpenSSL on its own and it gives the same error.
Reading through the error output, I find that the likely cause of this error is a missing file:
ffi.h: No such file or directory
How should I proceed from here?

A: Try with
sudo apt-get install libffi libffi-dev


text:
Q: ^m removing sed command removing ,M data as well I am using this code:
sed -E ':a;N;;s/(,"[^"]*)\n/\1/;$!ba' $target > Int.csv
#sed ':a;N;$!ba;s/\n//g' $target > Int.csv
sed -e "s/\r//g" Int.csv > Removejunk.csv

My requirement is to remove the \n character from the csv file and also remove the ^m character.
But in the output, M is also getting removed.
I.e i get 10-01-2020 08:16 AM,ichael Flores
instead of 10-01-2020 08:16 AM,Michael Flores


text:
Q: Should I create a new table? I have following tables in my database.
{account, post, comment}
an account can have 0 or more posts.
a post can have 0 or more comments.
I want to add the (type of post, e.g Q&A, notice, ads, etc).
Do I need to make a new table for this? (If so, what is the relationship between post and new table?)
OR
Do I create a new column (type) in post table?
I am using PHP and mysql

A: If you are completely certain that you will never add any other metadata associated with a post, I might just add another column to the post table.  But in reality, you probably will be adding more metadata other than the type, so creating a postmetadata table is probably a good idea.  Here is what the schema might look like:
id | postid | type | other columns ...

You would join this to the post table whenever you need to access the metadata.  But for other queries involving only the post table the meta table could be ignored.


text:
Q: List with Json asp.net mvc I've been trying to find an answer on google without any result. My question is how can I manipulate my Json data (List<string>) in my view? I'd like to show all the string returned in a div for example.
Here's where I'm currently stuck at:
CONTROLLER
    [HttpPost]
    public async Task<ActionResult> RetournerOP(int OF)
    {
        List<string> ops = new List<string>();
        Task verif = Task.Run(() =>
        {
            try
            {
                connection.Open();
                string sqlQuery = "SELECT Operation from ZZ where ordre = " + OF;
                SqlCommand command = new SqlCommand(sqlQuery, connection);
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        ops.Add(Convert.ToString(reader["Operation"]));
                    }
                }
            }
            catch (Exception) { }
            finally { connection.Close(); }
        });
        await verif;
        return Json(ops);
    }

VIEW
function retournerOp() {
    $.ajax({
        url: '@Url.Action("RetournerOp", "Home", new { area = "Ajout" })',
        data: {OF: document.getElementById("NumOf").value},
        type: 'POST',
        dataType: 'JSON',
        cache: false,
        success: function (data) {
            //How can I manipulate my data returned?
        }
    });
}

A: Your server action method is currently returning an array of strings. So in your ajax call's success callback, you may loop through them and use each item as needed ( like adding to your DOM). $.each method will be handy to loop.
For example, the below code loops through the array and wrap each item in a p tag and append the list of p tags to a div with id myDivId
success: function (data) {
    var t = "
";
    $.each(data,function(a, b) {
                t += '
'+b+'
';
        });
    $("#myDivId").html(t);
}

If you want to render a more complex html markup, i would strongly advise creating an action method (if you cannot update the existing one because other code is already using it) which returns a partial view result instead of the json. So you will pass the list of strings to the partia view and the partial view will have the code to render the sophisticated markup you want to return.
return PartialView(ops);

and in the partial view,
@model List<string>
@foreach (var item in Model)
{

@item

}

Now since the response coming from the server call is the HTML markup you want, simply update the DOM with that as needed.
$.ajax({
     url: '@Url.Action("RetournerOp", "Home", new { area = "Ajout" })',
    data: {OF:6},
    type: 'POST',
    success: function (data) {
        $("#myDivId").html(data);
    }
});

Also as others mentioned in the comments, your server code is prone to SQL injection. You should never concatenate the user input directly to a SQL statement like that. Consider using Parameterized queries.


text:
Q: How to solve ajax taking only the first row data when fetching data from php? I am having problem with my ajax code when I am trying to click update data into my database using ajax not to refresh the page. I am trying to have the user click on the button in each data that is taken from database. But the problem is that every time I click on each data it took only the first row of data. Can you help me to see what is wrong in my code?
Ajax here

Php Here
    <?php
    session_start();
    error_reporting(0);
    require '../../core/database/connect.php';
    require '../../core/functions/general.php';
    require '../../core/functions/users.php';
    //mysql_query("SET NAMES utf8");
    $current_file = explode('/', $_SERVER['SCRIPT_NAME']);
    $current_file = end($current_file);
    if (logged_in() == true) {
        $session_user_id = $_SESSION['user_id'];
        $user_data = user_data($session_user_id, 'user_id', 'username', 'password', 'first_name', 'last_name', 'email', 'password_recover','type','allow_email', 'profile', 'quote','dob','status','current_occupation','location','skill','about_user','joined_date','phone','ban','fbpname','fbpurl','fb','fbn','website','whatsapp','profile_view');
        $user_id = $user_data['user_id'];
        if (user_active($user_data['username']) == false) {
            session_destroy();
            header('Location: index');
            exit();
        }
        if ($current_file !== 'change_password.php' && $current_file !=='logout.php' && $user_data['password_recover'] == 1) {
            header('Location: change_password?force');
            exit();
        }
    }
    $errors = array();
?>
<?php
protect_page();
if($_POST){
    $question_id = $_POST['question_id'];
    $answer_id = $_POST['answer_id'];
    $rate = $_POST['score_input'];
    $user_id = $user_data['user_id'];
    $sql = "SELECT * FROM vote_action WHERE answer_id = ".$answer_id." AND user_id=".$user_id."";
    $result = mysql_query($sql);
    if(mysql_num_rows($result)!=0)
       {
           echo 'You\'ve already voted for this answer';
        //mysql_query("DELETE FROM `vote_action` WHERE `answer_id` = '$answer_id' AND `user_id` = '$user_id'");
       }else{
        mysql_query("INSERT INTO `vote_action` (`vote_id`, `question_id`, `user_id`, `rate_score`, `answer_id`) VALUES (NULL, '$question_id', '$user_id', '$rate', '$answer_id');");
         echo 'You\'ve voted for this answer the answer and give the user '.$rate.' Score(s)';
        }
}
?>

And html file is here
<form class="vote" data-id="<?php echo 'vote-'.$answer_id?>">
            <input type="hidden" data-id="<?php echo 'vote-'.$answer_id?>" value="<?php echo $question_id_get;?>" name="question_id_asnwer" class="vote">
            <input type="hidden" data-id="<?php echo 'vote-'.$answer_id?>" value="<?php echo $answer_id;?>" name="answer_id" class="vote">

<select id="first-disabled" name="score_input" data-id="<?php echo 'vote-'.$answer_id?>" class="selectpicker vote" data-hide-disabled="true" data-live-search="true" data-width="55%">
    <optgroup disabled="disabled" label="disabled">
      <option>Hidden</option>
    </optgroup>
    <optgroup label="SCORE">
      <option data-icon="glyphicon-heart">1</option>
      <option data-icon="glyphicon-heart">2</option>
      <option data-icon="glyphicon-heart">3</option>
      <option data-icon="glyphicon-heart">4</option>
      <option data-icon="glyphicon-heart">5</option>
    </optgroup>
</select>
            <button type="submit" name="vote" class="btn-text" data-vote="<?php echo $answer_id; ?>"></button> 25
            </form>

A: This is how it goes wrong. I have just found it. If someone meet the same problem you can see this. Thanks...
This is my new ajax code

This is my new working php to post data
<?php
protect_page();
if($_GET){
    $question_id = $_GET['question_id'];
    $answer_id = $_GET['answer_id'];
    $rate = $_GET['score_input'];
    $user_id = $user_data['user_id'];
    $sql = "SELECT * FROM vote_action WHERE answer_id = '".$answer_id."' AND user_id='".$user_id."'";
    $result = mysql_query($sql);
    if(mysql_num_rows($result)!=0)
       {
           echo 'You\'ve already voted for this answer';
        //mysql_query("DELETE FROM `vote_action` WHERE `answer_id` = '$answer_id' AND `user_id` = '$user_id'");
       }else{
        mysql_query("INSERT INTO `vote_action` (`vote_id`, `question_id`, `answer_id`, `user_id`, `rate_score`) VALUES (NULL, '$question_id', '$answer_id', '$user_id', '$rate')");
         echo 'You\'ve voted for this answer the answer and give the user '.$rate.' Score(s)';
        }
}
?>

And the last this is my working form:
<form action="" class="form">
    <input type="hidden" name="question_id" value="<?php echo $question_id;?>" />
    <input type="hidden" name="answer_id" value="<?php echo $answer_id;?>" />
    <select id="first-disabled" name="score_input" class="selectpicker" data-hide-disabled="true" data-live-search="true" data-width="width:10%;">
    <optgroup disabled="disabled" label="disabled">
      <option>Give Score</option>
    </optgroup>
    <optgroup label="Useless Answer">
      <option>0</option>
      <option>1</option>
      <option>2</option>
      <option>3</option>
    </optgroup>
    <optgroup label="Good Answer">
      <option>4</option>
      <option>5</option>
      <option>6</option>
    </optgroup>
    <optgroup label="Helpful Answer">
      <option>7</option>
      <option>8</option>
      <option>9</option>
      <option>10</option>
    </optgroup>
  </select>
  <input class="submit" type="submit" name="submit" value="submit" class="glyphicon glyphicon-ok icon-color-blue">
</form>


text:
Q: display 4 months in a full Calendar I am using full Calendar plugin in my project. I want to display contiously 4 months. Please look at the below image,

I want to display 4 months in a full calendar. Please Help me how can I do this?
Already I have an js file, it will display 3 months simultaniously. But I want 4 months calendar. Please look at the below link which has having 3 months,
https://code.google.com/p/fullcalendar/issues/detail?id=2236
In this link, fullcalendar-cc.js file is there. It will display 3 months.
Please help me how can I display 4 month ?

A: Have you tried creating a custom view and adding in views:
views: {
    agendaToDisplayFourWeek: {
        type: 'timeline',
        slotLabelFormat: 'ddd D', // Mon 3 etc
        slotDuration: '24:00', // slots per day? 12:00 i.e. 12 hours AM/PM
        duration: { weeks: 4 }
    }
}


text:
Q: jQuery: If error exists remove old one I use a small Ajax request for my contact form for showing my validation.
$('#contact-form').on('submit', function (event) {
    event.preventDefault();

    $.ajax({
        url: 'send-mail',
        type: 'POST',
        data: $('#contact-form').serialize(),
        success: function (data) {
            // Success...

            $("#validation-output-success").text("Success!");
        },
        error: function (data) {
            // Error...

            var errors = $.parseJSON(data.responseText);

            $.each(errors, function( k, v ) {
                $("#validation-output-error").text( v ).append('
');
            });

        }
    });
});

It works fine, when there is something empty it will return it and says what input is empty. And same goes for if it works, output will be success!
But now comes the problem, when there is a field empty he will output it, but when you push another time on the submit button he will give the same error but don't remove the old error. So you will get the same error message double.
And then if you complete it, he will return success. But he will still show the old error messages.
My question is, how can I use the .fadeOut(), .remove() or another jquery function to remove the old error(s) when you submit the form again.

A: You can empty the error text and fadeOut() out on submit. Then add fadeIn() to the success/error messages. Something like:
$('#contact-form').on('submit', function (event) {
    event.preventDefault();
     $("#validation-output-error").text("").fadeOut();

    $.ajax({
        url: 'send-mail',
        type: 'POST',
        data: $('#contact-form').serialize(),
        success: function (data) {
            // Success...

            $("#validation-output-success").text("Success!").fadeIn();
        },
        error: function (data) {
            // Error...

            var errors = $.parseJSON(data.responseText);

            $.each(errors, function( k, v ) {
                $("#validation-output-error").text( v ).append('
').fadeIn();
            });

        }
    });
});

Also, if you haven't already done so, you may want to give the error/success messages display: none; in the css.


text:
Q: Assembly Language Mid Section Method to find integer square root of a number I am attempting to utilize the Mid Section method to determine the integer square root of a number. I am attempting to program this loop in assembly code.
l=1; u=x;
while l<=u
    m=(l+u)/2
    if m*m>x
        l=m+1
    else
        u=m-1
return m

This is the code I have written for the Mid Section method in assembly
INCLUDE Irvine32.inc
.data
; PLACE DATA DIRECTIVES HERE
    value   SDWORD  1
    lower   SDWORD  1
    upper   SDWORD  0
    middle  SDWORD  ?

;Prompts and messages
prompt      BYTE    "Please enter a signed integer value. The program will terminate if a non-positive number or zero is entered.",0dh, 0ah, 0
endOfLine   BYTE    " ",0dh, 0ah, 0

.code
main PROC
; PLACE SOURCE CODE HERE

program_loop:
    mov     edx, OFFSET prompt      ;print prompt for user to enter height
    call    WriteString
    call    ReadDec
    mov     value, eax              ;read user's height and store it in a variable
    mov     eax, value
    cmp     eax, 0

    jle     endprogram
    mov     upper, eax
    while_loop:
        mov     eax, lower
        cmp     eax, upper
        jg      end_while
        add     eax, upper
        mov     dl, 2
        idiv    dl
        mov     middle, eax
        imul    middle
        cmp     eax, value
        jle     else_if
            mov     eax, middle
            add     eax, lower
            mov     lower, eax
            jmp     end_if
        else_if:
            mov     eax, middle
            sub     eax, lower
            mov     upper, eax
        end_if:

        jmp     while_loop
    end_while:
    mov     edx, OFFSET middle
    call    WriteDec
    call    CrLf
    jmp     program_loop
endprogram:
    call    DumpRegs
    call    WaitMsg
    exit
main ENDP
; PLACE ADDITIONAL PROCEDURES HERE
END main

Whenever I attempt to divide (l+u) and that is an odd number by 2 to find middle I get the value 258?


text:
Q: Specify a height constraints in code I want to specify a fixed NSView height in code. With the method addConstraint: I can specify relation between object property but I can' t say:"This NSView should be 50 pixel high". Anyone know how to do that? Thanks!

A: whatabout:
[myView addConstraint:
    [NSLayoutConstraint
        constraintsWithVisualFormat:@"V:[myView(50)]"
                                options:0
                                metrics:nil
                                  views:NSDictionaryOfVariableBindings(myView)
    ]
];

but remember, you now have only added a constraint to the view. You will probably want to have it in some kind of controller, related to other objects. It is perfectly fine to have views to set their own constraints. That is what happens in InterfaceBuilder all the time. The relation between other views and elements of the UI should be in the next higher level in the view tree.

A: If you don't like visual constraint format you can also set like this.
    var heightCosntraint    = NSLayoutConstraint(item: seperationView,
    attribute: NSLayoutAttribute.Height,
    relatedBy: NSLayoutRelation.Equal,
    toItem: nil,
    attribute: NSLayoutAttribute.NotAnAttribute,
    multiplier: 1,
    constant: 5.0)

    seperationView.addConstraint(heightCosntraint)


text:
Q: Interprocess message queue with different types of messages I'm trying to write (in Linux), a "Sender" and "Receiver" programs that can send/receive a few types of messages between them, using shared memory, and message_queue.
I decided to use boost/interprocess/ipc/message_queue as it looks like the best solution.
The problem is that since there are a few types of messages with different structures and sizes, the receiver cannot know how many bytes to receive() and how they are structured.
I can solve this by placing the "type enumerator" as the first field, and upon reading the type, the receiver knows what is the size and how to parse the message to be read.
mq.receive(&type, sizeof(type), recvd_size, priority);
switch (type) {
   case typeA:
      mq.receive(&VarOfStructA, sizeof(struct A), recvd_size, priority);
      break;
   case typeB:
      mq.receive(&VarOfStructB, sizeof(struct B), recvd_size, priority);
      break;
   default:
      break;
}

I tried to search for solutions, as I assume this is a common problem.
However, I couldn't find any helpful idea.

A: Since c++17 you can use std::variant for a tagged union and if c++17 is not an option for you, then pick boost::variant as you are already using boost.
Here is an example how to use a variant to send and receive messages between two processes or even over network. I used concepts which is available since c++20 to produce better error messages but you can do without them.
#include <variant>
#include <cassert> // for test

class BufferWriter;
class BufferReader;

// concepts for better error messages
template<class T>
concept Writable = requires(BufferWriter& writer, const T& msg) {
    writer << msg;
};
template<class T>
concept Readable = requires(BufferReader& reader, T& msg) {
    reader >> msg;
};

class BufferWriter {
    // your impl here
public:
    template<Writable Msg>
    void write(const Msg& msg) {
        *this << msg;
    }
};

class BufferReader {
    // your impl here
public:
    template<Readable Msg>
    void read(Msg& msg) {
        *this >> msg;
    }

    template<Readable Msg>
    Msg read() {
        Msg msg;
        *this >> msg;
        return msg;
    }
};

// for integral as the index is of integer type
template<std::integral I>
BufferWriter& operator<<(BufferWriter& writer, I msg);
template<std::integral I>
BufferReader& operator>>(BufferReader& reader, I msg);

template<Writable ... Msgs>
BufferWriter& operator<<(BufferWriter& writer, const std::variant<Msgs...>& msgs) {
    writer << msgs.index();
    std::visit([&writer](const auto& msg) { writer << msg; }, msgs);
    return writer;
}

template<std::size_t I, class Var>
bool try_read_one_var_msg(BufferReader& reader, Var& var, std::size_t i) {
    if (i == I) {
        using msg_type = std::variant_alternative_t<I, Var>;
        var.template emplace<I>(reader.read<msg_type>());
        return true;
    }
    return false;
}

template<class Var, std::size_t ... IndexSeq>
void read_msg_of_variant(BufferReader& reader, Var& var, std::index_sequence<IndexSeq...>) {
    auto index = reader.read<std::size_t>();
    bool success = (try_read_one_var_msg<IndexSeq>(reader, var, index) || ...);
    if (!success) // the index didn't match any variant index
        throw std::bad_variant_access{};
}

template<Readable ... Msgs>
BufferReader& operator>>(BufferReader& reader, std::variant<Msgs...>& msgs) {
    read_msg_of_variant(reader, msgs, std::index_sequence_for<Msgs...>{});
    return reader;
}

struct Msg1 {
    // your msg impl
};
struct Msg2 {
    // your msg impl
};

// pack a message into the writer using a serialization protocol
BufferWriter& operator<<(BufferWriter& writer, const Msg1& msg);
BufferWriter& operator<<(BufferWriter& writer, const Msg2& msg);
// extract a message from the writer using a serialization protocol
BufferReader& operator>>(BufferReader& reader, const Msg1& msg);
BufferReader& operator>>(BufferReader& reader, const Msg2& msg);

int main() {

    std::variant<Msg1, Msg2> msgs;
    msgs.emplace<Msg2>();

    BufferWriter writer;
    BufferReader reader;
    writer << msgs;

    std::variant<Msg1, Msg2> msgs2;
    reader >> msgs2;
    assert(msgs2.index() == 1);

    return 0;
}

I didn't include the serialization part because this is per application requirement. Also the compiler compiles this better than a hand written switch statement in some cases and I think at worst it will be identical to a switch or if. In the write method an exception will be thrown in std::visit if the variant is valueless_by_exception and in the read method an exception will be thrown if the index is not contained in the variant.
code and asm result on godbolt: https://godbolt.org/z/f4bM51x8E


text:
Q: Create a folder without read-only using c# I have tried several approaches and I don't understand why, the read-only property is not removed whatsoever.I have a directory which has several .xls files and I used directory.getfilename to copy files from this directory to a newly created directory. But when I try to access the new directory with copied .xls files, it says file might be read-only or encrypted. So instead I tried a mock up creating a folder and see that code does not remove read-only.
private void button3_Click(object sender, EventArgs e)
{
    Directory.CreateDirectory(@"c:\hello");
    var di = new DirectoryInfo(@"c:\hello");
    di.Attributes &= ~FileAttributes.ReadOnly;
}

I tried several other approaches but failed. Any idea why?


text:
Q: Lazy Loading in NHibernate If a Customer has many Orders attached to them. How would you lazy load the Orders List using NHibernate.
Is it something that needs to be set up mapping file? any help or an example would be great.

A: Chris' suggestion is how I'd do it, however if you want to do it at runtime you can set the Fetchmode on your criteria to be lazy like so:
criteria.SetFetchMode("Orders", FetchMode.Lazy)

A: Heres a good article:
http://blogs.chayachronicles.com/sonofnun/archive/2007/03/30/230.aspx
From the above article:
The most common is to simply mark the class with the 'lazy="true"' attribute or place 'default-lazy="true"' in the mapping declaration:
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="@core.assembly@"
 default-access="nosetter.camelcase-underscore" default-lazy="true">

Or
<class name="Cei.eMerge.Core.Domain.Contacts.Contact" table="Contact" lazy="true" >

A: To lazy-load a particular collection of an entity, use "lazy=true" on the collection mapping.  For instance:
<bag name="EmploymentHistory" cascade="all" inverse="true" lazy="true">
  <key column="PersonID" />
  <one-to-many class="MyDomain.EmploymentRecord, MyDomainAssembly" />
</bag>

A: All of the answers here are correct, but if there are so many Orders you migth also want to use filters, so that you don't have to load all of them.

Customer customer = session.CreateCriteria(...)
              .SetFetchMode("Orders", FetchMode.Lazy)
              .UniqueResult<Customer>();

Ilist<Order> orders = session.CreateFilter(customer.Orders," WHERE this.OrderDate < ?")
                      .SetDateTime(...).List();

A: Do you want that the Customer entity has a property that contains all his Orders ?
I think that this can be quite a large collection.
I think that, the question you'll have to ask yourself is:

How many times do I really need to have direct access to the Orders of a Customer ?
Perhaps, in this case, you don't want to have a bidirectional association ?  Perhaps you don't want to have an Orders collection in your Customer class.
Then, I would add a method to my Order Repository, which has the following signature:
IList<Order> GetOrdersForCustomer( Customer c );

But, I don't know if this is feasible for your situation.


text:
Q: When using "destination-in," only the last thing drawn seems to render I'm making a little library to emulate a curses-like interface in Javascript using a bitmap font. The font is a png with all the characters in it, and with a transparent background.
The method I'm using to render a character is as follows.

*

*Draw a square over the space where the character is going to go. The square is the foreground color of the character

*Change context.globalCompositeOperation to destination-in

*Draw the character over the square

This is all done in a function called putChar. For some reason, though, only the last putChar call seems to render.
In the following JSFiddle, I've removed everything from the library except what's needed to reproduce the issue. putChar is called in lines 56, 57, and 58. It should render a yellow "a", a green "b", and a blue "c" all in a row. But only the third putChar call is rendered (the blue "c".)
http://jsfiddle.net/r96Lh/3/
This is my first time using composite operations, so I must be missing something. Anyone know why this might be happening?

A: You can change the composite operation as many times as you want.
Here you can see the definition of the globalComposite Operation in the specification :
http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#dom-context-2d-globalcompositeoperation
And you have here a quick visual reminder of the various operations :
https://developer.mozilla.org/samples/canvas-tutorial/6_1_canvas_composite.html
So what's happening in your case ?
When using the composite mode 'destination-in', it is exactly the expected behavior, that only what's being drawn will remain on the canvas, and it will be drawn using the color of the pixels that were already there.
So each time you print a char, you erase everything else, that is not an issue, just not what you want.
How to get the behavior you seek ?
1) You can build your chars on a separate canvas, then drawImage the canvas on your main canvas.
2) But way easier is to using clipping : By clipping you limit the 'scope' of the effect to only the rectangle where you want your operations to happen :
Before drawing, just add :
    context.save();
    context.beginPath();
    context.rect(x * GenCon.font.width,
                      y * GenCon.font.height,
                      GenCon.font.width,
                      GenCon.font.height);
    context.clip();

and don't forget to :
    context.restore();

working fiddle here :    http://jsfiddle.net/gamealchemist/r96Lh/4/

A: From http://www.html5canvastutorials.com/advanced/html5-canvas-global-composite-operations-tutorial/

It's important to note that a canvas context can only support one
  composite operation throughout its life cycle.  if we want to use
  multiple composite operations, as this tutorial does, we need to apply
  the operations on a hidden canvas and then copy the results onto a
  visible canvas.

So, with this approach you may have to use two canvases and blit a portion of one onto the other for each character.


text:
Q: Why I can't connect 2 players in the same room on a GameCenter turn-based game? I'm trying to create a Turn-Based GameCenter multiplayer game and I can't connect 2 players in a match:
I'm connecting with a custom UI and both devices (iPhone and simulator) are running iOS 9.1.
I run on a device and after I run findMatch it creates a new room with me and a player with playerID nil which I read it's normal but when I run on the other device it also does same stuff. Devices are not in same room.
What am I doing wrong?
I am using the following code:
-(void)searchForTurnBasedMatch{
    GKMatchRequest *request = [[GKMatchRequest alloc] init];
//    request.minPlayers = 2;
    request.maxPlayers = 4;
    request.inviteeResponseHandler = ^(NSString *playerID, GKInviteeResponse response)
    {
        if (response == GKInviteeResponseAccepted)
        {
            NSLog(@"playerCeva");
        }
    };

    [GKTurnBasedMatch findMatchForRequest:request withCompletionHandler:^(GKTurnBasedMatch * _Nullable match, NSError * _Nullable error) {
        if (error)
        {
            NSLog(@"eroare la gasire meci: %@",error);
        }
        else if (match != nil)
        {
            self.myTurnBasedMatch = match;
            [self resumeMatch:match];

        }

    }];

}

- (void)resumeMatch:(GKTurnBasedMatch *)match {
    self.myTurnBasedMatch = match;
    NSLog(@"Created/Selected match");
    NSLog(@"ID: %@\tCreated: %@", match.matchID, match.creationDate);
    GKTurnBasedParticipant *firstParticipant = [match.participants objectAtIndex:0];
    if (firstParticipant.lastTurnDate != NULL) {
        if ([match.currentParticipant.playerID isEqualToString:[GKLocalPlayer localPlayer].playerID]) {
            NSLog(@"Taking turn ...");
        } else {
            NSLog(@"Not my turn ...");
        }
    } else {
        NSLog(@"New game ...");
    }
}


text:
Q: When is exFAT coming to Linux? It seems that exFAT is to be the next standard filesystem for removable media. The problem is, it is designed by Microsoft and made proprietary. However, it is the standard FS for the upcoming SDXC cards.
Since exFAT isn't available for Linux, will it eventually get there? And if so, when?
Formating removable media for Linux, Windows and Mac OS X, is really becoming a problem. There's FAT32 but the file size limit is becoming a problem as well.
I was hoping that UDF will be a cross platform filesystem, especially, since the latest revisions of UDF clearly state the targeting of hard drives. Microsoft, however, doesn't seem to care much about UDF on anything else than optical media, so I guess it'll become abandoned eventually.
It seems, that exFAT will take the place of FAT32, but since it's not available for Linux, I shouldn't format my USB sticks in it. Should I just wait till exFAT is available for Linux? Also, since Microsoft doesn't seem to be poised to open the filesystem for free implementations - there's licenses, etc involved - I might wait till infinity...
I still use FAT32 most of the time, but there are times, where I have to use something else, due to the file size limit. I usually reformat the drives in NTFS for that purpose, but still, the constant formating back and forth is quite a hassle.

A: There is an FUSE exFAT module available. It is in beta state however.
See this tutorial how to use it on Ubuntu.
Here is the status of exFAT on Linux.


text:
Q: Getters and Setters in Android please help me... i don't know what i'm doing wrong!!
I have 3 classes.
1 - Activity = TelaCadastroRestaurant.java
2 - Entity = Restaurant.java
3 - Method's Class = Metodos.java
Problem: When i call getNomeRestaurante() in method callMandarNuvem() or in ANY other method BUT pegarvalores(), it DOESN'T WORK... it shows null.
Error's print: http://i.imgur.com/sOcBkUM.png
********************EXAMPLE***************************
If i create a Restaurant object INSIDE the method pegarValores() and in a Toast, call: getNomeRestaurante()... IT IS ALL NORMAL.
but, if i create a Restaurant object OUTSIDE the method pegarValores() and in a Toast, call: getNomeRestaurante()... IT SHOWS NULL.
*********************METHOD'S MEANING*******************
method -> inicializaComponentes(): it references the components of Activity.
method -> acaoBotoes(): it deal with the clicks on buttons
method -> pegarValores(): it means, catching values.
method -> mandarNuvem(): it means, send to clound (save)
method -> caixaCerteza(): it means, you sure you wanna do that?
method -> taskInProgress(): it means, loading..wait

public class TelaCadastroRestaurante extends Activity {
private Button proximoButton;
private EditText nomeRestauranteEditText, emailRestauranteEditText, telefoneRestauranteEditText;

private String nomeRestauranteValores, emailRestauranteValores;
private int telefoneRestauranteValores;

private String voceTemCerteza = "Você tem certeza que deseja cadastrar o restaurante ";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tela_cadastro_restaurante);
    incializarComponentes();
    acaoBotoes();
}

public void incializarComponentes() {
    nomeRestauranteEditText = (EditText) findViewById(R.id.editTextNomeRestauranteTelaCadastroRestaurante);
    emailRestauranteEditText = (EditText) findViewById(R.id.editTextEmailRestauranteTelaCadastroRestaurante);
    telefoneRestauranteEditText = (EditText) findViewById(R.id.editTextTelefoneRestauranteTelaCadastroRestaurante);
    proximoButton = (Button) findViewById(R.id.buttonProximoTelaCadastroRestaurante);
}

public void acaoBotoes() {
    proximoButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            pegarValores();
            callMandarNuvem();
        }
    });
}

public void pegarValores(){
    Restaurante rest = new Restaurante();

    nomeRestauranteValores = nomeRestauranteEditText.getText().toString();
    emailRestauranteValores = emailRestauranteEditText.getText().toString();
    telefoneRestauranteValores = Integer.parseInt(telefoneRestauranteEditText.getText().toString());

    rest.setNomeRest(nomeRestauranteValores);
    rest.setEmailRest(emailRestauranteValores);
    rest.setTelefoneRest(telefoneRestauranteValores);

}

public void callMandarNuvem(){
    Runnable r = new Runnable() {
        public void run() {
            Metodos.mandarNuvem(TelaCadastroRestaurante.this);
        }
    };

    Restaurante rest = new Restaurante();
    Metodos.caixaCerteza(TelaCadastroRestaurante.this, voceTemCerteza + rest.getNomeRest() + "?",r);

}

}

public class Restaurante {
private String idRest;
private String nomeRest;
private String emailRest;
private int telefoneRest;

public Restaurante() {
}

public Restaurante(String nomeRest, String emailRest, int telefoneRest) {
    this.nomeRest = nomeRest;
    this.emailRest = emailRest;
    this.telefoneRest = telefoneRest;
}

public String getIdRest() {
    return idRest;
}

public void setIdRest(String idRest) {
    this.idRest = idRest;
}

public String getNomeRest() {
    return nomeRest;
}

public void setNomeRest(String nomeRest) {
    this.nomeRest = nomeRest;
}

public String getEmailRest() {
    return emailRest;
}

public void setEmailRest(String emailRest) {
    this.emailRest = emailRest;
}

public int getTelefoneRest() {
    return telefoneRest;
}

public void setTelefoneRest(int telefoneRest) {
    this.telefoneRest = telefoneRest;
}

@Override
public String toString() {
    return nomeRest;
}

}

public class Metodos {
private static ProgressDialog dialog;

// Metodo que mostra o Aguarde a verificação
public static void taskInProgres(boolean mostrar, Context context) {

    if (dialog == null) {
        dialog = new ProgressDialog(context);
        dialog = ProgressDialog.show(context, "","Espere um momento...", true);
    }
    if (mostrar) {
        dialog.show();
    } else {
        dialog.dismiss();
    }
}

// Metodo que mostra a caixa de certeza
public static void caixaCerteza(final Context context, final String texto, final Runnable func) {
    AlertDialog.Builder builderaction = new AlertDialog.Builder(context);
    builderaction.setTitle("Atenção!");
    builderaction.setMessage(texto);

    builderaction.setPositiveButton("Sim",new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    func.run();
                }
            });
    builderaction.setNegativeButton("Não",new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
    AlertDialog alert = builderaction.create();
    alert.setIcon(R.drawable.ic_stop);
    alert.show();
}

// Metodo que manda pra nuvem
public static void mandarNuvem(final Context context){

    Metodos.taskInProgres(true, context);

        Restaurante rest = new Restaurante();

        ParseObject restauranteParse = new ParseObject("Restaurante");
        restauranteParse.put("nomeRestaurante", rest.getNomeRest());
        restauranteParse.put("emailRestaurante", rest.getEmailRest());
        restauranteParse.put("telefoneRestaurante", rest.getTelefoneRest());
        restauranteParse.saveInBackground(new SaveCallback() {
            @Override
            public void done(ParseException e) {
                if (e == null) {
                    Toast.makeText(context,"Salvo com sucesso!", Toast.LENGTH_SHORT).show();
                    Metodos.taskInProgres(false, context);
                } else {
                    Toast.makeText(context, e.getMessage(),Toast.LENGTH_SHORT).show();
                }
            }
        });
}

}

A: Restaurante rest = new Restaurante();
Metodos.caixaCerteza(TelaCadastroRestaurante.this, voceTemCerteza + rest.getNomeRest() + "?",r);

you are calling the default Constructor of your Entity-Class to build an "empty" Restaurant. So the String nomeRest keeps its value which is null at that point.
So rather call the other Constructor where you pass your values or use the setters like you do in the other method!

A: You're creating a new instance of Restaurant and not setting any values. I think this is what you're looking for:
 public class TelaCadastroRestaurante extends Activity {

   private Button proximoButton;
   private EditText nomeRestauranteEditText, emailRestauranteEditText, telefoneRestauranteEditText;

   private String nomeRestauranteValores, emailRestauranteValores;
   private int telefoneRestauranteValores;

   private String voceTemCerteza = "Você tem certeza que deseja cadastrar o restaurante ";

   private final Restaurante rest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_tela_cadastro_restaurante);
     incializarComponentes();
     acaoBotoes();
        }

    public void incializarComponentes() {
     nomeRestauranteEditText = (EditText)                   findViewById(R.id.editTextNomeRestauranteTelaCadastroRestaurante);
     emailRestauranteEditText = (EditText) findViewById(R.id.editTextEmailRestauranteTelaCadastroRestaurante);
      telefoneRestauranteEditText = (EditText) findViewById(R.id.editTextTelefoneRestauranteTelaCadastroRestaurante);
      proximoButton = (Button) findViewById(R.id.buttonProximoTelaCadastroRestaurante);
   }

  public void acaoBotoes() {
   proximoButton.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        pegarValores();
        callMandarNuvem();
    }
});
}

  public void pegarValores(){
     rest = new Restaurante();

   nomeRestauranteValores =       nomeRestauranteEditText.getText().toString();
   emailRestauranteValores = emailRestauranteEditText.getText().toString();
   telefoneRestauranteValores = Integer.parseInt(telefoneRestauranteEditText.getText().toString());

   rest.setNomeRest(nomeRestauranteValores);
   rest.setEmailRest(emailRestauranteValores);
   rest.setTelefoneRest(telefoneRestauranteValores);

  }

  public void callMandarNuvem(){
     Runnable r = new Runnable() {
    public void run() {
        Metodos.mandarNuvem(TelaCadastroRestaurante.this);
    }
};

   Metodos.caixaCerteza(TelaCadastroRestaurante.this, voceTemCerteza + rest.getNomeRest() + "?",r);

}
In your Metodos class, change mandarNuvem to:
// Metodo que manda pra nuvem
public static void mandarNuvem(final Context context,Restaurante rest){

Metodos.taskInProgres(true, context);

    ParseObject restauranteParse = new ParseObject("Restaurante");
    restauranteParse.put("nomeRestaurante", rest.getNomeRest());
    restauranteParse.put("emailRestaurante", rest.getEmailRest());
    restauranteParse.put("telefoneRestaurante", rest.getTelefoneRest());
    restauranteParse.saveInBackground(new SaveCallback() {
        @Override
        public void done(ParseException e) {
            if (e == null) {
                Toast.makeText(context,"Salvo com sucesso!", Toast.LENGTH_SHORT).show();
                Metodos.taskInProgres(false, context);
            } else {
                Toast.makeText(context, e.getMessage(),Toast.LENGTH_SHORT).show();
            }
        }
    });
 }

And then change your call to the method to:
 public void callMandarNuvem(){
Runnable r = new Runnable() {
    public void run() {
        Metodos.mandarNuvem(TelaCadastroRestaurante.this,rest);
    }
};


text:
Q: install alphacep(VOSK APİ) Python Remembrances. I https://github.com/alphacep/vosk-api I'm trying to set it up, but I can't, can anyone set it up before ?

A: From doc (https://alphacephei.com/vosk/install):

On Windows make sure you have 64-bit Python. We do not support 32-bit python yet.


text:
Q: Zip list of tuples with flat list I'm wondering if there's an easy way to do the following in Python 3.x. Say I have two lists structured as follows:
list_a = [(1,2), (1,2), (1,2), ...]
list_b = [3, 3, 3, ...]

What's the simplest way to produce a generator (here represented by calling a function funky_zip) that would let me iterate through these two lists like so:
>>> for a, b, c, in funky_zip(list_a, list_b):
>>>      print(a, b, c)
...
1 2 3
1 2 3
1 2 3
# and so on

I could just do
for aa, b in zip(list_a, list_b):
    print(aa[0], aa[1], b)

but I'm wondering if there's a nice way to do this without having to unpack the tuples. Thanks!

A: You just need parentheses:
list_a = [(1,2), (1,2), (1,2)]
list_b = [3, 3, 3]
for (a, b), c in zip(list_a, list_b):
    print(a, b, c)

Result:
1 2 3
1 2 3
1 2 3


text:
Q: Placing SVC handler in SVC vector in Arm Cortex M0 I have a function that I want to put into the SVC exception vector, but I can't seem to find the syntax necessary to put the function's address into that vector.  Can anyone suggest a resource to help?

A: A good tutorial has been writen by valvers for bare metal raspberry pi programming.
Despite the CPU is not the same, the underlying concept of exception, is the same. You should definitely have a look there.
A former colleague of mine has written an HAL for Cortex M4. In it, he sets interrupt handlers in C, without any assembly calls, just using symbol's location. You should also have a look on RFLPC.

A: Assuming you have a symbol called your_function_name the following code would branch to it.
SVC_Handler
    EXTERN your_function_name
    ldr r0,=your_function_name
    bx r0

As a rule though the handlers are usually weakly linked so having a function void SVC_Handler(void) should end up linked rather than the handler defined in the startup file.

A: Too vague this is very specific to your code, and there are a number of ways to implement the cortex-m vector table and use GNU tools, so you have not provided enough information, and while finding that information for us it should become obvious where your table is.  You can start by disassembling the elf version of your binary and find label names in the vector table area then grep your code base for those names.
If you are riding on top of a bunch of someone elses libraries, etc it may be even more painful to deal with there may be function calls etc runtime that you use to register the handler.
There are a million ways to solve this and all may work, which one are you using?


text:
Q: How to resolve warning "Capturing 'self' strongly in this block is likely to lead to a retain cycle" in this case? My PhotosListCollectionViewController.h file:
@interface PhotosListCollectionViewController : UICollectionViewController <UICollectionViewDelegateFlowLayout> {
    FooterView *footerView;
    PhotosListCollectionViewViewModel *photosListCollectionViewViewModel;
}

@property (strong, nonatomic) NSString *userQuery;

@end

In PhotosListCollectionViewController.m (look comment):
@implementation PhotosListCollectionViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    footerView = [[FooterView alloc] init];

    photosListCollectionViewViewModel = [[PhotosListCollectionViewViewModel alloc] initWithUserQuery:_userQuery];

    [self.collectionView registerClass:FooterView.class forSupplementaryViewOfKind:UICollectionElementKindSectionFooter                withReuseIdentifier:NSStringFromClass([FooterView class])];

    __weak __typeof(self)weakSelf = self;

    photosListCollectionViewViewModel.getNextPage = ^(NSError *error) {
        if (nil == error) {
            [weakSelf.collectionView reloadData];
        } else {
            [weakSelf showAlertWithTitle:error.localizedDescription message:@"Try again."];
        }
        [self->footerView hideLoader]; // warning in this line.
    };
}

How to resolve my problem? I read another questions, but they did not solve my problem.
Change to
 [weakSelf->footerView hideLoader];

get error

Dereferencing a __weak pointer is not allowed due to possible null
  value caused by race condition, assign it to strong variable first

A: Thanks @matt for help me. Decision is:
__weak __typeof(self)weakSelf = self;

_photosListCollectionViewViewModel.getNextPage = ^(NSError *error) {
    if (nil == error) {
        [weakSelf.collectionView reloadData];
    } else {
        [weakSelf showAlertWithTitle:error.localizedDescription message:@"Повторите попытку."];
    }
    __typeof(self)strongSelf = weakSelf;
    [strongSelf->footerView hideLoader];
};


text:
Q: Windows 10, kill child process, can't get correct PID I use win10 if it's matters, in bash(git)
I have SH script:
start node ./e2e-tests/apimocker_runner.js & pid1=$!
start npm run protractor -- --binaryPath=./build/appInstaller/win-unpacked/ & pid2=$!

sleep 10
kill $pid1
kill $pid2

when i try kill processes by pid i have error:
bash: kill: (6616) - No such process

As i know in $! we have last child process pid, but this don't work.
Cuz then i type in bash:
start bash & pid=$!
echo $pid

$pid === 1000  (for example)

but if i type
echo $$

in created bash by previous command i have another pid

$$ ==== 1200 (for example)

Also I found what if i type start bash this create non-child process, but i want to create child process and wait for them like wait $pid
How i can do this?

A: A variable set in one bash instance is not visible in another bash instance which is not its child process (and only then if the parent did export variable to expose it to children).


text:
Q: Why bitwise operators are popular in sport programming I'm a newbie in one of a sport programming service and found that winning solutions often use bitwise operators.
Here is an example.

Write a function, which finds a difference between two
  arrays (consider that they differ by one element).

The solutions are:
let s = x => ~eval(x.join`+`);
let findDiff = (a, b) => s(b) - s(a);

and
let findDiff = (a, b) => eval(a.concat(b).join`^`);

I would like to know:

*

*The explanation of those two examples (bitwise part).

*What's the advantage of using bitwise operators on decimal numbers?

*Is that faster to operate with bitwise operations rather than normal one?

Update:
I didn't fully understand why my question is marked as a duplicate to ~~ vs parseInt. That's good to know, why this operator replaces parseInt and probably helpful for sport programming. But it doesn't answer on my question.

A: Code golf isn't focused on bitwise operators, is about code length.
Bitwise operators are not necessary faster, but generally fast enough. They are concise (and usually harder to read, but that's side effect).
~~ is a shorter (and usually more preformant) alternative to parseInt with a considerable number of remarks. In regular (non-golf) code it should be used only if it provides the behaviour that is more desirable than parseInt or in performance-sensitive context.
~a is roughly equal to parseInt(a) * -1 - 1. It can be used as a shorter alternative to ~~a in this particular example, s(b) - s(a), because * -1 - 1 part is eliminated on subtraction (the sign should be taken into account).


text:
Q: ¿Qué significado tiene el signo de exclamacion en esta linea #!/usr/bin/env python? Aunque es un pequeño detalle me gustaria saber porque comenzar esta linea con un signo de exclamacion que hace el ! en #!/usr/bin/env python.

A: Se le denomina Shebang a los caracteres #! juntos, es cosa de linux para determinar que interprete se va a utilizar seguido de la ruta, en esté caso /usr/bin/env
Es común verlo en los scripts de linux que corre con el interprete bash de la siguiente manera #!/bin/bash


text:
Q: DAX subtotal at item level for only visible row items I am having a hard time coming up with the right DAX for something that seems so simple!
Table1                  Table2
Year | Amount           Year
-------------           -----
2010 | 1                2010
2011 | 2                2011
2012 | 3                2012

Relationship:
Table1[Year] related to Table2[Year]

All I'm trying to do is, in a Pivot Table, return the subtotal of all years based on the years selected. So, for example, assume I have a Slicer for Table2[Year] and only 2010 and 2011 are selected (2012 is filtered out). The measure for each row should be 3 (the total of all visible years, or 1 + 2 for years 2010 + 2011), like so:
Rows    Measure
----    -------
2010          3
2011          3
 Total        3

But based on different variations of DAX I've tried, I either get the amount based on each row or I get a subtotal of ALL years, including 2012 which is filtered out.  I've tried variations of ALL, CONTAINS, VALUES but I am struggling!

A: Try this:
SUMVisible := CALCULATE(
                        SUM(Table1[Amount]),
                        ALLSELECTED(Table2[Year])
                       )


text:
Q: Why does runBlocking order coroutine execution in kotlin? If I run this code
fun main(){
    println("start")
    runBlocking {
        for (i in 0..10){
            launch {
                delay(2000L)
                println(i)
            }
        }
    }
    println("end")
}

the output is
start
0
1
2
3
4
5
6
7
8
9
10
end

So why are 0 to 10 coroutines ordered? The same code, changed to work with coroutineScope outputs the numbers in random order.
I am just curious about how this works since by the look of it runBlocking still launches the coroutines concurrently
Edit: Rewritten version
suspend fun main(){
    println("start")
    coroutineScope {
        for (i in 0..10){
            launch {
                delay(2000L)
                println(i)
            }
        }
    }
    println("end")
}


text:
Q: base64 encoded then decoded failing Here is the base64 encoded smilies generated form my android phone and saved into MySQL when I try to display it in browser first I need to check if the string is base64 encoded then I decoded and print it, but below code fails to
$mystring = "8J+YgPCfmInwn5iZ8J+YkPCflIfwn5Oi8J+OtfCfjqfwn5C18J+QiPCfpoTwn5CX8J+MjfCfl7vw\nn4+f8J+PofCfj4Himb/wn5uC8J+atA==\n";

if (base64_encode(base64_decode($mystring)) == $mystring) {
    echo base64_decode($mystring);
} else {
    echo  $mystring;
}

but if I directly decode same string and print it works
echo base64_decode($mystring);
// output ♿

however same code worked for iOS phone generated smiles.
$mystring = "8J+YgvCfkoHwn5iK8J+RqeKAjfCfkanigI3wn5Gn8J+ZiPCfpKPwn5mJ8J+QvPCfkLbwn5CT8J+MmeKaoe+4j/CfjY7wn42U8J+NlfCfpYPimr3vuI8=";

if(base64_encode(base64_decode($mystring)) == $mystring) {
    echo base64_decode($mystring);
} else {
    echo  $mystring;
}

//output  ⚡⚽

I don't understand what is the problem with this block:
if(base64_encode(base64_decode($mystring)) == $mystring)

A: if(base64_encode(base64_decode($mystring)) == $mystring)

You cannot compare the content of two strings in that way.
Use strcmp() function.
Moreover you cannot check in this way if $mystring is base64 encoded.
You will always get true as encoding a string and then decoding the result will always deliver the original string.
Comparing wil only tell you if encoding/decoding works.


text:
Q: Multiple message types with spring JMS I have 2 message types DealCreateDto and DealUpdateDto.
How can I work with 2 different message data types in one spring application? Should I create 2 JmsTemplate instances for each message type or something else?
For JMS using embedded ActiveMQ and MessageConverter implementations:
@Component
@RequiredArgsConstructor
public class DealCreateDtoConverter implements MessageConverter {

    private final ObjectMapper objectMapper;

    @NonNull
    @Override
    @SneakyThrows
    public Message toMessage(@NonNull Object object, @NonNull Session session) {
        TextMessage message = session.createTextMessage();
        message.setText(objectMapper.writeValueAsString(object));
        return message;
    }

    @NonNull
    @Override
    @SneakyThrows
    public DealCreateDto fromMessage(@NonNull Message message) {
        return objectMapper.readValue(((TextMessage) message).getText(), DealCreateDto.class);
    }
}

@Component
@RequiredArgsConstructor
public class DealUpdateDtoConverter implements MessageConverter {

    private final ObjectMapper objectMapper;

    @NonNull
    @Override
    @SneakyThrows
    public Message toMessage(@NonNull Object object, @NonNull Session session) {
        TextMessage message = session.createTextMessage();
        message.setText(objectMapper.writeValueAsString(object));
        return message;
    }

    @NonNull
    @Override
    @SneakyThrows
    public DealUpdateDto fromMessage(@NonNull Message message) {
        return objectMapper.readValue(((TextMessage) message).getText(), DealUpdateDto.class);
    }
}

But as I understood one JmsTemplate can contain only one message converter, and when I try to use both:
private final JmsTemplate jmsTemplate;

@Override
public void create(@NonNull DealCreateDto deal) {
    jmsTemplate.convertAndSend(ActiveMqConfig.DEAL_CREATE_QUEUE, deal);
}

@JmsListener(destination = ActiveMqConfig.DEAL_CREATE_QUEUE, containerFactory = "jmsFactory")
public void receiveCreate(@Payload @NonNull DealCreateDto dealDto) {
}

@Override
public void update(@NonNull DealUpdateDto deal) {
    jmsTemplate.convertAndSend(ActiveMqConfig.DEAL_UPDATE_QUEUE, deal);
}

@JmsListener(destination = ActiveMqConfig.DEAL_UPDATE_QUEUE, containerFactory = "jmsFactory")
public void receiveUpdate(@Payload @NonNull DealUpdateDto dealDto) {
}

Throwing an exception:
2022-08-16 08:41:19:131 ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.jms.support.converter.MessageConversionException: Cannot convert object of type [ltd.mydomain.dto.deal.DealCreateDto] to JMS message. Supported message payloads are: String, byte array, Map<String,?>, Serializable object.] with root cause
org.springframework.jms.support.converter.MessageConversionException: Cannot convert object of type [ltd.mydomain.dto.deal.DealCreateDto] to JMS message. Supported message payloads are: String, byte array, Map<String,?>, Serializable object.
    at org.springframework.jms.support.converter.SimpleMessageConverter.toMessage(SimpleMessageConverter.java:79)
    at org.springframework.jms.core.JmsTemplate.lambda$convertAndSend$5(JmsTemplate.java:661)
    at org.springframework.jms.core.JmsTemplate.doSend(JmsTemplate.java:604)
    at org.springframework.jms.core.JmsTemplate.lambda$send$3(JmsTemplate.java:586)
    at org.springframework.jms.core.JmsTemplate.execute(JmsTemplate.java:504)
    at org.springframework.jms.core.JmsTemplate.send(JmsTemplate.java:584)
    at org.springframework.jms.core.JmsTemplate.convertAndSend(JmsTemplate.java:661)
    at ltd.mydomain.service.DealServiceImpl.create(DealServiceImpl.java:39)
    at ltd.mydomain.service.DealServiceImpl$$FastClassBySpringCGLIB$$4deee829.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
    at org.springframework.aop.framework.CglibAopProxy.invokeMethod(CglibAopProxy.java:386)
    at org.springframework.aop.framework.CglibAopProxy.access$000(CglibAopProxy.java:85)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:704)
    at ltd.mydomain.service.DealServiceImpl$$EnhancerBySpringCGLIB$$b58a53c.create(<generated>)
    at ltd.mydomain.controller.DealController.create(DealController.java:30)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1070)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:517)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:584)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:96)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:360)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:890)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1789)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:833)

Jms configuration:
@EnableJms
@Configuration
public class ActiveMqConfig {

    public static final String DEAL_CREATE_QUEUE = "deal-create-queue";

    public static final String DEAL_UPDATE_QUEUE = "deal-update-queue";

    @Bean
    public JmsListenerContainerFactory<?> jmsFactory(
            @NonNull ConnectionFactory connectionFactory,
            @NonNull DefaultJmsListenerContainerFactoryConfigurer configurer) {
        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
        configurer.configure(factory, connectionFactory);
        return factory;
    }
}

A: Unfortunately, this violates the Liskov Substitution Principle, but is compact and works.
@Component
@RequiredArgsConstructor
public class MessageConverterImpl implements MessageConverter {

    private final ObjectMapper objectMapper;

    // set all message types here or get as bean from config class
    private final List<Class<?>> messageTypes = List.of(
            DealCreateDto.class,
            DealUpdateDto.class
    );

    private final Map<Class<?>, Function<Object, Boolean>> toMessageFunMap = new HashMap<>();

    private final Map<String, Function<Message, Object>> fromMessageFunMap = new HashMap<>();

    @PostConstruct
    public void init() {
        messageTypes.forEach(clazz -> {
            toMessageFunMap.put(clazz, o -> o.getClass().isAssignableFrom(clazz));
            fromMessageFunMap.put(clazz.getName(), message -> getMsg(message, clazz));
        });
    }

    @SneakyThrows
    private Object getMsg(@NonNull Message message, @NonNull Class<?> clazz) {
        return objectMapper.readValue(((TextMessage) message).getText(), clazz);
    }

    @NonNull
    @Override
    @SneakyThrows
    public Message toMessage(@NonNull Object object, @NonNull Session session) {
        Class<?> clazz = toMessageFunMap.keySet()
                .stream()
                .filter(cz -> toMessageFunMap.get(cz).apply(object))
                .findFirst()
                .orElseThrow();
        TextMessage message = session.createTextMessage();
        message.setText(objectMapper.writeValueAsString(object));
        message.setStringProperty("className", clazz.getName());
        return message;
    }

    @NonNull
    @Override
    @SneakyThrows
    public Object fromMessage(@NonNull Message message) {
        String type = message.getStringProperty("className");
        return fromMessageFunMap.get(type).apply(message);
    }
}


text:
Q: File upload not working with navbar in R Shiny I can't get the File Upload feature to work properly when using a navigation bar. Here is what I have for server.R:
library(shiny)
library(markdown)

function(input, output) {

  df <- NULL
  current_file <- NULL
  in_data <- reactive({
    inFile <- input$file1
    if (is.null(inFile)){
  return(NULL)}
else {df <<- read.csv(inFile$datapath, header=input$header, sep=input$sep,
                     quote=input$quote)
      current_file <<- inFile$name
}

return(NULL)
  })

output$fileInfo <- renderTable({
call.me = in_data()
data.frame(current_file)
})

}

And for ui.R I have this:
library(shiny)
library(markdown)

navbarPage('Navigation Bar',
       tabPanel('File Information', verbatimTextOutput('fileInfo'),
                sidebarLayout(
                  sidebarPanel(fileInput('file1', 'Choose CSV File',
                                         accept=c('text/csv',
                                                  'text/comma-separated-values,text/plain',
                                                  '.csv')),
                    checkboxInput('header', 'Header', TRUE),
                    radioButtons('sep', 'Separator',
                                 c(Comma=',',
                                   Semicolon=';',
                                   Tab='\t'),
                                 ','),
                    radioButtons('quote', 'Quote',
                                 c(None='',
                                   'Double Quote'='"',
                                   'Single Quote'="'"),
                                 '"'),
                    tags$hr()),
                  mainPanel()
                )))

I eventually want to have multiple tabs in the navigation bar, and I want to be able to access the data from each tab. All I'm looking for it to do now is for it to give me the name of the file uploaded. This works great when I don't try to fit the navigation bar in. But now it looks like some sort of HTML output. Any tips? Much appreciated.

A: It is an extremely bad idea to enlist the use of the global assignment <<- here. Your data will be globally available to the whole app if you use a reactive -- which is the way shiny is intended to be used.
Also, look into shiny::validate (example usage below) to validate inputs.
library("shiny")

options(shiny.maxRequestSize = 9*1024^2)

server <- function(input, output) {

  # the data read in by read.csv will now be accessible throughout the app
  # by calling this reactive, e.g. in_data().
  in_data <- reactive({
    shiny::validate(
      need(input$file1, "Select a file!")
    )

    read.csv(input$file1$datapath, header = input$header,
             sep = input$sep, quote = input$quote)
  })

  # an example, we're calling the reactive to access the data loaded
  output$file_info <- renderTable({
    data.frame(in_data())
  })

}

ui <- navbarPage('Navigation Bar',
  tabPanel('File Information', verbatimTextOutput('fileInfo'),
    sidebarLayout(
      sidebarPanel(
        fileInput('file1', 'Choose CSV File', accept = c('text/csv', 'text/comma-separated-values,text/plain', '.csv')),
        checkboxInput('header', 'Header', TRUE),
        radioButtons('sep', 'Separator', c(Comma = ',', Semicolon = ';', Tab = '\t'), ','),
        radioButtons('quote', 'Quote', c(None = '', 'Double Quote'='"', 'Single Quote' = "'"),'"'),
        tags$hr()
        ),
      mainPanel(
        tableOutput("file_info")
        )
      )
    )
  )

shinyApp(ui, server)


text:
Q: Unable to ping Internal network created by Vagrant I have been trying to create a internal network using Vagrant with VirtualBox. My host is a MacBook Air and my guests (Ubuntu) cannot ping each other. I have tried various resources online and according to the websites that I have viewed I seem to be doing the right thing. Below is my configuration file for Vagrant:
Vagrant.configure(2) do |config|
  config.vm.box = "ubuntu/trusty64"
  # config.vm.provision :salt do |salt|
  # salt.minion_config = "saltstack/etc/minion"
  # salt.run_highstate = true
  # salt.install_type = "git"
  # salt.install_args = "v2014.1.0"
  # salt.verbose = true
end

config.vm.define "web" do |web|
  web.vm.box = "ubuntu/trusty64"
  web.vm.network "private_network", ip: "10.0.2.16", virtualbox__intnet: true, virtualbox__intnet: "intnet"
end

config.vm.define "db" do |db|
db.vm.box = "ubuntu/trusty64"
db.vm.network "private_network", ip: "10.0.2.17", virtualbox__intnet: true, virtualbox__intnet: "intnet"
end

 config.vm.boot_timeout = 1000
end

As you can see I have assigned both ip addresses to my machines. When using the private network option, VirtualBox default is set to host only networking. I would like internal network. So, I added the virtualbox_intnet option to true which enables internal networking. I am using 1.7.2 of vagrant and VirtualBox version is 4.3.30.
Now, I am unable to ping both of these machines from within the guests. What am I doing wrong?
I have visited the main vagrant websites and others including https://forums.virtualbox.org/viewtopic.php?f=9&t=17747

A: The issue was that VirtualBox somehow contains information on the ip address starting from 10.0. So, I changed the ip address from 10.0 to 10.10 and that worked. The ip address for example 10.10.2.17.

A: After an upgrade of vagrant I had to manually enable the network as it was DOWN (host-system):
sudo ip link set up dev vboxnet0

After that communication between host and guest worked again.


text:
Q: JSP Get Title and Meta Tags of External site - Stack Overflow I want to try figure out how to get the website Title and Metadata from a link
I have seen the solution for PHP (Getting title and meta tags from external website), however I will like to know if there is a solution for JSP.

A: Use java.net.HttpURLConnection or http components to get the string of the external site. Use regex or htmlcleaner to extract title and metadata.


text:
Q: Differences in Observables between Angular2 and Angular8 I had created some functions related to Observables in Angular2 for an app I was developing. But since then, I haven't use Angular. So, my working functions related to Observables have to be modified accordingly in order to become functional in Angular8 and I can't get rid of some error messages.
The API from the server returns an array of objects from the database:
router.get('/getEntries, (req, res, next) => {
   db.get().collection('data').find().toArray((err, data) => { res.json(data); });
});

The problem probably is in the entry.service.ts file:
import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {map}        from 'rxjs/operators';
import {Entry}      from '../Classes/entry';

@Injectable()
export class EntryService {

   constructor(private http: HttpClient) { }

   getEntries(): Observable<Entry[]> {
      return this.http.get('http://192.168.1.3:3000/api/getEntries').pipe(map(res => res.json() as Entry[]));
   }

} //end of Service

The app.component.ts is the following:
import {Component, OnInit} from '@angular/core';
import {Entry}             from '../Classes/entry';
import {EntryService}      from '../Services/entry.service';

@Component({
   selector    : 'app-root',
   templateUrl : './app.component.html',
   styleUrls   : ['./app.component.css']
})

export class AppComponent implements OnInit {
   entries: Entry[];

   constructor(private entryService: EntryService) { }

   ngOnInit(): void {
      this.entryService.getEntries().subscribe(data => {this.entries=data;}, err => {console.log(err);});
   }

} //end of Component

The old working entry.service.ts file in Angular2 is the following:
import { Injectable }           from '@angular/core';
import { Http }                 from '@angular/http';
import { Observable }           from 'rxjs/Observable';
import { Entry }                from '../Classes/entry';
import 'rxjs/add/operator/map';

@Injectable()
export class EntryService {

   constructor(private http: Http) { }

   getEntries(): Observable<Entry[]> {
      return this.http.get('http://192.168.1.3:3000/api/getEntries').map(res => res.json() as Entry[]);
   }

} //end of Service

Now, in Angular 8, .json() function doesn't exist anymore.
How can I adjust my code in Angular 8 in order to work??
Generally speaking, is my method of handling http requests a good practice or could it be implemented with a better manner? I don't know Angular in-depth so this is why i'm asking.
Thank you in advance for your time!

A: Use the HttpClientclass from HttpClientModule if you're using Angular 4.3.x and above:
import { HttpClientModule } from '@angular/common/http';
 imports: [
   BrowserModule,
   HttpClientModule
 ],
 ...

 class MyService() {
    constructor(http: HttpClient) {...}

It's an upgraded version of http from @angular/http module with the following improvements:

*

*Interceptors allow middleware logic to be inserted into the pipeline

*Immutable request/response objects

*Progress events for both request upload and response download

*JSON is an assumed default and no longer needs to be explicitly parsed

*Typed, synchronous response body access, including support for JSON body types

You can read about how it works here.
Also pay attention that old http was injected using Http class token instead of the new HttpClient

@NgModule({
 imports: [
   BrowserModule,
   HttpModule
 ],
 ...

 class MyService() {
    constructor(http: Http) {...}

A: HttpClient.get() applies res.json() automatically and returns Observable>. You no longer need to call this function yourself.
See Difference between HTTP and HTTPClient in angular 4?
Don't need to use this method:
.map((res: Response) => res.json());


text:
Q: Kendo Scheduler with Adaptive Display takes over vertical scroll on mobile I am building a responsive web app with Kendoui, Bootstrap and Durandal.
I am using Kendo Scheduler along with other elements on a page and I have enabled adaptive display on the component by setting :
mobile: true
The page scrolls fine on mobile until I get to the scheduler and then my swipes (Up-Down) seem to be swallowed by the component and I can no longer scroll the page ...

A: According to the adaptive demo from Kendo the mobile property should be "phone" instead of true. Maybe that is your issue. Take a look here http://demos.telerik.com/kendo-ui/scheduler/adaptive


text:
Q: Calculate list of points inside a 3D region with specific spacing I'm trying to get a list of points inside a 3D region. However, I want these points to have a certain spacing in x-, y- and z-directions.
As of now I generate a list of points with the appropriate spacing and use Select with an appropriate RegionMemberFunction to filter for the desired points. This generates quite a bit of useless data, as millions of points get discarded after the use of Select.
An example:
h = 100;
r = 100;
rm = RegionMember[Cone[{{0, 0, 0}, {0, 0, h}}, r]];
pts = ParallelTable[{x, y, z}, {x, -r/2, r/2, r/100}, {y, -r/2, r/2,
    r/100}, {z, 0, h, h/100}];
selpts = Select[rm]@Flatten[pts, 2]

Around 1 million points are generated by pts, but around 50% are discarded for the desired points selpts. Is there a way to generate only points inside the desired 3D region without the overhead?

A: Pick seems faster.
h = 100;
r = 100;
reg = Cone[{{0, 0, 0}, {0, 0, h}}, r];
rm = RegionMember[reg];
n = 30;
pts = Tuples[Subdivide[##, n] & @@@ RegionBounds[reg]];
selpts = Pick[pts, rm[pts]];
Graphics3D[{Blue, Point@selpts, Opacity[.2], reg}]

A: You can get an explicit constraint:
Simplify[RegionMember[Cone[{{0, 0, 0}, {0, 0, h}}, r], {x, y, z}], Assumptions-> {r > 0, h >0, 0<=z/h <= 1, Element[_, Reals]}]

Then:
h = 10;
r = 10;
ps = Flatten[Table[If[x^2 + y^2 <= r^2*(h -z)^2/h^2,{x, y, z}, Nothing], {x, -r/2, r/2, r/10}, {y, -r/2, r/2,r/10}, {z, 0, h, h/10}] , 2];
ListPointPlot3D[ps,PlotRange->All]

Perhabs it is possible to move constraint to ranges.

A: This works but is not fast. I really hope to see a variety of answers to this question, and hopefully, somebody will benchmark them all.
pnts = Block[{h=20,r=10,rmf},
         rmf = Reduce@RegionMember[Cone[{{0, 0, 0}, {0, 0, h}}, r]][{x,y,z}];
         ReplaceAll[
            {x,y,z},
            Solve[rmf,{x,y,z}∈Integers]
        ]
]

Or a bit faster for version 12.3 and after
pnts = Block[{h=20,r=10,rmf},
         rmf = Reduce@ RegionMember[Cone[{{0, 0, 0}, {0, 0, h}}, r]][{x,y,z}];
         NSolveValues[rmf,{x,y,z}∈Integers]
];

Display
ListPointPlot3D[pnts,PlotRange->All]

A: Not an answer, just an analysis. Some details left out, just considering an alternate approach.
If you can accept a pretty close approximation, you can kind of use RandomPoint[ ]. As an example, I generate 10,000,000 points in the cone, taking just the integer part of the float number to get a sampling of the grid. This can be fast. I wonder about an additional transformation to make it almost surely cover the grid with fewer samples.
The slow part is then chopping off the edges of the cone to get the rectangular base.
r = h = 100;
cone = Cone[{{0, 0, 0}, {0, 0, h}}, r];
prePts = Union@(IntegerPart /@ RandomPoint[cone, 10000000]);) // Timing
(*  {3.26563, Null} *)

Length@prePts
(* 1045777 *)

ptsCube = Select[prePts, (-r/2 <= #[[1]] <= r/2 && -r/2 <= #[[2]] <= r/2 ) &]; // Timing
(*  {3.92188, Null} *)

Length@ptsCube
(* 625310 *)

The length of the true grid is
Length@selpts
(* 625310 *)

Also tried this approach, directly forming a region that is an intersection of the spaces. The sampling algorithm obviously has to wrestle with the odd space shape.
cube = Cuboid[{-r/2, -r/2, 0}, {r/2, r/2, h}];
ri = RegionIntersection[cube, cone];
coneCubePts = Union@(IntegerPart /@ RandomPoint[ri, 2000000]); // Timing
(* {9.79688, Null} *)

Length@coneCubePts
(* 582744 *)


text:
Q: How to join column and target entity manually in manytoone relation? I have two fields : account_type_id and account_id.
How can i manually map doctrine TargetEntity to join Company Entity if accountTypeId = 1 OR join User Entity if account_type_id = 2 ?
<?php
/** @Entity */
class Accounts
{
    // 1= Company, 2 = User
    private $accountType;

    /**
     * @ManyToOne(targetEntity="Companies")
     */
    private $company;

    /**
     * @ManyToOne(targetEntity="Users")
     */
    private $user;

    //...

}

A: Unfortunately, joining different columns on the fly cannot be done automatically, but you can have both fields set as nullable and only set the correct one when persisting the Account entity.
This would be the annotation:
/**
 * @ORM\ManyToOne(targetEntity="Users", inversedBy="users")
 * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=true)
 */
private $user;

Keep in mind that nullable=true is the default anyway, I'm just being specific here.
If you want to go defensively about this, you can have an additional check in getter
/**
 * @return User
 * @throws \Exception
 */
public function getUser()
{
    if ($this->accountType !== 2) {
        throw new \Exception("Entity is not of type 'user'");
    }
    return $this->user;
}


text:
Q: Recommended location of Resource Bundles for a Dynamic Web Project I'm looking at restructuring an old Web Application.
I have extracted out all Java source files from my Dynamic Web App and put them in a jar that gets added to the Web App WerContent/WEB-INF/lib when compiling using my build.xml.
So the intention is to only have my jsf/xhtml & resources files(js/css/images) in the web app.
The Jar also contains numerous java resource bundles properties files.
Is it standard practice to have these properties files in the Web App?
What is the recommended location of them?
Thanks

A: The resource bundles must be somewhere in the classpath of the webapp. Whether they're in WEB-INF/classes, or in a jar of WEB-INF/lib doesn't matter. What's important is that ResourceBundle.getBundle() uses the classloader to load them.
I would put them in the same location as the classes using them.


text:
Q: How to read tag and their related triggers name/ value in google analytics 4 using java I am using GA4 tutorial to make an API call to Google Analytics 4and the code provided in that link is listing my data based on defined dimension and metrics.Suppose in Google Tag Manager, I have created a tag and relative triggers like in this photo:
For example if the user clicks on the menu bar and the Click URL contains specific URL, then the tag is fired. Of course it is possible to see this information from  Google Tag Assistant.

Now I want to know if it is possible to list these tags and triggers using JAVA as well or not?
Thank you in advance

A: Finally I found out how to do it. As an example for the tag and trigger I created:
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import com.google.analytics.data.v1beta.BetaAnalyticsDataClient;
import com.google.analytics.data.v1beta.BetaAnalyticsDataSettings;
import com.google.analytics.data.v1beta.DateRange;
import com.google.analytics.data.v1beta.Dimension;
import com.google.analytics.data.v1beta.RunReportRequest;
import com.google.analytics.data.v1beta.RunReportResponse;
import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;

import io.grpc.LoadBalancerRegistry;
import io.grpc.grpclb.GrpclbLoadBalancerProvider;

public class Ga4DataAnalytics2 {

    static {
        LoadBalancerRegistry.getDefaultRegistry().register( new GrpclbLoadBalancerProvider());
    }
    public static void main(String[] args) throws IOException {

    String credentialsJsonPath="path to credential.json";
    String propertyId = "your property ID";
    Files.createDirectories(Paths.get(credentialsJsonPath).getParent());

    GoogleCredentials credentials =
            GoogleCredentials.fromStream(new FileInputStream(credentialsJsonPath));

    BetaAnalyticsDataSettings betaAnalyticsDataSettings =
            BetaAnalyticsDataSettings.newBuilder()
            .setCredentialsProvider(FixedCredentialsProvider.create(credentials))
            .build();

    try (BetaAnalyticsDataClient analyticsData =
            BetaAnalyticsDataClient.create(betaAnalyticsDataSettings)) {
        RunReportRequest request =
                RunReportRequest.newBuilder()
                .setProperty("properties/" + propertyId)
                .addDimensions(Dimension.newBuilder().setName("linkUrl"))
                .addDimensions(Dimension.newBuilder().setName("linkText"))
                .addDateRanges(DateRange.newBuilder().setStartDate("2022-09-25").setEndDate("2022-09-26"))
                .build();
        RunReportResponse response = analyticsData.runReport(request);
        System.out.println("Report result:\n"+response);

    }

}

}

and why I am using linkUrl and linkText as dimensions, that is because my tag configuration was :


text:
Q: Memory usage for global GCD queue I have a number of images I am filtering and when I do this in a serial queue that I create ,the memory is released after each block is complete. When I dispatch this work to the global GCD queue the memory doesnt release and gets out of control.
I wrapped the statements in an autorelease block but that doesnt seem to make a difference.
Is it due to the fact that the thread pool keeps references to the blocks somehow? After a while the memory gets released, but the app will crash before this with a large number of images.
Why is the memory being kept by the global queue and how could this be fixed so it releases after every block?

A: You mentioned in your comments that GCD seems to be creating too many threads causing too many images to be in memory at once. If GCD is spawning "loads of threads" where loads is > 3x number of cores, it probably means the blocks you're submitting to it are ending up blocked (perhaps on I/O). A more performant approach would be to serialize the I/O on a serial queue, and do only the in-memory processing in parallel. One way to get help from GCD in this regard is to use dispatch_apply which will limit the number of concurrent operations. IME dispatch_apply will not create more than 2 * number-of-cores threads. (Although that doesn't account for other, concurrent operations that may create threads.)
Also, as you noted, NSOperationQueue allows you to specify a maximum number of concurrent tasks, which is another approach.


text:
Q: My django project is missing a lot of defaults and installed packages are not working When I make my django app there is typically a default sqlite3 that comes with it but for some reason it does not show up so I created a database in the MySQL workbench and then in my settings.py I made sure to add the relevant info.
   DATABASES = {

    'default': {

        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'nameofDB',
        'USER': 'root',
        'PASSWORD': 'mypassword',
        'HOST': 'localhost',
        'PORT': '3306',
        }
   }

In my virtual environment 'env' after activating it I made sure to install everything django, django-admin, pip. The name of my project is 'studybud'
and the directory is:
C:\Users\User\Desktop\studybud

After making my project, I worked on it for a little and checked how the html was rendered so it was activted and I ran the server but after I left it alone for a while my powershell froze so i simply exited out of everything. Not sure if this affects my current problem.
I tried opening my project again but now I get this error:

in my virtual environment i did make sure to install mysqlclient before creating the mysql database but as you see its installed in a completely different directory which is the global one. although i would have thought the python packages i have in my global path would make it work though clearly the error says module for mysqlclient not found.
I literally followed every step of a tutorial and for some reason it still does not work and I dont know why.


text:
Q: meaning of the phrase "I would know" not in a condtional sentence? It is from a song by Katy Perry. Here is the part:

You change your mind like a girl changes clothes
  Yeah, you PMS like a b**** I would know.

That doesn't seem to be a conditional sentence and I cannot think of any connoted one.

A: The song title is 'Hot N Cold' (='Hot and Cold').
The phrase 'I would know' is on a line by itself:

You change your mind like a girl changes clothes
  Yeah, you PMS like a bitch
I would know
  And you overthink, always speak cryptically
  I should know that you're no good for me

The theme of the song is the singer's resentment of the addressed (male) person's mood swings and emotional unpredictability. To 'blow hot and cold' is a idiom meaning to be alternately warm and friendly, and cold and distant, without any apparent reason for changing from one to the other. 'To PMS' appears to mean 'to act like a woman who is suffering from Pre-Menstrual Syndrome (PMS)'. Symptoms of this include irritability and mood changes.
The singer says 'I would know' meaning 'I am very likely to know about PMS because I suffer (or have suffered) from it myself'. "Would" here is a modal verb referring to probability, to what is very likely.

Would modal verb (PROBABILITY)  also 'd used to refer to what is very
  likely:
"The guy on the phone had a Southern accent." "That would be Tom."

Would (Cambridge Dictionary)
'Like a bitch' is a double meaning - 'like a bitch' can mean both 'like an especially annoying woman (a "bitch")' and also 'very much, particularly in a bad or unwelcome way' - 'I cut my hand and it hurt like a bitch.' Needless to say, there is much about the language in the song that may be considered offensive or annoying by many people, because it trivialises, belittles, and stereotypes women (and men as well). Also, it trivialises mental illness (later, she says "Got a case of a love bipolar").

A: Consider the following conversation between an older brother and  younger one:

Mom!  Dmytro took a swig out of the whisky bottle.
   -- How would you know, you little twerp? You were in the bathtub with your rubber ducky.

A wooden paraphrase of the modal would there is something like "What circumstances enabled you to know this, since you can not have seen me do it?" It is a kind of irrealis in that it disputes the truth or reality of the assertion you will know.  How is it possible?
And as the question How would you know? asks incredulously about the conditions or circumstances, the assertion I would know alludes to specific conditions or circumstances that justify the earlier claim, and as an afterthought it is like a preemptive answer to the challenge How would you know?

... you PMS like a b****    — I would know

And those circumstances are it takes one to know one.  The Katy Perry lyric I would know in other words says "I do the same myself and therefore have no trouble recognizing that behavior when I see it".

You little twerp, you're such a liar!
  -- You would know, whisky-breath!

That is, you know a liar when you see one because you yourself are a liar, whisky-breath.