Q: entity framework query and performance I have a Project Like social Network
I have to write a query to get some  posts and last comment of post  that my followers (not blocked) liked That
my code
public List<PostProject> GetFavoritePosts(string userId, int currentPage, int noOfRecords)
    {
        var skipPosts = noOfRecords * currentPage;
        int i = -260;
        var day = DateTime.Now.AddDays(i);

        var blockedusers = DataContext.BlockedUsers.Where(bu => bu.BlockerId == userId);
        var followers = DataContext.FollowUser.Where(u => u.FollowFromUserId == userId);
        var posts = DataContext.Posts.Where(p => p.UserId != userId
        && p.DateOfUpdate > day
        && p.Likes.Any(l => followers.Any(fu => fu.FollowToUserId == l.UserId))
        && p.PostStatusId == 1
        && p.PostType == false
        && blockedusers.All(bu => bu.BlockedId != p.UserId));

        var feed = posts

            .OrderByDescending(post => post.Likes.Count)
            .Select(post => new PostProject
            {
                PostId = post.PostId,
                Content = post.Content,
                Image = post.Image,
                Location = post.Location,
                Video = post.Video,
                CreatedDate = post.CreatedDate,
                DateOfUpdate = post.DateOfUpdate,
                User = post.User,
                ILiked = post.Likes.Any(like => like.UserId == userId),
                LikeCount = post.Likes.Count,
                CommentsCount = post.Comments.Count,
                PostStatusId = post.PostStatusId,
                ShareCount = post.SharePosts.Count,
                Comments = new List<Comment> { post.Comments.OrderByDescending(c =>   c.CommentDate).FirstOrDefault() }
            });
        return feed.Skip(() => skipPosts).Take(() => noOfRecords).ToList();
    }

