text:
Q: Rspec request Active Model Serializer response doesn't contain root key I'm trying to test a JSON endpoint (Rails 5) that is built using active model serializers gem (version 0.10.2) with the JSON adapter.
When I make the request from http://localhost:3000/api/posts I get the root node in the response so that it looks like the documentation:
{
  "posts": [{
    "id": 1,
    "title": "Awesome Post Tile",
    "content": "Post content"
  }]
}

but when I make the request in Rspec (version 3.5) like this:

get '/api/posts'

the root node doesn't come through, so the response body looks like this:
[{
   "id": 1,
   "title": "Awesome Post Tile",
   "content": "Post content"
}]

My adapter is being set in an initializer:
ActiveModelSerializers.config.adapter = :json

Is there something I'm doing wrong here? I don't really know enough about either as to whether this is an issue with AMS or Rspec or a setup problem on my part.

A: It sounds like you might have enabled include_root_in_json for the development environment but not the test environment?
http://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html


text:
Q: Telegram bot in Talend open studio Maybe someone came across this problem.
I try run my jar with telegram bot on talend studio, but my job just stop after start.
If i run job without Talend studio, just java -jar TelegramBot.jar, or I run in intellij idea, it's worked perfect.
I create routines and export my jar file in tLibraryLoad and in tJava call main method.

import org.telegram.telegrambots.ApiContextInitializer;
import org.telegram.telegrambots.bots.DefaultBotOptions;
import org.telegram.telegrambots.meta.ApiContext;
import org.telegram.telegrambots.meta.TelegramBotsApi;
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;

public class StartBot {

    public static void start() {

        ApiContextInitializer.init();

        DefaultBotOptions botOptions = ApiContext.getInstance(DefaultBotOptions.class);

        FMTelegramBOTTest bot = new FMTelegramBOTTest(botOptions);

        TelegramBotsApi apiBots = new TelegramBotsApi();

        try {
            apiBots.registerBot(bot);
        } catch (TelegramApiRequestException e) {
            e.printStackTrace();
        }
        System.out.println("END");
    }

}

Work only this method
logs :
[statistics] connecting to socket on port 2607

[statistics] connected

END

[statistics] disconnected

A: If your are using windows operating system, please use below command to call the jar file directly, no need to use tLibraryLoad component. This component can be used in case you are accessing any method from the jar. If you just want to execute the jar you can use below,
Runtime.getRuntime().exec("cmd /c start path/to/jar/file_name.jar");

redpajama_set_name: RedPajamaStackExchange


text:
Q: Does it make sense to use === for string comparison in JavaScript? While it's clear how using the === operator for e.g. numbers is useful (0, null and undefined all being falsy values, which can lead to confusion), I'm not sure if there are benefits to using === for string comparisons.
Some of my team mates use this operator for all comparisons, but does it really make sense? Is there at least some minor performance impact?

A: If you know the types are the same, then there's no difference in the algorithm between == and ===.
That said, when I see ==, I assume that I'm using it for its type coercion, which makes me stop and analyze the code.
When I see === I know that there's no coercion intended, so I don't need to give it a second thought.
In other words, I only use == if I intend for there to be some sort of type coercion.

A: It is considered good practice to always use === for comparisons in JavaScript. Since JavaScript is a dynamic language, it is possible that what you think are two strings could be variables with different types.
Consider the following:
var a = "2", b = 2;
a == b  // true
a === b // false

The only way to guarantee a false result in this case would be to use === when comparing the two values.


text:
Q: drawing line between two coordinates on google map I am having two coordinate points on Google map. I calculated the distance between that points. But I want to draw a straight line between them. Please help me to draw.

A: *

*You have to use google  direction api for that follow the Direction API Link .

*Make request using NSURLConnection with direction api url and pass required addresses from it it and catch its response.

*From that you will get json or xml formatted response, which contains paths in the form of polyline encoded string .

*Then parse it and retrieve polyline encoded string.

*You have to simply decode it it then you will get all points of your path and pass it to viewForOverlay method of MKMapViewDelegate which will draw the path.

*For more information follow my question Stackoveflow question link .

If you have any more quires let me know. Hope this will help you....:)


text:
Q: Print enum value using value converter without data binding Let's say I have some enumeration, like:
enum MyEnum { value1, value2 }

and value converter:
[ValueConversion(typeof(MyEnum), typeof(string))]
class MyEnumToString : IValueConverter
{
    ...
}

Now I want to print two MyEnum values converted using MyEnumToString:
<Window.Resources>
    <converters:MyEnumToString x:Key="myEnumToString"/>
</Window.Resources>

...

<TextBlock Text="{here I want to print value1 converted by myEnumToString}"/>
<TextBlock Text="{here I want to print value2 converted by myEnumToString}"/>

How can I do this? Note that there is no data binding here, just two values.

A: Converter used together with a Binding, quote from MSDN:

IValueConverter: Provides a way to apply custom logic to a Binding.
If you want to associate a value converter with a Binding, create a class that implements the IValueConverter interface and then implement the Convert and ConvertBack methods.

Therefore, you need to write this:
<TextBlock Text="{Binding Path=value1, Converter={StaticResource myEnumToString}}" ... />

If this values located in ItemSource or for root Control defined DataContext, try this:
<TextBlock Text="{Binding Converter={StaticResource myEnumToString}}" ... />

Either like this:
<TextBlock Text="{Binding Path=., Converter={StaticResource myEnumToString}}" ... />

In this case, Text="{Binding Path=.}" is equivalent to Text="{Binding}".

A: Like Anatoliy said you can't use a converter without a binding.
That's why a converter is used to convert the bound data if the bound data is updated.


text:
Q: Connecting 2 tables I'm working on a site that handles books, and in my database I want to have 2 tables, one for Books and one for Authors.
The problem is, that I want to have a column in the books that points to the author, so when a person views a book he could have a button to go to the author's page.
And probably the bigger problem:
In the authors' page I want to have a list of books by that author and the ability to click on each book to view it.
I don't know what data-type to associate with the coloumns and how to make them interact with each other.
I'd be happy to get an explaination, a guide or a good reference.

A: Using a relational DB, you'd put an authorID column in the Books table and configure that to be a foreign key into Authors table.
You'd get the author of a given book via a SQL join; you could also get all the Books via a SQL join as well.
Check out this PHP tutorial which addresses a similar case: http://www.roseindia.net/sql/sqljoin/leftJoin.shtml

A: Your database schema ...
books

*

*id INT

*title VARCHAR

*author_id INT
authors

*

*id INT

*name VARCHAR

The author_id field in the books table will correspond to the id field in the authors table. You would then do simple joins to combine the two and pull out the data you need ... The MySQL manual is your friend in this endeavor, or here is a simple RIGHT JOIN / LEFT JOIN tutorial.

A: Books table:

*

*id

*name

*author

Authors table:

*

*id

*name

Getting all Books including the author's name.
SELECT * FROM Books LEFT JOIN Auhtors ON Authors.id = Books.author

Getting all Books by a specific author:
SELECT * FROM Books WHERE Author = $authorID

I think this is not that hard to understand, if you know basic SQL

A: So you want a relation between the books table and the authors table?
What you do is set up your authors table with an author id as your primary key. Each row will then contain one author. In your books table you add columns for all necessary information about the book, including the author. The author column should here be an integer that will contain the id of the author listed in the authors table.
In addition to this you should make the author column, in the books table, a foreign key that points towards the authors table and id column.
When you want information regarding a book you'll use JOIN to connect both tables and give you information about the author aswell. This also goes for the profile of the author. You just specify a simple query on the books table to list out all books with the authors id.


text:
Q: Has Sen quantized superstring fields? Today I saw a paper by Ashoke Sen titled "BV Master Action for Heterotic and Type II String Field Theories".

*

*Is it really the "quantization" of superstring fields for the first time?

*What can be its possible implications in string theory?

*Can it be helpful to "prove" Maldacena's original AdS/CFT conjecture (in the context of type IIB superstrings) as it incorporates Ramond-Ramond fields in the quantized theory?

A: (Note that I am only starting to study these works and I may be wrong on some points.)
The paper you are quoting is indeed providing a full definition of (type II and heterotic) superstring theory (type I is missing), valid at the quantum level and for both the NS and R sectors. The definition is basically following the construction of Zwiebach (arxiv:hep-th/9206084) up to two differences:

*

*In order to treat the R sector (which was the main difficulty up to now) an additional set of free fields (they don't even couple to gravity) are introduced.

*There is no canonical definition of the interactions as one can be found in the paper of Zwiebach (where he is using minimal area metrics) and one needs to go through the world-sheet / off-shell formulation defined in previous papers of Ashoke Sen (arxiv:1408.0571). Doing the same would require to generalize the minimal area prescription to super-Riemann surfaces.

The BV formalism ensures that the action is consistent at the quantum level. The action reproduces the scattering amplitudes (and off-shell correlation functions) and the physical states (plus a set of decoupled free fields) of the usual superstring theories. Due to the fact that it is a field theory loop corrections (susy breaking, vacuum shift, etc.) can be taken into account. Hence there is all the elements that one would require to say that the theory is quantized.
The main (immediate) application is to study some generic properties of (super)string theory in order to show that string field theory (SFT) possesses all the properties to be a well-defined QFT, such as unitarity. Ashoke Sen started this program recently (arxiv:1604.01783, arxiv:1606.03455).
Other goals would be to address non-perturbative effects, but due to the fact that the action is highly complicated (and without intrinsic definition of the vertices) I don't know how far one can go: it is quite inconvenient to work directly with this formulation.
For example the equations of motion are very complicated and it is not really realistic to solve them in order to get solitonic (D-branes) solutions as was done for the cubic bosonic SFT. Moreover I don't think it would help to show the background independence (since this point is not fully understood already for bosonic SFT).
One may hope that it could shed some lights on dualities if one can understand them through the SFT formalism. Hence in my opinion the best we can go for now is to show that string theory is well-defined from the constructive point of view.
To answer your third question I have no clue at all, but this is related to the fact that I have no idea what would be required to prove the adS/CFT conjecture.
Note that a set of 33 lectures given last semester have been recorded, hand-written notes are available (both are available on Ashoke Sen webpage) and we are preparing a review.


text:
Q: Google web app script doget() do not return any webpage after rendering/evaluating more than twice This is the link of my web app:
https://script.google.com/macros/s/AKfycbzmbR9ljp7d5T8vsPTKt4b_v461NDNtxh6w6s1FFuJOhSGh6EKE/exec?view=home

*

*Step1) at home page -> OK

*Step2) click enter-> OK

*Step3) click add weekly -> Renders nothing

>

Here is the LOG:

Well, weirdly, if I manually input the url paremeters, the page is rendered just fine:

here is the code snippet of doget():

