text:
Q: Append Custom Object in VB.NET I'm curious if it's possible to "append" a custom class object? I've created an object that is intended to be updated somewhat frequently and for readability purposes, it would be nice to do the following:
Dim nwObject As New CustomObject
nwObject += anotherCustomObject
nwObject += yetAnotherCustomObject
'' ... So on and so forth

I've started overriding the ToString() function already, so is there a similar process to allowing this sort of functionality?
Edit
Forgot to mention that the anotherCustomObject and yetAnotherCustomObject are defined "children" of the nwObject class. Currently there is already a series of overloaded functions that allow "appending" the nwObject with multiple, well-defined objects in a well-handled function. The functions look similar to the following:
Public Overloads Sub AppendObject(ByVal aObject As AnotherObject)
  '' Use the correct properties to append the base class properties
End Sub
Public Overloads Sub AppendObject(ByVal yaObject As YetAnotherObject)
  '' Use the correct properties to append the base class properties
End Sub

(That was off the top of my head, so please forgive basic mistakes. You should get the picture ;) )

A: I found what I was looking for on this MSDN page. Turns out I need to Override the "+" operator function just like I did with the ToString() function. Here's the code I used (using the example in the question):
Public Overloads Shared Operator +(ByVal nwObject As CustomObject,ByVal aObject As AnotherObject) As CustomObject
  nwObject.MainProperty = nwObject.MainProperty.Replace("Some String",aObject.SpecificProperty)
  Return nwObject
End Operator
Public Overloads Shared Operator +(ByVal nwObject As Custom Object, ByVal yaObject As YetAnotherObject) As CustomObject
  nwObject.MainProperty = nwObject.MaintProperty.Replace("Some String",yaObject.AnotherSpecificProperty)
  Return nwObject
End Operator


text:
Q: WordPress sitemap with Custom Post Types This is a really neat idea but I'd like to expand upon it. In his post, David Kennedy writes out some code to allow a basic wp_list_pages type feature for Custom Post Types to use as a sitemap. His code is as follows:

My Post Type

    <?php
        $terms = get_terms( 'my_taxonomy', 'orderby=name' );
        foreach ($terms as $term) {
            echo "

".$term->name."
";
            echo "
";
            $args = array(
                'post_type' => 'my_posttype',
                'posts_per_page' => -1,
                'tax_query' => array(
                    array(
                        'taxonomy' => 'my_taxonomy',
                        'field' => 'slug',
                        'terms' => $term->slug
                    )
                )
            );
            $new = new WP_Query($args);
                while ($new->have_posts()) {
                    $new->the_post();
                    echo '
'.get_the_title().'
';
                }
            echo "
";
            echo "
";
        } ?>

I like this idea but am wanting to take it a bit further. It'd be great to add depth, or levels of hierarchy, and to show parent/child relationship results instead of listing Custom Post Types alphabetically. In other words, mimic more of the functions that wp_list_pages offers.
Is there an easier way to do this or is there functionality in WordPress that already does what I'm looking for?

A: Here is a quick crack at it, which should work in two level depth:

My Post Type

<?php
    $not_in = array(); //to avoid naming the same post over and over
    //get top level terms
    $Parent_terms = get_terms( 'my_taxonomy', array('orderby' => 'name','parent' => 0));
    foreach ($Parent_terms as $term) {
        echo "

".$term->name."
";
        echo "
";
        //get all children of each term
        $child_terms = get_terms( 'my_taxonomy', array('orderby' => 'name','parent' => $term->ID));
        foreach ((array)$child_terms as $t){
            echo "

".$t->name."
";
            echo "
";
            $args = array(
                'post__not_in' => $not_in,
                'post_type' => 'my_posttype',
                'posts_per_page' => -1,
                'tax_query' => array(
                    array(
                        'taxonomy' => 'my_taxonomy',
                        'field' => 'slug',
                        'terms' => $t->slug
                    )
                )
            );
            $new = new WP_Query($args);
            while ($new->have_posts()) {
                $new->the_post();
                $not_in[] = $post->ID;
                echo '
'.get_the_title().'
';
                //here you should check for children posts and output them
            }
            echo "
";
            echo "
";
        }
        //get all posts that are only listed in top level term
        $args = array(
            'post__not_in' => $not_in,
            'post_type' => 'my_posttype',
            'posts_per_page' => -1,
            'tax_query' => array(
                array(
                    'taxonomy' => 'my_taxonomy',
                    'field' => 'slug',
                    'terms' => $term->slug
                    )
                )
        );
        $new = new WP_Query($args);
        while ($new->have_posts()) {
            $new->the_post();
            $not_in[] = $post->ID;
            echo '
'.get_the_title().'
';
            //here you should check for children posts and output them
        }
        echo "
";
        echo "
";
    } ?>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Exit gracefully from Python after SIGKILL The problem being that SIGKILL cannot be caught, is there a way to ensure that a block of code gets executed on program termination? I have a process that starts five subprocesses and changes the state of platform hardware - it handles SIGTERM and SIGINT, however a SIGKILL will kill the main process while the subprocesses continue to run. Is there a way to always execute a cleanup or do I have to accept that SIGKILL will leave the computer in a 'corrupt' state?

A: SIGKILL cannot be handled.  This signal used for critical cases where you dont want the program to be able to ignore the signal and you want to force it to be killed.
SIGTERM is the complement, this need to be use when you want to let the program cleanup before it closed
for more information you can read: http://en.wikipedia.org/wiki/Unix_signal#Handling_signals


text:
Q: How to find Hue value of an Image and use it to apply on other images of similar kind? I'm trying to replace color of an object in an image. Suppose if I want to replace the color in the below image object  to the color in the below image object
I change this color using CAD tool, I want to achieve this using python code
I'm replacing HUE color of an Image as below code
import cv2
import numpy as np

# read image
img = cv2.imread(r"C:\Research\Replace_colors\Bright\Test\b2\img_1_2_pid_13_group_18_P50_A174.png")

# convert img to hsv
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h = hsv[:,:,0]
s = hsv[:,:,1]
v = hsv[:,:,2]

# shift the hue
# cv2 will clip automatically to avoid color wrap-around
huechange = 10   # 0 is no change; 0<=huechange<=180
hnew = cv2.add(h, huechange)

# combine new hue with s and v
hsvnew = cv2.merge([hnew,s,v])

# convert from HSV to BGR
result = cv2.cvtColor(hsvnew, cv2.COLOR_HSV2BGR)

# save result
cv2.imwrite('result.png', result)

I was able to get color close to my required color but not exact color as I wanted
How can I change HUE value so I can replace color exactly ??
Any help or suggestion on this will be very helpful

A: Are you sure you are using the right value for huechange and you don't need to change the value channel? When I use a color picker on the large flat part to the top right I get the following HSV values:
Original: (51, 100%, 56.1%)
Modified: (70, 100%, 56.1%)
Desired: (60, 100%, 28.2%)


text:
Q: How to add cyrillic text to tikz image? I tried the following:
\documentclass[landscape]{article}
\usepackage{tikz}
\usetikzlibrary{backgrounds, shapes, arrows}
\begin{document}
\begin{tikzpicture}
  \node at (10pt, 50pt) {Й};
\end{tikzpicture}
\end{document}

and compiled with
xelatex test.tex

But the output is empty. What am I doing wrong?

A: whether you're drawing a tikzpicture or not, you should load fontspec and a font that supports Cyrillic:
\documentclass[landscape]{article}
\usepackage{tikz}
\usepackage{fontspec}
%\setmainfont{Minion Pro}
%\setmainfont{Times New Roman}
%\setmainfont{CMU Serif}
\setmainfont{Old Standard}
\usetikzlibrary{backgrounds, shapes, arrows}
\begin{document}
Андре́й Арсе́ньевич Тарко́вский — советский кинорежиссёр и сценарист. Народный артист РСФСР.
\begin{tikzpicture}
  \node at (10pt, 50pt) {Й};
\end{tikzpicture}
\end{document}


text:
Q: Android Process Stats: app only appears in the foreground I'm new in Android development. I built an app to access a web server to retrieve some data from the DB. Now I want to analyze the memory usage. To do that, I'm using Process Stats on Android 5.1, but my app only appears in the foreground, with no records of background usage. Why is that?
I don't have any services running on background, but I think it should display the memory usage when the user is not interacting with the app.
It's probably a dumb question, but I'm confused by this.