This code generate sqlQuery with 16 select   and 50ms to run !!!!
Where is my mistake
thanks
sql Query :
SELECT
[Project13].[PostStatusId] AS [PostStatusId],
[Project13].[PostId] AS [PostId],
[Project13].[Content] AS [Content],
[Project13].[Image] AS [Image],
[Project13].[Location] AS [Location],
[Project13].[Video] AS [Video],
[Project13].[CreatedDate] AS [CreatedDate],
[Project13].[DateOfUpdate] AS [DateOfUpdate],
[Project13].[Id] AS [Id],
[Project13].[VisualId] AS [VisualId],
[Project13].[ProfilePicUrl] AS [ProfilePicUrl],
[Project13].[DateCreated] AS [DateCreated],
[Project13].[Activated] AS [Activated],
[Project13].[ActivationCode] AS [ActivationCode],
[Project13].[RoleId] AS [RoleId],
[Project13].[TeamId] AS [TeamId],
[Project13].[RegisterToken] AS [RegisterToken],
[Project13].[Email] AS [Email],
[Project13].[EmailConfirmed] AS [EmailConfirmed],
[Project13].[PasswordHash] AS [PasswordHash],
[Project13].[SecurityStamp] AS [SecurityStamp],
[Project13].[PhoneNumber] AS [PhoneNumber],
[Project13].[PhoneNumberConfirmed] AS [PhoneNumberConfirmed],
[Project13].[TwoFactorEnabled] AS [TwoFactorEnabled],
[Project13].[LockoutEndDateUtc] AS [LockoutEndDateUtc],
[Project13].[LockoutEnabled] AS [LockoutEnabled],
[Project13].[AccessFailedCount] AS [AccessFailedCount],
[Project13].[UserName] AS [UserName],
[Project13].[C1] AS [C1],
[Project13].[C4] AS [C2],
[Project13].[C5] AS [C3],
[Project13].[C6] AS [C4],
[Project13].[C2] AS [C5],
[Project13].[CommentId] AS [CommentId],
[Project13].[CommentText] AS [CommentText],
[Project13].[PostId1] AS [PostId1],
[Project13].[CommentDate] AS [CommentDate],
[Project13].[UserId] AS [UserId],
[Project13].[RowVersion] AS [RowVersion]
FROM ( SELECT
    [Project11].[PostId] AS [PostId],
    [Project11].[Content] AS [Content],
    [Project11].[PostStatusId] AS [PostStatusId],
    [Project11].[Image] AS [Image],
    [Project11].[Location] AS [Location],
    [Project11].[Video] AS [Video],
    [Project11].[CreatedDate] AS [CreatedDate],
    [Project11].[DateOfUpdate] AS [DateOfUpdate],
    [Project11].[Id] AS [Id],
    [Project11].[VisualId] AS [VisualId],
    [Project11].[ProfilePicUrl] AS [ProfilePicUrl],
    [Project11].[DateCreated] AS [DateCreated],
    [Project11].[Activated] AS [Activated],
    [Project11].[ActivationCode] AS [ActivationCode],
    [Project11].[RoleId] AS [RoleId],
    [Project11].[TeamId] AS [TeamId],
    [Project11].[RegisterToken] AS [RegisterToken],
    [Project11].[Email] AS [Email],
    [Project11].[EmailConfirmed] AS [EmailConfirmed],
    [Project11].[PasswordHash] AS [PasswordHash],
    [Project11].[SecurityStamp] AS [SecurityStamp],
    [Project11].[PhoneNumber] AS [PhoneNumber],
    [Project11].[PhoneNumberConfirmed] AS [PhoneNumberConfirmed],
    [Project11].[TwoFactorEnabled] AS [TwoFactorEnabled],
    [Project11].[LockoutEndDateUtc] AS [LockoutEndDateUtc],
    [Project11].[LockoutEnabled] AS [LockoutEnabled],
    [Project11].[AccessFailedCount] AS [AccessFailedCount],
    [Project11].[UserName] AS [UserName],
    [Project11].[C1] AS [C1],
    [Limit1].[CommentId] AS [CommentId],
    [Limit1].[CommentText] AS [CommentText],
    [Limit1].[PostId] AS [PostId1],
    [Limit1].[CommentDate] AS [CommentDate],
    [Limit1].[UserId] AS [UserId],
    [Limit1].[RowVersion] AS [RowVersion],
    1 AS [C2],
    [Project11].[C2] AS [C3],
    [Project11].[C3] AS [C4],
    [Project11].[C4] AS [C5],
    [Project11].[C5] AS [C6]
    FROM   (SELECT
        [Project9].[PostId] AS [PostId],
        [Project9].[Content] AS [Content],
        [Project9].[PostStatusId] AS [PostStatusId],
        [Project9].[Image] AS [Image],
        [Project9].[Location] AS [Location],
        [Project9].[Video] AS [Video],
        [Project9].[CreatedDate] AS [CreatedDate],
        [Project9].[DateOfUpdate] AS [DateOfUpdate],
        [Project9].[Id] AS [Id],
        [Project9].[VisualId] AS [VisualId],
        [Project9].[ProfilePicUrl] AS [ProfilePicUrl],
        [Project9].[DateCreated] AS [DateCreated],
        [Project9].[Activated] AS [Activated],
        [Project9].[ActivationCode] AS [ActivationCode],
        [Project9].[RoleId] AS [RoleId],
        [Project9].[TeamId] AS [TeamId],
        [Project9].[RegisterToken] AS [RegisterToken],
        [Project9].[Email] AS [Email],
        [Project9].[EmailConfirmed] AS [EmailConfirmed],
        [Project9].[PasswordHash] AS [PasswordHash],
        [Project9].[SecurityStamp] AS [SecurityStamp],
        [Project9].[PhoneNumber] AS [PhoneNumber],
        [Project9].[PhoneNumberConfirmed] AS [PhoneNumberConfirmed],
        [Project9].[TwoFactorEnabled] AS [TwoFactorEnabled],
        [Project9].[LockoutEndDateUtc] AS [LockoutEndDateUtc],
        [Project9].[LockoutEnabled] AS [LockoutEnabled],
        [Project9].[AccessFailedCount] AS [AccessFailedCount],
        [Project9].[UserName] AS [UserName],
        CASE WHEN ( EXISTS (SELECT
            1 AS [C1]
            FROM [dbo].[Likes] AS [Extent10]
            WHERE ([Project9].[PostId] = [Extent10].[PostId]) AND (([Extent10].[UserId] = @p__linq__4) OR (([Extent10].[UserId] IS NULL) AND (@p__linq__4 IS NULL)))
        )) THEN cast(1 as bit) ELSE cast(0 as bit) END AS [C1],
        [Project9].[C1] AS [C2],
        [Project9].[C2] AS [C3],
        [Project9].[C3] AS [C4],
        [Project9].[C4] AS [C5]
        FROM ( SELECT
            [Project8].[PostId] AS [PostId],
            [Project8].[Content] AS [Content],
            [Project8].[PostStatusId] AS [PostStatusId],
            [Project8].[Image] AS [Image],
            [Project8].[Location] AS [Location],
            [Project8].[Video] AS [Video],
            [Project8].[CreatedDate] AS [CreatedDate],
            [Project8].[DateOfUpdate] AS [DateOfUpdate],
            [Project8].[Id] AS [Id],
            [Project8].[VisualId] AS [VisualId],
            [Project8].[ProfilePicUrl] AS [ProfilePicUrl],
            [Project8].[DateCreated] AS [DateCreated],
            [Project8].[Activated] AS [Activated],
            [Project8].[ActivationCode] AS [ActivationCode],
            [Project8].[RoleId] AS [RoleId],
            [Project8].[TeamId] AS [TeamId],
            [Project8].[RegisterToken] AS [RegisterToken],
            [Project8].[Email] AS [Email],
            [Project8].[EmailConfirmed] AS [EmailConfirmed],
            [Project8].[PasswordHash] AS [PasswordHash],
            [Project8].[SecurityStamp] AS [SecurityStamp],
            [Project8].[PhoneNumber] AS [PhoneNumber],
            [Project8].[PhoneNumberConfirmed] AS [PhoneNumberConfirmed],
            [Project8].[TwoFactorEnabled] AS [TwoFactorEnabled],
            [Project8].[LockoutEndDateUtc] AS [LockoutEndDateUtc],
            [Project8].[LockoutEnabled] AS [LockoutEnabled],
            [Project8].[AccessFailedCount] AS [AccessFailedCount],
            [Project8].[UserName] AS [UserName],
            [Project8].[C1] AS [C1],
            [Project8].[C2] AS [C2],
            [Project8].[C3] AS [C3],
            (SELECT
                COUNT(1) AS [A1]
                FROM [dbo].[SharePosts] AS [Extent9]
                WHERE [Project8].[PostId] = [Extent9].[PostId]) AS [C4]
            FROM ( SELECT
                [Project7].[PostId] AS [PostId],
                [Project7].[Content] AS [Content],
                [Project7].[PostStatusId] AS [PostStatusId],
                [Project7].[Image] AS [Image],
                [Project7].[Location] AS [Location],
                [Project7].[Video] AS [Video],
                [Project7].[CreatedDate] AS [CreatedDate],
                [Project7].[DateOfUpdate] AS [DateOfUpdate],
                [Project7].[Id] AS [Id],
                [Project7].[VisualId] AS [VisualId],
                [Project7].[ProfilePicUrl] AS [ProfilePicUrl],
                [Project7].[DateCreated] AS [DateCreated],
                [Project7].[Activated] AS [Activated],
                [Project7].[ActivationCode] AS [ActivationCode],
                [Project7].[RoleId] AS [RoleId],
                [Project7].[TeamId] AS [TeamId],
                [Project7].[RegisterToken] AS [RegisterToken],
                [Project7].[Email] AS [Email],
                [Project7].[EmailConfirmed] AS [EmailConfirmed],
                [Project7].[PasswordHash] AS [PasswordHash],
                [Project7].[SecurityStamp] AS [SecurityStamp],
                [Project7].[PhoneNumber] AS [PhoneNumber],
                [Project7].[PhoneNumberConfirmed] AS [PhoneNumberConfirmed],
                [Project7].[TwoFactorEnabled] AS [TwoFactorEnabled],
                [Project7].[LockoutEndDateUtc] AS [LockoutEndDateUtc],
                [Project7].[LockoutEnabled] AS [LockoutEnabled],
                [Project7].[AccessFailedCount] AS [AccessFailedCount],
                [Project7].[UserName] AS [UserName],
                [Project7].[C1] AS [C1],
                [Project7].[C2] AS [C2],
                (SELECT
                    COUNT(1) AS [A1]
                    FROM [dbo].[Comments] AS [Extent8]
                    WHERE [Project7].[PostId] = [Extent8].[PostId]) AS [C3]
                FROM ( SELECT
                    [Project6].[PostId] AS [PostId],
                    [Project6].[Content] AS [Content],
                    [Project6].[PostStatusId] AS [PostStatusId],
                    [Project6].[Image] AS [Image],
                    [Project6].[Location] AS [Location],
                    [Project6].[Video] AS [Video],
                    [Project6].[CreatedDate] AS [CreatedDate],
                    [Project6].[DateOfUpdate] AS [DateOfUpdate],
                    [Project6].[Id] AS [Id],
                    [Project6].[VisualId] AS [VisualId],
                    [Project6].[ProfilePicUrl] AS [ProfilePicUrl],
                    [Project6].[DateCreated] AS [DateCreated],
                    [Project6].[Activated] AS [Activated],
                    [Project6].[ActivationCode] AS [ActivationCode],
                    [Project6].[RoleId] AS [RoleId],
                    [Project6].[TeamId] AS [TeamId],
                    [Project6].[RegisterToken] AS [RegisterToken],
                    [Project6].[Email] AS [Email],
                    [Project6].[EmailConfirmed] AS [EmailConfirmed],
                    [Project6].[PasswordHash] AS [PasswordHash],
                    [Project6].[SecurityStamp] AS [SecurityStamp],
                    [Project6].[PhoneNumber] AS [PhoneNumber],
                    [Project6].[PhoneNumberConfirmed] AS [PhoneNumberConfirmed],
                    [Project6].[TwoFactorEnabled] AS [TwoFactorEnabled],
                    [Project6].[LockoutEndDateUtc] AS [LockoutEndDateUtc],
                    [Project6].[LockoutEnabled] AS [LockoutEnabled],
                    [Project6].[AccessFailedCount] AS [AccessFailedCount],
                    [Project6].[UserName] AS [UserName],
                    [Project6].[C1] AS [C1],
                    (SELECT
                        COUNT(1) AS [A1]
                        FROM [dbo].[Likes] AS [Extent7]
                        WHERE [Project6].[PostId] = [Extent7].[PostId]) AS [C2]
                    FROM ( SELECT
                        [Project5].[PostId] AS [PostId],
                        [Project5].[Content] AS [Content],
                        [Project5].[PostStatusId] AS [PostStatusId],
                        [Project5].[Image] AS [Image],
                        [Project5].[Location] AS [Location],
                        [Project5].[Video] AS [Video],
                        [Project5].[CreatedDate] AS [CreatedDate],
                        [Project5].[DateOfUpdate] AS [DateOfUpdate],
                        [Extent6].[Id] AS [Id],
                        [Extent6].[VisualId] AS [VisualId],
                        [Extent6].[ProfilePicUrl] AS [ProfilePicUrl],
                        [Extent6].[DateCreated] AS [DateCreated],
                        [Extent6].[Activated] AS [Activated],
                        [Extent6].[ActivationCode] AS [ActivationCode],
                        [Extent6].[RoleId] AS [RoleId],
                        [Extent6].[TeamId] AS [TeamId],
                        [Extent6].[RegisterToken] AS [RegisterToken],
                        [Extent6].[Email] AS [Email],
                        [Extent6].[EmailConfirmed] AS [EmailConfirmed],
                        [Extent6].[PasswordHash] AS [PasswordHash],
                        [Extent6].[SecurityStamp] AS [SecurityStamp],
                        [Extent6].[PhoneNumber] AS [PhoneNumber],
                        [Extent6].[PhoneNumberConfirmed] AS [PhoneNumberConfirmed],
                        [Extent6].[TwoFactorEnabled] AS [TwoFactorEnabled],
                        [Extent6].[LockoutEndDateUtc] AS [LockoutEndDateUtc],
                        [Extent6].[LockoutEnabled] AS [LockoutEnabled],
                        [Extent6].[AccessFailedCount] AS [AccessFailedCount],
                        [Extent6].[UserName] AS [UserName],
                        [Project5].[C1] AS [C1]
                        FROM   (SELECT
                            [Extent1].[PostId] AS [PostId],
                            [Extent1].[Content] AS [Content],
                            [Extent1].[PostStatusId] AS [PostStatusId],
                            [Extent1].[UserId] AS [UserId],
                            [Extent1].[Image] AS [Image],
                            [Extent1].[Location] AS [Location],
                            [Extent1].[Video] AS [Video],
                            [Extent1].[CreatedDate] AS [CreatedDate],
                            [Extent1].[DateOfUpdate] AS [DateOfUpdate],
                            (SELECT
                                COUNT(1) AS [A1]
                                FROM [dbo].[Likes] AS [Extent5]
                                WHERE [Extent1].[PostId] = [Extent5].[PostId]) AS [C1]
                            FROM [dbo].[Posts] AS [Extent1]
                            WHERE ( NOT (([Extent1].[UserId] = @p__linq__0) AND (0 = (CASE WHEN (@p__linq__0 IS NULL) THEN cast(1 as bit) ELSE cast(0 as bit) END)))) AND ([Extent1].[DateOfUpdate] > @p__linq__1) AND ( EXISTS (SELECT
                                1 AS [C1]
                                FROM ( SELECT
                                    [Extent2].[UserId] AS [UserId]
                                    FROM [dbo].[Likes] AS [Extent2]
                                    WHERE [Extent1].[PostId] = [Extent2].[PostId]
                                )  AS [Project1]
                                WHERE  EXISTS (SELECT
                                    1 AS [C1]
                                    FROM [dbo].[FollowUsers] AS [Extent3]
                                    WHERE ([Extent3].[FollowFromUserId] = @p__linq__2) AND ([Extent3].[FollowToUserId] = [Project1].[UserId])
                                )
                            )) AND (1 = [Extent1].[PostStatusId]) AND (0 = [Extent1].[PostType]) AND ( NOT EXISTS (SELECT
                                1 AS [C1]
                                FROM [dbo].[BlockedUsers] AS [Extent4]
                                WHERE ([Extent4].[BlockerId] = @p__linq__3) AND (([Extent4].[BlockedId] = [Extent1].[UserId]) OR (CASE WHEN ([Extent4].[BlockedId] <> [Extent1].[UserId]) THEN cast(1 as bit) WHEN ([Extent4].[BlockedId] = [Extent1].[UserId]) THEN cast(0 as bit) END IS NULL))
                            )) ) AS [Project5]
                        LEFT OUTER JOIN [dbo].[AspNetUsers] AS [Extent6] ON [Project5].[UserId] = [Extent6].[Id]
                    )  AS [Project6]
                )  AS [Project7]
            )  AS [Project8]
        )  AS [Project9] ) AS [Project11]
    OUTER APPLY  (SELECT TOP (1) [Project12].[CommentId] AS [CommentId], [Project12].[CommentText] AS [CommentText], [Project12].[PostId] AS [PostId], [Project12].[CommentDate] AS [CommentDate], [Project12].[UserId] AS [UserId], [Project12].[RowVersion] AS [RowVersion]
        FROM ( SELECT
            [Extent11].[CommentId] AS [CommentId],
            [Extent11].[CommentText] AS [CommentText],
            [Extent11].[PostId] AS [PostId],
            [Extent11].[CommentDate] AS [CommentDate],
            [Extent11].[UserId] AS [UserId],
            [Extent11].[RowVersion] AS [RowVersion]
            FROM [dbo].[Comments] AS [Extent11]
            WHERE [Project11].[PostId] = [Extent11].[PostId]
        )  AS [Project12]
        ORDER BY [Project12].[CommentDate] DESC ) AS [Limit1]
)  AS [Project13]
ORDER BY [Project13].[C3] DESC, [Project13].[PostId] ASC, [Project13].[Id] ASC, [Project13].[C2] ASC