function doGet(e){
  Logger.log(e);
  Logger.log("view="+e.parameters.view);

  if(e.parameters.view =="weekly"){
    Logger.log("view==weekly");

    var page = addWeeklyReport();

    //Logger.log(page.getTitle());
    //return page.evaluate();

    return page.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
  }else if(e.parameters.view == "home"){
    Logger.log("view is home");
    var home = HtmlService.createTemplateFromFile("homehs");
    return home.evaluate();
  //return addWeeklyReport();
  }else if(e.parameters.view == "projects"){
    Logger.log("here view is projects");
    return HtmlService.createTemplateFromFile("project-list").evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
  }else if(e.parameters.view=="addproject"){
    return HtmlService.createTemplateFromFile("add-project").evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
  }else{
    //return HtmlService.createTemplateFromFile("demo").evaluate();
    return HtmlService.createTemplate("
demo
").evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
  }

}

about the codes:

setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);

*

*If i didn't use this, it couldnt even last until 2)step, straight away nothing after clicking Enter.

*After adding this, it survived until the 2nd click ...

about the Access rights:

*

*it is published as latest version web app

*published as "ME" in order to gain the most access . although i have exhausted all other options and nothing seemed to work

*"anyone even anonymous can access app"

A: I got this working without changing the sandbox. See a demo of it here: https://script.google.com/macros/s/AKfycbzeTiyAvI3qQKodHfHFXPtSP0Sy-xU6Gwpb3SoCT8GzKLCa8i5J/exec.
Code.gs
function doGet(e)
{
  if(e.parameters.view == "two")
  {
    return HtmlService.createTemplateFromFile("two").evaluate();
  }
  else if(e.parameters.view == "three")
  {
    return HtmlService.createTemplateFromFile("three").evaluate();
  }
  else if(e.parameters.view)
  {
    return HtmlService.createTemplateFromFile("error").evaluate();
  }
  else
  {
    return HtmlService.createTemplateFromFile("one").evaluate();
  }
}

one.html
<!DOCTYPE html>

    <base target="_top">

    one

    <a href="<?= ScriptApp.getService().getUrl() ?>?view=two">two

two.html
<!DOCTYPE html>

    <base target="_top">

    two

    <a href="<?= ScriptApp.getService().getUrl() ?>?view=three">three

three.html
<!DOCTYPE html>

    <base target="_top">

    three

    <a href="<?= ScriptApp.getService().getUrl() ?>?view=four">four

error.html
<!DOCTYPE html>

    <base target="_top">

    error

A: You need to set base's target to the top frame. Otherwise you'll be creating a nesting frame loop because base target defaults to _self and you are loading  the html in a iframe.
<base target="_top">


text:
Q: transfer hidden value in html form I tried to transfer some variable in html which could not be manipulated by user to next page, like the var effort here, but it could not pass to the next page, what's wrong, thanks

    Name <input type="text" name="name" size="35">

    Guess <input type="number" name="guessNum" size="35" >

     <input type="hidden" name="effort" value="effort" >
    <input type="submit" value="submit">

 </form>

A:
I tried to transfer some variable in html which could not be manipulated by user to next page

That's impossible. You are giving it to the user and asking them to send it back. They can change it as much as they like.
If you don't want it to be changed then store it in on the server (e.g. in a session).

The code isn't working because you are setting a JavaScript variable called effort and not changing the value of the form field (which doesn't event exist when you set the variable).
<input type="hidden" name="effort" value="effort" >

You would then need some server side code to read it (unless it is a GET form, in which case you can use JS to pull it from the URL).
As I said, even if you fix that, the user can manipulate it.


text:
Q: How to use qDebug() with two parameters in qt? I am trying to use qDebug() with two parameters but it fails everytime.
When I use separately there is no problem, such as;
qDebug() << "img:width = " << img.width();
qDebug() << "img:height = " << img.height();

However when I combine them, it gives error.
qDebug() << "img:width = " << img.width() << "/t img:height = " << img.height() << std::endl;

Error is :
error: no match for 'operator<<' in '((QDebug*)((QDebug*)((QDebug*)qDebug()().QDebug::operator<<(((const char*)"img:width = ")))->QDebug::operator<<(img.QImage::width()))->QDebug::operator<<(((const char*)"/t img:height = ")))->QDebug::operator<<(img.QImage::height()) << std::endl'

Can I use two or more parameters in qDebug?
Edit::
Problem still continue for me if I delete std::endl

A: Remove std::endl at the end of the line, std::endl is used with combination with std::cout not with qDebug()
This will work:
qDebug() << "img:width = " << img.width() << "/t img:height = " << img.height();

A: I think you using /t instead of \t is the problem (I'm thinking you're trying to place a tab between the two items). Plus yes, std::endl is not needed.
qDebug() << "img:width = " << img.width() << "\t" << "img:height = " << img.height();

Or
qDebug() << "img:width = " << img.width() << "\t img:height = " << img.height();

should work.


text:
Q: Taylor Series for $\frac{1}{ 1+x+x^2}$ I tried to solve it in a way. The solution did not match. Please tell me where i went wrong.
$\cfrac {1} {1+x+x^2} = \cfrac 4 {4+4x+ 4x^2} = \cfrac 4{ 3+(2x+1)^2} = \cfrac 1{\sqrt 3}\cdot\cfrac 4{ 1+ \left(\frac {2x+1}{\sqrt 3} \right)^2 }$
And now, taking the $\cfrac 4 {\sqrt 3}$ as constant, and the rest part in the form $\cfrac 1{1+t^2} $, where $t= \frac {2x+1}{\sqrt 3}$ $$\frac 1{1+t^2} = 1 - t^2 + t^4 - \dots$$
Now, substituting t's value, and multiplying with $\cfrac 4{\sqrt 3}$, the answer is something other than $\sum x^{3n}$.
The answer given is $\sum x^{3n}$.

A: Hint: $$\frac 1{1+x+x^2}=\frac {1-x}{1-x^3}$$

A: $$\frac{1}{1+x+x^2}=(1-x)\sum_{n\geq 0}x^{3n} = \sum_{n\geq 0}\left(x^{3n}-x^{3n+1}\right).$$


text:
Q: Passing `git blame` options to `git gui blame` How can I pass git blame options such as -C to git gui blame? Merely typing
git gui blame -C somefile

results in

