text:
Q: Text-Wrapping in D3 I've been researching for a while about text-wrapping, but a lot of them involve using css to text wrap?
Is there any way that I can use D3 to text wrap something like this:
  p.append("text")
   .attr("transform", "translate(-20, -30)")
   .text("Relevance")
   .style("font", "bold 12px Arial");

A: I assume p is not already an xhtml element here. If it's some svg element like g you may append foreignObject to it and then afterwards append xhtml elements like div like in following code.
p = svg.append('g');
p.append("foreignObject")
 .attr("x", 5)
 .attr("y", 5)
 .attr("width", 100) // replace with width you want
 .attr("height", 100)// replace with height you want
 .append("xhtml:div")// replace with html element you want
 .append("p")
 .text("Relevance");

A: The other answers recommend using svg:foreignObject. Sadly no version of IE supports foreignObject, not even the latest (being 11 at the time of writing). Support across other browsers is inconsistent with some not supporting transitions. So, if you don't need transitions and don't need to support IE then you can use the foreignObject; it's the easiest method because it supports HTML + CSS.
Otherwise, if you need IE support or transitions...
Mbostock has an example for Wrapping Long Labels. It can be adapted for wrapping text in other situations, though it's not trivial.
D3plus supports text wrapping like so:
d3plus.textwrap()
  .container(d3.select("#rectWrap"))
  .draw();

I've used D3plus. It's very easy to use. But D3plus has other features you probably don't want so you might also consider d3textwrap, a plugin that only adds text wrapping.

A: You need to use svg:foreignObject with an HTML div or similar to make this work. SVG itself won't wrap the text.


text:
Q: Preserving cell properties between cells while using dequeueReusableCellWithIdentifier My application is a feed based application (think Instagram). Actually, it is very similar to Instagram - the difference is that instead of a picture, there is a swipeable, paginated view with different objects (link to demo):
https://www.youtube.com/watch?v=EYTjA3Bcv_A&feature=youtu.be

The swipeable functionality originates from this class: https://github.com/nicklockwood/SwipeView
In my UITableViewController class I am trying to remain efficient with my memory by implementing tableView.dequeueReusableCellWithIdentifier. The problem this creates is that as you scroll and cells are being dequeued, the reusable nature of the cells carries over old data. My problem is that I want to preserve which object in the SwipeView a user had swiped to while still implementing tableview.dequeueReusableCellWithIdentifier.  The property of the SwipeView that deals with this is currentItemIndex. This manages which item is currently centered in the SwipeView. Naturally, each SwipeView in the feed should remember its own currentItemIndex, however dequeueing cells carries over the old currentItemIndex from the cell that is being reused. This can be reset: cell.swipeView.currentItemIndex = 0 while setting up the new (reused) cell, however then the old cell loses its currentItemIndex when it gets reused. Video of original problem: http://youtu.be/CXTHyvF3adI (see how the old currentItemIndex is transferred between SwipeView cells)  Video of problem when currentItemIndex is reset when a cell is reused: http://youtu.be/VBw8Rm-s5Qk (see how the SwipeView cells don't remember which item they were swiped to)  Does anyone have an idea on how I can accomplish this? Thanks to all in advance!

A: That is what PrepareForReuse method is for

redpajama_set_name: RedPajamaStackExchange


text:
Q: Has anyone managed to install Python modules using Iron Python? I have been trawling the net looking for info on installing Python modules (eg. Setuptools) into Iron Python. The general consensus was that it was a work in progress a couple of years ago. Has anyone has any luck?
Thanks,
Chris

A: You cannot use CPython modules with IronPython.
It is possible to use regular Python scripts as long as they are not importing any C modules.
The Idea with Iron Python is to use .NET assemblies. And for an equivalent you will probably be using something like Nuget in .NET and just reference and import the .NET assemblies.
Also I think your question has been answered here.


text:
Q: UIPopoverController frame overlapping its contentView's UINavigationBar Any idea how to shift the navbar view so I have the expected padding? It looks like the popover frame is overlapped on the nav bar's top, left and right side.
This is my nav controller in a popover controller derived from the app's root splitViewController. It's an issue on < iOS 5.1

A: The solution is to remove the custom UINavigationBar styling when in a UIPopoverController. I'll post the implementation when it's ready.
Update
So this is a funny one. iOS 4.x and iOS 5.0 use a real, genuine popover, that is the floating popover. Custom navigation bars don't work in this popover (navBar setBackgroundImage in iOS 5.0 and the category drawRect override in iOS 4.x).
However, 5.1 uses more of a "slideover," where the custom navbar works nicely. It's a much cleaner design actually.
Anyway, my point is that now I need to remove the custom navBar formatting only when in portrait AND the OS is less than 5.1. Normally, you'd want to use respondsToSelector in lieu of manually figuring out an OS version. That doesn't work in this case.
Still working on the iOS 4.x fix, but here's iOS 5.0:
In my appDelete, where I set up the custom navBar:
//iOS 5.x:
if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)])
{
    UIImage *image = [UIImage imageNamed:@"header.png"];
    [self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
}

//iOS 4.x:
@implementation UINavigationBar (CustomBackground)
- (void)drawRect:(CGRect)rect
{
    UIImage *image = [UIImage imageNamed:@"header.png"];
    [image drawInRect:CGRectMake(0, 0, 320, 44)];
}
@end

I set up an observer in didFinishLaunching:
//start orientation notifications
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(didRotate:)
                                             name:@"UIDeviceOrientationDidChangeNotification"
                                           object:nil];
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];

- (void) didRotate:(NSNotification *)notification
{
    float version = [[[UIDevice currentDevice] systemVersion] floatValue];

    if (version < 5.1)
    {
        UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];

        if (UIDeviceOrientationIsPortrait(orientation))
        {
            if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)])
            {
                [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
            }
        }
        else
        {
            if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)])
            {
                UIImage *image = [UIImage imageNamed:@"header.png"];
                [self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
            }
        }
    }
}


text:
Q: What is the 'this' equivalent of $scope.$apply in AngularJS? In AngularJS there are two styles of writing controllers, the "the controller as syntax" and the "'attach to $scope' style of controller" (both quotes from the ngController documentation.) There are several questions on StackOverflow comparing these styles, for example this vs $scope in AngularJS controllers and Performance differences between controller functions defined on $scope or this - AngularJS.
I have a method on a controller which needs to prompt AngularJS after a model update. Using the $scope style of controller I can do that thus:
myApp.controller('MainController', ['$scope', function($scope) {
    $scope.content = "[Waiting for File]";
    $scope.showFileContent = function(fileContent) {
        $scope.content = fileContent;
        $scope.$apply();
    };
}]);

But if I write the controller using 'this'
myApp.controller('MainController', function () {
    this.content = "[Waiting for File]";
    this.showFileContent = function(fileContent){
        this.content = fileContent;
    };
});

how do I invoke $apply()?

A: If you really need $scope, you still can inject it. Assuming "controller as" syntax:
myApp.controller('MainController', function($scope) {
   this.content = "[Waiting for File]";
   $scope.$apply(); // etc.
});

The question is, do you really need to run $scope.$apply() there? Assuming you are using it properly in "controller as" syntax, it should see it:

{{main.content}}

Then div#content will be updated when you update your this.content var. Mind you, you need to be careful of how you use this, so you might need:
myApp.controller('MainController', function($scope) {
   var that = this;
   this.content = "[Waiting for File]";
   this.showFileContent = function(fileContent){
       // 'this' might not be set properly inside your callback, depending on how it is called.
       // main.showFileContent() will work fine, but something else might not
       that.content = fileContent;
   };
});


text:
Q: Loop through Ansible variable in in .j2 file I have one ansible var list defined in group_vars
member_list:
        - a
        - b