A: First, it seems there is confusion between Linq and Linq to SQL. Not all of Linq can be translated into SQL queries. For example: Any() and All() can't be used with Linq to Sql here - they are in-memory collection functions. This means that all rows need to be fetched and then resolved afterwards.
You are also not resolving your first two queries, for example by calling ToList().
var blockedusers = DataContext.BlockedUsers.Where(bu => bu.BlockerId == userId);
var followers = DataContext.FollowUser.Where(u => u.FollowFromUserId == userId);

This leaves them to run on-demand every time that they are used (deferred query execution) - meaning they call SQL each time. Beware the IEnumerable!
You could probably get rid of all your issues by doing joins onto BlockedUser and FollowUser all in the same query. For example, use a left join to BlockedUser and eliminate those rows by testing that the blocked user is null.

A: I think, you should firstly orderby, skeep, take and then select new PostObject in return


Q: boost asio timer hangs the second time I read async I have a RS485 communication that I talk over with boost::asio::serial_port. I'm testing what happens when there is no connection. The first time the timer cancels the operation. The second time the program just hangs on io.run(). I'm confused, because I create a new fresh timer, reset io and try to have a clean plate before I start to read anything from the wire.
boost::asio::io_context io;
boost::asio::serial_port port;

std::size_t readUntil(std::vector<char>& buffer, char delim, std::chrono::microseconds timeout) {
    using boost::system::error_code;
    error_code read_result {};
    size_t msglen = 0;
    io.reset();

    boost::asio::system_timer timer(io, timeout);
    boost::asio::async_read_until(port, boost::asio::dynamic_buffer(buffer), delim, [&](error_code ec, size_t n) {
            timer.cancel();
            read_result = ec;
            msglen = n;
        }
    );
    timer.async_wait([&](error_code ec) {
        if (!ec) {
            port.cancel();
            throw exception::read_exception(exception::read_exception::Code::TIME_OUT);
        }
    });
    io.run(); // Hangs here, the second time, not the first

    if (read_result) {
        std::stringstream sstream;
        sstream << read_result;
        throw exception::read_exception(exception::read_exception::Code::PORT, sstream.str());
    }
    return msglen;
}