error: unknown switch `-C'
usage: git cat-file ...

A: I see the --line=x option is supported for git gui blame, but other git blame options seem not to be included.
See git-gui/git-gui.sh
if {$subcommand eq "blame"} {
    set subcommand_args {[--line=<num>] rev? path}
} else {
    set subcommand_args {rev? path}
}


text:
Q: Disabling keys after enabling them with callback? I have this div that slides up (disappears) on keydown. But after the this event I have to disable the keys, otherwise they will continue to scroll to the position of the now "gone" div. I've tried several approaches, like adding and removing active classes, but it didn't work.
Can this work with a callback? Maybe I'm typing it down wrong. Can someone help me out? Thanks. The code:
$("#zero").bind("mousewheel mouseup mousedown", function() { //touchmove
  return false;
});

function start() {
  $("html, body").animate({
    scrollTop: 0
  }, "slow"); //665px
  $("#zero").slideUp();
  $("#nav").fadeIn(1500).delay(9000);
  $('html, body').css({
    overflow: 'auto',
    height: 'auto'
  });
  $("body").on("touchmove", true);
}

$(document).keyup(function(event) {
  if (event.keyCode == 40 || 13) {
    start(function() {
      // -- -- > CallBack ?
      if (event.keyCode == 40 || 13) {
        return false;
      }
    });
  }
});


text:
Q: Django suddenly gives "No module named "Django"" Been making a blog and I've been busy/ill for 2 weeks, I have came back to it today and go to start my virtual environment, fine so I type python manage.py runserver and just get
from django.core.management import execute_from_command_line
ModuleNotFoundError: No module named 'django'

I tried installing django again but that didn't fix the problem
I dont know if it's because my postgres isn't running but when i type psql into my CLI I get psql: error: FATAL:  role "toad" does not exist which I can find literally nothing about when I google it
At this rate I'll be starting a new project and copy pasting everything across

A: I fixed it by creating a new virtual env and re-installing all the packages I was using, not a great fix but still a fix


text:
Q: Weird print from simple program I'm creating a program where I ask the user to enter some of his personal informations, but for some reason I can't figure it out. When I ask the user to enter his birth date and his email, the message appears in a weird way for the user.
#include <stdio.h>
#define MAX  50
char name[MAX],date[MAX],email[MAX],cpf[MAX],tel[MAX],contatip[MAX],esc3[MAX],esc4[MAX];

int main()
{
    printf("\nEnter your name: ");
        scanf("%s",name);
    printf("\nBirth date:"); // The problem is here
        gets(date);
    printf("\Email: ");
        gets(email);
    printf("\nEnter your CPF: ");
        gets(cpf);
    printf("\nCelphone: ");
        gets(tel);
}

A: #include <stdio.h>

#define MAX 50

char name[MAX], date[MAX], email[MAX], cpf[MAX], tel[MAX], contatip[MAX], esc3[MAX], esc4[MAX];

int main()
{
    printf("\nEnter your name: ");
        fgets(name, MAX, stdin);
    printf("\nBirth date: ");
        fgets(date, MAX, stdin);
    printf("\nEmail: ");
        fgets(email, MAX, stdin);
    printf("\nEnter your CPF: ");
        fgets(cpf, MAX, stdin);
    printf("\nCellphone: ");
        fgets(tel, MAX, stdin);
    // printf("\n%s", name);
    // printf("%s", date);
    // printf("%s", email);
    // printf("%s", cpf);
    // printf("%s", tel);
}


text:
Q: SwiftUI - Create a list with navigation links with data and views from an array I'm trying to create a list with NavigationLinks, where I can store my views in an array and loop through them with a for loop. Unfortunately with what I have until now this just doesn't work.
I get this error all the time: Closure containing control flow statement cannot be used with result builder 'ViewBuilder'
My code:
struct ContentView: View {

    let list = [DiceView(), DomainResolver()] as [Any]

    var body: some View {
        NavigationView {
            List {
                for i in list {
                    NavigationLink{
                        i
                    } label: {
                        Label("Test", systemImage: "person").foregroundColor(.primary)
                    }
                }
            }
        }
    }
}

Thanks for every constructive answer.

A: In swiftUI, inside the struct you cannot use for loop. Instead, you can use ForEach.
struct ContentView: View {

    let list = [DiceView(), DomainResolver()] as [Any]

    var body: some View {
        NavigationView {
            List {
                ForEach(list, id: \.self) { i in
                    NavigationLink{
                        i
                    } label: {
                        Label("Test", systemImage: "person").foregroundColor(.primary)
                    }
                }
            }
        }
    }
}

Notice, that in Foreach you also use id: .self, which means that ForEach makes every object unique.


text:
Q: Post history not accessible without edits Normally, the close/lock/delete history of a post (including the reversal of such actions) is easily accessible along with the posts revisions.
However, if the post has not been edited (aside from closures/lockings/deletions), there is no link to the revision history, and no indication (aside from maybe comments) that the post was ever closed and reopened, locked and unlocked, or deleted and undeleted.
Example: Remove links from close question dialog for moderators
Of course, the revision history is still accessible via the direct URL, so the close/lock/delete history can be seen, but there is no indication that such history exists.
I propose that if there are no edits on a question that has been closed, locked, or deleted, there be a link to the revision history in the typical location, with a timestamp of the closure/locking/deletion activity.
It'd be useful to know by looking at the post that there is disagreement as to whether it should be open or closed, locked or unlocked, deleted or undeleted, and it's unclear enough that it's gone both ways without even being edited.

Another example is here: https://workplace.stackexchange.com/q/11006/869
The question was closed (and then reopened) by a moderator. There is a comment about expanding/improving the question, but no indication that it has been closed/reopened or why.

A: Some time ago, I wrote a User script to get the revision link to appear on all posts.
// ==UserScript==
// @name           Stack Exchange: Add revision link
// @namespace      Rob W
// @description    Add a (history) revision link to each post
// @include        http://stackoverflow.com/questions/*
// @include        http://meta.stackexchange.com/questions/*
// @include        http://superuser.com/questions/*
// @include        http://meta.superuser.com/questions/*
// @include        http://askubuntu.com/questions/*
// @include        http://meta.askubuntu.com/questions/*
// @include        http://mathoverflow.net/questions/*
// @include        http://meta.mathoverflow.net/questions/*
// @include        http://answers.onstartups.com/questions/*
// @include        http://meta.answers.onstartups.com/questions/*
// @include        http://serverfault.com/questions/*
// @include        http://meta.serverfault.com/questions/*
// @include        http://stackapps.com/*
// @include        http://*.stackexchange.com/questions/*
// @version        1.0
// ==/UserScript==

var vt = document.querySelectorAll('.vt');
var div = document.createElement('div');
div.className = 'user-info';
div.innerHTML = '
post history
';

for (var i=0; i<vt.length; i++) {
    let cell_vt = vt[i],
        cell_next = cell_vt.nextElementSibling,
        cell_sig = cell_next.nextElementSibling,
        cell_content;
    if (!cell_sig) {
        // Recycling cell_sig variable for postID
        cell_sig = /\d+/.exec(cell_vt.getElementsByTagName('a')[0].href);
        cell_next = cell_vt.parentNode.insertCell(1);
        cell_next.className = 'post-signature rw-post-history';

        cell_content = div.cloneNode(true);
        cell_content.getElementsByTagName('a')[0].href = '/posts/' + cell_sig + '/revisions';

        cell_next.appendChild(cell_content);
    }
}

var style = document.createElement('style');
style.type = 'text/css';
style.textContent = '.rw-post-history{opacity:0.2}.rw-post-history:hover{opacity:1;}';
document.documentElement.appendChild(style);


text:
Q: HTTP 404 after successfully deploying Angular app to heroku Following this guide and also this guide I am trying to deploy my Angular application to heroku.
I actually have two apps. One is working, the other one is not and I cannot see where the difference is.
It "looks like" as if everything is working if I deploy the app (which doesn't work):
..
remote: -----> Compressing...
remote:        Done: 59.7M
remote: -----> Launching...
remote:        Released v6
remote:        https://*********.herokuapp.com/ deployed to Heroku
remote:
remote: Verifying deploy... done.
To https://git.heroku.com/*********.git
   5604a1b..6ee9624  master -> master

Also in the heroku logs I see that the status gets set to up:
2018-11-04T10:10:19.360364+00:00 heroku[web.1]: State changed from up to starting
2018-11-04T10:10:20.374632+00:00 heroku[web.1]: Stopping all processes with SIGTERM
2018-11-04T10:10:20.492521+00:00 heroku[web.1]: Process exited with status 143
2018-11-04T10:10:31.000000+00:00 app[api]: Build succeeded
2018-11-04T10:10:33.593410+00:00 heroku[web.1]: Starting process with command `npm start`
2018-11-04T10:10:37.121051+00:00 app[web.1]:
2018-11-04T10:10:37.121068+00:00 app[web.1]: > ********@0.0.0 start /app
2018-11-04T10:10:37.121070+00:00 app[web.1]: > node server.js
2018-11-04T10:10:37.121071+00:00 app[web.1]:
2018-11-04T10:10:37.849823+00:00 heroku[web.1]: State changed from starting to up
2018-11-04T10:10:38.968886+00:00 heroku[router]: at=info method=GET path="/" host=********.herokuapp.com request_id=81ca531b-c462-4264-a593-7d9b2d676f1d fwd="84.115.204.37" dyno=web.1 connect=1ms service=76ms status=404 bytes=383 protocol=https

However, if I'm now accessing https://*********.herokuapp.com/ what I get is
Cannot GET /

coming from  a HTTP 404 Not Found response.
I don't see where I make the mistake so here's the package.json:
{
  "name": "********",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "node server.js",
    "build": "ng build --prod",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "postinstall": "ng build --aot --prod"
  },
  "engines": {
    "node": "8.12.0",
    "npm": "6.4.1"
  },
  "private": true,
  "dependencies": {
    "@agm/core": "^1.0.0-beta.3",
    "@angular/animations": "6.1.7",
    "@angular/cdk": "^6.4.7",
    "@angular/cli": "6.2.2",
    "@angular/common": "6.1.7",
    "@angular/compiler": "6.1.7",
    "@angular/compiler-cli": "6.1.7",
    "@angular/core": "6.1.7",
    "@angular/flex-layout": "^6.0.0-beta.18",
    "@angular/forms": "6.1.7",
    "@angular/http": "6.1.7",
    "@angular/material": "^6.4.7",
    "@angular/material-moment-adapter": "^6.4.7",
    "@angular/platform-browser": "6.1.7",
    "@angular/platform-browser-dynamic": "6.1.7",
    "@angular/router": "6.1.7",
    "@fortawesome/angular-fontawesome": "^0.2.0",
    "@fortawesome/fontawesome-svg-core": "^1.2.4",
    "@fortawesome/free-brands-svg-icons": "^5.3.1",
    "@fortawesome/free-solid-svg-icons": "^5.3.1",
    "@ngx-share/button": "^6.0.1",
    "@ngx-share/core": "^6.0.1",
    "angular-mentions": "^0.8.0",
    "chart.js": "^2.7.2",
    "core-js": "^2.5.7",
    "express": "^4.16.3",
    "http-status-codes": "^1.3.0",
    "ng-pick-datetime": "^6.0.16",
    "ngx-logger": "^3.1.0",
    "ngx-moment": "^3.1.0",
    "rxjs": "^6.3.2",
    "typescript": "^2.9.2",
    "zone.js": "^0.8.26"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^0.8.2",
    "@angular/language-service": "6.1.7",
    "@types/googlemaps": "^3.30.11",
    "@types/jasmine": "~2.8.3",
    "@types/jasminewd2": "~2.0.2",
    "@types/node": "~10.9.4",
    "codelyzer": "^4.4.4",
    "enhanced-resolve": "^4.1.0",
    "jasmine-core": "~3.2.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~3.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "^2.0.4",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^1.3.1",
    "protractor": "^5.4.1",
    "ts-node": "~7.0.1",
    "tslint": "^5.11.0"
  }
}

Here is a diff which shows you the difference to the package.json of the working to the non-working application. As you can see there are no essential differences.
This is server.js - which is identical down to the last character in both apps:
const express = require('express');
const app = express();

// Run the app by serving the static files
// in the dist directory
app.use(express.static(__dirname + '/dist'));

// Start the app by listening on the default
// Heroku port
app.listen(process.env.PORT || 8080);

Any ideas?

A: Okay, I can't remember if it was me who changed that or whether this is set per default but in angular.json there is also a way to set the output directory (outputPath). For some reason this was set to
"outputPath": "dist/<project-name>"

I changed that to
"outputPath": "dist"

and now everything works.

A: If you are serving your app's static files from /dist/ then you must tell that to angular by using a switch to the ng build command:
ng build --prod --deploy-url /dist/


text:
Q: What is the difference between the two statements below? self.window.rootViewController = self.tabBarController;
 [self.window addSubview:self.tabBarController.view];

They are used in the context below:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    // Add the tab bar controller's current view as a subview of the window

    //   self.window.rootViewController = self.tabBarController;
     [self.window addSubview:self.tabBarController.view];

    IntroViewController *introViewController = [[IntroViewController alloc] initWithNibName:@"IntroViewController" bundle:nil];

    //Lets place introViewController in navController
    UINavigationController * navController = [[UINavigationController alloc] initWithRootViewController:introViewController];

    //Now lets display it
    [self.tabBarController presentModalViewController:navController animated:YES];

    [navController release];
    [introViewController release];

    [self.window makeKeyAndVisible];
    return YES;
}

A: From iOS Reference:
rootViewController

The root view controller provides the content view of the window.
  Assigning a view controller to this property (either programmatically
  or using Interface Builder) installs the view controller's view as the
  content view of the window. If the window has an existing view
  hierarchy, the old views are removed before the new ones are
  installed.

addSubview

This method retains view and sets its next responder to the receiver,
  which is its new superview.
Views can have only one superview. If view already has a superview and
  that view is not the receiver, this method removes the previous
  superview before making the receiver its new superview.

So we can say that the main difference is that setting rootViewController destroys all the previous views contained in the UIWindow, and using addSubView: only adds an UIView on top.

A: self.window.rootViewController = self.tabBarController;
This statement is wrong because window is  a container you don't have any root controller there.
SubView:
[self.window addSubview:self.tabBarController.view];
Here you are adding the tabBarController as a subview which will add your windows container. And this is the right way to create the tab bar controller.


text:
Q: Maximum receive size of E-mail message Exchange server All E-mails with attachment bigger than 10MB are being reject by E-mail server of my company. When I try to send mail from my Gmail, to my work account I get following message:
Google tried to deliver your message, but it was rejected by the recipient domain.
We recommend contacting the other email provider for further information about the
cause of this error. The error that the other server returned was: 552 552 5.3.4
Message size exceeds fixed maximum message size (state 17).

In Exchange Management Console of our server, I set maximum receive size as show in following picture, but E-mails are still blocked.
You can see my image here
Also in SERVER Configuration->Hub Transport->My Receive Connector->Maximum Message Size I set value 20200, but still no results.

A: There are several places to make this change. You caught one of them...
Another spot is in Organization Settings -> Global Settings -> Transport Settings... (I'm on Exchange 2010, but it should be similar for you)

Also take a look at the relevant Send Connector in the Organization Configuration -> Hub Transport...


text:
Q: setTimeout with loop issue with field update I'm trying to loop through a list on a timer (currently 1 second but I want it faster). The problem is that the current value isn't being updated visually & I can't see why.
When I loop through with Firebug it works as intended but without firebug it's not showing the text change...is it skipping the text update somehow?
I set the timer to 1 second; surely a .html() call wouldn't take longer? Thanks for any info.
My HTML is simply:

My JS is:
var people = ["a", "b", "c"];
        var counter = 1;
        var run;
        $(document).ready(function(){
        $("#winner2 h1").html("a");
        $("#stop").hide();

        $( "#start" ).click(function() {
            $("#start").hide();
            $("#stop").show();
            run = setTimeout (nameIncrement(),1000);
        });

        $( "#stop" ).click(function() {
            $("#stop").hide();
            $("#start").show();
            clearTimeout(run);
        });

        function nameIncrement() {
            if(counter == people.length) {
                counter=0;
            }
            $("#winner2 h1").html(people[counter]);
            counter++;
            run = setTimeout (nameIncrement(),1000);
        }
        });

A: You are calling nameIncrement() and passing its return value to setTimeout(), rather than passing nameIncrement.
Remove the parentheses:
run = setTimeout(nameIncrement, 1000);

jsfiddle

A: It looks like you are running a recursive function without defining exit condition. this probably causes overload to the browser which decided not to run the function.
Try:
function nameIncrement() {
            if(counter == people.length) {
                counter=0;
                return;
            }
            $("#winner2 h1").html(people[counter]);
            counter++;
            run = setTimeout (nameIncrement(),1000);
        }
        });

on debug mode, however, the browser is less defensive, so you can see your erors yourself.


text:
Q: Forcing out of L[U] when we have a precipitous ideal in V The following theorem of Jech, Magidor, Mitchell and Prikry is well-known.
Theorem. (1) If $\kappa$ is a regular cardinal that carries a precipitous ideal, then $\kappa$ is a measurable cardinal in an inner model of ZFC.
(2) If $\kappa$ is a measurable cardinal, then there is some $\mathbb{P}$ such that $\mathbb{P}$ forces that $\kappa$ carries a precipitous ideal.
Problem. Suppose there is a precipitous ideal on $\omega_{1}$. Then by the theorem, we know there is some $U$ such that in $L[U]$, $U$ witnesses that $\omega_{1}$ is measurable.
Fixing such a $U$, is there a poset $\mathbb{P}$ and $\mathbb{P}$-generic $G\in V$ (this is the rub) over $L[U]$ such that $L[U][G]$ satisfies that $\omega_{1}$ has a precipitous ideal?

A: If more large cardinals exist, then there is such a filter.  That is, suppose that the least $\kappa_0$ such that there is a proper class transitive model of "$V=L[U_0]$", is countable, (correction) and so is $\kappa_0^{+L[U_0]}$. (This holds if there is a proper class transitive model with two measurables, for example.) Then there is a such a filter.
(EDIT: I had ignored the possibility that $\kappa_0^{+L[U_0]}=\omega_1$ in the previous version. But if there is a precipitous filter on $\omega_1$ and $\kappa_0<\omega_1$ then $\kappa_0^{+L[U_0]}<\omega_1$, because otherwise if $j:V\to M$ is a generic embedding with $\mathrm{crit}(j)=\omega_1$ then $j(\kappa_0^{+L[U_0]})>\kappa_0^{+L[U_0]}$, although $j(\kappa_0)=\kappa_0$, which gives us two distinct $L[U]$-type models with the same critical point in $V[G]$, which is impossible.)
The construction is along the lines suggested by @AsafKaragila in his comment above. There are also similar such constructions in the literature; I think Sy Friedman used such constructions, for example. It suffices to find an $(L[U],\mathrm{Coll}(\omega,{<\omega_1}))$-generic filter.
For this, first observe that because $\kappa_0^{+L[U_0]}<\omega_1$, the linear iteration of $L[U_0]$ of length $\omega_1$ does not send the measurable past $\omega_1$ at any stage ${<\omega_1}$, so the eventual $\omega_1$st iterate has measurable $\omega_1$, so it is just $L[U]$. Let $C\subseteq\omega_1$ is the club of critical points resulting from iterating $L[U_0]$ out to $\omega_1$, let $L[U_\alpha]$ be the $\alpha$th iterate of $L[U_0]$, with measurable $\kappa_\alpha\in C$. Choose a sequence $\left<G_\kappa\right>_{\kappa\in C}$ such that $G_\alpha$ is $\mathrm{Coll}(\omega,{<\kappa_\alpha})$-generic over $L[U_\alpha]$, and such that $G_\alpha\subseteq G_\beta$ when $\alpha<\beta$. We can proceed from $G_\alpha$ to $G_{\alpha+1}$ because
(i) $\mathrm{Coll}(\omega,{<\kappa_\alpha})^{L[U_\alpha]}=\mathrm{Coll}(\omega,{<\kappa_\alpha})^{L[U_{\alpha+1}]}$
(ii) $\mathcal{P}(\kappa_\alpha)\cap L[U_\alpha]=\mathcal{P}(\kappa_\alpha)\cap L[U_{\alpha+1}]$ is countable,
(iii) $\mathrm{Coll}(\omega,{<\kappa_{\alpha+1}})$ factors $\mathrm{Coll}(\omega,{<\kappa_\alpha})\times\mathrm{Coll}(\omega,[\kappa_\alpha,\kappa_{\alpha+1}))$
(iv) for limit $\lambda\leq\omega_1$, $\mathrm{Coll}(\omega,{<\kappa_\lambda})$ is just the direct limit of the $\mathrm{Coll}(\omega,{<\kappa_\alpha})$ under the iteration maps, which is the same thing as their finite support product, and $L[U_\lambda]$ is the direct limit of the $L[U_\alpha]$'s, so all dense subsets of $\mathrm{Coll}(\omega,{<\kappa_\lambda})$ in $L[U_\lambda]$ are met by some $G_\alpha$ where $\alpha<\lambda$.
In particular, $G_{\omega_1}$ is the desired $(L[U],\mathrm{Coll}(\omega,{<\omega_1}))$-generic filter.
But things seem more subtle if $\kappa_0=\omega_1$.


text:
Q: PowerShell - Add new line when appending multiple files I am trying to create a single file by appending multiple files in a folder. In between the files i wanted to add a new line character . I have tried out the below but it does not work. Please suggest what am i missing.
Get-ChildItem -Filter *.sql |sort CreationTime| % { Get-Content $_ -ReadCount 0 | Add-Content combined_files.sql| Add-Content combined_files.sql -value `n"dummy text before next file" }