A: You can monitor the data through Device Monitor tool (read more: http://developer.android.com/tools/help/monitor.html).
Android Studio gives you tools to do that, read the "Memory Monitor Walkthrough" article: https://developer.android.com/tools/performance/memory-monitor/index.html.


text:
Q: Is it preferable to define classes and functions at the beginning or at the end of code? The Javascript tutorial I follow always defines before using, but my PHP book always defines at the end, and in fact points out that this is considered good practice.
Is there a reason to do it one way or the other?

A: If you have inline code executing (e.g. executing as it is loaded), then global variables must be defined before the code that uses them.
Functions can be defined in whatever order you think makes the code the most tidy and easiest to read.
For example, in this code:
foo();

function foo() {
    alert(x);
}

var x = 4;

The call to foo() will alert undefined because x does not yet have a value when foo() is called, but you will notice that foo can be called in code that appears before the function definition because all functions are loaded before any code is actually executed.
As for a best practice, I think it makes sense to organize your code in the best way you can find that puts modules of related functionality together, but the order is not generally material.  I trust you realize that javascript doesn't have anything that is actually a class.  It can use function objects and prototypes to simulate some class-like behavior that other languages have, but it doesn't really have classes as it's objects are based on prototypes, not classes.

A: In Javascript is common practice to declare everything inside a closure, could be an object, or a function, so you don't pollute the global scope. When defining varaibles is often recommended to declare them at the top of the function to which they're scoped.
Javascript doesn't have classes, but defining object literals or constructor functions can be done anywhere as long as you keep in mind that function declarations are not the same as function expressions:
function foo () { ... } // Declaration, works anywhere
var foo = function () { ... } // Expression, works only after the assignment

More info here http://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/

A: In Javascript, a function must be defined before to use it.
So the function definition must precede the code using the function.
Some recommendations for enhancing page speed tell us to put the Javascript execution at the end of the HTML page. Doing so, the Javascript will start when the page and all elements are quite fully loaded. (see article here)
Nevertheless, the remaining usage for Javascript is to place the function declaration in the <header> section, so that the defined functions are immediately operational in any element of the body, including the <body> element itself. You can always place the bootstraps or other function execution at the end of the HTML page.
For PHP it is different.
In a PHP script, you can define the function anywhere in the code, even after the code that is using the functions. That is possible because PHP has to read the full script before the run the very first line of code.
Furthermore, for readability of the code, the remaining usage for PHP is to start with the algorithm, and to place the function definitions at the end of the script (or more often, to place the functions a a separated script).


text:
Q: Can't import my own file python, Flask pycharm Image of project structure:

I have got this kind of files. I want to import write_block function from block.py in main.py through from block import *.
It says name error and write_block is not defined.

A: Try a relative import.
from .block import *
By the way you should try to avoid * imports.
If you want learn more about imports just take a look at PEP 328


text:
Q: Conversion of data on the flutter Friends,
I am retrieving information from a WebService, using the following method, which returns me a MAP
Future &#706Map &#706String, String >> recoverTypesBenefits () async {...
I want to use it in a DropDown and I am trying to recover it as follows:
DropdownButton (
isExpanded: false,
value: dropdownValueBeneficios,
items: (recoverTypesBenefits () as Map <String, String>). entries.map <DropdownMenuItem <String>> ((entry) {...

But I'm getting this feedback:

type 'Future &#706Map &#706String, String >>' is not a subtype of type 'Map &#706String, String>' in type cast

I thought that both MAP &#706String, String> there would be no error.
A detail:
Creating the MAP directly outside FUTURE
Map <String, String> tipos = {"": "- Select the type of benefit -"};

, and calling this way
    items: tipos.entries.map &#706DropdownMenuItem &#706String>> ((entry) {...
I recover the data correctly. But this way I'm not accessing it dynamically,
of the webservice.
Can anyone help?
Thank you!


text:
Q: jQuery code to get data of other columns when the row is checked This is my html code and I would like to get the data of rows in which checkbox is checked.
HTML
<!DOCTYPE html>

          Expand Fed

    Fed Members

              Service Set
              Available Devices
              Status
              Add

        <input id="so-fedExpand-expand-button" class="button primary" type="submit" value="Expand"/>
        Cancel

jQuery
var FedExpandView = (function() {
    var EXPAND = '#so-fedExpand-expand-button';
    function FedExpandView() {
    this.init = function () {
    $(EXPAND).on('click', onExpand);
    var data = [{ SSet: "Service Set 1", ADevices: '46', Status: "Online"},
                { SSet: "Service Set 2", ADevices: '47', Status: "Online"},
                { SSet: "Service Set 3", ADevices: '48', Status: "Online"}];
    $('#my-table').dataTable({
                    bPaginate : false,
                    bFilter : false,
                    bInfo : false,
                    aaData: data,
                    aoColumns : [
                        {mDataProp: 'SSet', id: 'so-fed-ss'},
                        {mDataProp: 'ADevices', id: 'so-fed-adev'},
                        {mDataProp: 'Status', id: 'so-fed-status'},
                        {sDefaultContent: '',
                        fnRender: function (oObj) {
                            return '<input type="checkbox" id="so-fed-checkbox" name="select"">';
                        },
                        sWidth: '10px', sClass: "icon"}
                    ]
                }).rowReordering().
                addClass('reorderable');

            $('#my-table tbody tr').first().addClass('selected');
            this.resume();
            }
   this.resume = function () {
            }
        }
         return new FedExpandView();
    }());

This is how i am getting static data into the table...
can some one help me in getting data of the remaining rows...

A: Try this example
JS
function checkTable() {
  var rowElem;

  $('#my-table tr').each(function(idx, elem) {
    rowElem = $(elem);

    if(rowElem.find('input').is(':checked')) {
      console.log('row ' + (idx + 1) + ' is checked');
      console.log('data1 is: ' + rowElem.find('.data1').html());
      console.log('data2 is: ' + rowElem.find('.data2').html());
    }
  });
}

HTML

      <input type="checkbox">

    Row1 Data1
    Row1 Data2

      <input type="checkbox">

    Row2 Data1
    Row2 Data2

      <input type="checkbox">

    Row3 Data1
    Row3 Data2

<button onclick="checkTable()">Check table</button>

Plunker demo

A:             $("#my-table tbody tr").on('click', function (event) {
                serviceSets.length = 0;
                var rows = $('table tr td :checkbox:checked').map(function () {
                    return $(this).val();
                }).get();
                $( rows ).each(function() {
                    var that = this;
                    $( Tabledata ).each(function() {
                    if(that == this.ssid)
                    {
                        serviceSets.push(this);
                    }
                    });
                });
            });


text:
Q: Why all images become invalid after Cleaning the project? The console says :

Could not load the "xxx" image referenced from a nib in the bundle with identifier

And all my imageviews become blank.
How do I fix this problem? Thanks.

A: While adding the images to your project a dialog box is opened, click

Select "Create groups for any added folders" which Xcode generally select was not the case, & check whether it is added to your Target or not, the target checkbox should be clicked.

Hope this will solve your problem.

A: I guess this is a wired caching bug from xcode that the xib file wont get updated. Please delete "xxx" image and reference corresponding from the nib file. Now rename the "xxx" image to another name, copy to the project folder and add to the project. Reconnect to the nib. Clean the project and run.
Make sure that the image type is .jpg or .png
Hope this will help you.

A: For people who caught with the same problem:
I eventually copy all the files to a new project and everything works as charm.
So I guess it was caused by some unknown caching bugs in Xcode and Simulator. Hopes this would help.
Thanks to @Rajat and @rejupal


text:
Q: Prolog assigning "\r" when 13 is used Started learning prolog this past week and am having trouble with how variables are assigned in this particular case where it is a list containing one element inside of a list.
?- X = [[13]].
X = ["\r"]

Why is prolog assigning ["\r"]? What can be done so it assigns that actual value?

A: It is exactly that "actual value". It just shows up differently on the top level.
In most Prologs, a list of small integers and a list of character codes are identical. In other words, those two, [13] and "\r", cannot be told apart. So, when you put a 13 in a list, your particular Prolog thinks you meant to make a list of (ASCII) codes, and since 13 is the value of the carriage return, this is what it shows you. (Here, a string of characters enclosed in double quotes is just another way of representing that list of small integers). But this really depends on the implementation. Here is what my Prolog (SWI-Prolog v7) tells me:
?- X = [[13]].
X = [[13]].

Just to confuse you even more, you could have written the above in another way: as a list of character codes in 0' notation:
?- X = [0'\r], Y = [0'\xd].
X = Y, Y = [13].

(Not sure what you are going to see: consult the documentation of you implementation for such details.)
The 0' notation is a way to directly take the numerical value of a character: 0'a is the same as 97. So, the X above is the numerical value of the carriage return, which is 13, which is 0xD in hexadecimal.


text:
Q: Want to have my textarea format it's readonly text like html I have a read-only textarea that I display which acts as my old blog posts (which are editable in a field below it) and I'd like to be able to format it's contents somewhat.  Ideally, I'd like it to look like HTML code, but at the very least, I'd like when the entered a URL, I'd like to display it as a href link.
Are there any best practices for this?  Or do I have to process each and look for and format the items I want?
Thanks in advance.

A: Use a simple div (or paragraph element, or whatever) with the white-space: pre CSS property to display newlines.
#div-mimicking-textarea { white-space: pre; }

It is not possible to have an anchor element within a textarea.


text:
Q: filter angularjs don't working In my web the people can create events and sign up. In the event list there are two buttons ( sign up/ sign off ).
button ( sign up ): when you press this button you will add you in the event like assistant.
button (sign off). when you press this button you will remove of event.
this working well, but the problem is in the filter:
{{ event.attendees }} // working well because is updated when press the button
{{ ([event.attendees] | filter:currentUser.id).length }} // not working always is 0

<button id="signup" ng-click="sign(event.attendees, currentUser.id)" ng-show="([event.attendees] | filter:currentUser.id).length == 0">
<button id="signdown" ng-click="sign(event.attendees, currentUser.id)" ng-show="([event.attendees] | filter:currentUser.id).length == 0">

controller(){

$scope.signup = function(attendees, currentUser_id) {
    attendees.push(currentUser_id);
}

i want that when you press the button signup making fadeout in button signup and fadein in button signdown but the filter not working because don't update.

A: You're wrapping event.attendees in square brackets. That means what you're actually doing is filtering an array with a single element, your array of attendees. This will never find the string you're searching for. Try this instead:
{{ (event.attendees | filter:currentUser.id).length }}

Now, I have had bad experiences with infinite digest loops using the same filter in multiple places on a page, and this isn't really the way filters are supposed to be used anyway. So, I recommend you consider adding an isSignedUp function to your controller. You can implement this easily using underscorejs:
$scope.isSignedUp = function(attendees, id) {
    return _.findWhere(attendees, {id: id}) !== undefined;
}


text:
Q: Geometric Algebra formulation of EM in nonuniform dielectric media Normally, there is a straightforward formulation of Maxwell's equations in free space under the GA framework, which reduces to (picking the right units):
$$
\nabla F = \mu_0 J
$$
with some appropriately defined bivector field $F$, some current vector $J$, and $c=1$.
Now, I've been working on several topics with non-uniform dielectric media, where I seem to lose a lot of the symmetry that is necessary in order to deal with Maxwell's equations from a GA perspective without resorting back to the original vector formulation and using the geometric algebra framework as a mostly ad-hoc method to deal with a few operations.
Are there any papers covering GA in nonuniform dielectric media? E.g. for photonic crystals or other similar applications?


text:
Q: i want to zoom user1 location direction using direction render api form this pkg @react-google-maps/api I want zoom customer location direction
I was trying zoom user1 location like the user has driver zoom location and the customer has driver zoom
location


text:
Q: How to calculate the file size downloaded and the total data to be downloaded in Java? How to calculate the amount of data downloaded and the total data to be downloaded in Java?
E.G. 12kb/130kb...110kb/130kb

A: If you mean downloading files via http using URLConnection, then you can

*

*get the Content-Length response header to get the total size. This is done via connection.getContentLength()

*to get the already downloaded amount, just count the bytes you have processed from the stream.

A: To get amount of data that has been downloaded you can use
CountingInputStream from Apache Commons IO. See
http://commons.apache.org/io/apidocs/org/apache/commons/io/input/CountingInputStream.html
Wrap your stream in it.
To get total length you need to use information from the server. For example,
Content-Length header as previously mentioned. But it only works for http.
It may not always be possible in generic case.


text:
Q: Probabilities that a student will pass different tests (probabilty for each test)
*

*A student takes test with multiple variants (A, B, C, D) always picking up A.
There is only one correct answer and there is no pattern thus the answers are randomly placed. There are 100 questions.

As I understand, the chance that the student will answer all 100 questions correctly is (1/4)^100.
Q: What is the chance of the student getting:
a) 50 correct answers;
b) 75 correct answers;
c) 90 correct answers;
d) 0 correct answers (i feel like this one is (3/4)^100 but i'm not sure);
and how did you calculate each chance?

*A student takes true/false test always picking up true.
There is no pattern thus the answers are randomly placed. There are 100 questions.

As I understand, the chance that he will answer all 100 questions correctly is (1/2)^100.
Q: What is the chance that he will answer 50 questions correctly?
I feel like the chance is 50% but i don't have any calculations for this.

A: Hint -
You can use binomial distribution -
$p(Correct) = \frac14$
$q(Incorrect) = 1 - \frac 14 = \frac34$
Now according to bionamial distribution.
$P(X=r) = \binom nr × (q)^{n-r} × (p)^r$
a.) Here X = 50 and n = 100.
b.) Here X = 75 and n = 100.
You can similarly do other parts.