int main() {
//set up port options (baudrate etc)
for(size_t i = 0; i<10; i++) {
std::vector<char> buffer;
readUntil(buffer, '\', std::chrono::microseconds(1000));
}

}


Q: How to access txt file using relative path I'm currently trying to open a file using
io.open(file_name, "r")
My directory structure is
parent_dir
   -src
      -main.lua
   -tests
      -test.txt

I'm currently trying to open the txt file from the tests folder in the main.lua using
io.open(file_name, "r") but it won't recognize the file as existing. If I place the absolute path into the file_name it works. I'm not sure how to format a relative path? I've tried some version of ../../../tests/test.txt but I can't seem to get it to work.
The actual path of the file is something like /Users/user_name/parent_dir/tests/test.txt

A: The ../ syntax is correct to specify relative paths.
But this is not relative to the location of your Lua script but to your current working directory.
Refer to get current working directory in Lua
You cannot change the current working directory from within a Lua script unless you use libraries like LuaFileSystem.
If you're running a single script you can check if global arg[0] (if it is not nil) contains the path of that script. You can use that to build an absolute path from your script's location.


Q: From iPhone 4 to iPhone 5 - UIMageView I am working on my existing app to customize the screen to make compatible to iPhone 5 screen.
However as you could see in the following figures, my imageview is not properly placed. I dont know what I am doing wrong. Any help is appreciated! unlockView represent the arrow. lockViewOutlet image represent the outer of the arrow image.
- (void)viewDidLoad {
    [super viewDidLoad];
    float screenSizeHeight=[UIScreen mainScreen].bounds.size.height;

    if(screenSizeHeight==568)
    {
        [lockViewOutlet setFrame:CGRectMake(0, 20, 320, 548)];
        [unlockImageView setFrame:CGRectMake(24, 500, 68, 43)];
        [unlockText setFrame:CGRectMake(105, 500, 182,43)];

    }
    if(screenSizeHeight==480)
    {
        [lockViewOutlet setFrame:CGRectMake(0, 20, 320, 460)];
        [unlockImageView setFrame:CGRectMake(24, 411, 68, 43)];
        [unlockText setFrame:CGRectMake(105, 411, 182,43)];

 }
}

iPhone 5 screenshot
iphone 4 screenshot

A: Ok I got you,
The problem is with your image view lockViewOutlet.
in your code : [lockViewOutlet setFrame:CGRectMake(0, 20, 320, 548)];
You try to resize your background imageView. Resizing only the imageView does not solve your problem. Real problem is with the size of lockViewOutlet.image.
Best way is design a new image with the size 320, 568. Then set the image for iphone 5 after resizing your imageview.
if(screenSizeHeight==568)
    {
        [lockViewOutlet setFrame:CGRectMake(0, 20, 320, 548)];

        [lockViewOutlet setImage:[UIImage imageNamed:@"iPhone5LockNackground.png"]];

        [unlockImageView setFrame:CGRectMake(24, 500, 68, 43)];
        [unlockText setFrame:CGRectMake(105, 500, 182,43)];

    }


Q: Safe PDO mySQL SELECT statement with for loop I was told to use PDO to safely retrieve data from a database. Now I'm wondering if this would be safe or work at all:
$dbtype     = "sqlite";
$dbhost     = "localhost";
$dbname     = "test";
$dbuser     = "root";
$dbpass     = "admin";
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);

$firstName = htmlspecialchars($_POST["firstName"]);
foreach($conn->query('SELECT * FROM employeeTable WHERE firstName = ' . $firstName) as $row) {
    echo $row['lastName'].' '.$row['email'];
}

Because to me it looks like it would still be possible to "inject" something into the query.
So my question is: Is that really safe and if not how exactly would I make it safe?

A: I think you'd better use the following to prepare, the process of preparing is to void the injection
$sql = 'SELECT * FROM employeeTable WHERE firstName = :firstName';
$sth = $conn->prepare($sql);
$sth -> bindParam(':firstName', $firstName);
$sth -> execute();
$result = $sth->fetchAll(PDO::FETCH_OBJ);
foreach ($result as $key => $value) {
    echo $value->lastName, $value->email;
}

A: Just remember to don't directly concatenate post variables to your query, just use prepared statements. And after the execution of prepared statements, you need to fetch the results:
$select = $conn->prepare('SELECT * FROM employeeTable WHERE firstName = :firstName');
$select->execute(array(':firstName' => $_POST["firstName"));

while($row = $select->fetch(PDO::FETCH_ASSOC))
    echo $row['lastName'].' '.$row['email'];
}

Here is a good read:
http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers


Q: What type of amazon ec2 instance should i take ? And how many of them? I will be hosting a website . Our initial target will be around 50,000 unique visitors a day . Files are served using apache/php and the realtime events (likes,comments) are handled using a nodejs server . Also i am using redis as key-value store alongside mysql , for conventional relational data storage . In the worst case scenario i might have 2000 concurrent users and around a 400 of them uploading photos (5mb size at max) . Also in the future i would have to implement a recommendation system in the back end using user activity history for which i may need additional amount of storage and compute power .

A: Rather than trying to decide up front on a particular size that will work for you, I'd suggest you architect a solution that allows you to scale. This gives you a lot more resilience and redundancy as a bonus.
An Elastic Load Balancer with one or more servers behind it is cheap and easy to set up, and you can size the instances to suit or fire up (or shut down) servers automatically as the load varies with AutoScaling.


Q: How can I make one line of a bash script into multiple lines? Im tying to make some of my bash scripts a bit easier on the eyes. Lets says I have this script and its working fine.
if [ "$PASSWDCHECK" = "<title>401 Authorization Required</title>" ]
then echo "The Subsubscription password is wrong" ; exit
else mkdir /home/"$USERNAME"/src && mkdir /opt/logstash && mkdir /etc/snort && mkdir /etc/snort/rules/
fi

I would like to make it more like this, but it fails to execute. What am I missing?
if [ "$PASSWDCHECK" = "<title>401 Authorization Required</title>" ]
then echo "The Subsubscription password is wrong" ; exit
else mkdir /home/"$USERNAME"/src \ &&
    mkdir /opt/logstash \ &&
    mkdir /etc/snort \ &&
    mkdir /etc/snort/rules/ \ &&
fi

A: You need to put the \ at the end of each line, not before the &&. Make sure there is no whitespace after the \.

A: As long as the && is the last non-whitespace token on the line, the command will automatically continue onto the next line.
if [ "$PASSWDCHECK" = "<title>401 Authorization Required</title>" ]
then echo "The Subsubscription password is wrong" ; exit
else mkdir /home/"$USERNAME"/src &&
     mkdir /opt/logstash &&
     mkdir /etc/snort &&
     mkdir /etc/snort/rules/
fi

A && list joins two commands, so the parser knows that a newline before the second command should be discarded.

A: if [ "$PASSWDCHECK" = "<title>401 Authorization Required</title>" ]
then echo "The Subsubscription password is wrong" ; exit
else
  mkdir /home/"$USERNAME"/src && \
  mkdir /opt/logstash && \
  mkdir /etc/snort && \
  mkdir /etc/snort/rules/
fi


Q: Hide blue box around code during slideshow of a Jupyter Notebook I am preparing a presentation in Jupyter Notebook (version 6.1.4, not Lab)

(not the final notebook, just an example)
I also hide the code through a nbextension.
When I go into the slideshow (RISE), though, and arrive to the code cells, there is always the blue box around input-output.

Is there a way to hide or disable it in slideshow mode?
Or do I have to write everything in markdown somehow?

A: Just export the slides to html using the no input option:
jupyter nbconvert YOURNOTEBOOKSNAME.ipynb --to slides --no-input serve