I am able to get the combined_files.sql created with the contents of child files but the text inbetween files is missing. Please suggest.

A: Try constructing your data before writing it out
Get-ChildItem -Filter *.sql | Sort-Object CreationTime | ForEach-Object {
    $ThisFile = (Get-Content $_.FullName) + "`ndummy text before next file"
    Add-Content -Path combined_files.sql -Value $Thisfile
}


text:
Q: How can I find the file size of files in a list? I have a list of files, all in random folders and would like to know how to find their files size - is there a script that I can run to go through the list to find their sizes please?

A: Suppose you have a list of files:
List<File> list = new ArrayList<>(); //list of your files

Parse it and print the sizes:
 for(File file : list) {
        System.out.println(file.length());
    }

A: Use File#length() which returns the length of the file.

A: In the Java package: java.nio.file.Files
there is the method: public static long size(Path path)
Which returns the size in bytes and then just iterate over your list an give the absolute file path as parameter

A: Try this:
List<File> yourFiles = //...
Map<File, Long> fileSizeMap = new HashMap<>(); // We will map the files to sizes
for (File file : yourFiles) { // Iterate to set each one
    fileSizeMap.put(file, file.length);
}
System.out.println(fileSizeMap.get(yourFiles.get(0)));
// print the first file size just as an example


text:
Q: Is there a way to make a C# custom attribute raise a message at compile time? A colleague of mine is using ObsoleteAttribute on not-yet-implemented methods so we get the warning at compile time.
Since a method to be implemented is in the exact opposite place of an obsolete one, however, that bugs me.
I don't see a NotYetImplementedButPleaseBePatientWeVeGotLoadsOfOtherThingsToDoAsWellAttribute in the documentation, so I'm figuring maybe we could create one.
ObsoleteAttribute is sealed, so we can't inherit it. (Yes, I found that out when I tried it. Nice try, me.)
Is there another way to imitate ObsoleteAttribute, but with a more appropriate name?

A: You cannot achieve exactly the same as [Obsolete], because that is handled directly by the compiler. However, you could write a "Roslyn analyzer" that looks for anything you like, and adds warnings, errors, suggestions, etc, based on your preferences. It could perhaps even (perhaps additionally) try to look for throw new NotImplementedException();. Writing a Roslyn analyzer is not, however, a trivial task.


text:
Q: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare(); O que devo fazer para solucionar este problema ?
  private void callServer(final String method, final String data){

        new Thread(){

            public void run(){
               asw = Connection.getSetDataWeb("http://192.168.1.20/renan/process.php", method, data);

                if (data.isEmpty()){
                    degenerateJson(asw);
               }

                if(asw.equals("3")){
                    makeText(MainActivity.this, "Código da igreja inesistente, por favor escreva um código válido.", LENGTH_SHORT).show();
                }else if (asw.equals("2")){
                    makeText(MainActivity.this, "Senha incorreto, por favor escreva uma senha válida.", LENGTH_SHORT).show();
                }else if (asw.equals("1"))
                {
                    makeText(MainActivity.this, "E-mail incorreto, por favor escreva um email válido.", LENGTH_SHORT).show();
                }else{
                    Intent it = new Intent(MainActivity.this, MC_Home.class);
                    it.putExtra("email", email.getText().toString());
                    it.putExtra("cod_igrej", cod_igrej.getText().toString());
                    startActivity(it);
                }
            }
        }.start();
       }

O Logcat:
05-22 14:33:48.578  28186-28305/com.example.hotsystems.hs_celulas E/AndroidRuntime﹕ FATAL EXCEPTION: Thread-121
    Process: com.example.hotsystems.hs_celulas, PID: 28186
    android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
            at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6094)
            at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:824)
            at android.view.View.requestLayout(View.java:16431)
            at android.view.View.requestLayout(View.java:16431)
            at android.view.View.requestLayout(View.java:16431)
            at android.view.View.requestLayout(View.java:16431)
            at android.view.View.requestLayout(View.java:16431)
            at android.view.View.requestLayout(View.java:16431)
            at android.view.View.requestLayout(View.java:16431)
            at android.view.View.requestLayout(View.java:16431)
            at android.view.View.requestLayout(View.java:16431)
            at android.widget.TextView.checkForRelayout(TextView.java:6594)
            at android.widget.TextView.setText(TextView.java:3813)
            at android.widget.TextView.setText(TextView.java:3671)
            at android.widget.TextView.setText(TextView.java:3646)
            at android.app.ProgressDialog.setMessage(ProgressDialog.java:316)
            at com.example.hotsystems.hs_celulas.MainActivity$3.run(MainActivity.java:140)