I have one proxy.j2 template
{% for var in members_list %}
server {

server_name {{ var }}-{{ server_name }};
{% endfor %}

How could I loop through that list to get the value in .j2 file?

A: You should be using {{ item }} instead of {{ var }}.


text:
Q: How to get proper placed closing German doublequotes using lua|xelatex and Garamond Premier Pro Opticals (Regular)? Using Adobe's Garamond Premier Pro Opticals (latest version: 2.104) the closing German doublequotes are set exactly above (instead of behind) a sentence's closing dot (e.g. questionmark is not affected). The red mark within the following screenshot shows the result. The screenshot also shows that only the Regular-shape seems to be affected, as the output using Subhead-sizes and Caption-sizes is fine (see the green marks):

System environment: Windows 7 Pro 64-bit
Tex environment: texlive 2014; lates updates (frozen); lualtex or xelatex
Font: GaramondPremrPro Version 2.104;PS 2.000;hotconv 1.0.70;makeotf.lib2.5.5900
Minimum Working Example:
\documentclass[12pt]{article}

\usepackage{fontspec}
%\setmainfont{Times New Roman}
\setmainfont{Garamond Premier Pro}

\usepackage{polyglossia}
\setdefaultlanguage[babelshorthands=true,variant=german,spelling=new]{german}
\setotherlanguage[variant=british]{english}
\setotherlanguage{french}

\usepackage[autostyle=true,german=quotes]{csquotes}

\newcommand{\testOutput}{%
    "`Hallo Welt."' (old school)

    \enquote{Hallo Welt.} (enquote)

    \enquote{Hallo Welt,} (enquote)

    \foreignquote{english}{Hello World.} (foreignquote, en.)

    \foreignquote{french}{Salut tout le monde.} (foreignquote, fr.)

    \hrulefill
}

\begin{document}

\noindent
GaramondPremierPro-Regular:

\testOutput

\Large
\noindent
GaramondPremierPro-Subhead:

\testOutput

\tiny
\noindent
GaramondPremierPro-Caption:

\testOutput

\end{document}

With a comma instead of the dot, the result seems to look better to me, but far from excellent (in direct comparison to the subhead- or caption-size).
Question(s): Can you reproduce the output? If so, what's the most probable cause and what should be the next steps to further narrow the cause? And what could be a proper solution or at least a workaround?

A: I won't consider this as a bug. It's kind of common sense for – at least some – designer/typographers to kern the period and a quotations mark in that way. The amount of necessary kerning depends on the typeface and is subjective to the designer's eye, though.
On my system all optical sizes apply the same kerning:

In XeTeX you can define custom kerning between (groups/classes) of letters:

*

*Switch on custom kerning:
\XeTeXinterchartokenstate = 1

*Define a new class with:
\newXeTeXintercharclass <classmacro>

*Add letters to a class:
\XeTeXcharclass <letter code> = <classmacro>

To add a letter not by it's code but directly use a back tick, e.g. `"

*Add extra tokes (e.g. kerning) between tow classes:
\XeTeXinterchartoks <classmacro 1> <classmacro 2> = <tokens>

Note that the classes must be in the same rode as the letters would appear in the document.
Add this code to your example, to "fix" the kerning:
\XeTeXinterchartokenstate=1

\newXeTeXintercharclass \kernclassRQuote
   \XeTeXcharclass `" = \kernclassRQuote

\newXeTeXintercharclass \kerncharclassDot
\XeTeXcharclass `. = \kerncharclassDot
\XeTeXcharclass `, = \kerncharclassDot

\XeTeXinterchartoks \kerncharclassDot \kernclassRQuote = {\kern-0.05em}

As I said, the value you prefer is not necessarily the "right" one for others ;-)

A: I don't know what negative side effects this ugly workaround will cause, but it seems to work (tested with lualatex):
\enquote{Hallo Welt\mbox{.}}
Are there better alternatives?
Yes, next to Tobi's answer that addresses xeLaTeX the following solution is compatible with luaLaTeX. It implements a font feature file that introduces two additional features that are bound to regular-size (upright and bold). They are called:

*

*kruq (kern regular upright quotedblleft)

*krbq (kern regular bold quotedblleft)

The following MWE shows the details - the kerning spaces (900 - 1600) are very large, just to visualize the differences. You should be able to easily adept and extend them to your needs:
\documentclass[12pt]{article}

\usepackage{filecontents,fontspec}

\begin{filecontents*}{gpp20104.fea}
languagesystem DFLT dflt;
languagesystem latn dflt;

lookup reg_up_quotedblleft {
    pos [period ellipsis]' 1600 quotedblleft;
    pos comma' 1200 quotedblleft;
} reg_up_quotedblleft;

lookup reg_bd_quotedblleft {
    pos [period ellipsis]' 1200 quotedblleft;
    pos comma' 900 quotedblleft;
} reg_bd_quotedblleft;

feature kruq {
    lookup reg_up_quotedblleft;
} kruq;

feature krbq {
    lookup reg_bd_quotedblleft;
} krbq;
\end{filecontents*}

\setmainfont[%
FeatureFile=gpp20104.fea,
Extension = .otf ,
Path=C:/GaramondPremrPro/ ,
BoldItalicFont = {*-BdIt},
BoldFont = {*-Bd},
ItalicFont = {*-It},
UprightFont = {*},
UprightFeatures = {%
    SizeFeatures={%
        {Size={-8.9},Font={*-Capt}},
        {Size={8.91-14.9},Font={*},RawFeature={+kruq}},
        {Size={14.91-22.9},Font={*-Subh}},
        {Size={22.91-},Font={*-Disp}},
    },%
},%
ItalicFeatures = {%
    SizeFeatures={%
        {Size={-8.9},Font={*-ItCapt}},
        {Size={8.91-14.9},Font={*-It}},
        {Size={14.91-22.9},Font={*-ItSubh}},
        {Size={22.91-},Font={*-ItDisp}},
    },%
},%
BoldFeatures = {%
    SizeFeatures={%
        {Size={-8.9},Font={*-BdCapt}},
        {Size={8.91-14.9},Font={*-Bd},RawFeature={+krbq}},
        {Size={14.91-22.9},Font={*-BdSubh}},
        {Size={22.91-},Font={*-BdDisp}},
    },%
},%
BoldItalicFeatures = {%
    SizeFeatures={%
        {Size={-8.9},Font={*-BdItCapt}},
        {Size={8.91-14.9},Font={*-BdIt}},
        {Size={14.91-22.9},Font={*-BdItSubh}},
        {Size={22.91-},Font={*-BdItDisp}},
    },%
},%
]{GaramondPremrPro}

\usepackage{polyglossia}
\setdefaultlanguage[babelshorthands=true,variant=german,spelling=new]{german}

\usepackage[autostyle=true,german=quotes]{csquotes}

\newcommand{\hw}{Hallo}
\newcommand{\hwplain}{"`{\hw}"'}
\newcommand{\hwperiod}{"`{\hw}."'}
\newcommand{\hwcomma}{"`{\hw},"'}
\newcommand{\hwscolon}{"`{\hw};"'}
\newcommand{\hwcolon}{"`{\hw}:"'}
\newcommand{\hwellip}{"`{\hw} \ldots"'}
\newcommand{\hwquest}{"`{\hw}?"'}
\newcommand{\hwexcla}{"`{\hw}!"'}
\newcommand{\testOutput}{%
    {\hwplain} \emph{\hwplain} \textbf{\hwplain} \emph{\textbf{\hwplain}}\\
    {\hwperiod} \emph{\hwperiod} \textbf{\hwperiod} \emph{\textbf{\hwperiod}}\\
    {\hwcomma} \emph{\hwcomma} \textbf{\hwcomma} \emph{\textbf{\hwcomma}}\\
    {\hwscolon} \emph{\hwscolon} \textbf{\hwscolon} \emph{\textbf{\hwscolon}}\\
    {\hwcolon} \emph{\hwcolon} \textbf{\hwcolon} \emph{\textbf{\hwcolon}}\\
    {\hwellip} \emph{\hwellip} \textbf{\hwellip} \emph{\textbf{\hwellip}}\\
    {\hwquest} \emph{\hwquest} \textbf{\hwquest} \emph{\textbf{\hwquest}}\\
    {\hwexcla} \emph{\hwexcla} \textbf{\hwexcla} \emph{\textbf{\hwexcla}}%
}

\begin{document}

\tiny
\noindent
Caption:\\
\testOutput

\normalsize
\noindent
Regular:\\
\testOutput

\Large
\noindent
Subhead:\\
\testOutput

\Huge
\noindent
Display:\\
\testOutput

\end{document}

Update:
Instead of loading the FeatureFile globally, it can be loaded locally within the size-block, right before the RawFeature option:
{Size={8.91-14.9},Font={*},FeatureFile=gpp20104.fea,RawFeature={+kruq}}
Advantage: Slightly faster compilation as not every font loads unused features (you can compare the amount of font-lua-files in texmf-var\luatex-cache\generic\fonts\otf\*.lua, with locally asserted FileFeatures only two *-gpp20104.lua files should be present).
The additional kerning problems regarding e.g. colon I mentioned before (see my comment below the question) are not caused by the font's kerning table: The cause seems to be csquote's \foreignquote{}{} which does not switch back to the default language automatically. Perhaps I'll ask a new question - I did so.


text:
Q: How to shift bits in a color (hex value) I have the following hex value store in a variable:
0x04a8f5

I want to convert the value to:
0xff04a8f5

How can I accomplish this?
I've tried to do this by the following operation:
int result = 0x04a8f5 >> 8;

A: Use the following example as a guideline.
val = 0x04a8f5; //Your value
val |= 0xFF000000; //OR 0xFF000000 with your value, and assign the new value to val

Note, this isn't bit shifting because if your original value is a 32 bit (or larger) integer, then there is already a higher order byte available that can store the FF value.  In other words, your original variable is actually 0x0004a8f5. Using an |= assignment will OR FF with the byte that you are wanting to change.  No shifting necessary.
Also, shifting 0x0004a8f5 by 8 bits would result in 0x000004a8.

A: Because you want to prepend FF (1111 1111) to the front of your number, this isn't really a bit shift at all. You are just adding a constant to your color value.
As long as your color value is never going to take more than 6 hex digits to represent, you can just do:
color |= 0xFF000000


text:
Q: PHP y MySql Login, descifrar Tengo esto en la base de datos:

Pero al hacer el login en el formulario, no me lo hace bien. Se que puede ser la contraseña, porque en la base de datos esta cifrada, una de las soluciones es cifrar la contraseña que meto en el login de la pagina web, para despues compararla con la de la base de datos, ¿pero que tipo de cifrado es el que hace en la base de datos? Acepto otro tipo de soluciones

Este es mi archivo inicio_sesion.php:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login y Registro</title>
    <link rel="stylesheet" href="estilo.css">

Nos alegramos de verte

BIENVENIDO

Lorem ipsum dolor sit amet consectetur adipisicing elit. Quo quia nemo rem dolor eos illo. Modi quos adipisci aperiam temporibus nulla maxime error itaque eveniet iusto, voluptatem inventore explicabo repellat?

                <form action="" id="formulario_ini" method="POST">

Iniciar Sesion

                    <input type="text" name="name" placeholder="Correo Electronico" class="silvia3">
                    <input type="password" name="password" placeholder="Contraseña" class="silvia4">
                    <input type="submit" value="Inicar Sesion" id="inicio" name="enviar">

¿No tienes una cuenta?
Registrarse
                </form>
                <?php
                include ("conexion.php");
                $acentos = $conexion->query("SET NAMES 'utf8'");

                    if(isset($_POST['enviar'])){

                        $name = $_POST['name'];
                        $password = $_POST['password'];

                        //$filas = mysqli_num_rows($resultado);

                            if(strlen($name)==0 || strlen($password)==0){
                                echo"El usuario y la contraseña son obligatorios";
                            }else{
                                $query = "SELECT * FROM `users_table` WHERE `name`='".$name."' && `password`='".$password."'";
                                if(!$consulta = $conexion->query($query)){
                                    echo "ERROR: no se pudo ejecutar la consulta!";
                                }else{
                                    $filas = mysqli_num_rows($consulta);
                                    if($filas == 0){
                                        echo"";
                                    }else{
                                        echo"";
                                    }
                                }
                            }
                    }
                ?>

Este es el codigo de registrar usuario, lleva un password_hash y dentro la que es por defecto:
<?php

if ($_SERVER['REQUEST_METHOD'] =='POST'){

    $name = $_POST['name'];
    $email = $_POST['email'];
    $password = $_POST['password'];

    $password = password_hash($password, PASSWORD_DEFAULT);

    require_once 'connect.php';

    $sql = "INSERT INTO users_table (name, email, password) VALUES ('$name', '$email', '$password')";

    if ( mysqli_query($conn, $sql) ) {
        $result["success"] = "1";
        $result["message"] = "success";

        echo json_encode($result);
        mysqli_close($conn);

    } else {

        $result["success"] = "0";
        $result["message"] = "error";

        echo json_encode($result);
        mysqli_close($conn);
    }
}

?>

A: Usa la función password_verify(), ya que estás usando la función password_hash(), no hay forma de descifrar la contraseña, pero sí puedes comparar el texto que envías desde el login con el hash que tienes en DB, aquí un ejemplo:
<?php
    $hash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';

    if (password_verify('ejemplo123', $hash))
    {
        echo '¡La contraseña es válida!';
    }
    else
    {
        echo 'La contraseña no es válida.';
    }
?>

Fuente: https://www.php.net/manual/es/function.password-verify.php


text:
Q: Available commands for including LaTeX version information in document Already asked, it's possible to include the version of LaTeX in a PDF using \pdftexbanner. However, this is only one command. Is there a similar selection of commands as those presented for ConteXt to allow more customization of the version information used in the document?
On my machine, \pdftexbanner produces:
This is pdfTeX, Version 3.14159265-2.6-1.40.16 (TeX Live 2015/MacPorts 2015_9) kpathsea version 6.2.1

which is too verbose for my desired use.
Edit: it appears to be possible to programmatically extract substrings of \pdftexbanner, but this doesn't seem to be the most straightforward or portable solution to building a custom version string.


text:
Q: Turning down wireless button turns down external usb wireless. Lubuntu 12.10 I searched in other topics without luck.
I've got an Eeepc 1000h and lubuntu 12.10.
When I turn down my laptop wireless capability (FN+F2) it turns down the usb external antenna as well.
I don't want to exclude for ever my internal wireless (as suggested in other answers) I would like to turn down wireless with its button leaving USB-external-wifi ON. As it is intended to be.
Any chance to get this working?
Thanks in advance.
rfkill list all
0: asus-wlan: Wireless LAN
    Soft blocked: no
    Hard blocked: no
1: asus-bluetooth: Bluetooth
    Soft blocked: yes
    Hard blocked: no
2: phy0: Wireless LAN
    Soft blocked: no
    Hard blocked: no
4: phy2: Wireless LAN
    Soft blocked: no
    Hard blocked: no

A: Adding some infos.
With
sudo iwconfig wlan0 txpower off

it turns off both. Anyway in 20 seconds it turns on automatically. (and the led stays on, btw)
The only solution I can get by myself is to turn it down via BIOS. What an ugly workaroud :-(
Expert needed here!

A: Like exposed in another answer I actually use this workaround.
Add the following line to /etc/network/interfaces:
iface wlan0 inet manual

Then Restart. This disables internal Wifi. (or whatever you call wlan0).
If I need my internal wifi working again then I command out it with # and restart.
This is a very bad thing, but it works. Now, I can't believe in this community there isn't anyone that can't fix this to make it goes as it is supposed to do.
In Windows it's easy and immediate. Why couldn't be like that in Ubuntu?


text:
Q: Singleton in Linux with Shared Modules and Static Memory Access I have a process I am starting that is loading in multiple shared libraries. Some of the code in these shared libraries is the same (e.g. common files) and is using a singleton setup. e.g.
class MySingleton
{
  public:
    static MySingleton& GetInstance()
    {
      static MySingleton singleton;
      return singleton;
    }

    // ...
  private:
    // ...
}

I have run into a problem now where this MySingleton class is only being initialized once and being shared between the modules in memory (since they are being loaded into the same process). This seems to be a Linux specific problem, as I have had no issues with this on Mac OS or Windows where the application has been functioning fine.
To further emphasize/clarify the question, I have the following code for instance:
// module 1
MySingleton::GetInstance().DoSomething(); // GetInstance() returns 0xABCDEFF

// module 2
MySingleton::GetInstance().DoSomethingElse(); // GetInstance() also returns 0xABCDEFF

My question is the following: Is there a way to force Linux/the shared modules to have independent static memory pools? Or am I at the mercy of the Linux operating system and how it decides to implement this?
In my case I am using this Singleton all over my code for a logging system...and it would be extremely inconvenient to go and have to modify this all over the place. Thanks

A: After a few days (I know this question is only 30 minutes old, but I did finally find the solution)...I found what I was missing and doing on macOS but not on Linux.
I added the following extra compile flags to my common code and everything fell into place perfectly like it was on macOS -fPIC -fvisibility-inlines-hidden -fvisibility=hidden.
With these extra flags in place, the code is separate from each other and no longer overlapping in memory.


text:
Q: How to get a component type in Angular 2 (related to DynamicComponentLoader ) How do I get a "Type" for a component to pass it to:
loadIntoLocation(type: Type, hostLocation: ElementRef, anchorName: string)

I want to pass the Type via @Input of the child:
<searchComponent [componentToLoad]="component"></searchComponent>

A: You can assign a type to a variable:
@Component({
  selector: 'dyn-cmp',
  template: `
`})
class DynCmp {
}

@Component({
  selector: 'parent-cmp',
  template: `
<searchComponent [componentToLoad]="dynCmp"></searchComponent>
`})
class ParentCmp {
  dynCmp:Type = DynCmp;
}


text:
Q: How can I find y? The following equation is given: $$ye^y=e^{x+1}$$ when $x=0$. I tried to solve it as logarithmic equation but I can't go further. I know $y=1$ but I don't know how to prove it. Any idea? Thank you

A: You may write

*

*$ye^y = e^{\ln y + y} = e^{x+1} \Rightarrow \ln y + y = 1+x \stackrel{x= 0}{\Rightarrow} \Rightarrow \ln y + y = 1 \Rightarrow y =1$
The uniqueness of the solution follows from the monotonicity of $\ln y+ y$.

A: You can solve this equation by taking logarithms both side with respect to the base $e$.
The equation becomes:
$$\ln(ye^y)=\ln(e^{x+1})$$
$$\ln y+\ln e^y=\ln (e^{x+1})$$
$$\ln y +y = x+1$$
You are given the value of $x=0$, put it in the equation to get:
$$\ln y +y =1$$
From the equation, if we put $y=1$ it satisfies the equation. You can also plot a graph for the two functions.

Hope this helps...

A: If $x=0$, then $y=1$ is obviously a solution. But $e^{x+1}=e\cdot e^x>e^x$, and $x+1>x$, hence $xe^x$ is an increasing function. Since $y=1$ solves $ye^y=e$, and $e$ is constant, it is unique.


text:
Q: Setting up Forever to listen for events I am writing a new nodejs server and I would like to use forever to keep it running.  So far its been pretty easy:
forever start simple-server.js

However is there a way that I can catch specific events (like an error event) such that the server does not shutdown and restart on an uncaught error.  IE I would like to just log the error and continue. At this point I see a message like this stating that my server has been restarted each time an error is thrown:
Forever detected script exited with code: 1
Forever restarting script for 2 time

I know that I can programatically use forever but I have a couple problems:
1. Seems like when I use it programatically the process is not listed in 'forever list'
2. If I setup a handler for an 'error' event does forever still restart the server?
var forever = require('forever');

var server = new (forever.Monitor)('app.js', {
  max: 3,
  silent: true,
  options: []
});

server.on('error', function(err) {
  console.log('Just received an error in server: ' + err);
});

server.on('exit', function() {
  console.log('server exiting');
});

server.start();


text:
Q: When sending NULL for saving in MySQL DB but it is stored as null string instead of DbNull I'm in a weird situation where i'm unable to find why even sending proper NULL from C# code side, my db column [Having JSON type and has default null value] is storing null instead of DbNull.
I'm trying to save the data againts one JSON column that i have in DB side.
My C# code at data layer :
var options = new MySqlParameter("@pOptions", !string.IsNullOrEmpty(JsonSerializer.Serialize(settings.Options, options)) ? JsonSerializer.Serialize(settings.Options, options) : null);

As you can see in above image for options column, the row below null string is having dbnull same and im trying for the same but, unable to do so.
Any help or pointers are welcomed.

A: Solved the problem.  Silly me. Used following thing.
settings.Options != null ? JsonSerializer.Serialize(settings.Options, options) : null

And it worked.


text:
Q: object not rendered correctly when i take camera away from object in unity vuforia I am rendering TV object on image target. it is working prefect in webcamera of pc. but then i compiled and installed in my android phone.
it is rendering fine when camera is too much near to target but i take it far, all texture become bright yellow type.
All material are in asset folder and most shaders used are "Standard"
Screenshot 1. when camera is near to target
Screenshot 2. when camera is far
visit link :
http://techbytes.byethost6.com/online/storage/ABC/screeshot.png
(was not able to upload image because pf reputation is low and it require 10+..just asking question first time)

A: Do you by chance have a light attached to the ARCamera? From the screenshots, it looks like a very bright directional light is shining on the second screenshot.

A: Solved the problem..
Actually it was problem of Unsupported Shaders in Android...
I used another Shader like "Bumped Specular" from Legacy Shader.
And yes, you need to attach light source from proper direction to make it look nice and realistic..
otherwise it may look all dark.


text:
Q: How do I use Mindee API with Python3? I'm just playing about with code and interested in parsing receipts to text (end point csv file). I came across this tutorial on mindee API where they also provide code to run the parsing. However, I keep getting the below errors when attempting to parse.
import requests

url = "https://api.mindee.net/v1/products/mindee/expense_receipts/v3/predict"

with open("/Users/test/PycharmProjects/PythonCrashCourse", "rb") as myfile: # Here they mention to specify the PATH to file/files which is here as per my windows10 path.
    files = {"IMG_5800.jpg": myfile}
    headers = {"Authorization": "Token asdasd21321"}
    response = requests.post(url, files=files, headers=headers)
    print(response.text)

PermissionError: [Errno 13] Permission denied: '/Users/test/PycharmProjects/PythonCrashCourse'

Why is there permission denied? When I am admin and have full permissions enabled on the file iteself.
I have also tried modifying the code and running the below;
import requests

url = "https://api.mindee.net/v1/products/mindee/expense_receipts/v3/predict"
imageFile = "IMG_5800.jpg" #File is in the current directory
files = {"file": open(imageFile, "rb")}

headers = {"Authorization": "Token a4342343c925a"}
response = requests.post(url, files=files, headers=headers)
print(response.text)

#output
  {"api_request":{"error":{"code":"BadRequest","details":{"document":["Missing data for required field."],"file":["Unknown field."]},"message":"Invalid fields in form"},"resources":[],"status":"failure","**status_code":400**,"url":"http://api.mindee.net/v1/products/mindee/expense_receipts/v3/predict"}}

    Process finished with exit code 0

Status code 400 - suggests something has gone wrong with the syntax....Unfortunately I am stuck and simply just want the API to parse my receipt. Any ideas on what is going wrong please?
Desired output:

*

*get results from receipt in text format/json from Mindee API

References Used:

*

*https://medium.com/mindeeapi/extract-receipt-data-with-mindees-api-using-python-7ee7303f4b6d tutorial on Mindee API

*https://platform.mindee.com/products/mindee/expense_receipts?setup=default#documentation

A: From the error message, it was stated that the document was missing.
I'm glad you found the solution to this.
However, following the documentation, there is an improved code, the  authentication header X-Inferuser-Token has been deprecated.
You can try doing this instead
import requests

url = "https://api.mindee.net/v1/products/mindee/expense_receipts/v3/predict"

with open("./IMG_5800.jpg", "rb") as myfile:
    files = {"document": myfile}
    headers = {"Authorization": "Token my-api-key-here"}
    response = requests.post(url, files=files, headers=headers)
    print(response.text)

A: After brushing up on HTML format - https://www.codegrepper.com/code-examples/html/HTML+file+path. I realised the path I used was wrong and should've used the correct HTML format whether I am on Windows/Mac.
To resolve my issue, I mentioned to go 1 directory up to where the image file is, when running my code.
with open("./IMG_5800.jpg", "rb") as myfile: #modified here to go 1 directory up to where the image file is hosted
    files = {"file": myfile}
    headers = {"X-Inferuser-Token": "Token my-api-key-here"}
    response = requests.post(url, files=files, headers=headers)


text:
Q: nodejs express client Cannot GET /xxx.html before accessing main I have the following server side code:
var app = express();
app.get('/', function (req, res) {
    res.redirect('/main');
});
app.get('/main', function (req, res) {
    var d = new Date();
    res.sendFile(path.join(__dirname + '/main.html'));
    Info(req.ip + ' - Session to main.html built successfully! ');
    app.use(express.static(__dirname));
});

Also there are some other html files in the same directory, e.g. xxx.html.
I found the following behavior that confuses, if I build a new session, try to access localhost:7778/xxx.html, the client cannot get: Cannot GET /xxx.html:
Failed to load resource: the server responded with a status of 404 (Not Found)

On the other hand, after accessed localhost:7778/, and then try to access localhost:7778/xxx.html, will succeed.
Can anyone explain the behavior? Can I set the localhost/xxx.html be able to directly accessed?
Thanks a lot!

A: You need to move app.use(express.static(__dirname)); outside of the app.get('/main', ...) handler:
var app = express();
app.get('/', function (req, res) {
    res.redirect('/main');
});
app.get('/main', function (req, res) {
    var d = new Date();
    res.sendFile(path.join(__dirname + '/main.html'));
    Info(req.ip + ' - Session to main.html built successfully! ');
});
app.use(express.static(__dirname));

According to Express document:

app.use([path,] callback [, callback...])
Mounts the specified middleware function or functions at the specified path

The specified middleware (express.static) should be declared as itself, and be executed once the server is started. It should not be executed as part of logic in GET /main's handler.


text:
Q: Intent to take video in android I need to take video from my application using only front camera. I am using intent to perform this action.
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, videoUri);
intent.putExtra("android.intent.extra.durationLimit", 30);
intent.putExtra("android.intent.extras.CAMERA_FACING", 1); //to open front facing camera
startActivityForResult(intent, VIDEO_CAPTURE);

When I run the application, I am able to take video using front camera. But suppose when I click my record video button and the camera view is opened. In that user go and change the camera to rear camera, then always my intent is opening rear camera only after that. Its not taking the line
intent.putExtra("android.intent.extras.CAMERA_FACING", 1);

Could someone please tell me whats the issue and is it able to be solved using intent?

A: There is no reliable way to use intent to show the front camera all the time at least not on all devices. Only way to reliably do it is to create a SurfaceView and capture the video yourself.

A: See if this works :
try {
    if (Camera.getNumberOfCameras() == 2) {
        if (frontCamera) {
            frontCamera = false;
            prCamera.stopPreview();
            prMediaRecorder.release();
            prMediaRecorder = null;
            prCamera.release();
            prCamera = null;
        } else {

            frontCamera = true;
            prCamera.stopPreview();
            prMediaRecorder.release();
            prMediaRecorder = null;
            prCamera.release();
            prCamera = null;
        }
        Intent intent = new Intent(VideoCapture_New.this,
                VideoCapture_New.class);
        startActivity(intent);
    } else {
        Toast.makeText(VideoCapture_New.this,
                "Your device doesn't contain Front Camera.",
                Toast.LENGTH_SHORT).show();
    }
} catch (Exception e) {
    e.printStackTrace();
    Toast.makeText(VideoCapture_New.this,
            "Your device is not compatible for Front Camera.",
            Toast.LENGTH_SHORT).show();

}

source : Front camera in android
Else you could use Android keyEvents to trigger the button press of camera switch if video starts to record on back camera. KeyEvents need to timed perfectly otherwise they end triggering something else! Check : KeyEvent.
Also if you are making use of
mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));

This signature for CamcorderProfile.get() defaults to a profile for the back-facing camera.
So instead of using this, use :
public static CamcorderProfile get (int cameraId, int quality)

mediaRecorder.setVideoFrameRate(15);

use any value, 1 - 15 for frame rate.
check this for additional details.
Hope this helps.

A: Create your custom video taking application that assure to only use the Front camera
i think this is the only way to do this .
Hope that Helps .


text:
Q: ESRI World Light Gray Basemap - without labels? I am using the "World Light Gray Base" as my basemap in ArcGIS 10.3 Desktop. Is there any way I could turn off the street labels (they show up on ex. scale 1:12000)? I unchecked the "Reference" layer and it got rid of cities' labels, but not street names. Maybe any way around?

A: No, there is not. The labels are a part of the tiles.


text:
Q: Can i format the Note section of Email to have HTML in Docusign Templates? I am trying to understand if I can add HTML elements to the note in DOCUSIGN template.
The reason is I want certain text of NOTE to be BOLD and certain to be regular characters.
Appreciate your help

A: Based on my testing, it's possible to specify BOLD text within a note by using the API, but not by using the DocuSign web console (UI).
For example, if I submit a "Create Envelope" API request with the following recipients structure -- including a recipient note that specifies BOLD text -- the bold text correctly renders both in the email that the recipient receives, as well as in the Note that's displayed to the recipient when they open the Envelope:
<recipients>
  <signers>
    <signer>
     <email>johnsemail@outlook.com</email>
     <name>John Doe</name>
     <recipientId>1</recipientId>
     <routingOrder>1</routingOrder>
     <note>Test note with <b>BOLD text</b>.</note>
     <tabs>
        <signHereTabs>
            <signHere>
                <documentId>1</documentId>
                <pageNumber>1</pageNumber>
                <xPosition>10</xPosition>
                <yPosition>100</yPosition>
            </signHere>
        </signHereTabs>
    </tabs>
    </signer>
  </signers>
</recipients>

However, using that same technique to specify bold text within a Note using the DocuSign web console (UI) doesn't work -- the text is NOT bold in either the email that the recipient receives or in the note they see within the Envelope itself.  i.e., here's how I specified the Note via the DocuSign UI:

And here's how it renders both in the email and in the Envelope for the recipient:


text:
Q: Drawing shapes versus rendering images? I am using Pygame 1.9.2a with Python 2.7 for designing an experiment and have been so far using Pygame only on a need basis and am not familiar with all Pygame classes or concepts (Sprites, for instance, I have no idea about).
I am required to draw many (45 - 50 at one time) shapes on the screen at different locations to create a crowded display. The shapes vary from displaced Ts , displaced Ls to line intersections. [ Like _| or † or ‡ etc.]! I'm sorry that I am not able to post an image of this because I apparently do not have a reputation of 10, which is necessary to post images.
I also need these shapes in 8 different orientations. I was initially contemplating generating point lists and using these to draw lines. But, for a single shape, I will need four points and I need 50 of these shapes. Again, I'm not sure how to rotate these once drawn. Can I use the Pygame Transform or something? I think they can be used, say on Rects. Or will I have to generate points for the different orientations too, so that when drawn, they come out looking rotated, that is, in the desired orientation?
The alternative I was thinking of was to generate images for the shapes in GIMP or some software like that. But, for any screen, I will have to load around 50 images. Will I have to use Pygame Image and make 50 calls for something like this? Or is there an easier way to handle multiple images?
Also, which method would be a bigger hit to performance? Since, it is an experiment, I am worried about timing precision too. I don't know if there is a different way to generate shapes in Pygame. Please help me decide which of these two (or a different method) is better to use for my purposes.
Thank you!

A: It is easer to use pygame.draw.rect() or pygame.draw.polygon() (because you don't need to know how to use GIMP or InkScape :) ) but you have to draw it on another pygame.Surface() (to get bitmap) and than you can rotate it, add alpha (to make transparet) and than you can put it on screen.
You can create function to generate images (using Surface()) with all shapes in different orientations at program start. If you will need better looking images you can change function to load images created in GIMP.
Try every method on your own - this is the best method to check which one is good for you.
By the way: you can save generated images pygame.image.save() and then load it. You can have all elements on one image and use part of image Surface.get_clip()


text:
Q: How is it possible that Ember's service() function knows the key it is called at? A question from curiosity. I analyze some Ember app for the first time and I met such a code:
export default Service.extend({
  api: service(),
  router: service(),
  flashes: service(),
  intercom: service(),
  store: service()
  // ...
})

As I can see, the service function here is clever enough to return adequate results for every key it is called at. And my question is: how is it possible? I thought that I know JavaScript, but I have no idea how it could be implemented. JavaScript functions know only their arguments and this object they are called for, don't they?

A: As far as I can tell from the API docs and from the source this is able to work because you're calling service() on a special type of object which has what Ember calls an 'owner'. When the service gets called it can use the objects owner to lookup the name of the property and determine the name of the service. I might be reading this wrong, I'm like 50% confident.


text:
Q: how to insert value into data base using jquery/ajax? index.php

<a href='#' id='enquire' data-toggle="modal" data-target="#myModal<?php echo $id; ?>">Enquire
<div class="modal fade" id="myModal<?php echo $id; ?>" role="dialog">

        <button type="button" class="close" data-dismiss="modal">×</button>

        <form method="post" name="formid<?php echo $id; ?>" name="formname<?php echo $id; ?>">
            <input type="text" name="name" id="name" placeholder="Enter Your Name">
            <input type="text" name="fname" id="fname" placeholder="Enter Your Father's Name">

            <input type="text" name="email" id="email" placeholder="Enter Your Email">
            <input type="text" name="phone" id="phone" placeholder="Enter Your Phone">

            <input type="text" name="x" id="x" placeholder="Enter Your X Percent">
            <input type="text" name="xii" id="xii" placeholder="Enter Your XII Percent">

            <input type="text" name="qualify" id="qualify" placeholder="Enter Your Qualifying Exam(Optional)">

            <input type="submit" class="submit" name="" id="submit" value="submit" class="btn btn-primary">
        </form>

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

enquiry.php
<?php
    $cname = $_POST['cname'];
    $name = $_POST['name'];
    $fname = $_POST['fname'];
    $email = $_POST['email'];
    $phone = $_POST['phone'];
    $x = $_POST['x'];
    $xii = $_POST['xii'];
    $qualify = $_POST['qualify'];
    $sql = "insert into student_enquiry(college_name,name,father,email,phone,x_percent,xii_percent,qualify)values('$cname','$name','$fname','$email','$phone','$x','$xii','$qualify')";
    $result = mysqli_query($link,$sql);
    if($result == true)
    {
        echo "
your data has been submitted successfully
";
    }
    else
    {
        echo "
Error!
"
    }
?>

In this code I am creating a modal having form inside it and I want to insert form value into database using jquery/ajax. when I clcik on submit button it hide the modal and show nothing like successfull msg or any error msg. So, How can I do this ?please help.
Thank You

A:
Give an id to the form element.

 <form method="post" id="registration">

Submit the form as follows:
var formdata = jQuery('#registration').serialize();
 jQuery.ajax({
        type: 'POST',
        url: 'enquiry.php',
        dataType: 'json',
        data: formdata,
        success: function(result) {
            $("#msg").html(data);
        }

    });

A: Try below example for save data using ajax,
JS/CDN
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

HTML
Enquire

        <button type="button" class="close" data-dismiss="modal">×</button>

        <form method="post">
            <input type="text" name="name" id="name" placeholder="Enter Your Name">
            <input type="text" name="fname" id="fname" placeholder="Enter Your Father's Name">

            <input type="text" name="email" id="email" placeholder="Enter Your Email">
            <input type="text" name="phone" id="phone" placeholder="Enter Your Phone">

            <input type="text" name="x" id="x" placeholder="Enter Your X Percent">
            <input type="text" name="xii" id="xii" placeholder="Enter Your XII Percent">

            <input type="text" name="qualify" id="qualify" placeholder="Enter Your Qualifying Exam(Optional)">

            <input type="button" name="" id="submit" value="submit" class="btn btn-primary">
        </form>

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

Ajax File.
In this file you can get posted data and save them.
<?php
// Your mysql query.
$insert = mysql_query("insert into `table_name` set `field1`=''");
if($insert){
    echo "Inserted successfully !";
}
else{
    echo "Not Inserted !";
}
?>

A: Check Below jquery code and html code
$(document).ready(function () {
    $(".submit").click(function () {
        var formname = "formid"+$(this).attr("data-id");
        cname = $("#" + formname + " #cname").val();
        name = $("#" + formname + " #name").val();
        fname = $("#" + formname + " #fname").val();
        email = $("#" + formname + " #email").val();
        phone = $("#" + formname + " #phone").val();
        x = $("#" + formname + " #x").val();
        xii = $("#" + formname + " #xii").val();
        qualify = $("#" + formname + " #qualify").val();
        $.ajax({
            type: "POST",
            data: {"cname": cname, "name": name, "fname": fname, "email": email, "phone": phone, "x": x, "xii": xii, "qualify": qualify},
            url: "enquiry.php",
            success: function (data) {
                $("#" + formname + " #msg").html(data);
            }
        });
    });
});

HTML CODE
<a href='#' id='enquire' data-toggle="modal" data-target="#myModal<?php echo $id; ?>">Enquire
<div class="modal fade" id="myModal<?php echo $id; ?>" role="dialog">

        <button type="button" class="close" data-dismiss="modal">×</button>

        <form method="post" name="formid<?php echo $id; ?>" name="formid<?php echo $id; ?>">
            <input type="text" name="name" id="name" placeholder="Enter Your Name">
            <input type="text" name="fname" id="fname" placeholder="Enter Your Father's Name">

            <input type="text" name="email" id="email" placeholder="Enter Your Email">
            <input type="text" name="phone" id="phone" placeholder="Enter Your Phone">

            <input type="text" name="x" id="x" placeholder="Enter Your X Percent">
            <input type="text" name="xii" id="xii" placeholder="Enter Your XII Percent">

            <input type="text" name="qualify" id="qualify" placeholder="Enter Your Qualifying Exam(Optional)">

            <input type="button" class="submit" name="submit" data-id="<?php echo $id; ?>" id="submit" value="submit" class="btn btn-primary">
        </form>

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>


text:
Q: Understanding pullback of pushforward Sorry if this is sort of a soft question. I added an example at the end to mitigate. So I hope you can bear with me here.
Let $\phi : X \rightarrow Y$ be a morphism of noetherian schemes, $\mathscr F$ a coherent sheaf on $X$. I am looking to better understand $\phi^*\phi_*\mathscr F$, or the natural map $\phi^*\phi_*\mathscr F \rightarrow \mathscr F$.
I want to collect interesting or useful facts, that one ought to be aware of. No matter if trivial(-ish) or rather specific, I want to collect 'em all. Provide either proofs or references, both are fine.
Assumptions might, among others, include:

*

*$\phi_*O_X = O_Y$

*$\phi$ is birational

*$\mathscr F$ is generated by global sections (gbgs)

*...

Answers might, among others, concern any of the following:

*

*the morphism being injective / surjective / an isomorphism

*the $\phi$-movable part of a divisor $D$, which is defined by $M=$ Im$\{\phi^*\phi_*\mathscr L(D) \rightarrow \mathscr L(D)\}$ (e.g. the motivation behind the definition)

*...

One example statement:
[Hartshorne III.8.8]: $f:X\rightarrow Y$ a projective morphism of noetherin schemes, with $O_X(1)$ very ample, and $\mathscr F$ coherent on $X$. Then $\forall n>>0, f^*f_*\mathscr F (n) \rightarrow \mathscr F(n)$ is surjective. (Because $\mathscr F(n)$ is gbgs.)
Now the promised concrete example question:
consider two birational morphisms $f:X\rightarrow Y$, $f': X'\rightarrow Y$ of normal projective varieties. Let $V$ be a common resolution of $X$ and $X'$, with morphisms $s$ and $s'$ respectively. Suppose we have an $l$ such that $\mathscr L(lK_{X'})$ is very ample, and $\mathscr L (lK_X)$ is Cartier. (E.g. take $f'$ to be the flip of $f$, in which case we assume both morphisms to be small, $-K_X$ and $K_{X'}$ to be $f$- and $f'$-ample, respectively, and $\rho(X/Y)=\rho(X'/Y)=1$.) Then we write $s^*\mathscr L (lK_X) = \mathscr L (M) \otimes \mathscr L (F)$, where $$\mathscr L (M) = Im\{(f\circ s)^*(f\circ s)_*s^*\mathscr L (lK_X)\rightarrow s^* \mathscr L (lK_X)\}$$
is the $(f\circ s)$-movable part.
We have $$ \mathscr L (M) = Im\{(f'\circ s')^* f'_* \mathscr L (lK_{X'}) \rightarrow s^*\mathscr L (lK_X)\}, \tag{1}$$
where I would want to show:
$$= Im\{(f'\circ s')^* f'_* \mathscr L (lK_{X'}) \rightarrow s'^*\mathscr L (lK_{X'})\} ( = s'^*\mathscr L (lK_{X'}) \subset s^*\mathscr L (lK_{X})), \tag{2}$$
but I am not certain why the images of the two maps are the same.
Related questions:
[1]https://mathoverflow.net/questions/110866/interpreting-ff
[2]Pullback and Pushforward Isomorphism of Sheaves


text:
Q: How to delay response in Node/Koa? I am trying to use setTimeout to delay returning a response in Node. With the following code, the activateAccount api gives a 404. It logs "in setTimeout" but nothing ever gets returned. Is there a way to accomplish this?
module.exports.activateAccount = function *() {
    this.body = { ok: false };

    if(this.session.otherMembershipFound){
        console.log("in otherMembershipFound");
        setTimeout(function() {
            console.log("in setTimeout");
            this.status = 200;
            this.body = { ok: false, result: {
                    ok: false
                    , result: null
                    , message: "We encountered one or more validation errors."
                    , debug: "Other Membership Found"
                }
            };
        }, 3000)
    } else {}
}

As per the Promise explanation below, I tried the following but I am struggling with what the correct implementation should be.
if(this.session.otherMembershipFound){
    console.log("in otherMembershipFound");
    return new Promise(resolve => {
        setTimeout(resolve, 3000);
      })
      .then(() => {
        console.log("after");
        this.status = 200;
        this.body = { ok: false, result: {
                ok: false
                , result: null
                , message: "We encountered one or more validation errors. Please check the entered data and try again. For assistance please call 1 (800)617-3169."
                , debug: "Other Membership Found"
            }
        };
    }, 3000)
} else {

With that I get this error
(node:21796) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot remove headers after they are sent to the client
at ServerResponse.removeHeader (_http_outgoing.js:540:11)

A: When a Koa middleware function returns, koa considers the request done and will send back what it can.
However, if the Koa middleware function returns a promise, it will postpone this until the promise is resolved.
So the trick to letting koa wait is to return a promise, and resolving the promise only when you are fully done.
P.S.: The asterisk (*) makes me suspect you are using Koa 1, or you've followed a tutorial about Koa 1. Usually if you see * and yield, you will want async and await instead.

A: You can use koa-delay library for doing this job.
https://www.npmjs.com/package/koa-delay
Follow the documentation from library page.


text:
Q: Getting the date of the next day in PureScript Is there anyway to write the following function more elegantly?
I can see some patterns but I'm not sure how to abstract them or how to find a simpler way to write the function.
type HasRemainder = Boolean

tomorrow :: Date -> Date
tomorrow date = unsafePartial $ canonicalDate y (fst m) (fst d)
  where d :: Tuple Day HasRemainder
        d = case toEnum $ 1 + fromEnum (day date) of
          Just v -> Tuple v false
          Nothing -> Tuple (unsafePartial $ fromJust $ toEnum 1) true
        m :: Tuple Month HasRemainder
        m = if snd d then
              case toEnum $ 1 + fromEnum (month date) of
                Just v -> Tuple v false
                Nothing -> Tuple (unsafePartial $ fromJust $ toEnum 1) true
            else Tuple (month date) false
        y :: Year
        y = if snd m then
              case toEnum $ 1 + fromEnum (year date) of
                Just v -> v
                -- use 2018 arbitrarly if the conversion from int to Date fails
                Nothing -> unsafePartial $ fromJust $ toEnum 2018
            else (year date)

A: I'd do something like this:
import Data.DateTime as DT
import Data.Maybe (maybe)
import Data.Time.Duration (Days(..))

tomorrow :: DT.Date -> DT.Date
tomorrow dt = maybe dt DT.date $ DT.adjust (Days 1.0) (DT.DateTime dt bottom)

Although it will return the input date in the unlikely event that the given date is top (which is 31st December 275759 if I remember correctly).
There is an adjust function for Time and DateTime so it's just an oversight that Date is missing one.

A: I would try something along those lines
getDatePart datepart defaultval1 defaultval2 =
    case toEnum $ defaultval1 + fromEnum datepart of
    Just v -> Tuple v false
    Nothing -> Tuple (unsafePartial $ fromJust $ toEnum defaultval2) true

getDatePartDefault d datepart defaultval1 defaultval2 =
    if snd d then
        getDatePart datepart defaultval1 defaultval2
    else Tuple datepart false

 tomorrow :: Date -> Date
 tomorrow date = unsafePartial $ canonicalDate (fst y) (fst m) (fst d)
     where d :: Tuple Day HasRemainder
           d = getDatePart (day date) 1 1
           m :: Tuple Month HasRemainder
           m = getDatePartDefault d (month date) 1 1
           y :: Tuple Year HasRemainder
           y = getDatePartDefault d (year date) 1 2018

Take care: this is not tested

A: Using succ from Enum:
import Data.Date (Date)
import Data.Enum (succ)
import Data.Maybe (Maybe)

today :: Date
today = ...

tomorrow :: Maybe Date
tomorrow = succ today


text:
Q: Whenever I plug my headphones, I hear static noises whenever I plug in the earphones (headphones) in my laptop it starts a static sound, which so annoying.
sometimes, for this sound, original media sound can't be heard!
note that my laptop's loudspeaker is out of date!
Secondly my headphone port is like a Mobile phone's port.
I mean, it has only one port for headphone+microphone.
I don't have a headphone like this.
so where is the problem?
My laptop is HP Elitebook 2560p
It is new and came from foreign country! It's loudspeaker was all OK before giving it to me. But now it's out of date.

A: Open alsamixer and zero out mic and mic-boost levels from sound card options (F6 in alsamixer menu).


text:
Q: Sum the column while next value of rows is not null I have a MySQL table called agent_log like picture 1. I want output like picture 2.
That means, wait_sec will be sum with next rows while a new uniqueid has come. When come a new uniqueid then again it will be sum with next wait_sec while next uniqueid are null.
Please see the attached images for clear the concept.
Picture 1/My Table

Picture 2/Expected output

A: Solution 1
select max(uniqueid), sum(wait_sec)
from (
  select *, (select count(uniqueid) from agent_log a2 where a2.event_time < a1.event_time) gg
  from agent_log a1
) as a
group by gg

Solution 2
select uniqueid, wait_total
from (
  select a.*,
    if(@prev_id is null, @wait_tot := @wait_tot + a.wait_sec, @wait_tot  := a.wait_sec) AS wait_total,
    @prev_id  := a.uniqueid AS prev_id
  from ( select @prev_id  := NULL, @wait_tot := 0 ) i
  join ( select * from agent_log order by event_time ) a
)a
where uniqueid is not null


text:
Q: WordPress Getting post data for Post Grid of Visual Composer I'm using Visual Composer in WordPress and I want to make a custom Post Grid. But the default elements that the post grid supplies are not enough. I want to show the author of the post, the number of comments it has, the category it has and the Tags it has as well. I'm not really familiar with Visual Composer, but I need a point in the right direction for me to get this data? What can I do? I've search their documents but with no luck. If I need to move around the php code I would like to know what I'm moving around is the right thing. Any ideas? If you need any more information please do ask :D
Thanks in advance for the help.

A: If anybody is still looking to find out how to to get the id in a post grid or create a specific widget for the grid you can use the following snippet I creatd for adding an icon before the post title. You will see inside the first function you can call $post-ID for use on any query.
//** Case Study Title Block Shortcodes ***********
//********************************
add_filter( 'vc_gitem_template_attribute_case_study_title','vc_gitem_template_attribute_case_study_title', 10, 2 );
function vc_gitem_template_attribute_case_study_title( $value, $data ) {
   extract( array_merge( array(
      'post' => null,
      'data' => '',
   ), $data ) );
  $atts_extended = array();
  parse_str( $data, $atts_extended );
  $atts = $atts_extended['atts'];
  // write all your widget code in here using queries etc
  $title = get_the_title($post->ID);
  $link = get_permalink($post->ID);
  $terms = get_the_terms($post->ID, 'case_categories');
  $output = "
".  get_the_icon($terms[0]->term_id) . $title ."
";
  return $output;
}

add_filter( 'vc_grid_item_shortcodes', 'case_study_title_shortcodes' );
function case_study_title_shortcodes( $shortcodes ) {
   $shortcodes['vc_case_study_title'] = array(
     'name' => __( 'Case Study Title', 'sage' ),
     'base' => 'vc_case_study_title',
     'icon' => get_template_directory_uri() . '/assets/images/icon.svg',
     'category' => __( 'Content', 'sage' ),
     'description' => __( 'Displays the case study title with correct icon', 'sage' ),
     'post_type' => Vc_Grid_Item_Editor::postType()
  );
  return $shortcodes;
 }

add_shortcode( 'vc_case_study_title', 'vc_case_study_title_render' );
function vc_case_study_title_render($atts){
   $atts = vc_map_get_attributes( 'vc_case_study_title', $atts );
   return '{{ case_study_title }}';
}

A: I got the same issue; here is how I solve it:
According to Visual Composer documentation: https://kb.wpbakery.com/docs/developers-how-tos/adding-custom-shortcode-to-grid-builder/
When you add the code below to functions.php, a new component will be added in your custom grid builder (in my example the name will be "Author"). There are a number of values you can get by post data template variable function and one of it not the name of the author but their ID (that's sad but at least you can use this value to get the author name).
The value is 'post_author' => ID of the author (for example '1')
Here is the function where I get the post author and display it (if author component was added to your custom grid in "custom grid builder"). Put it in functions.php of your child theme:
add_filter( 'vc_grid_item_shortcodes', 'my_module_add_grid_shortcodes' );
function my_module_add_grid_shortcodes( $shortcodes ) {
    $shortcodes['vc_post_id'] = array(
        'name' => __( 'Author', 'my-text-domain' ),
        'base' => 'vc_post_id',
        'category' => __( 'Content', 'my-text-domain' ),
        'description' => __( 'Show current post author', 'my-text-domain' ),
        'post_type' => Vc_Grid_Item_Editor::postType(),
    );

    return $shortcodes;
}

// output function
add_shortcode( 'vc_post_id', 'vc_post_id_render' );
function vc_post_id_render() {
    $nn = '{{ post_data:post_author }}'; // usage of template variable post_data with argument "post_author"

    return get_the_author($nn);

}

There is a little problem. It works but get_the_author is a deprecated function in WordPress. I'd appreciate any suggestions to make it more modern or if you name other alternatives please suggest.
Also, here is the list of available variables of vc_post_id_render from docs. Here they are:
WP_Post::__set_state(array(
   'ID' => 69,
   'post_author' => '1',
   'post_date' => '2015-04-29 14:15:56',
   'post_date_gmt' => '2015-04-29 14:15:56',
   'post_content' => 'Your post content',
   'post_title' => 'Your post title',
   'post_excerpt' => '',
   'post_status' => 'publish',
   'comment_status' => 'open',
   'ping_status' => 'open',
   'post_password' => '',
   'post_name' => 'post name',
   'to_ping' => '',
   'pinged' => '',
   'post_modified' => '2015-06-17 11:18:41',
   'post_modified_gmt' => '2015-06-17 11:18:41',
   'post_content_filtered' => '',
   'post_parent' => 0,
   'guid' => 'http://wp.master/?p=69',
   'menu_order' => 0,
   'post_type' => 'post',
   'post_mime_type' => '',
   'comment_count' => '0',
   'filter' => 'raw',
   'filter_terms' =>
  array (
  ),
))

A: this is your response
https://kb.wpbakery.com/docs/developers-how-tos/adding-custom-shortcode-to-grid-builder/
at Template variables usage
Exemple, in visual composer template you can use {{ post_date:ID }} to show post ID. I don't know how show tag.


text:
Q: redhat linux sudo su - failed I am no more able to do sudo su - to get root authentication. I am logged in as test user. I mapped test from unconfined_u to SElinux user staff_u. I restarted the vm machine on google cloud. I can login to vm as test user, but if I do sudo su -, I get following error:
su: avc.c:74: avc_context_to_sid_raw: Assertion `avc_running' failed.
Aborted

A: It seems to be a known bug of CentOS and Redhat:

0011249: su: avc.c:74: avc_context_to_sid_raw: Assertion `avc_running'
failed.
Description   Whenever I execute a su - command after switching
into the sysadm_r, I get this fault. The system is in enforcing mode
when I get this error. When in permissive mode, this does trigger the
error. Attempted to address the problem with audit2allow to see if
that could temporarily resolved the problem while I looked for a
permanent solution but that did not work either

There are the 2 referencies:

*

*Centos bug

*RedHat Bug


text:
Q: Cmake 3.1 + "Protobuf_IMPORT_DIRS" importing another .proto error I'm still fairly new to CMAKE, but I'm using find_package(Protobuf Requried) to compile my .proto files as part of the build, and I'm having trouble getting imports to work, and I'm well and truly stumped.
I have 2 .proto files in the same direcotry, "protobuf" named "A.proto" and "B.proto"
Without an import, they compile fine.
If I change A.proto to have an import to B:
syntax = "proto3";
import "B.proto";

message MyMessage
{}

With a CMakeLists.txt file that sets the Protobuf_IMPORT_DIRS variable correctly (I think):
find_package(Protobuf REQUIRED)
set(Protobuf_IMPORT_DIRS ${Protobuf_IMPORT_DIRS} ${CMAKE_SOURCE_DIR}/protobuf)

...

protobuf_generate(TARGET ${MY_PROJECT_NAME})

I get this on build:
  Running cpp protocol buffer compiler on protobuf/A.proto
  B.proto: File not found.
  protobuf/A.proto:3:1: Import "B.proto" was not found or had errors.

Any help would be much appreciated, as I feel like i'm taking crazy pills! :)

A: So i found the answer, although it took some hacking. Bascially I just read all the CMAKE files associated with Protobuf until I figured it out. There's probably better docs out there but I couldn't find.
Short Story:
if you call PROTOBUF_GENERATE_CPP, it respects setting a Protobuf_IMPORT_DIRS variable.
However if you directly call the protobuf_generate for a target as I do, the variable is ignored.
The answer is to call protobuf_generate with an argument of IMPORT_DIRS, such as:
protobuf_generate(TARGET ${MY_PROJECT_NAME} IMPORT_DIRS protobuf)
IMPORT_DIRS is a multi argument, you can supply several.
Here's the relevant code:
function(protobuf_generate)
  include(CMakeParseArguments)

  set(_options APPEND_PATH)
  set(_singleargs LANGUAGE OUT_VAR EXPORT_MACRO PROTOC_OUT_DIR PLUGIN)
  if(COMMAND target_sources)
    list(APPEND _singleargs TARGET)
  endif()
  set(_multiargs PROTOS IMPORT_DIRS GENERATE_EXTENSIONS)

  cmake_parse_arguments(protobuf_generate "${_options}" "${_singleargs}" "${_multiargs}" "${ARGN}")

I hope this will save someone headache in the future!


text:
Q: How to access videos on USB drive with VLC video player? I often play videos and like to select multiple files.   The problem is, if the files are not on the main drive, say in the 'video' or 'download' directories, I don't see a way to access them.
I go to the file menu and select to open multiple files, but don't seem to be able to navigate to my usb drive.   I have a drive connected to my usb port but I can't navigate to it.   Anyone know how that's done?
Thanks

A: You can check if vlc is installed via apt
apt-cache policy vlc

or via snap
snap list vlc

I have checked and it works for me in both cases to play a file in a USB pendrive or USB SSD drive.
The partition, where you have the video file(s), must be mounted. Directories in USB drives are often automatically mounted, when you connect a USB drive. Check if it is mounted with the following command,
df

or if you want more details the following command in a wide terminal window,
lsblk -o name,size,fstype,label,mountpoint,model

The ownership and permissions of Microsoft file systems might prevent access, and you should unmount and mount again with suitable permissions. It is also possible that the partition with video files is not mounted.
In such cases you can mount it manually, for example with a mount command.
sudo umount /dev/sdxn            # unmount if necessary
sudo mkdir /mnt/usbxn            # create mountpoint only once

sudo mount -o rw,user,uid=1000,dmask=007,fmask=117 /dev/sdxn /mnt/usbxn

where x is the drive letter and n is the partition number. Modify if necessary, for example the uid number if not the 'first user'.
See a detailed description in this link to an answer to another question at AskUbuntu.

Edit: If you still have problems, when running the snap version, please remove it and install the apt version.


text:
Q: Rails PG form values being sent null to db despite ":name, null: false" being set ANSWER: Thanks to Deepak in the comments, I forgot to add Model level validations as well. These are done with validates :name, presence: true
My rails app decided to accept null values to the PG database for some reason that I cannot pick up.
Order migration file:
create_table :orders do |t|
  t.string :name, null: false
  t.string :company
  t.string :email, null: false
  t.string :event_type, null: false
  t.string :country, null: false
  t.text :description, null: false

  t.timestamps
end

My order_controller.rb
private
def order_params
params.require(:order).permit(:name, :company, :email, :event_type,
:country, :description)
end

With my create action.
@order = Order.new(order_params)
if @order.save
   redirect_to root_path
else

It is redirecting to the root_path of the home screen with this being send to the controller.
 Parameters: {"utf8"=>"✓", "authenticity_token"=>"longlongtoken",
 "order"=>{"name"=>"", "email"=>"", "company"=>"",
 "event_type"=>"", "country"=>"", "description"=>""},
 "commit"=>"Create Order"}`

All actions in my new.html.erb file follow this basic pattern

        <%= f.label "Email*"%>

        <%= f.text_field :email, class: "form-control", placeholder: "X"%>


text:
Q: Why can't I edit the style property with JavaScript? So, I was just trying to make a
 appear on an onkeyup event with javascript and for some reason, it didn't let me do it and I got the error:

Uncaught TypeError: Cannot read property 'style' of null

This is my code:
HTML:

Javascript:
function showContent() {
    document.getElementById('content').style.display = 'block';
}

Can you please help? Thanks.

A: I guess your function is called before your block "content" is added to DOM.
You may want to wait for the DOM to be ready before calling your function, or call it from a button as following:

function showContent() {
  document.getElementById('content').style.display = 'block';
}
.content {
  width: 200px;
  height: 100px;
  background: red;
}
<button onClick="showContent()">Show Block</button>


text:
Q: Lenovo g700 & Ubuntu 14.04 i have few problems with this computer and ubuntu. Firstly, if i slide across my touchpad multiple times, the computer freezes. But if i use USB mouse, the problem won't occur. Secondly i can't create a Wifi hotspot using access point mode. Lastly my bluetooth is softblocked and i can't connect any devices to it.
1: ideapad_bluetooth: Bluetooth
Soft blocked: yes
Hard blocked: no
I have tried rfkill unblock all, and few other options, nothing works.
Thank you for any help,
regards

A: You can use ap-hotspot from the webupd8 repository to create an infrastracture AP instead of adhoc. I am using this on Ubuntu, but it is available for Saucy, Raring and Quantal as well.
$ sudo su -
# add-apt-repository ppa:nilarimogard/webupd8
# aptitude update
# aptitude install ap-hotspot
# ap-hotspot configure
# ap-hotspot start

There is problem with Ubuntu 13.04. It is not connecting to other HotSpot.
But you can use ap-hostspot instead. Read how-to-set-up-wireless-hotspot-access to install ap-hotspot


text:
Q: Text inside a Pressable that is long enough to wrap to 2 lines goes over the padding of the Pressable For some reason, the text inside the styled pressable is respecting the padding of its parent if it is not long enough, however, if the text is long enough to wrap to a second line, it goes over the padding of the pressable. I imagine I'm doing something wrong with the flexbox of the Button element, however, I couldn't figure out what it is.
My code looks like this:
const Button: FunctionComponent<Props> = ({ title, icon, children, selected, onPress, ...rest }) => {
    return (
        <Animated.View
            layout={Layout}
        >
            <StyledButton
                accessibilityState={{ selected }}
                accessibilityRole="button"
                selected={selected}
                onPress={onPress}
                {...rest}
            >
                <StyledText variant="b2" accessible={false} selected={selected}>
                    {title || children}
                </StyledText>
            </StyledButton>
        </Animated.View>
    );
};

const StyledButton = styled(Pressable)<{ selected: boolean }>`
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    border-radius: 100px;
    width: auto;
`;

const StyledText = styled(Text)<{ selected: boolean }>`
    color: red;
`;


text:
Q: elementary circuit in a strongly connected directed graph Let $G$ be strongly connected directed graph with vertex set $\{1, 2, \ldots, n\}$. A circuit $i_0=i, i_1, \ldots, i_n=i$  is  elementary if path $ i_1, \ldots, i_{n-1}$ is a path in which
no vertex appears more than once.
In a paper, author claims that if  the length of any elementary circuit of $G$ is larger than or equal to 2, then there is a set $S=\{i_1,_2,\ldots, i_m\}\subseteq \{1, 2, \ldots n\}$ with  $m\leq [\frac{n}{2}]+1$ such that any elementary circuit of $G$ contains at least one vertex that belongs to $S$.
I do not know proof of it. Can you please help me to know it?
Indeed proof of the following lemme is not clear for me.
Lemma. Let  $G$ be strongly connected directed graph with vertex set $\{1, 2, \ldots, n\}$ and   the length of any elementary circuit of $G$ is larger than or equal to 2. If $i,j\in\{1, \ldots n\}$, then  there exists a (possibly empty) path $P_{ij}$ from $j$ to $i$ in $G$ that passes through at least one vertex of each (elementary) circuit of $G$ and that
has a length that is less than or equal to $\frac{n^2-1}{2}$.


text:
Q: How can you seed a first item with bufferWithCount in rx.js? Say you do something like:
Rx.Observable.range(1, 5).bufferWithCount(2, 1).subscribe(console.log);

This returns:
[1, 2]
[2, 3]
[3, 4]
[4, 5]
[5]

I'd like for the result to look like (basically force the first value to emit):
[<userDefined>, 1]
[1, 2]
[3, 4]
etc...

A: How about:
Rx.Observable.range(1, 5)
  // Note this value will get used for every subscription
  // after it is defined.
  .startWith(userDefined)
  .bufferWithCount(2, 1)
  .subscribe(console.log);


text:
Q: Comparison of two waveforms of audio files I am a VC++ developer and currently need help in comparing two audio files. Lets say I have two wave files and one of it is created using the other with some modifications like lowering the loudness etc.
Now, I have to compare these files and see if the modified one is almost copy of the original one, means, while creating the modified one, my application has unknowingly not distorted the file.
A percentage value would be better to signify how much different these files are.
I have tried taking FFT of both files and then computing the difference in dB (like, 10 * log10 (ft1/ft2)) and averaging out the result. i get a resultant number but I am not sure what that number signifies.
Thanks in advance for any kind of help.

A: The number you obtain doesn't really signify anything aside from how similar the spectra are.  There are so many ways of modifying an audio file and so many ways of comparing them that it's impossible to give a general answer.  If you know exactly which modifications are made then you can do a reasonable job.  For instance if you know that the only modification is that the volume has been changed by a constant factor then if you take the squared magnitude of the FFT and normalise it (ie rescale so that the peak is 1.0) then this will be identical for the original and modified signals.  You can calculate the sum of the differences of the two FFT magnitudes, but this is just a number and you can't convert it to a percentage in any meaningful way (what does it mean if I say two sounds are 30% different?)
So I would step back a bit and work out the problem that you're actually trying to solve.


text:
Q: Date Range is not working in AWS ElasticSearch 6.0 I'm new to elastic search. I'm use elastic search to do some queries.
I want to find the products within a time window.
Here is the query:
Here is the mapping:
config = {
"settings": {
        "number_of_shards" :   1,
        "number_of_replicas" : 0
    },
"mapping":{
  "topselling":{
        "properties":{
        "order_id":{"type":"long","store":"yes","index":"no"},
        "product":{"type":"string","store":"yes","index":"no"},
        "created_at":{"type":"date","store":"yes", "format":"yyyy-MM-DD HH:mm:ss", "index":"analyzed"},

        }
  }
}
}

query={
"from" : 0,
"size" : 30,
"query":{
"range":{
    "created_at":{
        "gte":"2010-01-27 02:47:19",
        "lte":"2010-01-27 23:16:59",
        "format": "yyyy-MM-dd HH:mm:ss"
    }
}
}
}

This is the code to search elasticsearch
response = es.search(index="topselling", doc_type="topselling", body=query)

I'm sure the data is in the cluster as I can get the data by query id.
Thanks!


text:
Q: Numbered balls in numbered boxes There are 2n different balls so that each ball numbered from 1 to 2n.
There are 2n different boxes numbered from 1 to 2n.
How many ways are there so that there is a single even numbered ball in an
even numbered box(the box and the ball can have different numbers - example
ball number - 4, box number 6. they just have to both be even).
My solution for some reason isnt true -
Pick an even numbered box - n choices, to which we will place an even
numbered ball - n choices. Now to make sure the rest of even numbered boxes
get uneven numbered balls - we have n uneven balls so we pick a random
even box and have n choices, then n-1,..., and we get n!/2 choices
to stuff all n-1 even boxes with uneven numbered balls.
Now we have 1 uneven ball left and n-1 even balls, so n balls in total.
We can randomly distribute them. so n!.
So my answer is (nn(n!)^2)/2=n^3(n!)/2
Where did I go wrong?
The correct answer is n^4*((n-1)!)^2


text:
Q: Multipart POST on AppEngine (Java) simple problem (am confused I could not find an answer here):
I want to do a Multipart encoded HTTP POST from my AppEngine Java servlet (outbound). AppEngine does not seem to support the Apache HTTP lib and does not offer an API themselves (only  setPayload(byte[])), but I would like to avoid implementing a Multipart encoding myself. So:

*

*Is there a way to send Multipart HTTP bodies from AppEngine Java?

*Is there a library that encodes such a body into a byte[] array? (Note that MultiPartEntity.getContent() is not implemented.) Then I could use the AppEngine internal URLFetch API (which I would prefer because of the async calling capabilities).

A: I wrote a little helper method that adds Multipart POST support to AppEngine (using the Apache HTTP client lib).
public static void addMultipartBodyToRequest(MultipartEntity entity, HTTPRequest req) throws IOException{

    /*
     * turn Entity to byte[] using ByteArrayOutputStream
     */
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    entity.writeTo(bos);
    byte[] body = bos.toByteArray();

    /*
     * extract multipart boundary (body starts with --boundary\r\n)
     */
    String boundary = new BufferedReader(new StringReader(new String(body))).readLine();
    boundary = boundary.substring(2, boundary.length());

    /*
     * add multipart header and body
     */
    req.addHeader(new HTTPHeader("Content-type", "multipart/form-data; boundary=" + boundary));
    req.setPayload(body);
}

The calling code then looks like this:
            MultipartEntity e = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            e.addPart("part1", new StringBody("value1"));
            e.addPart("part2", new StringBody("value2"));

            HTTPRequest req = new HTTPRequest(new URL(myUrl), HTTPMethod.POST);
            ServletHelper.addMultipartBodyToRequest(e, req);

            URLFetchServiceFactory.getURLFetchService().fetchAsync(req);

A: You can use MultipartEntity from httpmime.
Hers is an example.


text:
Q: Переменные сбрасываются при запуске в unity?
Когда я запускаю игру в редакторе Text(text) сбрасывается и там появляется None(text)
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.UI;
    using UnityEngine.SceneManagement;

    public class Settings : MonoBehaviour
    {
        public Text sensitivity;
        // Start is called before the first frame update
        void Start()
        {
            sensitivity = GetComponent<Text>();
            sensitivity.text = Convert.ToString(PlayerPrefs.GetFloat("Sensitivity"));
        }

        // Update is called once per frame
        void Update()
        {

        }

        public void SensorUpdate(float value)
        {
            Debug.Log(value);
            PlayerPrefs.SetFloat("Sensitivity", value);
            sensitivity.text = Mathf.RoundToInt(value * 100) + "%";
        }

        public void OnMenuButtonClick()
        {
            SceneManager.LoadScene("Menu");
        }
    }

A: У вас глупая ситуация, либо компонент Text находится на том же объекте, что и Settings и тогда код выглядит так:
[DisallowMultipleComponent]
// RequireComponent исключает ошибки, обязывая наличие
// подобно тому, как Text не существует без CanvasRenderer
[RequireComponent(typeof(Text))]

public class Settings : MonoBehaviour
{
    private Text _text;

    private void Awake ()
    {
        _text = GetComponent<Text>();
    }
}

Либо Text и Settings находятся на разных объектах и поле с ссылкой на компонент Text задаётся в инспекторе. Ни какого GetComponent в этом случае нету.
[DisallowMultipleComponent]

public class Settings : MonoBehaviour
{
    // SerializeField отображает поле в инспекторе несмотря на приватность
    // а поле наверняка внутренней кухни, не должно быть публичным
    [SerializeField] private Text _text;

    // свойство на случай, если другим нужна ссылка, но без прав изменить эту ссылку
    public Text Text { get => _text; }
}

Одновременно устанавливать и в инспекторе и запрашивать через GetComponent одно и тоже бессмысленно.
П.С.
Convert.ToString(PlayerPrefs.GetFloat("Sensitivity")); можно писать проще: PlayerPrefs.GetFloat("Sensitivity").ToString(). ToString() есть у всего, хоть 123.ToString() или (1+2.3f).ToString().
Mathf.RoundToInt(value*100) не имеет смысла потому, что float*int=int(value*100) или float/int или float+int, он и так это округлит, но всегда в меньшую сторону как FloorToInt, а не RoundToInt. Нужно value*100f, что бы указать вещественное число float. Либо приведением типов value*(float)100.


text:
Q: Azure DevOPs YAML based multi-stage pipeline APPROVAL using REST API (APPPROVALID for Release stage) Is it possible to programmatically approve the DevOps YAML based pipeline using REST API? I looked around found some APIs but not sure if supported for YAML pipelines.
Does anyone know how we can get the APPROVALID for a release in azure devops that we can use in the REST API call to Update the APPROVAL status?
Following is the REST API which can be called for APPROVAL:
https://learn.microsoft.com/en-us/rest/api/azure/devops/approvalsandchecks/approvals/get?view=azure-devops-rest-6.1
Unfortunately I have not even able to get all the Releases listed waiting for approval using the following REST API (approvals):
https://learn.microsoft.com/en-us/rest/api/azure/devops/release/approvals/list?view=azure-devops-rest-6.0
Any help on how to retrieve the ApprovalID for pending Release (stage in the YAML pipeline) so that we can approve it using the REST API.
Thank you


text:
Q: Converting a select form to a dropdown buttons UPDATE: I'm almost there! See my partial answer at the end of this question.
I've got a working form with two select dropdowns, the first for countries, the second for cities. When you select a country, an ajax request automagically gets the countries and updates the countries box.
The problem is the select dropdowns are ugly, and I can't really style them. What I want is a dropdown button, which I can use Bootstrap on to make pretty: Bootstrap Button
I don't have to change the jquery or controller logic, I just have to update my view. But I don't even know where to start. This is what I have:
<%= form_for :trip, url: {action: "index"}, html: {method: "get"} do |f| %>
  <%= f.select :country_obj_id, options_for_select(@countries.collect { |country|
    [country.name.titleize, country.id] }, @countries.first.name), {}, { id: 'countries_select' } %>
  <%= f.select :city_obj_id, options_for_select(@cities.collect { |city|
    [city.name.titleize, city.id] }, 0), {}, { id: 'cities_select' } %>
  <%= f.submit "Go!" %>
<% end %>

How can I convert the selects into dropdown buttons?

UPDATE: I can now get a response back. I just don't know how to handle it to update the button.
The view has two dropdown buttons. The first is the countries, the second is the cities for the first country. I want to update the list of cities for the country that is selected:

  <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Select A Country
  </button>

      <% @countries.each do |country| %>
        <%= content_tag(:li, link_to(country.name.titleize, update_cities_path(country_obj_id: country.id), remote: :true)) %>
      <% end %>

  <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Select A City
  </button>

      <% @cities.each do |city| %>
        <%= content_tag(:li, city.name.titleize) %>
      <% end %>

Selecting a country goes into the update_cities function, which gets the cities for the country_obj_id that is passed.
def update_cities
  @cities = CityObj.where("country_obj_id = ?",
                           params[:country_obj_id]).order(:name)
  respond_to do |format|
    format.js
  end
end

Then the part that i don't understand. The format.js takes me to update_cities.js.coffee, which I have not changed from my original version that worked on the select dropdown:
$("#cities_select").empty()
  .append("<%= escape_javascript(render(:partial => @cities)) %>")

That ends up updating my old select dropdown, which I left in the view for now. But how can I modify the js to update my new dropdown button?

A: You will need a mix of Javascript with Rails:

*

*First, you will need to print all options in Bootstrap's button format:

    <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Countries
    </button>

        <% @countries.each do |country| %>
            <%= content_tag(:li, country.name.titleize) %>
        <% end %>

*Add funcionality to select an option from this dropdown:
https://stackoverflow.com/a/22000328/891807

A: Got it. This is the coolest thing ever. It starts out with two buttons. The first says "Select A Country," and the second says "Select A City." The second button is not active to start with, and I'll probably hide it.
The view:

  <button id="country-select-btn" class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Select A Country
  </button>

      <% @countries.each do |country| %>
        <%= content_tag(:li, link_to(country.name.titleize, update_cities_path(country_obj_id: country.id), remote: :true)) %>
      <% end %>

  <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Select A City
  </button>

The dropdown items are just links, with a route set so clicking a link goes to the controller update_cities action with a country passed:
def update_cities
  @cities = CityObj.where("country_obj_id = ?",
                           params[:country_obj_id]).order(:name)
  @country = CountryObj.find_by(id: params[:country_obj_id])

  respond_to do |format|
    format.js
  end
end

The format.js goes into update_cities.js
$("#cities_select").empty()
  .append("<%= escape_javascript(render(:partial => @cities)) %>")

$("#country-select-btn").empty()
  .append("<%= escape_javascript(render(:partial => @country )) %>")

That renders two partials. _city_obj.html.erb renders a link for each of the cities, which will go to the controller's index action when clicked:

<%= link_to(city_obj.name.titleize, index_path(:trip => {country_obj_id: city_obj.country_obj.id, city_obj_id: city_obj.id}), id: "cities_select") %>

The _country_obj.html partial just updates the "Select A Country" label on the button to the name of the selected country:
<%= country_obj.name.titleize %>

Now, when you click one of the city links, the controller index action can find all the guides for that city/country, then the view will render it.

A: From what I understood, you want to add style to your html form using bootstrap. If this is the case then this is how you can do that:
1.Add bootstrap gem if you have not done it already following the documentation(https://github.com/twbs/bootstrap-sass)
In short, you need to add following at your Gemfile:
gem 'bootstrap-sass', '~> 3.3.5'

Add following line at your app/assets/stylesheets/application.scss so that bootstrap styles gets added at every page:
@import "bootstrap-sprockets";
@import "bootstrap";

2.Using bootstrap styles, at your ugly select tag you need to add form-control at your class name as bootstrap documentation suggests. add class: "form-control" parameter like this:
<%= form_for :trip, url: {action: "index"}, html: {method: "get"} do |f| %>
  <%= f.select :country_obj_id, options_for_select(@countries.collect { |country|
    [country.name.titleize, country.id] }, @countries.first.name), {}, { id: 'countries_select', class: "form-control" } %>
  <%= f.select :city_obj_id, options_for_select(@cities.collect { |city|
    [city.name.titleize, city.id] }, 0), {}, { id: 'cities_select', class: "form-control" } %>
  <%= f.submit "Go!" %>
<% end %>


text:
Q: Finite difference method for elliptic method MATLAB Here is the question:
If R is the region of the plane (0,1) x (0,2), Let L be the 2-d Laplace operator and consider the Poisson equation Lu = 4 on R. One solution is the function v(x,y) = (x-y)^2. Let g be the restriction of v to the boundary of R. To obtain it, we set h = k = 1/2, and m=3, n =5.
Here is my code: but it doesn't work. Could someone help?
function w=poisson(xl,xr,yb,yt,M,N)
f=@(x,y) 0; % define input function data
g1=@(x) (x^2-2*x+1); % define boundary values
g2=@(x) (x^2-4*x+4); % Example 8.8 is shown
g3=@(y) y^2;
g4=@(y) y^2;
m=M+1;n=N+1; mn=m*n;
h=(xr-xl)/M;h2=h^2;k=(yt-yb)/N;k2=k^2;
x=xl+(0:M)*h; % set mesh values
y=yb+(0:N)*k;
A=zeros(mn,mn);b=zeros(mn,1);
for i=2:m-1 % interior points
  for j=2:n-1
    A(i+(j-1)*m,i-1+(j-1)*m)=1/h2;A(i+(j-1)*m,i+1+(j-1)*m)=1/h2;
    A(i+(j-1)*m,i+(j-1)*m)=-2/h2-2/k2;
    A(i+(j-1)*m,i+(j-2)*m)=1/k2;A(i+(j-1)*m,i+j*m)=1/k2;
    b(i+(j-1)*m)=f(x(i),y(j));
  end
end
for i=1:m % bottom and top boundary points
  j=1;A(i+(j-1)*m,i+(j-1)*m)=1;b(i+(j-1)*m)=g1(x(i));
  j=n;A(i+(j-1)*m,i+(j-1)*m)=1;b(i+(j-1)*m)=g2(x(i));
end
for j=2:n-1 % left and right boundary points
  i=1;A(i+(j-1)*m,i+(j-1)*m)=1;b(i+(j-1)*m)=g3(y(j));
  i=m;A(i+(j-1)*m,i+(j-1)*m)=1;b(i+(j-1)*m)=g4(y(j));
end
v=A\b; % solve for solution in v labeling
w=reshape(v(1:mn),m,n);  %translate from v to w
mesh(x,y,w')

A: The matrix construction seems fine -- I didn't look into the the details. But I spotted a few apparent mistakes.
The source function $f(x,y)$ is wrong, it should equals 4 instead of 0;
The boundary functions (those g's) are wrong, they should be something like:
g1=@(y) (y^2-2*y+1); % right
g2=@(x) (x^2-4*x+4); % top
g3=@(x) x^2; % bottom
g4=@(y) y^2; % left

Then the two boundary loops should be changed accordingly
for i=1:m % bottom and top boundary points
  j=1;A(i+(j-1)*m,i+(j-1)*m)=1;b(i+(j-1)*m)=g3(x(i));
  j=n;A(i+(j-1)*m,i+(j-1)*m)=1;b(i+(j-1)*m)=g2(x(i));
end
for j=2:n-1 % left and right boundary points
  i=1;A(i+(j-1)*m,i+(j-1)*m)=1;b(i+(j-1)*m)=g4(y(j));
  i=m;A(i+(j-1)*m,i+(j-1)*m)=1;b(i+(j-1)*m)=g1(y(j));
end

Those were the only changes I made, after that, MATLAB draws the following picture with command
solPoisson(0,1,0,2,8,8)


text:
Q: Android Navigation Components popupto logic with shared screens So I have an interesting flow of screens in our app.  Feature A and Feature B with a shared end flow at the end.  I am not sure best practices for implementing the popupto in the navigation graph
So feature A's flow goes like this
Main - > Feature A Screen 1,Feature A Screen 2, Shared Flow Screen 1, Shared Flow Screen 2.
I want to popupto Feature A Screen 1 when launching Shared end flow Screen 2.  Which is obvious when you are not doing a shared end flow.  But lets say I had another flow like
Main - > Feature B Screen 1,Feature B Screen 2, Shared Flow Screen 1, Shared Flow Screen 2.
I am not able to set popupto to Feature B Screen 1 and Feature A Screen 1 in the nav graph.
I have thought of different solutions but are not sure on best practices

*

*Put Feature A and B into a nested nav graph where popupto the whole nav graph not inclusive and deep link

*Dynamically change the nested nav graph start destination to Feature A or B and popup to the nav graph.

*Have 2 different nav graphs for the 2 flows and for the different nav graphs have different popuptos

*Pass popupto param to the nav graph to say where to go back

*Somehow inspect the nav graph to identify where they came from and popupto via code.

Any blog articles on this or what do you think you would do in this situation.  I am not sure if all of these situations would work but I am exploring 3 but it will require duplication of nav graph code.

A: I also was unable to find an elegant solution to the problem, but I was able to get the desired result by adding a intermediate screen, which immediately forwards to the shared screen. I could then popUpTo that fragment, with popUpToInclusive set to true. I hope this might be helpful.


text:
Q: Solving given log inequality for another bound of x Here's a log inequality I found from Sedgewicks Algorithms in C :
$$ (lnx)^2 < 2\sqrt x $$
Its obviously need to be solved using Lambert W function.. So I proceeded as :
Taking natural logarithm
$$
2 ln(lnx) < ln2 + \frac 1 2 lnx $$ Allowed since its monotonically increasing,
Lets suppose : $$ lnx = m $$ for simplicity.And dividing by 2
$$ ln(m) < \frac {ln2} 2 + \frac m 4$$
Taking exponentiation,
$$ m < \sqrt 2. e^{m/4} $$
$$ m e^ {\frac {-m} 4} < \sqrt 2 $$
$$ \frac {-m} 4 e^ {\frac {-m} 4} > \frac {-\sqrt 2} 4 $$
Using Lambert W Function (+ve branch) on both sides,
$$ \frac {-m} 4 > W(\frac {-1} {2\sqrt 2}) $$
$$ m < -4 W(\frac {-1} {2\sqrt 2})$$
And,
$$ x < e^{-4W( \frac {-1} {2\sqrt 2} ) } $$
Similarly, taking -ve branch we will get,
$$ x > e^{-4 W_{-1}(\frac {-1} {2\sqrt 2})}$$
Pluging the approximate value we get, from above
$$ x < 19.6077 $$$$
x > 187.867 $$
Its not complete solution and I'm still missing lower bound of x for which :
$$ y < x < 19.6077 $$
How can y be found ? Is there any way to extract it from above process?

A: There are three positive real solutions of $\ln(x)^2 = 2 \sqrt{x}$: in increasing numerical order they are
$$ 64 W(\sqrt{2}/4)^4, 64 W(-\sqrt{2}/4)^4, 64 W_{-1}(-\sqrt{2}/4)^4 $$
where $W$ is the principal branch of Lambert W and $W_{-1}$ the "$-1$" branch.
Your inequality is true for $64 W(\sqrt{2}/4)^4 < x < 64 W(-\sqrt{2}/4)^4$ and
$x > 64 W_{-1}(-\sqrt{2}/4)^4$


text:
Q: For each character $f$ of a finite abelian group $G$, $|f(a)|=1$
Let, $G$ be a finite abelian group of order $n$. So there are exactyly $n$ characters of the group $G$. For each character $f$ we have $|f(a)|=1$.Hence the reciprocal $\displaystyle \frac{1}{f(a)}$ is equal to the complex conjugate $\overline{f(a)}$. Thus the function $\bar f$ defined by $\bar{f}(a)=\overline{f(a)}$ is also a character of $G$. Moreover we have, $\displaystyle \bar f(a)=\frac{1}{f(a)}=f(a^{-1})$ ofr every $a\in G$.

My question is on the first line. How $|f(a)|=1$ for each character $f$ of $G$ ?

A: Since $f$ is a character and $G$ has order $n$, we have
$$ 1=f(e)=f(a^n)=f(a)^n$$
where $e$ is the identity element of $G$.
Therefore $f(a)$ is an $n$th root of unity, so in particular $|f(a)|=1$.