For more check out nbconvert's documention


Q: How to count real total number of chars in a string? Sorry if the question is silly. I need to count real number of chars in a string. For example I have the following string:
हा य
With .length I have the following result:

let chars = "हा य";
console.log(chars.length);

for(var i = 0; i < chars.length; i++){
 console.log(chars[i]);
}

As you can see, it's wrong. I have three chars here:
This one - हा,  - this one (empty space) and य this one. Which is proper and shortest way to count it correctly?

A: Hope this helps.
For all languages you can try Count number of characters present in foreign language

function countChars(text){
  return text.split("").filter( function(char){
let charCode = char.charCodeAt(); return charCode >= 2309 && charCode <=2361 || charCode == 32;
  }).length;
}

let chars = "हा य";
console.log(countChars(chars));


Q: How to change timestamp column size in DB2? Any idea how to change timestamp column size in DB2?
I tried altering table, drop and then create table. Both didn't work.
Here are the queries I've tried:
alter table clnt_notes alter column lupd_ts set data type timestamp(26)

create table CLNT_NOTES
    (NOTE_ID int not null generated always as identity (start with 1, increment by 1),
     CLNT_ID varchar(10) not null,
     TX varchar(200),
     LUPD_TS timestamp(26) not null)

A: It depends on your DB2 platform and version.  Timestamps in DB2 used to all have 6 digit precision for the fractional seconds portion.  In string form, "YYYY-MM-DD-HH:MM:SS.000000"
However, DB2 LUW 10.5 and DB2 for IBM i 7.2 support from 0 to 12 digits of precision for the fraction seconds portion.  In string form, you could have from  "YYYY-MM-DD-HH:MM:SS"  to "YYYY-MM-DD-HH:MM:SS.000000000000".
The default precision is 6, so if you specify a timestamp without a precision (length), you get the six digit precision.  Otherwise you may specify a precision from o to 12.
create table mytable (
  ts0 timestamp(0)
  , ts6 timestamp
  , ts6_also timestamp(6)
  , ts12 timestamp(12)
);

Note however, that while the external (not exactly a string) format the DBMS surfaces could vary from 19 to 32 bytes.  The internal format the TS is stored in may not.  On DB2 for IBM i at least the internal storage format of TS field takes between 7 and 13 bytes depending on precision.

*

*timestamp(0) -> 7 bytes

*timestamp(6) -> 10 bytes (default)

*timestamp(12) -> 13 bytes