Utilizando AsyncTaks, porem ainda não testei, esta dando erro ao chamar outra activity, se caso tiver tudo correto.:
package com.example.hotsystems.hs_celulas;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
public class Atividade_Entrar extends AsyncTask {
    private Context context;
    private ProgressDialog progresso;
public Atividade_Entrar(Context context){
    this.context = context;
}

protected void onPreExecute(){
    ProgressDialog progresso = new ProgressDialog(context);
    progresso.setMessage("Aguarde...");
    progresso.show();
}
protected String doInBackground(String... asw){
    if(asw.equals("3"))
        progresso.setMessage("Código da igreja inesistente, por favor escreva um código válido.");
    else if (asw.equals("2")){
        progresso.setMessage("Senha incorreto, por favor escreva uma senha válida.");
        // makeText(MainActivity.this, "Senha incorreto, por favor escreva uma senha válida.", LENGTH_SHORT).show();
    }else if (asw.equals("1"))
    {
        progresso.setMessage("E-mail incorreto, por favor escreva um email válido.");
        // makeText(MainActivity.this, "E-mail incorreto, por favor escreva um email válido.", LENGTH_SHORT).show();
    }

    return null;
}
protected void onProgressUpdate(){

}
protected void onPostExecute(){
    progresso.setMessage("Seja Bem vindo.");
    progresso.show();

    Intent it = new Intent(context, MC_Home.class);
    startActivity(it);
    progresso.dismiss();

}

}


text:
Q: photoswipe js on mobile device can't scroll vertically when swiping on the main image I am using PhotoSwipe.js on an ecommerce site to display the product on the Product Detail Page. When I am trying to scroll up and down the page using my mobile device, it does not scroll if you happen to scroll directly on the main image. (I have disabled the zoom-in/expand-image button because I don't want it by just commenting out in the code for the expand image button. So I am not referring to you expanding the image). So all I have to do now is disable whatever makes this "stop scrolling feature" happen on mobile.
Is there any javascript that I can use to help me give mobile the ability to scroll vertically down the page even when you happen to scroll your finger across the main image ?
Here I have provided a link to an example of the same html theme that I am using that is also using PhotoSwipe.js.
If you resize your chrome browser to mobile and select the responsive mobile toggle emulator on inspect element you can test this out or just go to this link on a real mobile device itself. CLICK THIS LINK
Steps:

*

*On a mobile device go to the link. Or on desktop chrome as mobile device using inspect element.

*On mobile try to scroll down the page, try to scroll by swiping your finger directly on the large main image itself and watch it not move. Then try to scroll up and down on white space and see it work properly.

Solution to this ?


text:
Q: how to get detailed logs from docker build (list of files) I am using the standard docker command:
docker build -t  XXX -f Dockerfile .
to build my container.  I would like to know if there is a way to get some more detailed logs about which files are being copied into the image.
Alternatively, is there a way from the DockerFile to list the files in a directory to the stdout (commandline from where docker command was run or log to a file).
Unfortunately my container dockerfile is crashing at a later point so I cannot examine the image as it is not being created.


text:
Q: Print out the alphabet using for loop and setw When I compile my program, run it and enter values I will get a rather strange and unexpected output:
So if I enter:
Enter width and height: 9 5
Enter characters: X O
1  XOXOXOXOX
2  OXOXOXOXO
3  XOXOXOXOX
4  OXOXOXOXO
5  XOXOXOXOX
A   BCDEFGHI

When it's supposed to be:
Enter width and height: 9 5
Enter characters: X O
1  XOXOXOXOX
2  OXOXOXOXO
3  XOXOXOXOX
4  OXOXOXOXO
5  XOXOXOXOX
   ABCDEFGHI

When do my void print_alphabet in another program it will work out just fine so I don't know the problem. I believe it has something to do with my other function but I can not seem to get it to work. Why does it act that way? Why does it print out A and then it does setw and prints out the rest?
This is my code:
#include <iostream>
#include <iomanip>

using namespace std;

void print_chess_board (int const height,
                        int const width,
                        char const char_1,
                        char const char_2)
{

    int index {};

    for (int i = 1; i <= height; ++i)
    {
        if (i%2)
        {
            index = 0;
        }
        else
        {
            index = 1;
        }

        cout << left << setw(3) << i;

        for (int j {}; j < width; ++j)
        {

          if (++index%2 == 0)
          {
              cout << char_2;
          }

          else
          {
              cout << char_1;
          }
        }

        cout << endl;
    }

}

void print_alphabet (int const width)
{

  cout << setfill(' ') << setw(4);

    for (int i {}; i < width; ++i)
    {
        cout << char('A' + i);
    }
}

int main()
{
    int width {};
    int height {};
    char char_1 {};
    char char_2 {};

    cout << "Enter width and height: ";
    cin >> width >> height;

    cout << "Enter characters: ";
    cin >> char_1 >> char_2;

    print_chess_board(height,width,char_1,char_2);
    print_alphabet(width);
    return 0;
}

A: You need to change
cout << setfill(' ') << setw(4);

to
cout << right << setfill(' ') << setw(4);


text:
Q: Parallelize a depth-first algorithm in python I need to create a connected graph from two dataframes called nodes and edges.
I am using https://www.educative.io/edpresso/how-to-implement-depth-first-search-in-python algorithm to filter out the nodes, which are not connected.
Here is the code:
# Using a Python dictionary to act as an adjacency list
graph = {
    'A' : ['B','C'],
    'B' : ['D', 'E'],
    'C' : ['F'],
    'D' : [],
    'E' : ['F'],
    'F' : []
}

visited = set() # Set to keep track of visited nodes.

def dfs(visited, graph, node):
    if node not in visited:
        print (node)
        visited.add(node)
        for neighbour in graph[node]:
            dfs(visited, graph, neighbour)

# Driver Code
dfs(visited, graph, 'A')

So first, I create the graph dictionary from my dataframes, and then use dfs() function to choose the connected nodes.
However this process, is a little bit time consuming. For a decent size nodes, edges dataframe it takes 157 seconds to execute. I would like to beat that via multiprocessing.
Is it possible to multiprocess this dfs function? If yes how?
NOTE: I am guessing, creating the graph dictionary is not the bottleneck here. However, here is also its code:
graph = dict.fromkeys(nodes['id'])

for key in graph.keys():
    t = []
    for i in edges.index:
        if key in edges['node_id'][i]:
            if edges['node_id'][i].index(key) == 0:
                index = 1
            else:
                index = 0

            t.append(edges['node_id'][i][index])
    graph[key] = list(set(t))

A: This is as far as I get at the moment with multiprocessing. So the idea is, since we know 'A' is the root of the tree, 'B' and 'C' path could processed parallel.
from multiprocessing.dummy import Pool as ThreadPool

def dfs(visited, graph, node):
    if node not in visited:
        visited.add(node)
        for neighbour in graph[node]:
            dfs(visited, graph, neighbour)

if __name__ == '__main__':
    visited = set()
    graph = {
        'A': ['B', 'C'],
        'B': ['D', 'E'],
        'C': ['F'],
        'D': [],
        'E': ['F'],
        'F': []
    }

    a = [visited, visited]
    b = [graph, graph]
    c = ['B', 'C']

    pool = ThreadPool(2)
    pool.starmap(dfs, zip(a, b, c))
    pool.close()
    pool.join()

    print(visited)

Since we already know 'A', 'B' and 'C' are connected, we can add those to the set in the end as well.
Finally in an ideal world, the paths of the network would be really seperated from each other so that, we could use multiprocessing efficiently...


text:
Q: ByteBuddy: AbstractMethodError when set interceptor The following is my learning code, when I executing the code, an exception happened:
Exception in thread "main"
java.lang.AbstractMethodError: org.learning.UserRepository$ByteBuddy$etz0xUhc.$$_pharos_set_interceptor(Lorg/learning/Interceptor;)V**

ByteBuddy version: 1.10.14
final TypeCache.SimpleKey cacheKey = getCacheKey(learningClazz, interceptor.getClass());
Class proxyClass = load(learningClazz, proxyCache, cacheKey, byteBuddy ->
  byteBuddy
    .subclass(learningClazz)
    .defineField(ProxyConfiguration.INTERCEPTOR_FIELD_NAME, Interceptor.class, Visibility.PRIVATE)
    .method(not(isDeclaredBy(Object.class)))
    .intercept(MethodDelegation.to(ProxyConfiguration.InterceptorDispatcher.class))
    .implement(ProxyConfiguration.class)
    .intercept(FieldAccessor.ofField(ProxyConfiguration.INTERCEPTOR_FIELD_NAME)
    .withAssigner(Assigner.DEFAULT, Assigner.Typing.DYNAMIC)));

final ProxyConfiguration proxy = (ProxyConfiguration) proxyClass.getDeclaredConstructor().newInstance();
proxy.$$_pharos_set_interceptor(interceptor);
return (T) proxy;

public interface ProxyConfiguration {

  String INTERCEPTOR_FIELD_NAME = "$$_pharos_interceptor";

  void $$_pharos_set_interceptor(Interceptor interceptor);

  class InterceptorDispatcher {
    @RuntimeType
    public static Object intercept(
      @This final Object instance,
      @Origin final Method method,
      @AllArguments final Object[] arguments,
      @StubValue final Object stubValue,
      @FieldValue(INTERCEPTOR_FIELD_NAME) Interceptor interceptor,
      @SuperMethod Method superMethod
    ) throws Throwable
    {
      if (interceptor == null) {
        return stubValue;
      }
      else {
        return interceptor.intercept(instance, method, arguments, superMethod);
      }
    }
  }

}

A: Package-private methods are overriden but the JVM will not dispatch them dynamically if the subclass is loaded on a different class loader. If you declare the method public, the problem should be solved. Alternatively, inject the class into the target class loader.


text:
Q: Slow Serial Connection between Arduino and Python I currently have a project where my goal is to graph (in real time) the air flow going through an air flow sensor. The sensor is connected via IIC to an Arduino Uno, which is then collects the data and sends it to my COM3 Serial line with a baudrate of 1,000,000. In python, I read, line by line, the Serial line, and then graph the data. My goal is to graph about 500 data points/second (500hz), but it seems that Python is reading in the data too slowly.
Here is a small 'test' I performed:
I blew on the air flow sensor. From the Serial Monitor on my Arduino program, I immediately see the readings spike. However, from Python's console output (which is just reading the serial line and printing out the contents), the spike from my blowing is significantly delayed. The longer the program runs, the more backed up Python gets with keeping up with the Serial line.
From the Arduino side:
Serial.println((double)average, 4);
 //Serial.print(" , ");
 // Serial.println((double)Flow, 4);

 delay(2);
}

And on the Python side:
print("PRESS 's' TO BEGIN RECORDING DATA!")

while not pressedStart:
    if keyboard.is_pressed('s'):
        print("Timer and Program Started!")
        startTime = hour.time()
        pressedStart = True

while pressedStart: #Program begins reading Serial Line when 's' is pressed.

    while flowData.inWaiting()==0:
        pass

    dataArray = flowData.readline().split(",")
    currentAverage = float(dataArray[0])

    averageArray.append(currentAverage)
    print(currentAverage) #this line is as far as my question goes. Why does Python print out this number
                          #more slowly than Arduino sends it out????

A: Python is a scripting language. It runs through an interpreter and therefore runs very slowly. Although and Arduino micro-controller is very under-powered, it runs faster than your python because python is that much slower. Unless you are willing to have less frequent data points by increasing the Arduino delay, I don't think this can be solved. Good luck still!