text:
Q: How to change the resolution from static to dynamic in fragment shader I have working fragment shader for resolution 1920x1080. However, I want to change to a dynamic resolution whatever user select.
I have referred < http://www.fourcc.org/source/YUV420P-OpenGL-GLSLang.c > this link and modified the line ny=576.0-gl_TexCoord[0].y;\n to ny=1080.0-gl_TexCoord[0].y;\n for 1920 x 1080.
The full source of my program is
#include <cplaywidget.h>
#include <mainwindow.h>

#define ATTRIB_VERTEX 3
#define ATTRIB_TEXTURE 4
#define BHANU
#define WORKING_420P
#define YUY2_test

extern int g_cs_Index;
#ifdef BHANU
QOpenGLTexture* texName;
GLuint texture;
#endif

#ifdef YUY2_test
GLubyte *Ytex,*UVtex;
GLhandleARB FSHandle,PHandle;
QOpenGLExtension_ARB_shader_objects* myShader = new QOpenGLExtension_ARB_shader_objects();

// fy   = /*1080.0-*/gl_TexCoord[0].y;
const char *FProgram=
      "uniform sampler2DRect Ytex;\n"
      "uniform sampler2DRect UVtex;\n"
      "void main(void) {\n"
      "  float fx, fy, y, u, v, r, g, b;\n"

      "  fx   = gl_TexCoord[0].x;\n"
      "  fy   = 1080.0-gl_TexCoord[0].y;\n"

      "  y = texture2DRect(Ytex,vec2(fx,fy)).a;\n"
      "  u = texture2DRect(UVtex,vec2(fx/2.0,fy)).b;\n"
      "  v = texture2DRect(UVtex,vec2(fx/2.0,fy)).r;\n"

      "  y=1.164*(y-0.0627);\n"
      "  u=u-0.5;\n"
      "  v=v-0.5;\n"
      "  r = y+1.5958*v;\n"
      "  g = y-0.39173*u-0.81290*v;\n"
      "  b = y+2.017*u;\n"
      "  gl_FragColor=vec4(r, g, b, 1.0);\n"

      "}\n";
#endif
extern camera_t* camera;

CPlayWidget::CPlayWidget(QWidget *parent):QOpenGLWidget(parent)
{
    textureUniformY = 0;
    textureUniformU = 0;
    textureUniformV = 0;

    id_y = 0;
    id_u = 0;
    id_v = 0;

    m_pBufYuv420p = NULL;
    m_pVSHader = NULL;
    m_pFSHader = NULL;
    m_pShaderProgram = NULL;
    m_pTextureY = NULL;
    m_pTextureU = NULL;
    m_pTextureV = NULL;
    m_pYuvFile = NULL;
    m_nVideoH = 0;
    m_nVideoW = 0;
}

CPlayWidget::~CPlayWidget()
{

}

void CPlayWidget::initializeGL()
{

    initializeOpenGLFunctions();

#ifdef YUY2_test
    int i;
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0,1920,0,1080,-1,1);
    glViewport(0,0,1920,1080);
    glClearColor(0,0,0,0);
    glColor3f(1.0,0.84,0.0);
    glHint(GL_POLYGON_SMOOTH_HINT,GL_NICEST);

     myShader->initializeOpenGLFunctions();

    PHandle = myShader->glCreateProgramObjectARB();
    FSHandle= myShader->glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB);

    myShader->glShaderSourceARB(FSHandle,1,&FProgram,NULL);
    myShader->glCompileShaderARB(FSHandle);

    myShader->glGetObjectParameterivARB(FSHandle,GL_OBJECT_COMPILE_STATUS_ARB,&i);

    myShader->glAttachObjectARB(PHandle,FSHandle);
    myShader->glLinkProgramARB(PHandle);

    myShader->glUseProgramObjectARB(PHandle);

#endif
}