A: Since you refer to 10 as the length, I'm going to assume you're looking in SYSIBM.SYSCOLUMNS (or another equivalent table in the catalog.
The LENGTH column in the catalog refers to the internal length of the field. You can calculate this using the following formula:
FLOOR( ((p+1)/2) + x )

*

*p is the precision of the timestamp (the number of places after the decimal [the microseconds])

*x is 7 for a timestamp without a timezone, or 9 if it has a timezone (if supported by your platform)

If you are comparing the to a field in the SQLCA, that field will be the length of a character representation of the timestamp.  See this Information Center article for an explanation between the two fields.

If you truly want to change the scale of your timestamp field, then you can use the following statement. x should be an integer for the number of places after the decimal in the seconds position.
The number of allowed decimals varies by platform and version. If you're on an older version, you can likely not change the scale, which is set at 6. However, some of the newer platforms (like z/OS 10+, LUW 9.7+), will allow you to set the scale to a number between 0 and 12 (inclusive).
ALTER TABLE SESSION.TSTAMP_TEST
ALTER COLUMN tstamp
SET DATA TYPE TIMESTAMP(x);


Q: PHP date format variable I would like to change the date format in the following code:
#search for all event start dates
$starts = $sxml->xpath('//event/startdate');

#get the unique start dates of these event
$dates = array_unique($starts);

foreach($dates as $date) {
   echo "

{$date}

" ."\n";

currently, it pulls from an XML feed as 25/11/2021 and I would like to show it as Thursday 25 November 2021 - probably as multiple variables. However,  date() is not working.
Any help is appreciated!

A: Using the DateTime object it can be easy and accurate
$dates = ['25/11/2021','24/11/2021','23/11/2021'];

foreach ( $dates as $date){
    $df = (DateTime::CreateFromFormat('d/m/Y', $date))->format('l d F Y');
    echo "

{$df}

" ."\n";
}

RESULTS

Thursday 25 November 2021

Wednesday 24 November 2021

Tuesday 23 November 2021

PHP Manual for DateTime object


Q: Why does Quidditch Through the Ages not discuss the Snitch's flesh memory enchantment? From Chapter Seven of Deathly Hallows:

"Because Snitches have flesh memories," she said.
"What?" said Harry and Ron together; both considered Hermione's Quidditch knowledge negligible.
"Correct," said Scrimgeour. "A Snitch is not touched by bare skin before it is released, not even by the maker, who wears gloves. It carries an enchantment by which it can identify the first human to lay hands upon it, in case of a disputed capture."

This would seem to be an important fact about Quidditch, and as such I would expect it to be mentioned in the authoritative book on Quidditch — Quidditch Through the Ages by Kennilworthy Whisp. Yet it does not appear to be mentioned there. Other enchantments on the Snitch are mentioned. For instance:

Unlike the Snidget, however, the Snitch had been bewitched to remain within the boundaries of the field.

And:

It is bewitched to evade capture as long as possible.

So why does the very pertinent fact about their flesh memory enchantments not appear in Quidditch Through the Ages?

A: It's probably a minor retcon. Quidditch Throughout the Ages was published in 2001, Goblet of Fire in 2000, and Order of the Phoenix in 2003. Deathly Hallows, which was where the detail was mentioned, was published in 2007, six years and three whole books since Quidditch Throughout the Ages.


Q: Create link "node" instead of "NavigationNode" I'm able to create subtitles in my sites. I create title under others, this create subtitles.
I use New-Object Microsoft.SharePoint.Navigation.SPNavigationNode which create titles, but what the object if I want to create a "link node" instead of a title ? Which is possible in graphical mode.
Is there something like New-Object Microsoft.SharePoint.Navigation.SPLinkNode ?
Hope I'm pretty clear =)
Nico.

A: The Security Trimming of SPNavigatinNode is controlled by th IsExternal property:
If this is false then the Url is only shown if the user has access to the list.
IsExternal is specified as the third parameter to the contructor


Q: Unexpected line wrap A very simple html:

f 22222222222222222222222222

will be rendered as:
f
22222222222222222222222222

and what I was expected is:
f 222222222222222
22222222222

is it possible to fix this?
Fiddle: http://jsfiddle.net/8yL6j/

A: Use word-wrap: break-word to break the text up in the middle of a word:
.container {
    width: 200px;
    word-wrap: break-word;
}

Demo: http://jsfiddle.net/8yL6j/1/

A: It seems that you would like browsers to put as many characters on a line that fit there and then break, with no regard to normal line breaking behavior, rules of languages, etc., then use word-break: break-all on the element.


Q: Variable inequality: Show that $ {(\sum\limits_{i = 1}^{2n + 1} {{a_i}} )^2} \geqslant 4n\sum\limits_{i = 1}^{n + 1} {{a_i}{a_{i + n}}}.$ For any positive integer $n$, and real numbers (not necessarily positive)  $a_1\geqslant a_2 \geqslant …\geqslant a_{2n+1}$, show that $$
{(\sum\limits_{i = 1}^{2n + 1} {{a_i}} )^2} \geqslant 4n\sum\limits_{i = 1}^{n + 1} {{a_i}{a_{i + n}}}.$$
What I've tried: I set $x_i :=a_i - a_{i+1}$ for $i\leqslant 2n$ and $x_{2n+1}:=a_{2n+1}$, and calculate the coefficients on both sides, but gradually  find it difficult to go further, perhaps it just can't.
Please help.
Something more: if all $a_i=1$ except $a_{2n+1}=0$, the equality holds.

A: I'm close to a solution,
but I can't go all the way,
so I'll show what I've got
in the hope that
someone else
can complete the proof.
Let
$a_i = a-b_i$,
where
$a = a_1$ and
$b_1 = 0$
so $b_i \ge 0$
and
$b_i \le b_{i+1}$.
The inequality becomes
${(\sum\limits_{i = 1}^{2n + 1} {(a-b_i)} )^2}
\ge 4n\sum\limits_{i = 1}^{n + 1} {(a-b_i)(a-b_{i + n})}
$.
The left side is,
if
$B = \sum\limits_{i = 1}^{2n + 1} b_i$,
$\begin{array}\\
(\sum\limits_{i = 1}^{2n + 1} {(a-b_i)} )^2
&=((2n+1)a-\sum\limits_{i = 1}^{2n + 1} b_i )^2\\
&=((2n+1)a-B )^2\\
&=(2n+1)^2a^2-2(2n+1)aB+B^2\\
\end{array}
$
The right side is
$\begin{array}\\
4n\sum\limits_{i = 1}^{n + 1} {(a-b_i)(a-b_{i + n})}
&=4n\sum\limits_{i = 1}^{n + 1} (a^2-a(b_i+b_{i+n})+b_ib_{i + n})\\
&=4n((n+1)a^2-\sum\limits_{i = 1}^{n + 1}a(b_i+b_{i+n})+\sum\limits_{i = 1}^{n + 1}b_ib_{i + n})\\
&=4n(n+1)a^2-4na\sum\limits_{i = 1}^{n + 1}(b_i+b_{i+n})+4n\sum\limits_{i = 1}^{n + 1}b_ib_{i + n}\\
&=4n(n+1)a^2-4na(B+b_{n+1})+4n\sum\limits_{i = 1}^{n + 1}b_ib_{i + n}\\
&=4n(n+1)a^2-4na(B+b_{n+1})+4nS
\qquad\text{where } S=\sum\limits_{i = 1}^{n + 1}b_ib_{i + n}\\
\end{array}
$
The left-right is thus
$((2n+1)^2a^2-2(2n+1)aB+B^2)-
(4n(n+1)a^2-4na(B+b_{n+1})+4nS)\\
\quad=((2n+1)^2-4n(n+1))a^2-(2(2n+1)-4n)aB+B^2+4nab_{n+1}-4nS\\
\quad=a^2-2aB+B^2+4nab_{n+1}-4nS\\
\quad=(a-B)^2+4nab_{n+1}-4nS\\
\quad=(a-B)^2+4n(ab_{n+1}-S)\\
$
So if we can show that
$(a-B)^2+4n(ab_{n+1}-S)
\ge 0$,
or, equivalently,
$a^2-2aB+B^2+4nab_{n+1}-4nS
\ge 0$,
we are done.
At this point,
I'm stuck.
I think that
we somehow need to use
$b_i \le b_{i+1}$
to bound $S$ in relation
to $B$,
but I don't see how.

A: Inspired by marty's answer, I finally solve the problem.
Let $b_i:=a_i-b$, where $b:=a_{2n+1}$, so $b_{2n+1}=0$ and $0\leqslant b_i\leqslant b_{i+1}$ for every $i$.
The equality becomes $${\left( {\sum\limits_{i = 1}^{2n + 1} {\left( {{b_i} + b} \right)} } \right)^2} \geqslant 4n\sum\limits_{i = 1}^{n + 1} {\left( {{b_i} + b} \right)} \left( {{b_{i + n}} + b} \right)$$
$$\Leftrightarrow {\left( {\sum\limits_{i = 1}^{2n} {{b_i}}  + (2n + 1)b} \right)^2} \geqslant 4n\sum\limits_{i = 1}^{n + 1} {\left( {{b^2} + {b_i}b + {b_{i + n}}b + {b_i}{b_{i + n}}} \right)}$$
$$\Leftrightarrow (4{n^2} + 4n + 1){b^2} + (\sum\limits_{i = 1}^{2n} {{b_i}{)^2}}  + (4n + 2)b\sum\limits_{i = 1}^{2n} {{b_i}}  \geqslant (4{n^2} + 4n){b^2} + 4nb({b_{n + 1}} + \sum\limits_{i = 1}^{2n} {{b_i}} ) + 4n\sum\limits_{i = 1}^n {{b_i}{b_{i + n}}}$$
$$\Leftrightarrow {b^2} + (\sum\limits_{i = 1}^{2n} {{b_i}{)^2}}  + 2b\sum\limits_{i = 1}^{2n} {{b_i}}  \geqslant 4nb{b_{n + 1}} + 4n\sum\limits_{i = 1}^n {{b_i}{b_{i + n}}}$$
$$\Leftrightarrow {(b + \sum\limits_{i = 1}^{2n} {{b_i}}  - 2n{b_{n + 1}})^2} \geqslant 4{n^2}b_{n + 1}^2 + 4n\sum\limits_{i = 1}^n {{b_i}{b_{i + n}}}  - 4n{b_{n + 1}}\sum\limits_{i = 1}^{2n} {{b_i}}$$
$$\Leftarrow 4{n^2}b_{n + 1}^2 + 4n\sum\limits_{i = 1}^n {{b_i}{b_{i + n}}}  - 4n{b_{n + 1}}\sum\limits_{i = 1}^{2n} {{b_i}}  \leqslant 0$$
$$\Leftrightarrow \sum\limits_{i = 1}^n {({b_{n + 1}} - {b_i})({b_{n + 1}} - {b_{i + n}})}  \leqslant 0$$, which is obviously true since $${b_1} \geqslant {b_2} \geqslant  \cdots  \geqslant {b_{2n}}.$$
To complete, it's easy to find that the equality holds iff $${a_1} = {a_2} =  \cdots  = {a_{2n}} \geqslant {a_{2n + 1}} = 0.$$

A: Let's $a_{n+1} = a$ and for $i = 1,\dots,n$

*

*$a_i = a + x_i$;

*$a_{i+n+1} = a - y_{i+1}$

with both $x_i,y_i \ge 0$. Also let's $x_{n+1} = y_1 = 0$. For example, if $n=2$ we use the following notation:
$$
a_1 = a+x_1,\; a_2 = a+x_2,\; a_3 = a,\; a_4 = a-y_2,\; a_5 = a-y_3.
$$
Finally, let's $\sum x_i = X$, $\sum y_i = Y$ and $X-Y = S$.
Using this notation we have for sum in RHP:
$$
\sum_{i=1}^{n+1}a_ia_{i+n} = \sum_{i=1}^{n+1}(a + x_i)(a - y_i) \le \sum_{i=1}^{n+1}a(a+x_i-y_i) = (n+1)a^2 + aS.
$$
Now we need to prove that
$$
\left(\sum_{i=1}^{2n+1}a_i\right)^2 = \big((2n+1)a + S\big)^2 \ge 4n(n+1)a^2 + 4naS.
$$
We have
\begin{align}
\big((2n+1)a + S\big)^2 = (2n+1)^2a^2 + S^2 + 2(2n+1)Sa,
\end{align}
thus
\begin{align}
\big((2n+1)a + S\big)^2 - 4n(n+1)a^2 - 4naS = \\
a^2 + S^2 + 2aS = (a+S)^2 \ge 0.
\end{align}
QED.


Q: How to do a conditional write in dynamodb transactions using boto3 python library I have two documents in dynamodb with Id as hash key (no range key)
one document looks like this
{
  'Id': 'x',
  'ExpiresAt': 1634889543
}

another document looks like below
{
  'Id': 'y',
  'counter': 1
}

If the document with id x does not exist or it exists but expires_at is less than current time, then I want to increment counter in document with id y. I believe I have to use transactions.
I found this article where they tell us how to do this using a transaction manager library in Java - https://aws.amazon.com/blogs/developer/performing-conditional-writes-using-the-amazon-dynamodb-transaction-library/
But I couldn't find anything where they explain how to do this in python. How can I achieve this in python using Boto3?

A: Use query to find the current status of document with 'Id':x and the update the other document using UpdateExpression with "ADD"
import boto3
from boto3.dynamodb.conditions import Key, Attr
from datetime import datetime

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('your_table_name')

result = table.query(
    KeyConditionExpression=Key('Id').eq('x')
)

if result is None or result['ExpiresAt'] < datetime.now():
    table.update_item(
        Key={
            "Id": "y"
        },
        UpdateExpression='ADD counter :inc',
        ExpressionAttributeValues={
            ':inc': {'N': '1'}
        }
    )


Q: How to set context of provided module through ProvidePlugin? I have wrapper module over promise-polyfill -
/* jshint node: true */
/* global Promise: false */
"use strict";

if ( typeof Promise === "undefined" ) {
    module.exports = require('promise-polyfill');
} else {
    module.exports = Promise;
}

Then i inject it into all my modules:
new webpack.ProvidePlugin({
    'Promise': 'require-promise',
})

And i getting a problem. Promise is an empty object, instead native Promise or undefined. How i can pass context (window or global) to this module?
Generated code looks like:
function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(Promise) {/*** IMPORTS FROM imports-loader ***/
(function() {

/* jshint node: true */
/* global Promise: false */
"use strict";

console.log(Promise);

if ( typeof Promise === "undefined" ) {
    module.exports = __webpack_require__(59);
} else {
    module.exports = Promise;
}

/*** EXPORTS FROM exports-loader ***/
module.exports = Promise;
}.call(window));
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7)))