text:
Q: Is there any way I can compare two sql strings to check if they are semantically equivalent? I am writing some Java unit tests and I need to compare two sql strings where the sql statements are semantically equivalent but can be syntactically different. I can't do string comparison since an order of the from clause and where clause can be different yet the two queries might be equivalent.
Is there anyway to do this in java without having to write my own Oracle SQL Parser ? :)
P.S. The query can be very complicated !
Thank you !

A: The general answer is NO, because you can always call some kind of stored procedure which hides a Turing machine.
The fact that you can do arithmetic in a SQL statement I think pushes you over the Turing cliff, too.
Of course, theorists always tell us everything is impossible, so we should all roll over and die.
Nah.
So what can you do?  Well, a "simple" possibility is to normalize the SQL queries, much as you simplify algebraic equations. If you could somehow, for a SQL statement, "normalize" (convert) it into the absolutely shortest equivalent SQL that did the same thing, then you could normalize both SQL statements and compare the result statements; if the they are equal modulo identifier renaming, then they have the same "semantics".   For every operator in SQL, there is some semantics behind it, and some set of equivalent operations, just as there is in algebra.  So, if you can determine the set of algebraic equivalences for each SQL operator, you can replace each algebraic computation by the shortest algebriac equivalent which does the same thing.
To do this, you have to be able to parse SQL, and apply SQL rewrites to the parsed SQL, which means you need a program transformation engine. (You can see an analog of this at Parsing and Rewriting Algebra)
This doesn't work in all cases.  First, there may be several same-length "shortest" SQL statements that are equivalent (2+X is the same as X+2 but it isn't obvious to a a tool). Now you've got a theorem proving problem (for our X+2 example, use the commutative law to prove they are equal), back to stuck in theory.  Second, you may not know how to generate the shortest possible sequence using your rewrites; even math equations sometimes have to swell up before they can get small again.  Technically you have to search all possible algebraic equivalences to find the shortest, and that's impossibly large.
So, hard to do in practice, too.  So, NO.

A: Not a direct solution for your problem, but you may want to look into JSqlParser which may already cover part of what you need.


text:
Q: Changing Text in JavaFX in another thread I have a time-consuming method that has to run on action of a button, and while I have that method running, I want the UI to be still active (i.e. the user can still interact with it). I have tried several solutions. One is to just run the method:
Label label = new Label("current text");
Button button = new Button("Button text");
button.setOnAction(event -> label.setText(runConputation())); // takes a long time

But that will lock the UI while it's running.
Another solution was to use a separate thread:
Label label = new Label("current text");
Button button = new Button("Button text");
button.setOnAction(event -> {
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            label.setText(runConputation()); // takes a long time
        }
    });
    thread.start();
});

But this throws an IllegalStateException: not in javafx thread or something similar.
I tried adding a Platform.runLater(), as I read that will fix the Exception:
Label label = new Label("current text");
Button button = new Button("Button text");
button.setOnAction(event -> {
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    label.setText(runConputation()); // takes a long time
                }
            });
        }
    });
    thread.start();
});

...but it locks the UI. It also looks ugly.
I tried to use Task as well:
Label label = new Label("current text");
Button button = new Button("Button text");
button.setOnAction(event -> {
    Thread thread = new Thread(new Task<Void>() {
        @Override
        public Void call() throws Exception {
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    label.setText(runConputation()); // takes a long time
                }
            });
            return null;
        }
    });
    thread.start();
});

With similar results.
I wanted to do something like:
Label label = new Label("current text");
Button button = new Button("Button text");
button.setOnAction(event -> {
    Task<String> task = new Task<String>() {
        @Override
        public String call() throws Exception {
            return runConputation();
        }
    };
    Thread thread = new Thread(task);
    thread.start();
    // wait until thread is done
    label.setText(task.getValue());
});

Is there a way to do this?


text:
Q: Derived table not allowed for delete My data looks like -
+-------+------------+------------+
|  ID   | START_DATE |  END_DATE  |
+-------+------------+------------+
| 12345 | 11/09/2008 | 02/02/2011 |
| 12345 | 11/09/2008 | 11/09/2008 |
| 12345 | 02/02/2011 | 12/31/9999 |
+-------+------------+------------+

How I want it to be -
+-------+------------+------------+
|  ID   | START_DATE |  END_DATE  |
+-------+------------+------------+
| 12345 | 11/09/2008 | 02/02/2011 |
| 12345 | 02/02/2011 | 12/31/9999 |
+-------+------------+------------+

Basically I am deleting the duplicates under column ID and START_DATE and keeping the latest END_DATE one
My Query - Using this I can see the duplicates
 SELECT * FROM (SELECT ID,START_DATE,END_DATE,
   ROW_NUMBER() OVER (PARTITION BY ID, START_DATE order by END_DATE desc) RN
 FROM MYTABLE) a WHERE a.RN>1

The above SELECT query works just fine but when I try to DELETE using same query like this -
 DELETE FROM (SELECT ID,START_DATE,END_DATE,
   ROW_NUMBER() OVER (PARTITION BY ID, START_DATE order by END_DATE desc) RN
 FROM MYTABLE) a WHERE a.RN>1

I get prompted with -

ERROR [42000] [Teradata][ODBC Teradata Driver][Teradata Database]
  Syntax error: derived table not allowed for delete.

My ask -
Is there a way I can delete those dupes without going into derived tables or any other way to transform the current query without using derived tables

A: If you don't have duplicates on (id, start_date, end_date), then you can do:
delete from mytable t
    where t.end_date < (select max(t2.end_date)
                        from mytable t2
                        where t2.id = tid and t2.start_date = t.start_date
                       );

A: You could delete record that first query selects and use their ID:
Delete from MYTABLE WHERE ID IN (
 SELECT ID FROM (SELECT ID,START_DATE,END_DATE,
   ROW_NUMBER() OVER (PARTITION BY ID, START_DATE order by END_DATE desc) RN
 FROM MYTABLE) a WHERE a.RN>1)


text:
Q: How to achieve this style of border? css only preferred I'm trying to get header effect like this:

I want the dotted border along the bottom of the element, with the background the same color as the dots.
I've tried looking up how to set up a border offset but haven't found anything that works for the look I'm trying to achieve. I've tried using an outline as well, only to find that the outline property can't be specific to a single edge.

A: Put a div underneath the box with a border-style of dashed:

.box-border{
    border-bottom:dashed 3px red;
}

https://jsfiddle.net/oo31w9x4/

A: You can use box-shadow as background.

div {
  color: white;
  box-shadow: inset 1000px 0px red;
  border-bottom: 1px dashed red;
}

the header


text:
Q: How to open a window without toolbars and addressbar? Is there a way to open ( via javascript ) a new window but without toolbar, addressbar, etc ?
I have tested this code:
window.open('http://example.it','example','height=300px,width=724px,resizable=1,alwaysRaised=1,location=1,links=0,scrollbars=0,toolbar=0');

but in Opera, it shows the bookmarks bar and the address bar.

A: Opera doesn't support hiding the bookmark or address bar. Here is one site that documents this, although it look old. A quick search brings up a lot of browser quirks with window.open(), and unfortunately, there probably aren't any workarounds since opening a window a certain way is strictly controlled by the browser.
Edit: I just found a page on the site I posted that says "Last update: April 28th 2012", so maybe the tacky old 90s look is just for fun.


text:
Q: Vue v-for no data display using Laravel and Vuejs Im using v-for and axios for displaying data but when I run my website, the data wont show but there are no errors in the console and in my vue developer tool, I can see the data in it. Can someone help me?

Users.vue

                          Id
                          Name
                          Email
                          Type
                          Created

                        {{user.id}}
                        {{user.name}}
                        {{user.email}}
                        {{user.type}}
                        {{user.created_at}}

script>
    export default {
       data() {
    return {

      users: {},
      form: new Form({
        id:'',
        name: "",
        email: "",
        password: "",
        type: "",
      })
    };
  },
  methods: {
      loadUsers(){
           axios.get("api/user").then(({ data }) => (this.users = data));
      }
  },
    created() {
            console.log('Component mounted.')
            this.loadUsers()

        }
    }

</script>

api.php
Route::apiResource('user', 'API\UserController');

UserController.php
<?php

namespace App\Http\Controllers\API;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return User::all();
    }

}

A: Try this...


text:
Q: How to turn images into thumbnail size using foreach loop in Wordpress Pods CMS I am using Wordpress Pods CMS and I have a foreach loop to show an unordered list of images.
I would like to turn the images into thumbnail size (using the WordPress media thumbnail settings in the dashboard).
My code currently look like this...

<?php
foreach ($thePod->get_field('images') as $photo) {
  echo "

";
}
?>
      <?php else:?>

no photos

      <?php endif;?>

I tried putting .... "{$photo['guid'], 'thumbnail'}" but that doesn't work and I know this usually works ... "wp_get_attachment_image_src($image['0']['id'], 'thumbnail');" when I want to display one image only.

A: try this:
foreach ($thePod->get_field('images') as $photo) {
  $thumbnail = wp_get_attachment_image_src( $photo[ID], 'thumbnail' );
  echo "

";
}

mkm


text:
Q: Query Hive (SQL) between start of day and end of day Given a date, I'd like to query Hive between the start and end of that day. How do I calculate the beginning and end of day in hive?
So instead of:
SELECT *
FROM blah
WHERE created_at > '1437940563'
AND created_at < '1438026982';

It would be:
SELECT *
FROM blah
WHERE created_at > '<some function DATEID>'
AND created_at < '<some function DATEID>';


text:
Q: MySQL query to get count of current month and last month to get percentage of growth What im trying to achieve is to get the current count and last month count so i can do a formula to get the growth percentage
(CountCurrent - CountLastMonth) / CountLastMonth

My table has the following fields
activity, upload_date

This is the query im trying now.
SELECT
        Y.CurrentMonth,     Y.CountCurrent,
        Z.LastMonth,  Z.CountLastMonth

 FROM
        (SELECT
        upload_date,
        activity,
            DATE_FORMAT(upload_date,'%M %Y') AS CurrentMonth,
        COUNT(activity) AS CountCurrent
            FROM appmaster
            WHERE activity = 'com.google.test'
            GROUP BY DATE_FORMAT(upload_date,'%m%y'))
    Y INNER JOIN
        (SELECT
        activity,
        DATE_FORMAT(upload_date,'%M %Y') AS CurrentMonth2,
            DATE_FORMAT(upload_date - INTERVAL 1 MONTH,'%M %Y') AS LastMonth,
            COUNT(activity) AS CountLastMonth
        FROM appmaster
        WHERE activity = 'com.google.test'
        GROUP BY DATE_FORMAT(upload_date - INTERVAL 1 MONTH,'%m%y'))
    Z ON Z.CurrentMonth2 = Y.CurrentMonth

GROUP BY DATE_FORMAT(upload_date,'%Y%m')
ORDER BY DATE_FORMAT(upload_date,'%Y%m')