void CPlayWidget::resizeGL(int w, int h)
{
    if(h == 0)
    {
    h = 1;
    }
    glViewport(0,0, w,h);
}

 void CPlayWidget::paintGL()
 {
 #ifdef YUY2_test
     int i;
     glClear(0);

     glActiveTexture(GL_TEXTURE1);
     i=myShader->glGetUniformLocationARB(PHandle,"UVtex");
     myShader->glUniform1iARB(i,1);  /* Bind Utex to texture unit 1 -YUY2 working*/
     glBindTexture(GL_TEXTURE_RECTANGLE_NV, 1);
     glEnable(GL_TEXTURE_RECTANGLE_NV);

     glTexParameteri(GL_TEXTURE_RECTANGLE_NV,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
     glTexParameteri(GL_TEXTURE_RECTANGLE_NV,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
     glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_DECAL);
     glTexImage2D(GL_TEXTURE_RECTANGLE_NV,0,GL_RGBA8, 1920/2/*(camera->width/2)*/, 1080/*(camera->height)*/,0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, UVtex); //UV

     glActiveTexture(GL_TEXTURE0);
     i=myShader->glGetUniformLocationARB(PHandle,"Ytex");
     myShader->glUniform1iARB(i,0);  /* Bind Ytex to texture unit 0 -YUY2 Working*/
     glBindTexture(GL_TEXTURE_RECTANGLE_NV, 2);//id_y);
     glEnable(GL_TEXTURE_RECTANGLE_NV);

     glTexParameteri(GL_TEXTURE_RECTANGLE_NV,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
     glTexParameteri(GL_TEXTURE_RECTANGLE_NV,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
     glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_DECAL);
     glTexImage2D(GL_TEXTURE_RECTANGLE_NV, 0, GL_LUMINANCE_ALPHA, 1920, 1080, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE,Ytex); //Y

     glBegin(GL_QUADS);
     glTexCoord2i(0,0);
     glVertex2i(0,0);
     glTexCoord2i(1920,0);
     glVertex2i(1920,0);
     glTexCoord2i(1920,1080);
     glVertex2i(1920,1080);
     glTexCoord2i(0,1080);
     glVertex2i(0,1080);
     glEnd();

     glDrawArrays(GL_QUADS, 0, 4);

#endif
    return;
 }

void CPlayWidget::PlayOneFrame(unsigned char *l_ui_arr)

{

    m_nVideoW = camera->width;
    m_nVideoH = camera->height;
    int nLen;

    switch (g_cs_Index)
    {
    case I420:
    case I422:
    case YV12:
     nLen = m_nVideoW*m_nVideoH*3/2;
    break;
    case RGB24:
     nLen = m_nVideoW*m_nVideoH*3;
    break;
    case YUY2:
    case UYVY:
    nLen = m_nVideoW*m_nVideoH*2;
       break;
    case RGB32:
     nLen = m_nVideoW*m_nVideoH*4;
    break;
    default:
     qDebug() << "Unsupported format\n";
    }

    if(NULL == m_pBufYuv420p)
    {
    m_pBufYuv420p = new unsigned char[nLen];
    Ytex=(GLubyte *)malloc(nLen);
    UVtex = (GLubyte *)malloc(nLen);
    qDebug("CPlayWidget::PlayOneFrame new data memory. Len=%d width=%d height=%d\n",
           nLen, m_nVideoW, m_nVideoH);
    }
    m_pBufYuv420p = l_ui_arr;

    Ytex =UVtex = (GLubyte *)m_pBufYuv420p;
    update();
    return;
}

How to change the resolution from static to dynamic in the fragment shader (dynamic means the user will select the resolution it can be 640x480, 800x600, 1920x1200 and so on)?

A: Don't hardcode your constants. Instead calculate them at runtime in the hostcode and pass them to the shader via uniforms.


text:
Q: HttpURLConnection failing on POST with HTTP 400 HttpURLConnection sometimes fails on POST operations to a http URL. In my case the following fails about one of a hundred times:
byte[] formData = ("mgnlUserId=" + user + "&mgnlUserPSWD=" + user).getBytes(StandardCharsets.UTF_8);
URL url = new URL("http://localhost:8080/magnoliaAuthor/.magnolia/admincentral");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", Integer.toString(formData.length));
connection.getOutputStream().write(formData);
connection.connect();

// Sometimes fails with response code being 400
assertEquals(200, connection.getResponseCode());

The server complains about the bad request too:
HTTP Status 400 – Bad Request
Invalid character found in method name [User-Agent:]. HTTP method names must be tokens
The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).
java.lang.IllegalArgumentException: Invalid character found in method name [User-Agent:]. HTTP method names must be tokens

Here's some example code for reproducing the problem.
For now this looks like a bug to me but I couldn't find anything related in the Java bug tracker.
Anyone experiencing similar issues and has a workaround?

A: This is indeed a bug of HttpURLConnection.
Looking at the HTTP request going over the wire I can see the HTTP method is set to User-Agent: instead of GET:

And the log output show the same faulty request being sent:
Nov 03, 2021 8:37:01 PM sun.net.www.protocol.http.HttpURLConnection plainConnect0
FINEST: ProxySelector Request for http://localhost:8080/magnoliaAuthor/.magnolia/admincentral
Nov 03, 2021 8:37:01 PM sun.net.www.http.HttpClient logFinest
FINEST: KeepAlive stream retrieved from the cache, sun.net.www.http.HttpClient(http://localhost:8080/magnoliaAuthor/.magnolia/admincentral;jsessionid=44DEE0C8C535782A6B4932E9F0D455ED)
Nov 03, 2021 8:37:01 PM sun.net.www.protocol.http.HttpURLConnection plainConnect0
FINEST: Proxy used: DIRECT
Nov 03, 2021 8:37:01 PM sun.net.www.protocol.http.HttpURLConnection writeRequests
FINE: sun.net.www.MessageHeader@15b170d89 pairs: {POST /magnoliaAuthor/.magnolia/admincentral HTTP/1.1: null}{Content-Type: application/x-www-form-urlencoded}{Cookie: csrf=ZOxgq4P_WMgLjCm3J4mWPEFFNhmIUiHlq9of5JhtKys}{charset: utf-8}{User-Agent: Java/1.8.0_181}{Host: localhost:8080}{Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2}{Connection: keep-alive}{Content-Length: 92}
Nov 03, 2021 8:37:01 PM sun.net.www.protocol.http.HttpURLConnection writeRequests
FINE: sun.net.www.MessageHeader@15b170d89 pairs: {POST /magnoliaAuthor/.magnolia/admincentral HTTP/1.1: null}{Content-Type: application/x-www-form-urlencoded}{Cookie: csrf=ZOxgq4P_WMgLjCm3J4mWPEFFNhmIUiHlq9of5JhtKys}{charset: utf-8}{User-Agent: Java/1.8.0_181}{Host: localhost:8080}{Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2}{Connection: keep-alive}{Content-Length: 92}
Nov 03, 2021 8:37:01 PM sun.net.www.protocol.http.HttpURLConnection getInputStream0
FINE: sun.net.www.MessageHeader@52ae5ad55 pairs: {null: HTTP/1.1 302}{Set-Cookie: JSESSIONID=88DCCC46C9E70CBA8262CF8060A033C0; Path=/magnoliaAuthor; HttpOnly}{Location: /magnoliaAuthor/.magnolia/admincentral;jsessionid=88DCCC46C9E70CBA8262CF8060A033C0}{Content-Length: 0}{Date: Wed, 03 Nov 2021 19:37:01 GMT}
Nov 03, 2021 8:37:01 PM sun.net.www.protocol.http.HttpURLConnection followRedirect0
FINE: Redirected from http://localhost:8080/magnoliaAuthor/.magnolia/admincentral to http://localhost:8080/magnoliaAuthor/.magnolia/admincentral;jsessionid=88DCCC46C9E70CBA8262CF8060A033C0
Nov 03, 2021 8:37:01 PM sun.net.www.protocol.http.HttpURLConnection plainConnect0
FINEST: ProxySelector Request for http://localhost:8080/magnoliaAuthor/.magnolia/admincentral;jsessionid=88DCCC46C9E70CBA8262CF8060A033C0
Nov 03, 2021 8:37:01 PM sun.net.www.protocol.http.HttpURLConnection plainConnect0
FINEST: Proxy used: DIRECT
Nov 03, 2021 8:37:01 PM sun.net.www.protocol.http.HttpURLConnection writeRequests
FINE: sun.net.www.MessageHeader@774fca3c4 pairs: {User-Agent: Java/1.8.0_181}{Host: localhost:8080}{Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2}{Connection: close}
Nov 03, 2021 8:37:01 PM sun.net.www.protocol.http.HttpURLConnection getInputStream0
FINE: sun.net.www.MessageHeader@57256a0d6 pairs: {null: HTTP/1.1 400}{Content-Type: text/html;charset=utf-8}{Content-Language: en}{Content-Length: 2244}{Date: Wed, 03 Nov 2021 19:37:01 GMT}{Connection: close}

Digging deeper I found out that, when HttpURLConnection initiates a POST on a reused connection but finds the socket closed, it will internally recover and open a new connection. If this POST succeeds and the server sends a redirect status (302) it will attempt to follow the redirect. However, internally it fails to correctly initialise the request headers: after creating a new set of headers, it will not set the HTTP method because failedOnce is true at this point from the first POST on the closed socket
Update: this is now tracked as a bug.
Update 2: this has now been fixed


text:
Q: Один из параметров JSON в качестве значения переменной долго думал но так и не получилось сделать чтобы работало но я знаю что подобное можно.
У меня следующий код
jsoncod = "https://SITE/category/initCall?service_id=ID&key=KEY&phone=" + phone + "&client=test"
    response = requests.get(jsoncod)
    print(response.json())
    print(response[0]["ucaller_id"])

Мы получаем параметр из get запроса и записываем его в jsoncod.
Как мне из jsoncod вывести определённое значение?
Так выглядит json:
{
    "status": true,
    "ucaller_id": 103000,
    "code": 7777,
    "client": "nickname",
}

В результате я должен получить переменную в которой будет значение ucaller_id тоесть 103000
(статьи с этого же сайта не помогли)

A: Нашёл выход сам.
    jsoncod = "https://SITE/category/initCall?service_id=ID&key=KEY&phone=" + phone + "&client=test"
    response = requests.get(jsoncod)
    response1 = response.json()
    print(response1)
    print(response1['ucaller_id'])
    print('Звонок отправлен!')

Пришлось попотеть чтобы это сделать на питоне...

A: import requests
import json
phone = '+7922250000'

url = f"https://SITE/category/initCall?service_id=ID&key=KEY&phone={phone}&client=test"
response = requests.get(
    url
)

try:
    data: dict = response.json()
except json.JSONDecodeError:
    print('check the number')
else:
    print(data.get('ucaller_id'))

Если не поможет, шлите живой url сайта
Но параметры service_id=ID&key=KEY меня откровенно смущают.   Надеюсь у Вас в рабочей версии поставлены реальные ID и KEY


text:
Q: Why the GIT quotient $\mathbb{A}^m//\mathbb G_{m}$ is empty? Let $\mathbb{A}^m ={\text{Spec }}\mathbb{C}[x_1,\dots,x_m]$, and the multiplicative group $\mathbb G_m \cong \mathbb{C}^*$ acts on $\mathbb{C}[x_1,\dots,x_m]$ by
$$\lambda_t (x_1,\dots,x_m)= (t^{a_1}x_1,\dots,t^{a_m}x_m)$$
suppose for all $i, a_i >0$.
Then it is claimed the GIT quotient $\mathbb{A}^m//\mathbb G_{m}$ is empty, but I did not see why this is true. I am not good at GIT stuff, and I don't know why this is different from
$$\mathbb{A}^m//G_{m} = \text{Spec }\mathbb{C}[x_1,\dots,x_m]^{G_m} = \text{Spec }\mathbb{C}?$$

A: Denote $A=\mathbb C[x_1, \ldots, x_m]$, $X=\operatorname{Spec} A$ and $G=\mathbb G_m$. First, there is an affine quotient $X/G := \operatorname{Spec} \left( A^G \right)$, which in this particular case is a point.
Second, there is a GIT quotient
$$X //_{\mathcal L} G=\operatorname{Proj} \left( \bigoplus_{k \geqslant 0} H^0(X, \mathcal L^{\otimes k})^G \right),$$
which depends on the choice of $G$-linearized line bundle $\mathcal L$ on $X$. There are no non-trivial line bundles on $X=\mathbb A^m$, and $G=\mathbb G_m$ is connected, therefore $\mathcal L=\mathcal O(\chi)$ for a character $\chi: G \to \mathbb G_m$. It implies that
$$H^0 \left( X, \mathcal O(\chi^k) \right)^G=A^G_{\chi^k}:=\{ f \in A: f(gx)=\chi^k(g) f(x) \},$$
a subspace of $\chi^k$-semi-invariant functions.

*

*If $\chi(g)=1$ for all $g \in G$, then
$$X //_{\mathcal O(\chi)} G=\operatorname{Proj} \left( A^G[t] \right)=\operatorname{Spec} \left( A^G \right)$$
is an affine quotient again.

*Instead one should take $\chi(g)=g$, then
$$X //_{\mathcal O(\chi)} G=\operatorname{Proj} A$$
with the usual grading on $A$, that is a weighted projective space.

*More generally, if $\chi(g)=g^k$ with $k>0$, then the grading is $\deg x_i=k  \cdot a_i$, but the quotient is still a weighted projective space.

*At last, if $\chi(g)=g^k$ with $k<0$, then
$$X //_{\mathcal O(\chi)} G=\operatorname{Proj} \left( A^G \right)$$
is indeed empty.
For details, see Mukai An introduction to invariants and moduli, chapter 6.1.


text:
Q: SimpleXML IF condition I have an XML document that will either return a URL or an error code. If it returns an error code I'd like to redirect the page to an error image. I can get SimpleXML to return the URL, but I am not sure how to write a condition if the error returns. If anyone has any suggestions, that'd be great! This is what I have right now:
<?php
error_reporting(0);

$url = 'http://radiocast.co/art/api1/key=KeyHere&album=' . htmlspecialchars($_GET["album"]) . '&artist=' . htmlspecialchars($_GET["artist"]) . '';
$xml = simplexml_load_file($url);

$img = $xml->xpath('//image[@size="large"]');

$large = (string)$img[0];

header("Location:".urldecode($large));

?>

This is what the XML document returns if it cannot be found:
<?xml version="1.0" encoding="utf-8"?>
<lookup status="failed">
<error code="3">Art not found</error></lookup>

A: How about checking for the error node in your XML, and if you find it then handling the various errors? If you don't find it you can continue with your normal logic.
if (isset($xml->error)) {
    switch ($xml->error['code']) {
        case '3':
            // not found stuff here
            break;

        // other error codes here
    }
} else {
    // success logic here
    $img = $xml->xpath('//image[@size="large"]');
    $large = (string) $img[0];
    header("Location: " . urldecode($large));
}


text:
Q: Calculate time energy is stored in capacitor I have this problem:
I've calculated A) to be 8 nJ, and my Vc(0) = 4 V and Vc(∞) = 0 V. I tried using the wc(t) = 1/2CVc^2 formula to calculate the time when the energy of the capacitor is 1 nJ. However I failed. How should I think when trying to calculate the time?


text:
Q: C++: Writing to a file inside of a function, opening that file in main I've been trying my best to solve a little problem I have but am struggling to find a sensible solution/explanation so I was hoping someone could help?
I have basically created a function which, inside, writes to a file, and I was hoping that outside of this I would be able to open that said file but I get the following error:

Undefined symbol: ReadingAFile(std::__1::basic_string<char,
std::__1::char_traits, std::__1::allocator >)

My codes are as follows:
Function:
void CreatingAFile(int n)
{
    matrix_Struct matrix_A;
    matrix_A.value = n;
    matrix_A.symmetric = 1;

    std::ofstream writeFile;
    writeFile.open("fileToOpen.dat");
    assert(writeFile.is_open());

    writeFile << "Symmetry" << "\n";
    writeFile << matrix_A.symmetric << "\n";
    writeFile << "Number to Iterate";
    writeFile << matrix_A.value << "\n";
}

My main:
int main()
{
    CreatingAFile(3);
    csr_matrix file3 = ReadingAFile("fileToOpen.dat");
}

where ReadingAFile is a file from another header of mine, that runs perfectly fine - it has a function prototype:
matrix_Struct ReadingAFile(std::string nameOfFile);


text:
Q: How does Bruce Wayne justify his Batman expenses? Just recently, I took a job as a DBA (Database Administrator) in a huge financial company. One of the Databases I mantain is the accounting database, where every single penny spent on anything by anyone in the company is registered.
That got me thinking. How would Bruce Wayne justify all the expenses he has made for his Batman persona? The batmobile, the gadgets, probably the batcave construction, the suit...I could go on, and on. After all, most if not all of those things are based on Wayne Enterprises own investigation and technology division.
Now, I know in the Nolan trilogy some accountant caught that and tried to blackmail Lucius Fox, only to be "persuaded" not to. But what about in the other Batman continuities? (Comics, cartoons, TV shows).
Can he just do whatever he wants with his company money only because he's Bruce Wayne?

A: Here's the thing. You're thinking this through from the point of a company having to report their money and thinking, "Bruce gets all his toys from Wayne Tech so they have to hide it in some way." This isn't the case. He uses Wayne Tech R&D, but nothing off the books in that way. And anything he does use like that it's replicated on his scale, not using Wayne Tech, but however he does it; personal workshop, personal manufacturing, hiring out people, etc. There is no "hiding things on the books". Lucious doesn't do anything with the financial in regards to what you're asking. What he does is fund allocation and help give Bruce access to and apprised of that information without Bruce having to look into it directly or allocate funds for projects directly and look suspicious.
This brings us back to the question at hand, "the how does he fund it all?" It's an insane answer, but there are 2 sources. Any finances he does that has to do with Wayne Enterprises is Petty Cash. He does use this for various things, mainly on the fly when needed things that turn up right that second things. The other source is, as I said, insane. It's his liquid assets that he has. Obviously he doesn't keep all his cash on hand, but he assuredly has millions on hand in Wayne Manor.
I know you're thinking that it's impossible, because noone is that rich. Even the richest men on Earth don't have that kind of money to keep that much on hand. I'd agree that it's ludicrious to assert that this is where the money comes from (well that which can't be written off in some other way for example, hiring construction crews to build supports and such in caves under a house isn't all that strange when the entire area is on a fault line with sink holes and caves running through it...) but in the case of Bruce Wayne, it is true and Bruce Wayne really is "that rich". How rich you ask? Bruce Wayne is the primary owner of the biggest most successful conglomerates in his world, many of his companies being worth multi-billions and he's the primary stake holder of those too. That puts him as richer than any person on real Earth you might be thinking of with that alone. He is also finances a good number of all the business in Gotham (it's something like 1 in 4 to 10. It's been a while since I saw the number). So he's got lots of capital coming in from all of that, but then he also has his Mother's family personal wealth (The Kanes. I think they went Bankrupt though I forget) and Father's family's personal wealth which was separate from the corporate endeavors. The Wayne Fortune has a bunch of literal gold bars like fort knox as a part of it, but ignoring trying to find out what else it has in it there is only 1 thing that is really important from it, and that is Bruce Wayne literally owns 1/3 of Gotham... before getting into any of that other ownership that his Company or those businesses own or anything like that. All the land that is Gotham, at least 1/3 of it is owned by Bruce Wayne. So what does this mean? Gotham is one of the biggest cities in the world and is supposed to be equivelant to a New York. Theoretically Gotham's land should be worth more than New York's and New York's land is, if I remember right, the most valuable in the world.
In other words Bruce Wayne is literally worth Trillions of dollars without even discussing his corporate holdings, probably in the multi hundreds, if not tens of trillions, not Billions, Trillions. He has that much cash to just have on hand.
This fact, along with the Playboy, risk taking, crazy buying, persona hides all the costs he needs. And yes "Batman" is a multi-million dollar expense to set-up, but not as expensive as people think, because they things that generally get trashed aren't as expensive as you might think, or don't get trashed in the way that makes them expensive...
Another thing that hides it, which is weird, is that he is constantly upgrading and manufacturing things that are expensive like the different Batwings and Batmobiles. It looks strange for you to have a sudden expense that just happens to match the cost of repairing something that Batman just lost. It doesn't look strange if your costs are constant.
So... Lots of untraceable money + understanding how things look to people who investigate this stuff + being able to explain a lot of things due to the circumstance of Gotham

A: With the help of Lucius Fox
In most iterations of the mythos, Bruce funnels technology and resources from Wayne Enterprises with the help of its CEO, Lucius Fox.

DCComics.com has this to say about Mr. Fox:

If Alfred Pennyworth is the man behind the Bat—the voice of reason and emotional support for the Dark Knight—Lucius Fox is the man behind Bruce Wayne, providing him with the technology and gadgetry he needs while single-handedly maintaining the financial integrity of Wayne Enterprises.
As CEO, Lucius presides over the strategy and management of Bruce Wayne's multi-billion dollar company, ensuring it remains profitable while remaining ethical. Very intelligent and with a knack for business that's second to none, Lucius plays a crucial role in ensuring the financial security of the business, which allows Bruce to concentrate on his more nocturnally inclined activities as Batman. Whether or not Lucius is fully aware of his employer's vigilantism is unclear, but he has admitted that he prefers to retain a level of "plausible deniability." Regardless, Lucius does tend to allocate funds toward research and development projects that would be incredibly beneficial to the Dark Knight's cause.
Lucius Fox's resourcefulness and business acumen place him alongside Alfred and Commissioner Gordon as a valuable asset to the Dark Knight, without whom Batman's success would be much more difficult to achieve…if not outright impossible.

What if the hero-funding was ever questioned?
It's worth taking note of the bolded text from the quote that says that Lucius single-handedly maintains the financial integrity of Wayne Enterprises. A typical DBA, financial officer, or other employee wouldn't be suspicious because there is no illegitimate activity going on. Everything Fox provides for Batman presumably has a legitimate purpose within the company he can refer to if anything was ever questioned.


text:
Q: MongoDB Transform element fields into array of values only I need help with following thing in MongoDB, what I'm trying to do is to get only marks in reviews into it's own array of values only.
Code i got so far:
db.lodging.aggregate([
    {$project:{
        reviews:"$host.reviews",host:"$host"
        }
    },
    {$unwind: "$reviews"},
])

JSON Example:
 "host" : {
    "name" : "Grimes",
    "surname" : "Terrell",
    "gender" : "male",
    "age" : NumberInt(55),
    "picture" : "https://api.adorable.io/avatars/285/GrimesTerrell.png",
    "reviews" : [
        {
            "reviewer" : "Mae Ryan",
            "date" : "2015-06-01T02:41:46 -02:00",
            "helpful" : NumberInt(8),
            "kind" : NumberInt(1),
            "responsive" : NumberInt(5)
        },
        {
            "reviewer" : "Nixon Johnson",
            "date" : "2016-02-08T10:35:12 -01:00",
            "helpful" : NumberInt(1),
            "kind" : NumberInt(1),
            "responsive" : NumberInt(9)
        },
    ]
}

This is what im trying to achieve:
{
    "host" : {
    "name" : "Grimes",
    "surname" : "Terrell",
    "gender" : "male",
    "age" : NumberInt(55),
    "picture" : "https://api.adorable.io/avatars/285/GrimesTerrell.png",
    "reviews" : [
        {
            "marks" : [8,1,5],
        },
        {
            "marks" : [1,1,9],
        },
    ]
}

A: Assuming your marks' field names are always helpful, kind, responsive, you can use $map.
Here is a mongo playground for you reference


text:
Q: Python while loop not working with two conditions Im trying to make a while loop that stops when two variables are equal to 0, but when one of them reaches 0 the loop ends, and I have no clue why. This is what I have...
  movement=3
  attacks=1
  while (attacks != 0) and (movement != 0):
    do = input('what to do?')
    if do == 'move':
      movement -=1
    if do =='attack':
      attacks -=1

I could be missing something obvious, but any help is appreciated

A: You had two mistakes in your code.
The first one was you did not close your quotes in your input.
The second was you used an assigning operator = instead of a comparison operator = on line 7.
Cleaned up code.
movement=3
attacks=1
while (attacks != 0) and (movement != 0):
    do=input('what to do?')
    if do=='move':movement-=1
    if do=='attack':attacks-=1

A: The loop will continue as long as the predicate (attacks != 0) and (movement != 0) is true. Therefore the loop will stop once the predicate is false. The predicate is false exactly when EITHER attacks == 0 OR movement == 0. This is the negation of the predicate.
If you want the loop to end ONLY when both are 0, then you're saying you want the loop to continue as long as (attacks != 0) or (movement != 0) as the negation of that predicate is attacks == 0 and movement == 0.
To find out more, see De Morgan's Laws

A: There are some syntax errors in your code, after fixing it it seems that in a while loop with 2 conditions doesn't work, here's a working version of it:
movement = 3
attacks = 1
while True:
    if attacks == 0 and movement == 0: break
    do = input('what to do?')
    if do == 'move':
        movement-=1
    if do == 'attack':
        attacks-=1

So you create an infinite loop and inside it you check if the attacks and movement are both equal to 0, and if they're, then break out of the loop.


text:
Q: Finding the path with the least number of edges under a certain ticket cost I'm having trouble with this local contest problem. We need to find the shortest number of "plays" for 3 players in [position1, position2, position3] to move to [dest1, dest2, dest3]. All players must move each play, none of them can be in the same place at once, and we are given an adjacency list with neighbours and mode of transportation. We also have a maximum number of tickets for each mode of transportation (There are 3 different modes of transportation, and they all cost 1 ticket per usage). Any ideas?
Only thing I've come up with so far is brute-force BFS with heuristic, since we are also given physical coordinates for each position, but this is way too slow.


text:
Q: ¿Error al agregar dos condiciones WHERE en una consula MySQLi? Quiero mostrar datos mediante dos condiciones WHERE, preguntas por categorías y que estas preguntas estén habilitadas al publico.
Realizo lo siguiente:
$categoria = "categoria_uno";
$habilitado = "1";
$stmt = $conexion->prepare("SELECT id,pregunta,fecha FROM questions WHERE categoria=? AND WHERE habilitado=? order by id DESC");
$stmt->bind_param("si",$categoria,$habilitado)

Pero me muestra un error en la linea: $stmt->bind_param("si",$categoria,$habilitado)
Mostrándome lo siguiente:

Fatal error: Call to a member function bind_param() on boolean

Porque el error, que otro parámetro debo pasar en WHERE categoria=? AND WHERE habilitado=?

A: No es necesario agregar más de una vez WHERE, no es necesario repetirlo por cada condición que desees agregar a la consulta.
Debes quitar el WHERE adicional, de la siguiente manera:
WHERE categoria=? AND habilitado=?

Y así sucesivamente si deseas pasarlas más condiciones simplemente añades otro AND ejemplo:
WHERE categoria=? AND habilitado=? AND otracondicion=? AND otros=?

Al final la consulta debe quedar de tal forma:
$stmt = $conexion->prepare("SELECT id,pregunta,fecha FROM questions WHERE categoria=? AND habilitado=? order by id DESC");

A: Tienes 2 detalles mal:

*

*Si el campo de habilitado en tu bind_param() lo marcas como integer, entonces quitale las comillas al valor en la variable

*quita el where que esta de mas
<?php
$categoria = "categoria_uno";
$habilitado = 1;
$stmt = $conexion->prepare("SELECT id,pregunta,fecha FROM questions WHERE
categoria=? AND habilitado=? order by id DESC");
$stmt->bind_param("si",$categoria,$habilitado)

Debes comprender que si agregas comillas a un valor lo estas
  transformando a cadena de texto


text:
Q: Switching the direction of DC current flow to a load I am a beginner (Software field) trying to do some basics in electronics.
I have got a load and a power source like this

My requirement is just to switch direction of dc current to the load in a controlled way.
I mean just switch the positive and negative to the load dynamically based on situation.
For example for few seconds current flows from left to right and for next second I need to switch it.
So in my code I am deciding how long and when to switch. I am using arduino.
And in my scenario its not actually just micro seconds sometimes, not even seconds a direction stays there.
How to achieve that?

A: It's not clear from your question how fast you need to switch or how often but if the requirements are fairly slow then you could use a DPDT (Double Pole, Double Throw) relay.


text:
Q: Can I get the list of Caman.js filters? Is there any way to return the list of all the built-in filters within the library.
For example:
var caman_Default_List = [];
Caman('myCanvas', function(){

     caman_Default_List= this.getAllFilters();
});

For now I'm using this and it works okay:
var filters =
[
   "vintage", "lomo", "clarity", "sinCity", "sunrise",
   "crossProcess", "orangePeel", "love", "grungy", "jarques", "pinhole",
   "oldBoot", "glowingSun", "hazyDays", "herMajesty", "nostalgia",
   "hemingway", "concentrate"
];

myList.push(filters[   some filters   ]);

Caman("#myCanvas", function(){

     this[myList[index]]().render();
});

But I was wondering if there is a way to get the values of the filters without delcaring them customly. (eg. list = [ "vintage", "lomo", ......... ])

A: I was looking through their docs, but could not find anything helpful for the data you are trying to get. I took a look at their code and came up with the below for you.
I am not sure I would 100% trust the code, because the order of properties might change, but at least it gives you what you wanted.

console.log(Object.keys(Caman.prototype).slice(75, 93))
<script src="https://cdnjs.cloudflare.com/ajax/libs/camanjs/4.1.2/caman.full.min.js"></script>

A: I used the code below to achieve what I wanted as @AndrewLohr stated:

    //Declare lists to store filter names
    var list4,list5,list6,list7 = [];

    //Get Caman Filters (Samples : "vintage", "clarity", ... )
    list4 = (Object.keys(Caman.prototype).slice(75, 93));
    list5 = list4.toString().toUpperCase(); //To upper Case as string value (use as Label Button Name)

    //Get Caman Filters (Customs : "brightness", "saturation")
    list6 = Object.keys(Caman.prototype).slice(45, 55);
    //Add some more elements in the list
    list6.push("clip", "stuckBlur", "exposure", "noise", "sharpen");

    list7 = list6.toString().toUpperCase(); //To upper Case as string value (use as Slider Name)

    //Print lists
    console.log(list4);console.log(list5);console.log(list6);console.log(list7);
<script src="https://cdnjs.cloudflare.com/ajax/libs/camanjs/4.1.2/caman.full.min.js"></script>


text:
Q: how to add a class into the existing classes based on a bool condition in angular 2 How do you place the "active" class in an element based on a typeScript boolean condition?
My use case:
Instead of just the class="collapsible-header " like this

My Title

I would like this to be written:

My Title

As you see there is also the "active" class in there.
But this should appear only and only if myBool is true
How do we make this happen?

A: You can also use:
[class.active]="someCondition"

Class binding syntax resembles property binding. Instead of an element
  property between brackets, start with the prefix class, optionally
  followed by a dot (.) and the name of a CSS class: [class.class-name]

More info on the official docs: https://angular.io/guide/template-syntax#class-binding

A: A summary of all solutions to the original question:
solution 1)

...

solution 2)

...

solution 3)

...

solution 4)