/***/ },

A: Fixed:
new webpack.ProvidePlugin({
    'Promise': 'imports?Promise=>window.Promise!require-promise',
})


Q: Filling fields in Word using c# and Microsoft Word Interop I tried to Fill out Form Fields in Microsoft Word using C# Interop Assemblies with the following Code
string filename = @"N:\mehler\Vorlage2.dotx";

Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document doc = new Microsoft.Office.Interop.Word.Document();

doc = word.Documents.Open(filename);
doc.Activate();

foreach (Microsoft.Office.Interop.Word.FormField field in doc.FormFields)
{
    switch (field.Name)
    {
        case "Text2":
            field.Range.Text = "1";
            break;

        default:
            break;
    }
}

doc.SaveAs2(@"N:\mehler\Ausgefuellt.docx");
doc.Close();
word.Quit();
System.Diagnostics.Process.Start(@"N:\mehler\Ausgefuellt.docx");

Microsoft Word can not open the File Ausgefuellt.docx and Shows a Message saying that an unknown Error has occured.
I created a simple Word Document with a bit of unformated text and 2 Text-Form-Fields
can anyone tell me, what went wrong or if ia have an Error in my Source Code
Edit:
I managed to specify the Problem. I created an Document only conaining one Text Form Field.
In Word 2013 this is found unter the Topic "Formulare aus Vorversionen" (I would translate this to "Formfields from former Versions")
If I comment out the whole foreach Block so that I would only open and save the Document, I get the same result.
If I open the Source File directly in Word it is no Problem. I also tried to load the Document and make Word Visible. The Result looked like an empty Word instance with no Document loaded.

A: Use that, it should work:
Word.Application WordApp;
Word.Document WordDoc;

object misValue = System.Reflection.Missing.Value;

WordApp = new Word.ApplicationClass();
WordDoc = WordApp.Documents.Open(filePath2, misValue, misValue, misValue, misValue, misValue,
        misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue);
WordDoc.Activate();

A: You should use:
doc = Word.Documents.Add(filename);

Instead of:
doc = Word.Documents.Open(filename);

So Word will use the template to create a document file, and not open the template itself.
It seems Word behaves differently when the active document is a Template.


Q: Error inflating class com.google.android.material.floatingactionbutton.FloatingActionButton Estoy desarrollando una aplicación móvil, estoy usando lo que es menú lateral. Cuento con un botón flotante el cual se espera sea como un carrito de compras. Al ejecutar la aplicación en el dispositivo virtual, me aparece el siguiente error:

Unable to start activity ComponentInfo{com.example.creps/com.example.creps.Home}: android.view.InflateException: Binary XML file line #12 in com.example.creps:layout/activity_home: Binary XML file line #25 in com.example.creps:layout/app_bar_main: Error inflating class com.google.android.material.floatingactionbutton.FloatingActionButton.

Tengo mucho tiempo tratando de solucionarlo, pero no he encontrado la manera.
Aquí mi layout/app_bar_main
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Home">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppBarOverlay">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            android:textAppearance="@style/TextStyle"
            app:popupTheme="@style/PopupOverlay" />

    </com.google.android.material.appbar.AppBarLayout>

    <include layout="@layout/content_main" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:theme="@style/MyMaterialTheme"
        android:tint="@android:color/black"
        app:srcCompat="@drawable/ic_baseline_shopping_cart_24"
        tools:ignore="VectorDrawableCompat" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

Mi build.gradle
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.0"

    defaultConfig {
        applicationId "com.example.creps"
        minSdkVersion 16
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.3.0'
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.google.firebase:firebase-analytics:17.2.2'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'com.google.android.material:material:1.1.0'
    implementation 'androidx.navigation:navigation-fragment:2.3.0'
    implementation 'androidx.navigation:navigation-ui:2.3.0'
    implementation 'androidx.lifecycle:lifecycle-extensions:2.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

    //Add Library
    implementation'com.google.firebase:firebase-core:17.4.4'
    implementation'com.google.firebase:firebase-database:19.3.1'
    implementation'info.hoang8f:fbutton:1.0.5'
    implementation'com.rengwuxian.materialedittext:library:2.1.4'
    //noinspection GradleCompatible
    implementation'com.android.support:cardview-v7:26.+'
    //noinspection GradleCompatible
    implementation'com.android.support:recyclerview-v7:26.+'
    implementation'com.squareup.picasso:picasso:2.5.2'
    implementation'com.firebaseui:firebase-ui-database:1.2.0'
    implementation 'com.google.android.material:material:1.2.0'
    //noinspection GradleCompatible
    implementation 'com.android.support:design:28.0.0'
    implementation 'com.google.android.material:material:1.2.0-alpha01'
}
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

A: este se produce al inflar el FloatingActionButton , la definición de la clase es correcta pero el problema seguramente es un recurso que cargas para este elemento, generalmente el problema son las imagenes, en este caso hay que revisar esta linea app:srcCompat="@drawable/ic_baseline_shopping_cart_24" :.
<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/fab_margin"
    android:theme="@style/MyMaterialTheme"
    android:tint="@android:color/black"
    app:srcCompat="@drawable/ic_baseline_shopping_cart_24"
    tools:ignore="VectorDrawableCompat" />