My CurrentMonth, CountCurrent and LastMonth work fine. But the CountLastMonth is coming out the same as CountCurrent.
I was trying this before and it would give me everything but the CountLastMonth
SELECT b.CurrentMonth, sum(b.CountCurrent), b.LastMonth
FROM (SELECT DATE(a.upload_date - INTERVAL 1 MONTH) AS LastMonth, DATE(a.upload_date) AS CurrentMonth, COUNT(a.activity) AS CountCurrent
FROM appmaster a WHERE a.activity = 'com.google.android.googlequicksearchbox'
group BY MONTH(a.upload_date)) AS b

group BY MONTH(b.CurrentMonth)

A: Maybe there's a simpler way to do this, using a little trick with user variables.
First, you need to write a query that groups your data by month; I'll store it in a temp table to ease things a bit:
drop table if exists temp_count;
create temporary table temp_count
select last_day(upload_date) as month -- A little trick to get
                                      -- the last day of the month
     , count(activity) as count_current
     -- Add any other fields or expressions you need
from app_master
-- Add the needed joins
-- Include any WHERE conditions here
group by last_day(upload_date);
-- Let's add an index to this temp table... add any indexes you may need
alter table temp_count
    add index idx_month(month);

And now, let's use this temp table to get what you need:
select a.month
     , @count_last as count_last    -- This is the value of the user variable
                                    -- before reassigning it
     , (a.count_current - @count_last) / @count_last as increment
     , @count_last := a.count_current -- Here the variable is updated with the
                                      -- current value
from
    (   -- This subquery is used to initialize the user variable
        select @count_last := 0
    ) as init
    , temp_count as a
-- It's important to order the data, otherwise God knows what may happen ;)
order by a.month;

Hope this helps

A: No temporary table required:
SELECT
    a.ym,
    CASE @totals
        WHEN 0 THEN 0
        ELSE (a.totals - @totals) / @totals
    END increment,
    @totals := a.totals totals
FROM
    (
    SELECT
        EXTRACT(YEAR_MONTH FROM upload_date) ym,
        COUNT(1) AS totals
    FROM
        appmaster
    WHERE
        activity = 'com.google.test'
    GROUP BY ym -- no ORDER BY required
    ) a
CROSS JOIN (SELECT @totals := 0) x

A: Revenue growth over each month - This is based on the answer provided by Barranka but it is suitable for Monthly revenue growth:
 SELECT
  a.YM,
  CASE @Revenue
          WHEN 0 THEN 0
          ELSE (a.Revenue - @Revenue) / @Revenue
      END Increment,
      @Revenue := a.Revenue Revenue
     FROM
       (
        SELECT
        LEFT(payment_date, 7) YM,
        SUM(amount) AS Revenue -- Toatl is SUM of Amount
         FROM
          payment

      GROUP BY YM -- no ORDER BY required
       ) a
         CROSS JOIN (SELECT @Revenue := 0) x
 ;

SELECT
    a.YM,
    CASE @Revenue
      WHEN 0 THEN 0
      ELSE (a.Revenue - @Revenue) / @Revenue
 END Increment,
  @Revenue := a.Revenue Revenue
    FROM
 (
 SELECT
      EXTRACT(YEAR_MONTH FROM payment_date) YM,
      SUM(amount) AS Revenue
 FROM
      payment

 GROUP BY YM -- no ORDER BY required
 ) a
CROSS JOIN (SELECT @Revenue := 0) x
;

A:             #Rental number Growth per month -- This is the example for monthly growth where "Total count of activity per month" is concerned -- This answer was developed based on Barranka answer and credit goes to him.
        SELECT
            a.YM,
            CASE @Num_of_Rentals
                WHEN 0 THEN 0
                ELSE (a.Num_of_Rentals - @Num_of_Rentals) / @Num_of_Rentals
            END increment,
            @Num_of_Rentals := a.Num_of_Rentals Num_of_Rentals
        FROM
            (
            SELECT
                LEFT(rental_date,7) YM,
                COUNT(rental_id) AS Num_of_Rentals
            FROM
                rental
                GROUP BY ym -- no ORDER BY required
            ) a
        CROSS JOIN (SELECT @Num_of_Rentals := 0) x;

        -- OR
        SELECT
            a.YM,
            CASE @Num_of_Rentals
                WHEN 0 THEN 0
                ELSE (a.Num_of_Rentals - @Num_of_Rentals) / @Num_of_Rentals
            END increment,
            @Num_of_Rentals := a.Num_of_Rentals Num_of_Rentals
        FROM
            (
            SELECT
                LEFT(rental_date,7) YM,
                COUNT(1) AS Num_of_Rentals
            FROM
                rental
                GROUP BY ym -- no ORDER BY required
            ) a
        CROSS JOIN (SELECT @Num_of_Rentals := 0) x;


text:
Q: How to pass localized message from server to client? I have spring-mvc application.
On the server side inside controller methode I have wrote the following code:
return new ResponseEntity<>(messageSource
                        .getMessage("Common.wrongFileFormatOrSizeLimitExceeded", null, LOCALE_RU),
                        HttpStatus.NOT_EXTENDED);

On the server side in debug I see that
messageSource.getMessage("Common.wrongFileFormatOrSizeLimitExceeded", null, LOCALE_RU)