..

..

I think the solution 2 is the most straightforward one for my use case.


text:
Q: Advanced Filter: Excel VBA not working I want to filter all "X" in column F in the range A:F using Excel VBA. Here is the part of code. After selecting the autofilter it gives me a Run-time error '1004' - Method 'Range' of object'_Global' failed. Help me out:
Function Advanced_Filter()

    Sheets("Email").Range("M1").Select
    ActiveCell.FormulaR1C1 = "Date"
    Range("M2").Select
    ActiveCell.FormulaR1C1 = "X"
    Range("A2:F2").Select
    Selection.AutoFilter
    Range("A2:F244").AdvancedFilter Action:=xlFilterCopy, CriteriaRange:=Range( _
        "Email!Criteria"), CopyToRange:=Range("M3"), Unique:=False


text:
Q: Matlab, using meshgrid to create 3D Plot I am trying to create a 3D plot. I am trying to use the values from xvals and yvals to get a Z value,but I am getting two errors. One is saying that the data dimensions should agree and its also saying that the mesh(X,Y,Z) has an error while evaluating callback. Any suggestions to get this to plot? Thanks
        xvals = 1.00:0.1:5.75;
        yvals = 2.5:0.1:12.5;
        [X,Y] = meshgrid(xvals,yvals);

        AB01 = sqrt((-21.6 - X).^2 + (-5.612 - Y).^2);
        AA0 = 22.269;
        pivotlength = sqrt(X.^2 + Y.^2);
        l = AB01-7.5;
        b = (pivotlength.^2 + AB01.^2 - AA0^2);
        ee = (2*pivotlength.*AB01);
        bb= b/ee;
        thetalmax = acosd(bb);

        c = (pivotlength.^2 + l.^2 -AA0^2)/(2*pivotlength.*l);
        thetalmin = acosd(c);

        Z = thetalmin - thetalmax ;

        mesh(Y,X,Z);