con respecto a la imagen "ic_baseline_shopping_cart_24", revisa si es un vector asset y muy importante, que esta se encuentre en el directorio /drawable de tu proyecto.

A: una solucion es cambiar app:srcCompat="@drawable/ic_baseline_shopping_cart_24" a:
android:src="@drawable/ic_baseline_shopping_cart_24"

Otra es seguir usando app:srcCompat="@drawable/ic_baseline_shopping_cart_24"
y agregar el soporte para los vector drawable en el gradle:
defaultConfig {
    applicationId "com.example.creps"
    vectorDrawables.useSupportLibrary = true
    ....


Q: Using couchbase as a single node Can couchbase  be used as only one node for development purposes, or benchmarking inserts, updates and reads?
And can couchbase run in a computer with 1vCPU and 512 MB of RAM?

A: This page covers the minimum recommended specification for running Couchbase Server.

The minimum hardware specifications to install and effectively operate
  Couchbase Server are:
Dual-core x86 CPU running at 2GHz. 4GB RAM (physical).

It then goes on to say...

The specification can be as low as 1GB of free RAM beyond operating
  system requirements and a single CPU core.


Q: Minimal amount of swaps Assume we have got sequence (of length n) of ones and zeroes, eg. 10100100. We want to rearrange them, so 1 follows every 0, and 0 follows every 1 - but in the end there can be some 0s or 1s left - so our sequence will become 10101000. Let's say there is k amount of 1 and n-k amount of 0, so we need to have min(n, n-k) groups of 10 (or 01) and then the rest left.
We can do one operations - swap two chosen elements. We need to calculate the minimum amount of swaps to rearrange sequence into given order - e.g. we need just one swap (between indexes 4 and 5, indexing from 0), to rearrange that correctly. For 0101011111 or 10101000000 we need 0 swaps.
Any ideas how to calculate that? Any complexity actually would be apprieciated - I got no idea how to do that.

A: From your example, I'm assuming that your surplus characters must appear at the right side of the string.  This means that the previous characters must alternate.  This gives you only two possible solutions for the final string.  In the case you give, these would be
10101000
01010100

Your entire algorithm is simple: produce both of these sequences (k 0's alternating with k 1's) and append the n-k extras.  Compare each with the original to see which of the two has the smaller quantity of displaced characters.  Identify those pairs and swap.  For instance, using the above:
10100100  original
10101000  candidate
--------
....!!..  two differences, one swap

10100100  original
01010100  candidate
--------
!!!!....  four differences, two swaps

You use the first candidate, with locations 4 and 5 already identified.

A: Convert String to collection of Ints:
("10100100".toList).map (_.toInt-'0')
= List(1, 0, 1, 0, 0, 1, 0, 0)

Zip it with index:
.zipWithIndex
List((1,0), (0,1), (1,2), (0,3), (0,4), (1,5), (0,6), (0,7))

with modulo, find for index (0,1,2...), which value we either expect, (010...) a is string value, b is possible, alternating value of 01, c is index in String
.map {case (a,b)=> (a, b%2, b)}
List((1,0,0), (0,1,1), (1,0,2), (0,1,3), (0,0,4), (1,1,5), (0,0,6), (0,1,7))

filter those who match expectation (do the same for those in opposite order, a!=b):
.filter {case (a,b,c) => a==b }
List((0,0,4), (1,1,5), (0,0,6))

group by alternating value for later counting:
.groupBy {case (a,b,c)=> b}
Map(1 -> List((1,1,5)), 0 -> List((0,0,4), (0,0,6)))

get the lenghts and count:
.map {case (a, b) => (a, b.length)}
Map(1 -> 1, 0 -> 2)

Ignore the 1 and 0 as identifier, just take the count:
.map (i => (i._2))
List(1, 2)

Since we can only perform swaps for 1 where we have a corresponding 0 and vice versa, take the minimum of both:
"10100100".toList).map (_.toInt-'0').zipWithIndex.map {case (a,b)=> (a, b%2, b)}.filter {case (a,b,c) => a==b }.groupBy {case (a,b,c)=> b}.map {case (a, b)=> (a, b.length)}.map (i => (i._2)).min
1

In the end, we didn't need the c-value, it was just useful for keeping track, what's happening. Here is the version without c, and which starts with 1, not 0:
("10100100".toList).map (_.toInt-'0').zipWithIndex.map {case (a,b)=> (a, b%2)}.filter {case (a,b) => a!=b }.groupBy {_._2}.map {case (a, b)=> (a, b.length)}.map (i => (i._2)).min
2

The minimum of those two values (1, 2) is the solution.


Q: 'TypeErroe: cannot read property NAME of undefined' after trying to retrieve key/ value from nested object I am trying to fetch some data in react-native where I store the fetched data in a state variable so I can access them anywhere in the component. This is the code:
export default class Result extends Component {
    state = {
        data: {}
    };

    async componentDidMount() {
        const that = this;
        const url = 'https://world.openfoodfacts.org/api/v0/product/8002270014901.json';
        let response = await fetch(url);
        if (response.status == 200) {
            let data = await response.json();
            this.setState({ data });
        }
    }

    ... some code ...

    render() {
      console.log(this.state.data.product);

    ...some more code ...
    }
}

I got the code from the componentDidMount from another SOF article to make sure that I have some data I can work with.
When I try to test the outcome it works perfectly fine with the console.log you see in the code. But if I try to go just one layer deeper within the object (e.g. console.log(this.state.data.product.brands); I get the error message mentioned in the subject. Why is that? How do I make sure that the entire object is 'loaded' before I proceed?

A: What comes to my mind in this case is that you are receiving the response after the render method is being executed.
You may ask But how it works when I log just this.state.data.product?
Well, when you initialize your state you are defining that it have a data object, so in that case the code won't break because this.state.data.product is undefined, but when you try to get one layer deeper now you are trying to access to a property of an undefined value, which leads to the error you are getting (cannot read property x of undefined).
So, what can I make to fix that?
You have to store a boolean variable in your state, let's call it fetchingData and give it a default value of true, so now you have
state = {
  data: {},
  fetchingData: true
};

then, on your render method you validate if its fetching the data or if you already have te response from the server, modify it to be like this:
render() {
  if(this.state.fetchingData) return <View><Text>Fetching data...</Text></View>
  console.log(this.state.data.product.brands);
  return(
    Whatever you want to do with the data...
  )
}

What it does is when you are still waiting for the data, a Fetching data... message will be shown, now when you receive the data you also have to change fetchingData to false.
if (response.status == 200) {
  let data = await response.json();
  this.setState({
    data: data,
    fetchingData: false
  });
}


Q: Nouveau driver doesn't recognize my GTX 1060 Whenever I use the Nouveau driver with my GTX 1060, the desktop is forced to use software rendering. It doesn't seem to recognize the GPU at all.
As far as I know, Unity 8 doesn't work with NVIDIA's proprietary drivers, so I need to use Nouveau.


Q: JQuery UI Tooltip on span with disabled child link I'm working on a project that frequently requires the use of tooltips on disabled links. The project includes a draft/publish system, so I like to inform the user why a certain action is not available through the use of a tooltip.
The way I've been adding these tooltips is by wrapping the link in a  and adding the tooltip to the  instead of the link itself.

     Action Name

Up until now this seemed to do the trick. Recently, this method no longer works. Hovering over the  does not open the tooltip.
I am using chrome, but have experienced the same result in firefox as well.
JSFiddle Example
Any ideas why this stopped working? Suggestions for a workaround or a better solution to my problem are also welcome! Thanks!