returns properly localized message.
on the client side I have the following code:
$.ajax({
        ....
        error: function (data) {
                    console.log(data.responseText);
               }

The client code write the following message to console:

???????????????????????????????????????

When I pass latin message from server - code works properly.
How to pass localized message from server to client ?


text:
Q: get sum and difference of fields from two tables I have two tables

*

*sales:

sale_date
total_amount

2021-03-24
59000

2021-03-24
25000

2021-03-25
88000

2021-03-25
10000

2021-03-26
67000

2021-03-27
99000

*credit_sales:

credit_sale_date
amount

2021-03-24
10000

2021-03-24
2000

2021-03-24
3000

2021-03-25
1000

2021-03-25
5000

2021-03-25
6000

2021-03-26
22000

2021-03-27
15000

Expected Result:

date
total_amount
cash_amount
credit_amount

2021-03-24

2021-03-25

2021-03-26

2021-03-27

total_amount is the sum of 'total_amount' from sales table of a particular date
credit_amount = sum of 'amount' from credit_sales table of the particular date
cash_amount = sum of 'total_amount' from sales table - sum of 'amount' from credit_sales table of the particular date

A: select
    sale_date as date, sum(DISTINCT total_amount) as total_amount, sum(DISTINCT amount) as credit_amount, sum(DISTINCT total_amount) + sum(DISTINCT amount) as cash_amount
from
    sales, credit_sales
where
    sales.sale_date = credit_sales.credit_sale_date
GROUP BY sales.sale_date

A: Union and group
select sale_date, sum(total_amount) as total_amount,
   sum(credit_amount) as credit_amount,
   sum(total_amount) - sum(credit_amount) as cash_amount
from (
    select sale_date, total_amount, 0 as credit_amount
    from sales
    union all
    select credit_sale_date, 0 as total_amount, amount as credit_amount
    from credit_sales
) t
group by sale_date


text:
Q: make an image to be center of the page when the page size is changed using bootstrap4? I need to add the thumbnail before the video using Jquery. I have added the image but when I change the page size the thumbnail is should be centered of the place As per the below image,

But, My image is responsive as below,

My Jquery,

$(document).ready(function () {
$("body").prepend('

');

    $('#thumbnailPlayIcon').on("click", function () {
     thumbnailClick($(this));
    });

    $('#llthumbnail').on("click", function () {
     thumbnailClick($(this));
    });

  });
<!DOCTYPE html>

 <meta http-equiv="X-UA-Compatible" content="IE=edge" />
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta charset="utf-8" />
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">

can any one please help me to resolve the issue?

A: To position the image container in the middle of the page use following style (note that you need to remove position: fixed; from image).
#thumbnailcontainer {
  position: relative;
  transform: translateY(-50%);
  top: 50%;
}

In the snippet (view in full screen) I added a
to emulate a larger page, which you should probably remove for your own page. Also you should keep the styles in a css file and HTML in html file, since it is hard to maintain a big blob in javascript.

$(document).ready(function () {
$("body").prepend('

');

    $('#thumbnailPlayIcon').on("click", function () {
     thumbnailClick($(this));
    });

    $('#llthumbnail').on("click", function () {
     thumbnailClick($(this));
    });

  });
#thumbnailcontainer {
  position: relative;
  transform: translateY(-50%);
  top: 50%;
}
<!DOCTYPE html>

 <meta http-equiv="X-UA-Compatible" content="IE=edge" />
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta charset="utf-8" />
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">


text:
Q: catopen() does not set errno when it fails in some cases catopen is failing to open same cat file in different servers, with same setup.
When errno is 0 it means no error from my understanding.
Please tell me if anyone has seen like this before.
If any one knows the reason why it is happening it will be very helpful for me
Sample code i wrote
int main()
{

   nl_catd cat;

   string fileName;

   cout<<"Enter the cat file name: ";

   cin>>fileName;

   cat = catopen(fileName.c_str(), 0);

   if (cat == (nl_catd)-1)

   {

      cerr << "Unable to open catalogue: " << fileName <<" ....and the Error number: "<<errno<<"\n";

      exit(1);

   }

   printf("File opened...\n");

   catclose( cat );

   exit(0);

}

Output for above code
For successful case:

./a.out

Enter the cat file name: LinkMonitor.epod.cat

File opened...

For faliure case:

./a.out

Enter the cat file name: ehap_ac_in.epod.cat

Unable to open catalogue: ehap_ac_in.epod.cat0

Here 0 is the error code.

A: You cleared errno when you wrote the string "Unable to open catalogue: " to cerr.
You have to save the value of errno straight away.
cat = catopen(fileName.c_str(), 0);

if (cat == (nl_catd)-1)

{
   int errno_catopen = errno;
   cerr << "Unable to open catalogue: " << fileName <<" ....and the Error number: "<<errno_catopen <<"\n";
   exit(errno_catopen);
}


text:
Q: Is it possible to detect when a user opens the chat window on Facebook? I'm trying to create a chatbot where in order to avoid the user opening the chat window and not knowing the available options, I want to give some basic instructions when the user opens the chat window.
Is there any trigger available when the user opens a chat window? Maybe then I can check, and if there's not an ongoing conversation I could provide basic instructions.
I did some googling and found nothing about this. Is it possible to do something like this, and if not, is there a way to mitigate this problem, and provide the user with information regarding the chatbot capabilities and supported instructions?

A: Facebook does not allow bots to initiate a conversation, unlike Skype or other platforms.
There are still some tricks you can do :

*

*Go on the Settings of your Facebook page, then Messaging and check "Show a Messenger Greeting" as below, and write your greeting sentence.

The result will look like this :

*

*You can also set a "Get Started" button to trigger an event.
Here's the doc :
"https://developers.facebook.com/docs/messenger-platform/thread-settings/get-started-button"

A: You can monitor for two event types: ConversationUpdate and ContactRelationUpdate.
The first one (ConversationUpdate) is called when a user is added or removed from the conversation. So, there's a place where you can introduce available options. It will be each type the new conversation has started. So, it may become annoying, you may add a check - do not show it if the user has been using the bot for some time.
The second (ContactRelationUpdate) is called when a user adds or removes the bot to/from the contacts. In general, it is only called once per user action.
Here's the extract from the Bot-Frameworks examples:
For Node.Js
bot.on('conversationUpdate', function (message) {
   // Check for group conversations
    if (message.address.conversation.isGroup) {
        // Send a hello message when bot is added
        if (message.membersAdded) {
            message.membersAdded.forEach(function (identity) {
                if (identity.id === message.address.bot.id) {
                    var reply = new builder.Message()
                            .address(message.address)
                            .text("Hello everyone!");
                    bot.send(reply);
                }
            });
        }

        // Send a goodbye message when bot is removed
        if (message.membersRemoved) {
            message.membersRemoved.forEach(function (identity) {
                if (identity.id === message.address.bot.id) {
                    var reply = new builder.Message()
                        .address(message.address)
                        .text("Goodbye");
                    bot.send(reply);
                }
            });
        }
    }
});

bot.on('contactRelationUpdate', function (message) {
    if (message.action === 'add') {
        var name = message.user ? message.user.name : null;
        var reply = new builder.Message()
                .address(message.address)
                .text("Hello %s... Thanks for adding me. Say 'hello' to see some great demos.", name || 'there');
        bot.send(reply);
    } else {
        // delete their data
    }
});

For C#
private void HandleMessage(Activity message)
{
    if (message.Type == ActivityTypes.ConversationUpdate)
    {
                if (activity.MembersAdded.Any(m => m.Id == activity.Recipient.Id))
                {
                    var connector = new ConnectorClient(new Uri(activity.ServiceUrl));

                    var response = activity.CreateReply();
                    response.Text = "Hi! I am Bot. Here's what you can do...";

                    await connector.Conversations.ReplyToActivityAsync(response);
                }
    }
    else if (message.Type == ActivityTypes.ContactRelationUpdate)
    {
        if (Activity.AsContactRelationUpdateActivity().Action ==                ContactRelationUpdateActionTypes.Add)
        {
                    var connector = new ConnectorClient(new Uri(activity.ServiceUrl));

                    var response = activity.CreateReply();
                    response.Text = "Hi! I am Bot. Thanks for adding me. Here's what you can do...";

        }
    }
    return null;
}

A: I think the acid answer is not.
But you can intercept the IConversationUpdateActivity type message to know if the user has added the bot to a conversation. In the C# project template you can find a code block that ask for this message type but do nothing.


text:
Q: How to deal with Exceptions in C++ programming when there are a lot of memory allocation I am a novice in the field of C++ program and I read the book More Effective C++. There is one specific section about how to deal with C++ exceptions. In terms of the item 10, the author claims that we should avoid the memory leak in the constructors as the following example.
BookEntry::BookEntry(const string& name, const string& address,
                    const string& imageFileName,
                    const string& audioClipFileNmae):theName(name), theAddress(address),
                    theImage(0), theAudioClip(0) {
    try {
        if (imageFileName != "") {
            theImage = new Image(imageFileName);
        }
        if (audioClipFileName != "") {
            theAudioClip = new AudioClip(audioClipFileName);
        }
    }
    catch (...) {
        delete theImage;
        delete theAudioClip;
   }

In this way, we can avoid the source leak when there is an error of creating theImage or theAudioClip. My question is that if there is a lot of functions which contains memory allocation as the following.
void BookEntry::test1() {
    float *A = new float[1000];
    float *B = new float[1000];

    ....
    delete [] A;
    delete [] B;
}

Do I have to use the try catch structure to deal with the danger of memory leak? Usually, I prefer to just testing whether the pointer A and pointer B are null pointer or not and if the allocation fail, I will abort the program immediately.

A: You are probably misunderstanding what the book meant by "memory leak". A failure to allocate may be the eventual result of a memory leak, but the two things are not the same.
What the book is talking about is what happens if AudioClips constructor fails. Not the memory allocation of AudioClip, but AudioClip's constructor. Because remember, constructors only have one way to signal failure: throwing an exception.
If it throws, and someone in the call stack of your BookEntry constructor invocation catches that exception, then the previously allocated theImage will never be cleaned up. BookEntry's constructor never successfully completed, so its destructor will never be called (since the object never existed, you can't delete it).
This is why nowadays (aka: post-C++11), we would store those allocated members in smart pointers. While BookEntry's destructor will never be called, the destructors for any of its successfully constructed subobjects will be called. So if theImage is a unique_ptr<Image>, its destructor will be called, which will delete the Image it holds.

Usually, I prefer to just testing whether the pointer A and pointer B are null pointer or not and if the allocation fail, I will abort the program immediately.

Then exceptions for memory allocation failure are even better for you, since you don't have to test for anything. You just let the allocation failure exception reach main, and your program will terminate.
However, the above issue is not about allocation failure exceptions.


text:
Q: Cocoa app, Xcode Console - Red Numbers I'm trying to debug an application that compares up to 9 numbers in a certain way. It's working great for up to 4 or more numbers but once you try an run 3 or less it starts returning a NaN error where it should be returning a zero.
I'm working through the console and ~20% of the numbers are highlighted in red. Before I get to checking the code here I wanted to see what the red vs black numbers mean and if that applies to what I'm looking for. I don't think it applies because when the application is working correctly as I go through the debugger some of the numbers are still red. However I still would like to learn.
If it's something obvious I apologize because I'm both starting out and just letting Xcode do the memory management.
Thanks in advance!
Graham
** Edit
I'm not too worried about debugging right now, I want to give it an honest college try before I come back for help but the error is coming when I use a combination of 5000/3000/5500. It's not limited to that specific arrangement and I have it narrowed down to one of my functions.
As shown it is giving me the correct number in the +/- which is the end and I've run about 10 scenario's that are all correct as long as there is more than 4 stacks.
As asked it is in the test phase and I should have mentioned that it was my variables that are colored.

A: That's not a console. That's the debugger. The red values are values that have changed. It lets you easily see how the values change over time by drawing your eyes to the interesting rows.


text:
Q: When Worklight Adapter release java Objects? I have Worklight HTTP Adapter, which creates Java Object, this object makes connection with DB, fire specified query and returns result to adapter, which in turn returns the result to mobile application.
The Java Object closes connection of Database in finalize method, but problem is that finalize method have not been called even after finishing the adapter call.
I have also assigned null to object before returning from adapter.
Hence, I want to know when the Adapter releases Java Object, and when its finalize method will be Called?

A: JavaDoc says about finalize():

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

So, your finalize method invokes when GC will start.


text:
Q: checking if a array value is not empty without php warnings I'm using Zend_Form subclasses to pass array of data to my controllers and sometimes I need some extra logic in the controllers, as such:
$post = $request->getPost();
if (array_key_exists('signatureData', $post) && !empty($post['signatureData'])) {
   ...
}

To avoid getting php warnings, first, I need to check if the signatureData key exists and only then I can check if the value is not empty.
Anyway I can make this IF statement a little shorter without adding custom php function?

A: Accepted standard :
if (isset($post['signatureData']) && !empty($post['signatureData']))

Apparently, this is also possible :
if (!empty($post['signatureData']))

-edit-
If you're really lazy, there's a dirty way :
if (@$post['signatureData'])

I'd recommend against it though.
As pointed out in the comments, don't actually use this. It's bad, bad, bad bad, bad. Really though, please don't ever use it. It's only here as a reference.

A: Using zf, use this
If ($request->getParam('signatureData', false))

Best practice IMO


text:
Q: HTML tags' placement change using javascript I want to make a swap button or any button whenever it is clicked, tags' placement changes.
For example,

h11

h22

h33

Whenever the up button is clicked, it becomes

h22

h11

h33

Whenever the down button is clicked, it becomes

h11

h33

h22

Is it possible to swap the tags' placement?
Thank you!

A: It's a little goofy since there isn't an insertAfter method.

function move(id, direction) {
  let el = document.getElementById(id);
  let next = el.nextElementSibling == null ? null : el.nextElementSibling.nextElementSibling;
  let prev = el.previousElementSibling;

  if (direction === 'down') {
    el.parentElement.insertBefore(el, next);
  } else {
    if (prev) el.parentElement.insertBefore(el, prev);
  }
}
<link href="//cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" rel="stylesheet" />

h11

h22

h33

h44

h55

h66

<button onclick="move('1', 'down')">Down</button>
<button onclick="move('1', 'up')">Up</button>

A: You can use flex-box for changing the order of elements

.flex-container {
  display: flex;
  flex-direction: column;
}

.first-item {
  order: 2;
}
.second-item {
  order: 3;
}
.third-item {
  order: 1;
}

I'm first

I'm second

I'm third

So you will need the only change the class name.


text:
Q: Discrete stochastic integral and optional sampling theorem I want to prove the optional sampling theorem using the fact that discrete stochastic integrals for martingale integrators are still martingale.
To prove: if $(M_t)_{t\in T}$ is a martingale and $\sigma,\tau$ stopping times, then $\mathbb{E}[M_\tau\mid \mathcal{F_\sigma}]=M_{\sigma\wedge\tau}$
As hint I have that it is convenient to use the martingale $(M_t-M_{t\wedge \tau})_{t\in T}$ and stop it with respect to $\sigma$.
So by considering the predictable function $1_{t\leq \sigma}\in\mathcal{F}_{t-1}$ I consider the stochastic integral $(V\cdot M)_t= \int_0^t 1_{s\leq\sigma}d(M_s-M_{s\wedge \tau})=(M_{t\wedge \sigma}-M_{t\wedge\tau\wedge \sigma})$ which is a martingale. But now I am confused since I have that $\mathbb{E}[M_\tau\mid\mathcal{F}_\sigma]=M_{\sigma\wedge\tau}$. Am I doing all right here or am I doing some mistake? Thanks


text:
Q: Confusion about System.Data.SQLite.dll The site, http://sqlite.phxsoftware.com/, talks about a mixed-mode assembly and a managed-only version of the provider.  Are they both named System.Data.SQLite.dll?  I installed the managed-only version in windows and it is working.  Which, as I understand it, means that I must also have the native sqlite3.dll file somewhere on my machine that it is finding, right?
When I try to get my assembly to run on Linux with Mono, I get an EntryPointNotFoundException looking for sqlite3_open_v2.  So I downloaded the precompiled shared-library for Linux without the TCL bindings from http://www.sqlite.org/download.html and placed it in the same folder as the other assemblies.  But that didn't change anything.
The page at http://www.mono-project.com/Interop_with_Native_Libraries says Linux will look at my LD_LIBRARY_PATH environment variable.  So I set that to contain '.', the current directory.  That didn't work either.
So then I copied sqlite-3.6.19.so to sqlite-3.so, sqlite3.so and sqlite.so.  Still no change.
What am I missing?

A: Instead of using System.Data.SQLite.dll on Windows and Linux, I decided to use Mono.Data.Sqlite.dll on both sides.