A: You have problems with the dimensions. I think I fixed it:
xvals = 1.00:0.1:5.75;
yvals = 2.5:0.1:12.5;

[X,Y] = meshgrid(xvals,yvals'); % added '

    AB01 = sqrt((-21.6 - X).^2 + (-5.612 - Y).^2);
    AA0 = 22.269;
    pivotlength = sqrt(X.^2 + Y.^2);
    l = AB01-7.5;
    b = (pivotlength.^2 + AB01.^2 - AA0^2);
    ee = (2*pivotlength.*AB01);
    bb= b./ee; % added .
    thetalmax = acosd(bb);

    c = (pivotlength.^2 + l.^2 -AA0^2)./(2*pivotlength.*l);% added .
    thetalmin = acosd(c);

    Z = thetalmin - thetalmax ;

    mesh(Y,X,Z);

BUT
you'l now get an error because Z values are complex. But that's a problem of initial values I think


text:
Q: Programming data in Excel to string to workbook to CSV I'm trying to create a VBA where I input information regarding payments across 22 columns. These columns include payment amount, account, etc. I can then run a macro and it formats the data to a usable string, then exports the data to a CSV file. The data has to be formatted with apostrophe's and commas between the info.
For example, column B is merchant ID and column C is merchant name (Column A is blank).  I type 123 in column B and xyz in column C. It gets converted to '123','xyz', ... , ..., The goal is to have the formatting completed, concatenated and then exported to a CSV. Currently I'm using a mix of formulas/functions and a macro.
I use formulas to get to the formatting correct by using:   ="'"&B2&"'"&","
Then use concatenate to merge all 22 rows to a single string
Then I recorded a macro with the following:
    Sub BCM_CSV_export()
'
' BCM_CSV_export Macro

    Range("B21").Select
    ActiveCell.FormulaR1C1 = "=""'""&R[-19]C&""'""&"","""
    Range("B21:V21").Select
    Selection.FillRight
    Range("B21:V30").Select
    ActiveWindow.SmallScroll Down:=9
    Selection.FillDown
    Range("B40").Select
    ActiveCell.FormulaR1C1 = "=CONCAT(R[-19]C:R[-19]C[20])"
    Range("B40:B49").Select
    Selection.FillDown
    Workbooks.Add
    Windows("BCM CSV Workbook.xlsm").Activate
    Selection.Copy
    Windows("Book1").Activate
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    Range("E13").Select
    Application.CutCopyMode = False
    ActiveWorkbook.SaveAs "CSVDate.csv", _
        FileFormat:=xlCSV, CreateBackup:=False
    ActiveWindow.Close
    Selection.ClearContents
    Range("B21").Select
    Range(Selection, Selection.End(xlDown)).Select
    Range(Selection, Selection.End(xlToRight)).Select
    Selection.ClearContents
    ActiveWindow.SmallScroll Down:=-24

End Sub

The code seems to work on my laptop. The CSV file shows up in 'My Documents'. But my colleague encounters errors. The code doesnt seem to run.
My question is 2 fold:
1. Is there something inherently wrong with my macro that it only runs on my laptop?
2. Is there a way to convert the 22 rows of data into a single text string and into a new CSV workbook without the intermediate steps of my using the text string formatting and concatenate function?
I used the search function and didnt see anything exactly matching this. Thanks a lot everyone!

A: You'd better to check the two lines of codes:
   Windows("BCM CSV Workbook.xlsm").Activate

   Windows("Book1").Activate

Maybe your colleague don't have the name of worrkbook BCM CSV Workbook.xlsm and Book1 opened


text:
Q: how to delete the lines which contains character that start after a specific string and ends with character found in a file in java? I have a file with abc.txt
abc.txt
hhjj
myhome _ dfdfdsfds
fdsfds
dfdfdsfdsd
fdsfdsf
dfdfdsfdsdfdsfd
dfdsfds
dfdsfds
_
hhhh
jjj
kkkk
The character after myhome could be any character it could be special characters,letters or numbers.I need to find the character after myhome and delete the lines in between and that end with character. In my file I have mentioned as '' after myhome and with ''.
The output should be
abc.txt
hhjj
hhhh
jjj
kkkk
I have tried how to read a file by line by line
package test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class ReadStringFromFileLineByLine {

public static void main(String[] args) {
    try {
        File file = new File("abc.txt");
        FileReader fileReader = new FileReader(file);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        StringBuffer stringBuffer = new StringBuffer();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuffer.append(line);
            stringBuffer.append("\n");
        }
        fileReader.close();
        System.out.println("Contents of file:");
        System.out.println(stringBuffer.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}
Could anyone help ??

A: Structure

App.java
package main;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Scanner;

public class App {

    public static void main(String[] args)
    throws FileNotFoundException, UnsupportedEncodingException {
        App app = new App();
        app.parseFile();
    }

    void parseFile() throws FileNotFoundException, UnsupportedEncodingException {
        // Reading from package main
        File file = new File(getClass().getResource("/main/abc.txt").getFile());
        // If you want to read from HDD, for example :
        // File file = new File("/home/user/abc.txt"); or File file = new File("c:\\abc.txt");
        Scanner input = new Scanner(file);
        StringBuilder sb = new StringBuilder();
        while (input.hasNextLine()) {
            sb.append(input.nextLine());
            sb.append("\n");
        }
        input.close();
        String text = sb.toString();
        text = text
            .replace(
                text.substring(
                    text.indexOf("myhome _"),
                    text.lastIndexOf('_')+1
                ),
                ""
            )
            .replace("\n\n", "\n");
        Path newFile = Paths.get("abc_new.txt");
        Files.write(newFile, Arrays.asList(text.split("\n")), Charset.forName("UTF-8"));
    }
}

New written file will be in project folder.


text:
Q: Replacing a bs4 element with a string So I have a HTML document, where I want to add HTML anchor link tags so that I can easily go to a certain part of a webpage.
The first step is to find all divs that need to replaced. Secondly, an anchor link tag needs to be added, based on the text that is within the div. My code looks as follows:
from bs4 import BeautifulSoup
path= "/text.html"

with open(path) as fp:
    soup = BeautifulSoup(fp, 'html.parser')

mydivs = soup.find_all("p", {"class": "tussenkop"})

for div in mydivs:
    if "Artikel" in div.getText():
        string = div.getText().split()[1]
        div_id = f"""{div}"""
        full =f"{div_id}{div}"
        html_soup = BeautifulSoup(full, 'html.parser')
        div = html_soup

A div looks as follows:

Artikel 7.37 text text text

After adding the anchor tag it becomes:

Artikel 10.6 Inwerkingtreding

Artikel 7.37 text text text

But the problem is, div is not replaced by the new div. How should I correct this? Or is there another way to insert an anchor tag?

A: I'm not quite sure what your expected output to look like, but BeautifulSoup has methods to create new tags and attributes, and insert them into the soup object.
from bs4 import BeautifulSoup

fp = '
Artikel 7.37 text text text'

soup = BeautifulSoup(fp, 'html.parser')
print('soup before: ', soup)

mydivs = soup.find_all("p", {"class": "tussenkop"})

for div in mydivs:
    if "Artikel" in div.getText():
        a_string = div.getText().split()[1]
        new_tag = soup.new_tag("a")
        new_tag['id'] = f'{a_string}'
        div.insert_before(new_tag)

print('soup after: ', soup)

Output:
soup before:
Artikel 7.37 text text text

soup after:
Artikel 7.37 text text text


text:
Q: Remove child from parent created in FXML I have a series of nested Split Panes created in an FXML file. I have buttons which set the max size of their children to zero, effectively hiding them.
This leaves the Split Panes divider there, and causes issues when re-sizing as the Split Panes are nested and the dividers are colliding.
What would work is removing the child node from the split pane, causing it to have only one remaining node, and not drawing the extra divider.
The issue is that I can't access getChildren() for the SplitPanes, as their protected.
Split panes as defined in fxml
        <SplitPane fx:id="splitPane1" dividerPositions="0.75" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2"  GridPane.columnIndex="1" GridPane.columnSpan="3" GridPane.rowIndex="2" GridPane.rowSpan="4" >
            <items>
                <SplitPane fx:id="splitPane2"  orientation="VERTICAL"  dividerPositions="0.4,0.8,1" >
                    <SplitPane fx:id="splitPane3"  orientation="HORIZONTAL" dividerPositions="0.5"  >
                        <items>
                            <Viewport fx:id="viewB" minWidth="0" minHeight="0"  />
                            <TilePane fx:id="view3D" prefHeight="200.0" prefWidth="200.0" style="-fx-background-color: black;" />
                        </items>
                    </SplitPane>
                    <Viewport fx:id="viewC" minWidth="0" minHeight="0"  />
          <Viewport fx:id="viewA" minWidth="0" minHeight="0"  />
      </SplitPane>

Controller code I want to use:
splitPane2.getChildren().remove(viewA);

Any ideas?

A: For a SplitPane, getChildren() is not really what you want anyway; it will produce a list of all the nodes contained in the SplitPane: not just the actual content but the representation of the dividers (and maybe other stuff) as well.
The getItems() method gives a list of all the nodes that are displayed between the dividers. So all you need is
splitPane2.getItems().remove(viewA);


text:
Q: How to get thumbnail image from Amazon S3 video via PHP or JavaScript? I read this Upload video and extract thumbnail using Amazon s3 but I think answer is really complicated.
I'm searching for simple solution to get a thumbnail from an already uploaded video on Amazon S3.
When a user place in a form a video URL I want to somehow fetch the thumbnail and display it like an image with a link to the original video and my only problem is to get that thumbnail in a proper way.

A: You can create a thumbnail in Javascript on the client side when you stream the video from the server - there are some good examples of this available such as: https://stackoverflow.com/a/29806483/334402.
Your browser will also generally automatically create a thumbnail for any video you include but do not start to play.
You need to be aware that, creating the thumbnail this way, means that the client needs to download the video header information and enough frames of the video to generate a good thumbnail.
It does not have to download the whole video however, as most videos will support some form of streaming allowing the browser to only request a small portion of the video.
Most commercial video services will generate the thumbnail on the server side, typically when the video is loaded. This is partly to allow quicker and easier download of thumbnails, and also to enable quality control - i.e. someone to check the thumbnail is actually a good one.


text:
Q: How to set the original option for picker view? I have a UILabel that display 3 options which is walk, run, and swim. I have a corresponding picker view that displays these 3 options for users to choose when the users tap the UILabel. The default option for the UILabel is depend on what the users choose last time. I want the picker view to show the correct option when it is showed first time.
it seems there is no delegate method for picker view to do that.

A:
The default option for the UILabel is depend on what the users choose
  last time.

Then, you need to save the value within the App by using the NSUserDefaults.
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    [[NSUserDefaults StandardDefaults] setObject:[NSNumber numberWithInt:row] objectForkey:@"selcetdRow"]
}

in the ViewDidLoad , just call this
 [picker selectRow:[[NSUserDefaults StandardDefaults] objectForkey:@"selcetdRow"]intValue] inComponent:0 animated:YES];


text:
Q: Qt: как сделать чтобы форма открывалась внутри приложения, а не как новое окно Например, как в Excel скрин 1, скрин 2

A: Попробуйте виджету указать тип окна Qt::Tool (перечисление Qt::WindowType).
Это можно сделать, например, через метод setWindowFlag


text:
Q: Windows Universal App Platform (UAP) SDK is missing in Visual Studio 2015 I am getting this error on creating a C# Windows Universal App and got this error. The link is dead and I couldn't find an answer in other threads, or a download link for the missing SDK

I have already installed Visual Studio Tools for Universal Windows Apps (14.0.23121.00 D14OOB) and it didn't change a thing.

A: after installing Windows 10 Developer Tools I didn't get this error anymore

A: I had the same problem. I suggest you repair or modify visual studio. You will need to be connected to enable visual studio download the required files. Its really strange and annoying that it has to do that. All needed files should have been included in the ISO.

A: You can also try to lower target platform version.

*

*Unload project to edit solution file (is already unloaded when error occures)

*Change TargetPlatformVersion to minimum or other that u have installed.

TargetPlatformVersion:    10.0.10240.0
TargetPlatformMinVersion: 10.0.10240.0


text:
Q: Navigation bar back button disappears when hiding and showing navigation bar I'm trying to recreate a behaviour similar to the one seen for the UINavigationController in Apple News app.
I have two controllers A and B, A is embedded in a UINavigationController and has a segue to B.
The navigation bar in A is hidden while in B its visible and when moving from one to the other it animates correctly.
To achieve this I'm setting A as the delegate for UINavigationController and adding
func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationController.Operation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
    if operation == .push {
        navigationController.setNavigationBarHidden(false, animated: false)
    }
    return nil
}

func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
    if let coordinator = navigationController.topViewController?.transitionCoordinator {
        if let _ = viewController as? ViewControllerA {
           navigationController.setNavigationBarHidden(true, animated: false)
        }

        coordinator.notifyWhenInteractionChanges { (context) in
            if context.isCancelled == true {
                navigationController.setNavigationBarHidden(false, animated: false)
            }
        }
    }
}

The issue I'm encountering is with the swipe back gesture.
When the gesture starts I'm hiding the navigation bar in order for it to not be visible on ViewControllerA but if the gesture is cancelled I'm showing the bar again.
Unfortunately when showing it again, while the bar itself is visibile, the back button doesn't reappear for some reason.
Do you know why is that?

A: I think you do not have to work with the navigation controller delegate in this case but simply show / hide the navigation bar in the view controllers' viewWillAppear methods:
class ViewControllerA: UIViewController {

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(true, animated: animated)
    }

}

class ViewControllerB: UIViewController {

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(false, animated: animated)
    }

}

I think this is the simpler solution that does not make any problems with missing back bar button items. :)


text:
Q: Collaborate using git and separate branches without adding a bunch of redundant commits I'm collaborating with a designer on a project called "Verified Accounts"
I'm developing on a branch called verified_accounts and the designer is on a branch called chris_verified_accounts. We've been periodically merging each other's changes, and when the project is done we'll merge verified_accounts into master
However, all this merging has been causing a bunch of junk / duplicative commits. For example:
http://dl.dropbox.com/u/2792776/screenshots/2012-03-02_1024.png
Commit (1) is a merge of a pull request that contains only commit (2). This means that these commits are essentially identical (they have the same diffs, etc). Likewise, commit (3) is a merge that merges only commit (4), meaning 3 and 4 are also essentially identical
What's the best way to manage these identical commits? I.e., for each functional change in my code I want one associated commit. This way if I'm commenting on a change set I can be sure I'm commenting in the right place (versus commenting on the exactly-similar change set of another dupe-y commit)
What's the best practice for this kind of thing?

A: Since you merge you get merge commits, which is unavoidable when you are merging branches. What you could do instead is to pull and rebase at the same time:
git pull --rebase

A: The best practice is to see these commits as what they are: merge commits. There are not simply "duplicate commits." (In fact, they are not duplicate commits at all.) They contain the information that a branch was merged into another. When you try to have a linear history (which — lets face it — is a relict of systems that couldn't handle branching and especially merging in a sane way) you inevitably lose information about how your source code came into being the way it is now. Merge commits are an important part of your project's history, allowing you to see which commits belonged to which branch at which point in time. It allows you to follow each branch even years after you have written them. If there's anything fishy in a commit you can use that context information to re-understand why you did it that way.
Please don't artificially hobble your repository by trying to have it look nice in some visualization tool. Try to harness the full power of branching and merging.
(Yes, I love Git. And branches. And merging.)


text:
Q: How Stirling numbers of first kind add to $n!$ I have a very basic doubt here.
How actually is
$$\displaystyle \sum_{k=0}^n{S_1(n,k)} = n!$$?
For example, if we have a string 'ABCDEF', its permutation be 'BACDEF' and which cycle is this representing. Since if we are assuming it to be [AB][CDEF] then it is not counted differently in a cycle. I don't understand how to visualize this sum.

A: The Stirling number of the first kind $s(n,k)$ counts the number
of permutations in $S_n$ with $k$ cycles. So $\sum_k s(n,k)$
counts all permutations in $S_n$; of course there are $n!$ of them.


text:
Q: Browser Compilation Error for Flex I'm having an odd problem that isn't mission critical since I can use the command line with no probs.
In my earlier post Flex Web-Tier Setup, I had problems getting the web compiler to work.
Now that it's working I use this in a browser to compile:
http://localhost/flex/topsight.mxml?username=xxxxx&password=xxxxx

and I get this error as a result:
ERROR : Could not resolve to a component implementation.

349 <mx:filters>
350 <mx:DropShadowFilter alpha=".25" angle="90" />
351 </mx:filters>

Everything is legit and the most recommended solution is that the namespaces aren't correct. I've checked those and they're fine. Other answers I've come across relate to external components causing a problem but as you can see, I'm not using an external component.
Here's the kicker. If I do a compile via command line:
mxmlc topsight.mxml

it compiles perfectly.
Specs are still the same from the prior post and I'm using the Flex 3 SDK.
Not sure if this would help but I did the download from http://opensource.adobe.com/wiki/display/flexsdk/Download+Flex+3 and I clicked on the Open Source Flex SDK - Milestone 3.3
Cheers!
Adrian

A: Only thing I can think of is that your compiler.conf can't find the Flex framework.  Does it work with just a:
<mx:Application> </mx:Application>
? ( basically no components )  There is an option in there flex_config that points to the SDK version you want the compiler to use.  I haven't used the web-tier in a long time so, I could be totally off track.

A: My guess is you are trying to apply the filters to a custom component. If you change the filter's namespace from mx to that of the component you're applying it to it should work. ie. if you are trying:
 <bt:Rectangle x="187" y="80">
    <mx:filters>
        <mx:DropShadowFilter distance="4" angle="45" alpha="0.5"/>
    </mx:filters>
</bt:Rectangle>

It would become:
<bt:Rectangle x="187" y="80">
    <bt:filters>
        <mx:DropShadowFilter distance="4" angle="45" alpha="0.5"/>
    </bt:filters>
</bt:Rectangle>


text:
Q: How to export trained models from Kubeflow? I have a functional pipeline with Kubeflow that preprocess data / train the model / test it.
At the end of the pipeline, I would like to export the model with the ONNX format to use it in another application.
Is there any way to do that?


text:
Q: WP API - How to get draft posts I am trying to get draft/preview/trash posts using the wordpress JSON API but adding the filter doesn't seem to do anything at all.
As a test, I am trying to get posts in the trash (there are non) but all published posts are returned.
http://localhost/wp-json/posts?&filter[post_status]=trash

I have tried this whilst logged in and out of the admin panel, giving the same results.
I am assuming this was the way to do it based on the wordpress docs http://codex.wordpress.org/Class_Reference/WP_Query#Status_Parameters
I have attempted multiple params other than trash, all return only published posts.
EDIT:
I figured out that you cannot be logged into the admin panel for basic auth to work, otherwise it just gets overridden. Logging out of this and it all worked.

A: You have to be authenticated as a user with edit_posts permissions to access private query variables such as post_status. At which point you will be able to use the following (drop the &).
http://localhost/wp-json/posts?filter[post_status]=trash
EDIT:
I believe there is a way to add post_status manually, I haven't tested this but it should work.
function my_allowed_post_status( $valid_vars ) {

    $valid_vars = array_merge( $valid_vars, array( 'post_status' ) );
    return $valid_vars;
}
add_filter( 'rest_query_vars', 'my_allowed_post_status' );


text:
Q: Restart a Python script if killed I write this post because I have not found solutions for my specific case. I refer to this article, which, however, did not work for me on Windows 10 version 1909.
I programmed a "python_code_a.py" script that has the task of uploading, one at a time, all the images contained in a local folder on a converter server and to download them, always one at a time, from the server to my PC in another folder. How the script works depends on the server, which is public and not owned by me, so it is possible, approximately every two and a half hours, that the script crashes due to an unexpected connection error. Obviously, it is not possible to consider the fact that he stays all day observing the Python shell and acting in case the script stops.
As reported in the article above, I compiled a second file with the name "python_code_b.py", which had the task of acting in case "python_code_a.py" had stopped by restarting the latter. When I try to get it to run from the "python.exe" CMD, however, the latter responds to the input with "...", nothing else.
I attach a general example of "python_code_a.py":
processnumber= 0

photosindex= 100000

photo = 0
path = 0

while photosindex<"number of photos in folder":
  photo = str('your_path'+str(photoindex)+'.png')
  path = str('your_path'+str(photoindex)+'.jpg')

  print ('It\'s converting: '+ photo)

  import requests
  r = requests.post(
      "converter_site",
      files={
          'image': open(photo , 'rb'),
      },
      headers={'api-key': 'your_api_key'}
  )

  file= r.json()

  json_output = file['output_url']

  import urllib.request

  while photosindex<'number of photos in folder':
      urllib.request.urlretrieve( json_output , path )
      print('Finished process number: '+str(processnumber))
      break

  photosindex= photosindex +1
  processnumber= processnumber +1

  print(
  )

print('---------------------------------------------------')
print('Every pending job has been completed.')
print(
)

How can I solve it?

A: you can use error capturing:
  while photosindex<"number of photos in folder":
    try:
      @Your code
    except:
      print("Something else went wrong")

https://www.w3schools.com/python/python_try_except.asp


text:
Q: Add Text to an Existing Input Field on Button Click I am creating a site where admins on the site will routinely post articles (much like a blog). I as an admin can write a basic HTML document easily, but the other admins are not at all familiar with HTML.
I have a form that they will use to publish their articles with author, title, and content fields. I am currently taking the 'content' field and displaying it as HTML after the form is submitted. To help the other users I have added buttons that say "header", "paragraph", "image", and "line break". When these buttons are clicked I would like to add html tags to the existing field (usually already filled with article text).
The idea is this:
I click the paragraph button and my field shows this:
    "
type here
".
I then type the paragraph and go to a new line. I decide to add a sub heading after it and click the heading button:

I replaced the text

type sub-heading here

I don't want the button to create a new input or add to the form in any way. I also don't want it to replace or reset the text that is there, but simply add text where the cursor is located. I've found plenty of methods to add form fields, replace them, hide them, etc, but can't dig up any posts about editing existing text with a button.
Anyone know how I can do this? I am using angular 2 as a framework, so any solution that fits with it (javascript, typescript, angular 2 data binding, etc) will work.
Here is my HTML:

Edit an Article

Add an Article

    Title
    <input mdInput id="title" type="text" [(ngModel)]="title">

    Author
    <input mdInput id="author" type="text" [(ngModel)]="author">

    Content
    <input mdInput id="article-content" type="textarea" class="multi-line-input" [(ngModel)]="content">

    <button class="button secondary" (click)='onAddHeader()'>Header</button>
    <button class="button secondary" (click)='onAddParagraph()'>Paragraph</button>
    <button class="button secondary" (click)='onAddImage()'>Image</button>

    <button class="button primary" (click)="onSaveArticle()">Save</button>

TS file:
export class ArticleEditComponent {
  isEdit = false;

  public title: string;
  public author: string;
  public content: string;

  constructor(
    public dialogRef: MdDialogRef<any>, @Inject(MD_DIALOG_DATA) private dialogData: any,
    public afAuth: AngularFireAuth, public afDB: AngularFireDatabase,
    public articleService: ArticleService) {
  }

  onSaveArticle() {
    this.articleService.createArticle(new Article(
    this.title, this.author, this.content));
  }

onAddHeader(){
    document.getElementById("article-content").innerText += '

';
    console.log('running header function');
  }

  onAddImage(){
    document.getElementById("article-content").innerText += 'add image tag';
    console.log('running header function');
  }

  onAddParagraph(){
    document.getElementById("article-content").innerText += '

';
    console.log('running header function');
  }

A: If you're using ngModel, the contents of whatever is in the corresponding input field will be bound to the variable you have listed.
<input mdInput id="title" type="text" [(ngModel)]="title">

Anything the user types will be bound to the "title" variable in the above input, and you can modify that variable anywhere in your component or template and it will be reflected in the view. So if you just wanted to add text to the input field, you could do something like:
<button class="button secondary" (click)="title = '
 type here
' + title">Paragraph</button>

or you could do it in the component code
<button class="button secondary" (click)="addText()">Paragraph</button>

 ...somewhere in your component....

addText() {
   f.title = '
 type here
' + f.title;
}

(The above is assuming you have wrapped your form in an ngForm group, and given it the identifier #f , as they have done here: https://angular.io/api/forms/NgForm )
That method will add that text to the beginning of whatever is already in the title input field (note: you may have to escape that backslash, I can't remember). You shouldn't need to use the document.getElementById queries at all. Those are best avoided in Angular. And you shouldn't really need to access the innerText attribute either, if you're using ngModel. The beauty of 2-way binding is its basically already giving you that innerText attribute in the form of the 'title' variable. In fact, accessing the document object and nativeElement properties can almost always be avoided and should whenever possible.
You may need to import NgForm from '@angular/forms' if you haven't already. I can't remember if ngModel works properly without it.

A: The following is an example that you could adapt:
HTML:
<input #input type="text">
<button (click)="addText()">Click me to add some text</button>
<button (click)="reset()">Reset</button>

TypeScript:
  @ViewChild('input') private input;

  addText(){
    this.input.nativeElement.focus();
    let startPos = this.input.nativeElement.selectionStart;
    let value = this.input.nativeElement.value;
    this.input.nativeElement.value=
    value.substring(0, startPos) +' I am inserted ' + value.substring(startPos, value.length)
  }

  reset(){
      this.input.nativeElement.value='';
  }

Plunker


text:
Q: Microsoft.AspNet.WebApi.Client IsSuccessStatusCode not working Environment:
    .net 4.0 console app
Microsoft.AspNet.WebApi.Client version=4.0.30506.0 targetFramework="net40"

Microsoft.Net.Http" version=2.0.20710.0 targetFramework="net40"

Newtonsoft.Json version=4.5.11 targetFramework="net40"

Ok, so I have set up a self hosted web API service, and I am able to access that service without issue.
I would like to gracefully handle the scenario where the service is not running.
The problem is the code errors out on the GetAsync call, before it can even check IsSuccessStatusCode .
However if I start up Fiddler, then the code runs as I expect, which seems really strange to me.
Here is some demo code.
Private Function GetConnInfo(hostIP As String, hostPort As Integer) As Boolean
    GetConnInfo = False
    Dim client As HttpClient = New HttpClient()
    client.BaseAddress = New Uri("http://" & hostIP & ":" & hostPort)
    client.DefaultRequestHeaders.Accept.Add(New MediaTypeWithQualityHeaderValue("application/json"))

    Dim resp = client.GetAsync("api/clientconnectioninfo/GetAllConnections").Result

    If resp.IsSuccessStatusCode Then
        GetConnInfo = True
    End If

    Return GetConnInfo

End Function

Stack Trace:
System.AggregateException was unhandled
HResult=-2146233088
Message=One or more errors occurred.
Source=mscorlib
StackTrace:
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
at DemoApiServiceNotRunning.Module1.GetConnInfo(String hostIP, Int32 hostPort) in C:\Users\tonye\Documents\Visual Studio 2012\Projects\DemoApiServiceNotRunning\DemoApiServiceNotRunning\Module1.vb:line 19
at DemoApiServiceNotRunning.Module1.Main() in C:\Users\tonye\Documents\Visual Studio 2012\Projects\DemoApiServiceNotRunning\DemoApiServiceNotRunning\Module1.vb:line 8
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.Net.Http.HttpRequestException
   HResult=-2146233088
   Message=An error occurred while sending the request.
   InnerException: System.Net.WebException
        HResult=-2146233079
        Message=Unable to connect to the remote server
        Source=System
        StackTrace:
             at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
             at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
        InnerException: System.Net.Sockets.SocketException
             ErrorCode=10061
             HResult=-2147467259
             Message=No connection could be made because the target machine actively refused it 192.168.20.124:8700
             NativeErrorCode=10061
             Source=System
             StackTrace:
                  at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
                  at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
             InnerException:`

A: IsSuccessStatusCode will only return a value if a HTTP request is made.  If it can't connect to the server you will get an exception throw instead.  It works with fiddler running because your client is actually connecting to fiddler and then fiddler is trying to connect to your server.
You have two choices.  Either catch the Exception, or install a second self-host web api that is running on the same port but using a Weak Wildcard.  That second service will only get hit if your main service is not running.