text:
Q: Number of DAX code lines in entire Power BI report Is there a way to monitor the total number of DAX lines of all DAX measures of the Power BI report? Or alternatively, the total string length of all DAX measures in the Power BI report?
I want to get a glimpse of the DAX code complexity. Similarly, View Metrix in Dax Studio shows basic stats on the physical part of the model but not on the DAX part. The total length of a DAX code of all measures how complex the report is.
One of the key characteristics of the code is its readability which is, to a great extent, achieved by brevity.

A: You can run queries against the Dynamic Management Views or DMVs in Dax Studio, eg:
select * from $System.TMSCHEMA_MEASURES


text:
Q: Why I get 404 when I using ecs-cli? I'm using ecs-cli to deploy my docker-compose.yml to ecs with SSL support.
When I run the command it's show me that the container is running. but when I browse to url is show me 404 error.
why?
this is my docker-compose.yml:
version: '2'
services:
  tester-cluster:
    image: yeasy/simple-web:latest
    environment:
      VIRTUAL_HOST: mydomin.net
      LETSENCRYPT_HOST: mydomin.net
      LETSENCRYPT_EMAIL: mydomin@gmail.com

  nginx-proxy:
    image: jwilder/nginx-proxy
    ports:
      - '80:80'
      - '443:443'
    volumes:
      - '/etc/nginx/vhost.d'
      - '/usr/share/nginx/html'
      - '/var/run/docker.sock:/tmp/docker.sock:ro'
      - '/etc/nginx/certs'

  letsencrypt-nginx-proxy-companion:
    image: jrcs/letsencrypt-nginx-proxy-companion
    volumes:
      - '/var/run/docker.sock:/var/run/docker.sock:ro'
    volumes_from:
      - 'nginx-proxy'

A: You will have to set the WORDPRESS_DB_HOST for the wordpress server as well. This will be something similar to the following:
WORDPRESS_DB_HOST: mysql:3306

Note the host name would be the name of the db container.
You can view container logs by running the following:
docker-compose logs -f -t

redpajama_set_name: RedPajamaStackExchange


text:
Q: If I have two rectangles of different sizes(10 by 10 and 20 by 20) in Pygame, how can I figure out when the two rectangles collide? I am unable to detect when two rectangles of different sizes collide.
I've tried, "if x == obj_x and y == obj_y:" where x is one rectangle's x-value, obj_x is the other rectangle's x value, and the same for the y-values.
import pygame
import time
import random

pygame.init()
white = (255,255,255)
black = (0,0,0)
red = (255,0,0)

display_width = 500
display_height = 500

screen = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Avoid')

x_change = 0
y_change = 0

FPS = 30
block_size = 10

font = pygame.font.SysFont(None, 25)
smallfont = pygame.font.SysFont("comicsansms",25)

def showLives(lives):
    text = smallfont.render("Lives: "+str(lives), True, white)
    screen.blit(text, [0,0])
def message_to_screen(msg,color):
    screen_text = font.render(msg, True, color)
    screen.blit(screen_text, [100,250])

clock = pygame.time.Clock()

def gameLoop():
    gameExit = False
    gameOver = False

    x = 250
    y = 425

    x_change = 0
    y_change = 0

    obj_speed = 5

    obj_y = 0
    obj_x = 0

    obj2_y = 0
    obj2_x = 0
    obj2_speed = 3

    lives = 3
    while not gameExit:
        while gameOver == True:
            screen.fill(white)
            message_to_screen("Game Over, Press C to play again or Q to quit", red)
            pygame.display.update()
            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        gameExit = True
                        gameOver = False
                    if event.key == pygame.K_c:
                        gameLoop()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                gameExit = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    x_change = -block_size
                    y_change = 0
                elif event.key == pygame.K_RIGHT:
                    x_change = block_size
                    y_change = 0
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                    x_change = 0
                if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
                    x_change = 0
                    y_change = 0
        if x > 500-block_size:
            x-=block_size
        if x < 0+block_size:
            x+=block_size
 #       if x >= display_width-block_size-block_size or x < 0:
 #           gameOver = True
        obj_y = obj_y + obj_speed
        if obj_y > display_height:
            obj_x = random.randrange(0, display_width-block_size)
            obj_y = -25
        obj2_y = obj2_y + obj2_speed
        if obj2_y > display_height:
            obj2_x = random.randrange(1, display_width-block_size)
            obj2_y = -27

        x += x_change
        y += y_change
        screen.fill(black)

        pygame.draw.rect(screen,white, [obj_x,obj_y,20,20])
        pygame.draw.rect(screen,white, [obj2_x,obj2_y,20,20])
        pygame.draw.rect(screen, red, [x,y,block_size,block_size])
        showLives(lives)
        pygame.display.update()
        if x == obj_x and y == obj_y:
            lives -= 1
        if lives == 0:
            gameOver = True
    clock.tick(FPS)
    pygame.quit()
    quit()

gameLoop()

I want the program to detect when any part of the rectangles collide instead of just detecting when one point on each of the rectangles collide.

A: PyGame has class pygame.Rect() to keep rectangle's position and size. It uses it to draw images/sprites and check collision between sprites.
x = 250
y = 425

obj_y = 0
obj_x = 0

rect_1 = pygame.Rect(x, y, 10, 10)
rect_2 = pygame.Rect(obj_x, obj_y, 20, 20)

and then you can check collision
rect_1.colliderect(rect_2)

You can also use it to draw rectangle on screen
pygame.draw.rect(screen, white, rect_2)
pygame.draw.rect(screen, red, rect_1)

You can also use it to check collision between rectangle and point - ie. to check if button was clicked by mouse
button_rect.collidepoint(event.pos)

To change values in rectangle you have rect_1.x, rect_1.y, rect_1.width, rect_1.height but also
x,y
top, left, bottom, right
topleft, bottomleft, topright, bottomright
midtop, midleft, midbottom, midright
center, centerx, centery
size, width, height
w,h

Some of them takes tuple with (x, y)
for example: center rectangle on screen
rect_1.center = (display_width//2, display_height//2)

or event using screen
rect_1.center = screen.get_rect().center

OR center text on screen
screen_text_rect = screen_text.get_rect()
screen_text_rect.center = screen.get_rect().center

screen.blit(screen_text, screen_text_rect)


text:
Q: Take out characters and put in a new column in Excel Hi I'm a bit new to vba so I will try to explain my problem as far as possible.
I have a dataset in Excel in Column A, I have a lot of file names like this:
 1. AB000**1234**45.tif
 2. AB000**1235**45.tif
 3. AB000**1236**45.tif
 4. AB000**1237**45.tif

etc..
From this I want to take out all the strong characters and put in column C  so it will look like this:
 1. 1234
 2. 1235
 3. 1236
 4. 1237

etc..
At the moment I have a code that looks like this:
Sub TakeOut
    Dim str1 As String
    Dim LR As Long
    Dim cell As Range, RNG As Range

    LR = Range("A" & Rows.Count).End(xlUp).Row
    Set RNG = Range("A1:A" & LR)

    For Each cell In RNG
        L = Len(RNG)
        If L > 0 Then
           RNG = ...
        End If
    Next cell

    Range("C:C").Columns.AutoFit

End Sub

I have tried to count left(5) and right(6) but don't know how to take out the 4 character that I want.
Hope you can help me with this.

A: Take a look at the Mid() Function link.
usage in your case:
Mid(cell.Value, 6, 4) 'First parameter is the string, 6 is the start character, 4 is length

A: The easiest way without looping would be something like this:
Sub TakeOut()
  Dim rng As Range
  Set rng = Range("A1", Range("A" & Rows.Count).End(xlUp))
  rng.Offset(, 1) = Evaluate("IF(" & rng.Address & "="""","""",MID(" & rng.Address & ",6,4))")
End Sub

A: If you want to take out the strong characters from the string. Try it below. It will take all the Bold Characters in a cell and place it in C column.
Hope you are looking for this?
Sub get_bold_content()
    Dim lastrow, i, j, totlength As Long
    lastrow = Range("A" & Rows.Count).End(xlUp).Row
    For i = 1 To lastrow
        totlength = Len(Range("A" & i).Value)
        For j = 1 To totlength
            If Range("A" & i).Characters(j, 1).Font.Bold = True Then
                outtext = outtext & Range("A" & i).Characters(j, 1).Text
            End If
        Next j
        Range("C" & i).Value = outtext
        outtext = ""
    Next i
End Sub


text:
Q: Queuing Promises (ES6) I'm writing a NodeJS service that requests data from APIs. Under load, I don't want to hammer the API with potentially hundreds of simultaneous requests, so I am trying to queue up the requests so they are executed one-by-one and with a delay between them.
const request = require( 'request' );
class WebService {
  constructor() {
    this.RequestQueue = [];
  }

  _Get( uri, options, reply ) {
    return new Promise( ( resolve, reject ) => {
      request.get( uri, options, ( err, resp, body ) => {
        if ( err )
          reject( err );

        reply( resp );
        resolve( resp );
      } );
    } );
  }

  async onRequest( data, reply ) {
    this.RequestQueue.push( this._Get( data.uri, data.opts, reply ) );
  }

  async execute() {
    while( this.RequestQueue.length > 0 ) {
      var current = this.RequestQueue.shift();
      await current();
      await Utils.Sleep(5000); //promise that resolves after 5 seconds
    }
  }
}

Due to the nature of ES6 promises, they start executing when constructed, so this._Get() inside of the onRequest event returns a promise that is already executing. Is there a clean way to avoid this so that I can properly queue the request for later?

A: Try adding the request options to the queue instead of the actual request Promise:
onRequest(data, reply) {
    this.RequestQueue.push({
        uri: data.uri,
        opts: data.opts,
        reply: reply
    });
}

async execute() {
    while(this.RequestQueue.length > 0) {
        var current = this.RequestQueue.shift();
        await this._Get(current.uri, current.opts, current.reply);
    }
}


text:
Q: Custom Post Type URL rewrite with Post Type Template I am building a Wordpress site for a video production company. They produce videos for adults as well as for kids and therefore I split the posts in the backend to keep a structure. So the setup is the following:

*

*Two Custom Post Types named productions_big and productions_small

*A page named Productions, placed in the main navigation with links to
For Big and For Small pages

*One page listing the posts of productions_big, one listing posts of
productions_small. The page names are for-big and for-small and both are children of the Productions page

*The URLs are perfectly fine for the pages as I made a parent/child relation of the relevant pages. example.com/productions leads to the right page as well as example.com/productions/for-big and example.com/productions/for-small do.

*For reasons that are irrelevant to this question the templates for
the CPTs differ, but in some occasions template-big is used for productions_small and vice versa. There is no actual logic behind this and therefore the decision on which template to use is done in the backend via the Post Type Template feature introduced with Wordpress 4.7

What I want to achieve is a logical URL structure like example.com/productions/for-big/name-of-adult-production. Right now I have URLs like example.com/productions_big/name-of-adult-production as productions_big is the name of the CPT.
I am familiar with the rewrite argument you should pass when registering custom post types. I have done this in all the ways suggested at stackoverflow but it is just not working. Here is an excerpt of the code I use to register my CPTs:
add_action('init', 'all_custom_post_types');

function all_custom_post_types() {

  $types = array(

    array('the_type' => 'productions_big',
                ...

    array('the_type' => 'productions_small',
                ...

);

  foreach ($types as $type) {

  $the_type = $type['the_type'];
    ...

  $args = array(
    'labels'        => $labels,
    'public'        => true,
    'publicly_queryable' => true,
    'show_ui'       => true,
    'query_var'     => true,
    'rewrite'       => true,
    'capabilities'  => array(
      ...),
    'rewrite'       => array('has_archive' => false, 'slug' => 'bla', 'with_front' => false),
    'has_archive'   => false,
    'map_meta_cap'  => true,
    'hierarchical'  => false,
    'menu_position' => 5,
    'supports'      => array('title','editor','thumbnail', 'taxonomies'),
    'taxonomies'    => array( 'category' )
  );

    register_post_type($the_type, $args);

  }

}

As you see I tried 'rewrite' => array('slug' => 'bla') because I wanted to know if it does not work because of a conflict of page names when I write 'rewrite' => array('slug' => 'productions/for-big')
But whatever value I give the slug, it always redirects me to index.php.
I thought the reason why it is not working is caused by the way I am assigning post templates (remember: as a post attribute in the backend, not a dedicated single-xxx.php file) but I couldn't find a solution anywhere. All solution-seekers posting their questions were assigning templates the good old fashioned single-name_of_cpt.php way (which is not possible for me).
Sidenote: The ultimate goal would be to make the slug "dynamic". Meaning that it changes in case the page names are altered in the backend. I might try this approach but beforehand I'll have to get rid of the basic problems described here.
Any idea is much appreciated. And thank you for reading this far.

A: Oh boy, seems you have to post your questions in order to find an answer yourself. After trying to setup another CPT everything worked like a charm.
That made me investigate the registration of the previous CPTs. As you can see above I tried to register my CPTs inside of one function
function all_custom_post_types() {

  $types = array(
    array('the_type' => 'productions_big', ...
    array('the_type' => 'productions_small', ...
  );

  foreach ($types as $type) {

  $args = array(...
    'rewrite'       => array('slug' => 'bla'),...
  );

  register_post_type($the_type, $args);

  }

}

So ultimately there was no conflict between the slugs of my pages and custom post types but a conflict of giving one and the same slug to two different post types.


text:
Q: Simplification ideas Looking for a neat simplification idea to be able to solve for $x$ analytically in the expression below: $$S=k\tan x-Bk^2\frac{1}{\cos^2x}$$
where $\{S,k,B\}\neq0$ and $\in \mathbb{R}^+.$

Of course one could Taylor expand the ($\tan x$) and ($\frac{1}{\cos^2x}$) into ($\approx x+x^3/3$) and ($\approx 1+x^2$) respectively and reinsert into the main equation and solve the cubic polynomial, but aside from the fact that the obtained result in this way would only be an approximation valid around $0$, the analytic expressions would be too long and ugly. I figured there may be another more straightforward or reasonable way of attacking this.

A: Write
$$\frac{1}{\cos^2(x)} = \sec^2(x)=\tan^2(x)+1.$$
The resulting equation is a quadratic in $\tan(x)$ which can be solved in terms of $S,k,B$. The $\arctan$ of this result gives $x$.

A: Hint:$$\dfrac{1}{\cos^2(x)}=\sec^2(x)=\tan^2(x)+1$$
Then use $\displaystyle u=\tan(x)$
in the resulting equation.


text:
Q: context of file inclusion in php Good morning,
I am trying to to learn how the file inclusion in php works. Today, I am having a problem that I can not solve. This is my scenario:
Files at same directory:
- config.php
- db.php
- functions.php
- form.php

config.php
<?php
$config['json_file'] = 'test.json';

functions.php
<?php
function writeInFile()
{
    echo $config['json_file']; // just for debugging porpuses
    file_put_contents($config['json_file'], json_encode(time()));
}

model.php
<?php
class Model{

    public function __construct();

    function create()
    {
        writeInFile();
    }
}

form.php
<?php
include('config.php');
include('functions.php');
include('model.php');

$model = new \Model();
$m->create();

When I execute the form.php I get this error:

Warning: file_put_contents() [function.file-put-contents]: Filename
  cannot be empty in
  functions.php

I know that this happens because the var $config['json_file'] is null inside of writeInFile() in functions.php. But, theorically it should works because I am doing the inclusion at the begginig of form.php. Or am I wrong?

A: Read variable scope from here [variable scope][1]
[1]: http://php.net/manual/en/language.variables.scope.php .
Right at the begining it sais that a function from another file that was included can't use a variable from another file beause it is considered to be in local scope . That's why you get error . Read more about var scope .


text:
Q: Table column sorting and toggling of image This is HTML snippet
View of table header with the arrow definedThis image shows the arrow postion in the columns

$scope.all_columns = ["RAG Status","Status","Bundle ID","Bundle Name", "#of orders","# of closed orders","Actions"];

  $scope.options1 = ["1","5","10","15"];
  $scope.bundles = {
   RAGStatus: "",
   Status: "",
   BundleID: "",
   BundleName: "",
   ofOrders: "",
   ofClosedOrders: "",
   Actions: ""
  }
        $scope.toggleCustom = function() {
   $scope.custom = !$scope.custom;

  };

  $scope.dataSort = function(predicate){
   //$scope.predicate = predicate;
   $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
   $scope.predicate = predicate;
   $scope.toggleCustom();
 <input type="checkbox" ng-model="allItemsSelected" ng-change="selectAll()">Select All

                        {{ all_columns[0]}}&nbsp

                        {{ all_columns[1]}}&nbsp

                                {{ all_columns[2]}}&nbsp

                                {{ all_columns[3]}}&nbsp

                        {{ all_columns[4]}}&nbsp

                                {{ all_columns[5]}}&nbsp

                                {{ all_columns[6]}}&nbsp

This is controller CODE which contains object details which is populating the code and function for sort.
So i am trying to click on particular column for sorting that column its image(arrow) is changing which is acceptable but image(arrow) of other columns are also changing which is not acceptable and it is getting changed as for toggling i have used same bollean vaiable(custom).


text:
Q: Running Portable Exe file through batch file I have created a batch file which runs multiple commands in the Windows command prompt, which is working just fine, however, I want to run a portable exe file through the same batch file as well. E.g. if I transfer the zip file to another computer, all I would like to do is run the batch file and that portable exe would run along with the other commands as well
:start
cls
color 1A
cls
@echo off
echo.
echo.
echo.
echo ********************************************
echo ************* Test Program **************
echo ********************************************
echo.
echo.
echo.
echo 01) System information
echo 02) Ping
echo 03) IP configuration
echo 04) Verify Drivers
echo 05) Driver List
echo 06) Get Serial Number
echo 07) Disk Defragmentation
echo 08) DiskPart
echo 09) Repair Load Preferences
echo 10) Run CCleaner
echo.
REM This is a test program
REM echo This is a Test Program
set /pnum= Type the corresponding number to perform an operation:
if %num%==01 (
cls
systeminfo
)
if %num%==02 (
cls
ping www.google.com
)
if %num%==03 (
cls
ipconfig /all
)
if %num%==04 (
cls
verifier
)
if %num%==05 (
cls
driverquery
)
if %num%==06 (
cls
wmic bios get serialnumber
)
if %num%==07 (
defrag c: /a
pause
cls
)
if %num%==08 (
diskpart
pause
cls
)
if %num%==09 (
cls
lodctr /r /f
echo.
pause
)
if %num%==10 (
cls
C:\Users\kumar\Desktop\CCleaner.exe
echo.
pause)

    set /p choice="Do you want to restart? Press 'Y' to continue, or any other key to exit: "
if '%choice%'=='y' goto start

So for example in the last condition I am running CCleaner which is on the Desktop at the moment, but if i copy a zip file which consists of the BAT File and the CCleaner.exe how would i enable it to run on another PC after copying?
Any help would be appreciated.

A: If the "portable" directory will contain all executable files, another way is to make the location of the .bat script the current working directory.
@ECHO OFF
PUSHD "%~dp0"

: do things, the directory of the .bat script is the current directory

POPD
EXIT /B 0

A: place your tools into the same folder as the batchfile and instead of
C:\Users\kumar\Desktop\CCleaner.exe

do
%~dp0\CCleaner.exe

%~dp0 is Drive and Path of your batchfile.
You may also put your tools into a subdir (tools) and:
%~dp0\tools\CCleaner.exe

A: This could be useful in the case your app uses some system variables (e.g. PATH)
and you might want to reassign them locally before starting the application. The provided .exe will pass control to a .bat where you can do this and much more.
At the end of this .bat run the App.exe


text:
Q: == Not working with scanned string to test user/password Solved in comments, '(tempuser.equals(actualuser)' was the correct way.
This is a snippet of my code;
if (tempuser != "a"){
  System.out.println("FAIL");
    logincount=logincount+1;
  }
else {
  System.out.println("Success");
  }

The program is printing out FAIL, even when I print out the scanned variables and everything is "a".
Any ideas?
Can post more code on request

A: String comparison using == is not recommended. The correct way to compare Strings are with equals()
if(!tempuser.equals("a")) {
    // rest of code
}
else {
    // rest of code
}

A: You need to use equals() with an object.
if (tempuser == null || !tempuser.equals("a")) {
  System.out.println("FAIL");
} //etc.

The reason is that == checks to see if it is the same reference. This works for primitives, like int, but for objects you need to rely on the implementation of the equals() method for class specific instructions for testing equivalency.

A: To compare strings you need to use String.equals
if (tempuser.equals("a"){

A: Allways use String.equals(otherString) to compare the content of Strings. with == you compare the Object IDs.

A:
To compare Strings for equality, don't use ==. The == operator checks
  to see if two objects are exactly the same object. Two strings may be
  different objects, but have the same value (have exactly the same
  characters in them). Use the .equals() method to compare strings for
  equality. Similarly, use the .compareTo() method to test for unequal
  comparisons.  For example:

String s = "something", t = "maybe something else";
if (s == t)      // Legal, but usually WRONG.
if (s.equals(t)) // RIGHT
if (s > t)    // ILLEGAL
if (s.compareTo(t) > 0) // CORRECT>

A: Using == and != in Java will check if the references are pointing at the exact same object. This is highly unlikely.
You would want to use the .equals() method instead to check if the content of the Strings are equal.
if (!tempuser.equals("a")){
    // Do stuff
}

A: As no doubt countless others have said by the time I've submitted this answer, == checks whether the reference to the object on the left (String tempuser in this case) is equal to  the reference of the object on the right (String "a"). What you probably want to do is use the String.equals() method, as follows:
if(!tempuser.equals("a")) {
    //Foo
} else {
    //Barr
}

A more comprehensive answer can be seen here.


text:
Q: Django 1.9 error - 'User' object has no attribute 'profile' So I recently added an optional user profile model that is linked to a user via a OneToOneField like so:
class UserProfile(models.Model): # Creating class
    user = models.OneToOneField(User, on_delete=models.CASCADE)

This worked fine, and my current UserProfile models were intact both before and after I added in this field to link the profile to a user.
The problem comes when I log in on the website as a valid user, after submitting the log in form comes an error:

AttributeError at /login/
'User' object has no attribute 'profile'

I have searched through my files for anything along the lines of 'User.profile', and similar queries, however I can't seem to find anything that would allow me to properly log in as a user.
I wasn't sure what other code to post here, and didn't want to spam this question with potentially unnecessary code so tell me if there's anything more specific (views.py, models.py, forms.py, etc) that will be needed to solve this sort of problem, or if you know of any possible solutions.
Thank you

A: You haven't set any related_name attribute on that one-to-one field, so the reverse accessor will be called userprofile not profile.

A: Make sure your app is in settins.py INSTALLED_APPS


text:
Q: Hardware for Operating System development I am heavily interested in Operating System theory and design and have decided I would like to play with developing an OS. I have a background in x86 assembly and have looked into ARM also. I would like a development board to develop the OS for. Has anyone had experience with OS development and/or can suggest some hardware to use?
One board I am considering is the LPC1769 LPCXpresso board.
I am aware I could use a VM, but I would like to use actual hardware.

A: Use a normal PC.  These come with x86 processors and all the other hardware and are exactly the kind of platforms that benefit from operating systems.  Even a old junker PC would be fine for this.  You develop on a regular PC running a real operating system and test on the klunker.  The other advantage to this is that it's free.  Surely you have some old PC or motherboard sitting around in some dusty corner, or know someone who does that has gotten around to tossing it out yet.

A: What are you after? A complete PC OS, or rather an RTOS (Real Time Operating System)? If you are going to write your own PC OS , I would suggest an old PC like Olin said.
Coincidently I am currently trying to (just for fun) write my own RTOS on a small PIC24FJ32GA002 (had it lying around, easy to work and test with). This is a simple 28-pin 16MIPS 16-bit controller, but does the job in my case. I currently got a task kernel working so I can switch tasks, use delays handled by the RTOS etc. Now moving on to more abstract features with memory and peripheral communication (handled by the RTOS).
I don't think you need a monster microcontroller to run any RTOS. The task kernal only consumes 500~600 instructions and about 300~400 bytes of RAM for 2(+1idle) tasks. Even this low memory device has 10.5k instructions and 8KB of RAM, so I am only using about 5% now.
For an RTOS its very important that the CPU supports some kind of easy stack changing, so you can change the application context fast. For example, I know some of the older PICs (like a PIC16 or a PIC18 device) have got hardware based stacks. On the PIC24 I am storing the context (pushing CPU registers onto the stack), changing the stack pointer (to the stack of another task) and resuming the context (popping CPU registers from the stack).
The ARM chips doesn't have a hardware based stack, so they are good to go. Note that the LPCXpresso board comes with it's own compiler and development environment. This means you must use the code_red compiler and environment for the onboard debugger.  The debugger doesn't work with another environment, because the software for the debugger is loaded by their own IDE. The free compiler version of the compiler also has a 128KB code restriction. This is amount of code that can be debugged, I believe. 128KB is plenty for a small RTOS to start with.
You can always get your own JLINK or JTAG programmer, but you would have to wire the SW or JTAG port to the LPC1769 board. Other than that, the LPC1769 has plenty of resources and peripherals to start going. I don't know from my experience how good the debugging tools is on the LPCxpresso when you're debugging really low-end stuff (like task switching). On the PIC24 I had to second-guess what is going on, MPLAB didn't properly capture hang-ups.. Nevertheless it's still possible. For ARM there also plenty of RTOS and resources out there to take a peek at.


text:
Q: Is it possible to express acceleration in a gravitational field as a logarithmic spiral? The derivation starts from a logarithmic spiral:
$r=de^{b\theta}$
The lenght of a part of the spiral i calculated by:
$\int_{\theta_1}^{\theta_2} \sqrt{(\frac{dr}{d\theta})^2+r^2} d\theta$
From 0 to 2$\pi $:
$l=d\sqrt{b^2+1}\int_{0}^{2 \pi} e^{b\theta} d\theta=\frac{d\sqrt{b^2+1}}{b}(e^{b2\pi}-1)$
The difference in radius:
$s=r_{2\pi}-r_0=d(e^{b2\pi}-1)$
The acceleration can now be calculated by the distance s the an object has moved by the time t.
$a=\frac{2s}{t}$
The time is the time it takes for an object to move the distance l at the speed of light:
$t=\frac{l}{v}=\frac{\frac{d\sqrt{b^2+1}}{b}(e^{b2\pi}-1)}{c}$
$a=\frac{2c^2b^2}{d(e^{b2\pi b}-1)(b^2+1)}$
Compare to gravity on earth and other planets the constants are found:
$d=r,    b=k\frac{m}{r}$
Final expression:
$a=\frac{2c^2k^2m^2} {r^3(e^{2\pi \frac{km}{r}}-1)(\frac{k^2m^2}{r^2} +1)}$
where $k=\frac{\pi G}{c^2}$
Expressed in terms of the Schwarzschild radius:
$a=\frac{\pi^2 c^2r^2_s} {2r^3(e^{\pi^2 \frac{r_s}{r}}-1)(\frac{\pi^2 r^2_s}{4r^2} +1)}$
It predicts the acceleration a of particles towards a large object with mass m at large distances r compared to $r_s$ accurate, but differs from Newton and Einstein at small distances.
Is there any physical reality behind this equation or does it just give a very good approximation on larger scales?

A: Assuming a two body system and gravitational interaction, we can completely solve the problem. This gives us the allowed orbits namely: circular, elliptic, parabolic and hyperbolic orbits depending on the energy of the particles.  If you are in the newtonian limit, you have to state all the forces acting on your particle and given initial conditions ;this uniquely chooses a path in phase space. In GR, you have to first (in the simplest cases) state your metric and then solve Einstein's field equations.What you have done is started with an equation of motion and massaged it by plugging into it different constants. This is not how physics is done. Any correct prediction it makes will be completely coincidental since there is no reason from the physical point of view why the equation of motion was a logarithmic spiral to begin with.


text:
Q: Boundary Condition Problem - Diffusion Equation So, in my 1D diffusion equation, everything works as I would expect.
    eq = \!\(
\*SubscriptBox[\(\[PartialD]\), \(t\)]\(p[x, t]\)\) ==
   diffusionrate*Laplacian[p[x, t], {x}];

diffusionrate = 1;

iv = {p[x, 0] == 0, p[0, t] == Sin[t], p[1, t] == 0};

s1D = NDSolve[{eq, iv}, {p[x, t]}, {x, 0, 1}, {t, 0, 10}]

Plot3D[p[x, t] /. s1D, {x, 0, 1}, {t, 0, 10}]

And gives a nice result

But when I try to do this in 3D, I expand on the above like so,
eq2 = \!\(
\*SubscriptBox[\(\[PartialD]\), \(t\)]\(p[x, y, z, t]\)\) ==
   diffusionrate*Laplacian[p[x, y, z, t], {x, y, z}];

diffusionrate = 1;

iv = {p[x, y, z, 0] == 0, p[0, 0, 0, t] == Sin[t], p[1, 1, 1, t] == 0};

s3D = NDSolve[{eq2, iv}, {p[x, y, z, t]}, {x, 0, 1}, {y, 0, 1}, {z, 0,
    1}, {t, 0, 10}]

And I get the error
NDSolve::bcedge: Boundary condition p[0,0,0,t]==Sin[t] is not specified on a single edge of the boundary of the computational domain.

But, I think this is defined along the boundary. I don't understand why it isn't working and why I'm getting this error.

A: You'd need to specify boundary conditions and initial conditions, for example like so:
eq2 = Derivative[0,0,0,1][p][x,y,z,t] ==
   Laplacian[p[x,y,z,t], {x,y,z}];
iv = {p[x, y, z, 0] == 0};
bcs = {p[0, y, z, t] == Sin[t], p[1, y, z, t] == 0};
Dynamic["time: " <> ToString[CForm[currentTime]]]
s3D = NDSolveValue[{eq2, iv, bcs},
  p, {x, 0, 1}, {y, 0, 1}, {z, 0, 1}, {t, 0, 10},
  Method -> {"MethodOfLines",
    "SpatialDiscretization" -> {"FiniteElement",
      "MeshOptions" -> {"MaxCellMeasure" -> 0.01}}}
  , EvaluationMonitor :> (currentTime = t;)
  ]


text:
Q: How to print Chinese Characters in DataNitro? I am new to DataNitro. I want to deal with some Chinese Characters in my excel sheet but fail.
When I print Chinese Characters in Python Shell, everything is right. However, when I print Chinese Characters in an imported python file, it tells me UnicodeDecodeError: 'gbk' codec can't decode byte 0xad in position 36: illegal multibyte sequence.
I think codec should be utf-8 so I tried adding headers below. But this still doesn't work.
# -*- coding: utf-8 -*-

Hope some one could give me some tips. Thanks.


text:
Q: How to handle a variable that might be an array or not in javascript inline? I need to pass an argument, that is either an array of one type or the type on its own, to a function that requires the only argument be an array:
// myFunction throws an error if the first argument is not an array
const foo = typeOrArrayOfType => myFunction([...typeOrArrayOfType, oneDefault]);

However if I do this:

const anArray = ['oneItem', 'twoItem'];
const notAnArray = 'oneItem';
const nonIterator = 300;
const oneDefault = 20;

const foo = typeOrArrayOfType => console.log([...typeOrArrayOfType, oneDefault]);

foo(anArray) // prints array items
foo(notAnArray) // spreads the string
foo(nonIterator) // error

It either works, spreads the string into characters or breaks entirely.
How can I flexibly take arguments that may or may not be an array?
I know about Array.isArray but I don't want helper function or conditionals if possible. I don't care about nested arrays, but if they behave differently it would be worth a note about it.

A: Create an array only if necessary
Declare a simple helper that wraps non-array values in an array or leaves the original intact:
const toArray = data =>
  Array.isArray(data)
    ? data
    : [data];

Example:

const anArray = ['oneItem', 'twoItem'];
const notAnArray = 'oneItem';
const nonIterator = 300;
const oneDefault = 20;

const toArray = data =>
  Array.isArray(data)
    ? data
    : [data];

const foo = typeOrArrayOfType => console.log([...toArray(typeOrArrayOfType), oneDefault]);

foo(anArray) // works
foo(notAnArray) // works
foo(nonIterator) // works

Convert everything to new arrays
The above has a slight weakness - it returns the original array in some cases. Which means that mutations might affect it:

const toArray = data =>
  Array.isArray(data)
    ? data
    : [data];

function test(input) {
  const arrOutput = toArray(input);
  arrOutput.push("world");

  return arrOutput;
}

const arrInput = ["hello"];

const output = test(arrInput);
console.log(output);   // [ "hello", "world" ]
console.log(arrInput); // [ "hello", "world" ]

To handle this, you could copy every array uniformly using Array#concat() - if given an array, it will produce a new array with a copy of its contents (only one level), if given non-array it will create a new array with the argument(s) as item(s):
const toArray = data =>
  [].concat(data);

Example:

const anArray = ['oneItem', 'twoItem'];
const notAnArray = 'oneItem';
const nonIterator = 300;
const oneDefault = 20;

const toArray = data =>
  [].concat(data);

const foo = typeOrArrayOfType => console.log([...toArray(typeOrArrayOfType), oneDefault]);

foo(anArray) // works
foo(notAnArray) // works
foo(nonIterator) // works

Example which does not have a problem with shared arrays:

const toArray = data =>
  [].concat(data);

function test(input) {
  const arrOutput = toArray(input);
  arrOutput.push("world");

  return arrOutput;
}

const arrInput = ["hello"];

const output = test(arrInput);
console.log(output);   // [ "hello", "world" ]
console.log(arrInput); // [ "hello" ]

This might be even simpler to use, since it removes the need to spread items. The .concat() method already creates a new array and accepts variable number of arguments, it can be used directly as a way to create a new array with extra items:

const anArray = ['oneItem', 'twoItem'];
const notAnArray = 'oneItem';
const nonIterator = 300;
const oneDefault = 20;

const foo = typeOrArrayOfType => console.log([].concat(typeOrArrayOfType, oneDefault));

foo(anArray) // works
foo(notAnArray) // works
foo(nonIterator) // works

Note: the @@isConcatSpreadable well-known symbol property can affect how Array#concat() works. When set to true then concatinating the object will be "flatten" similar to how arrays are. This will work on any array-like. Conversely setting the property to false will prevent .concat() from spreading the object:

//make an object string
const str = new String('bar');
//make it spreadable
str[Symbol.isConcatSpreadable] = true;

console.log([].concat(str));

//a spreadable array-like:
const arrayLike = {
  0: "h", 1: "e", 2: "l", 3: "l", 4: "o",
  length: 5,
  [Symbol.isConcatSpreadable]: true
};

console.log([].concat(arrayLike));

//non-spredable array:
const arr = ["x", "y", "z"];
arr[Symbol.isConcatSpreadable] = false;

console.log([].concat(arr));
.as-console-wrapper { max-height: 100% !important };

A: You should handle the variable by testing if it's an array with Array.isArray():
e.g.

const anArray = ['oneItem', 'twoItem'];
const notAnArray = 'oneItem';
const nonIterator = 300;
const oneDefault = 20;

const foo = typeOrArrayOfType =>
  console.log(Array.isArray(typeOrArrayOfType)
  ? [...typeOrArrayOfType, oneDefault]
  : [typeOrArrayOfType, oneDefault]);

foo(anArray) // prints array items
foo(notAnArray) // spreads the string
foo(nonIterator) // error

It would take very little effort to factorise the check into a utility function, which other answers do.

A: You can wrap it in an array and then use .flat() before spreading*
I've not seen this anywhere else on Stack Overflow.
This means that you always end up spreading an array:

const anArray = ['oneItem', 'twoItem'];
const notAnArray = 'oneItem';
const nonIterator = 300;
const nestedArray = ['lets', ['go', 'nest', ['arrays']]];
const anIterator = new Set([1,3,5,3]);
const oneDefault = 20;

const foo = typeOrArrayOfType => console.log([...[typeOrArrayOfType].flat(), oneDefault]);

foo(anArray) // nested array items is flattened one level
foo(notAnArray) // wrapped string doesn't get flattened
foo(nonIterator) // wrapped number doesn't get flattened
foo(nestedArray) // only flattens one level, added to show how .flat(works)
foo(anIterator)  // this does not work, and results in {}

N.B. Using .flat() only goes down one level by default (unlike, say lodash.flattenDeep or some other libraries). You could optionally supply a number, but that is out of the scope of the question.
const foo = (typeOrArrayOfType, depth=1) => console.log([...[typeOrArrayOfType].flat(depth), oneDefault]);

And not useful for the situation in the question.

* As an aside, some of the other answers use [].concat(variable) which to me is as clear or slightly less clear, but is somewhat more performant, as per this jsbenchmark without spreading or with spreading.


text:
Q: AutoHotkey diacrictics mappings not working correctly with Vim I've been using some mappings in Vim to avoid having to switch keyboard layouts to type in diacritics in my language (Croatian). However, now I wanted to move these mappings "up" so that they're available globally. I tried using AutoHotkey for this. Here are the mappings I wrote
#CommentFlag //
!;::Send {U+010D} // č
!'::Send {U+0107} // ć
!]::Send {U+0111} // đ
![::Send {U+0161} // š
!\::Send {U+017E} // ž

These work great in every application I've tried (browsers, notepad, MS Word), but don't work in Vim, which is pretty annoying as I do most of my typing there. More specifically, only 'š' and 'ž' work as expected, while both Alt-; and Alt-' give me a 'c' (instead of 'č' and 'ć'), and Alt-] gives a 'd' (instead of a 'đ').
I'm using AutoHotkey_L (though I had the same results with the "regular" AHK), Vim 7.3 (trying this in gVim; it doesn't work in the terminal version either (in a slightly different way) but I don't really care about that) on Win8.
I can give more info on the Vim version, but it's basically one of those windows binaries from vim.org. Things I guess might be important is that it has +multi_byte, and I've been using Unicode in it with no problems whatsoever.
Update:
As per Ingo's suggestion below, I've tried using IfWinNotActive to not have the mappings present in Vim and continue to use my old ones there. Here's one example I've tried
SetTitleMatchMode 2
IfWinNotActive GVIM
{
    #CommentFlag //
    !;::Send {U+010D} // č
    !'::Send {U+0107} // ć
    !]::Send {U+0111} // đ
    ![::Send {U+0161} // š
    !\::Send {U+017E} // ž
}

I've also tried many other variations with the Vim window class (using ahk_class), with #IfWindowNotActive etc., but to no avail... The mappings are still there in Vim. Btw, the window title always contains the string "GVIM", and AHK sees that as I've confirmed with WinGetTitle.

A: I don't have a solution, but a workaround: When I faced with the same issue, I decided to emulate Vim's digraphs globally (also using AutoHotkey), and just except Vim (and applications like Remote Desktop) from that feature (so that the full range can still be used there; my script only supports a subset). You can find my implementation here.

A: You can also edit a keyboard layout itself, using Microsoft Keyboard Layout Creator.
For example, the English one that you use: choose combination of some character and some function key (Ctrl or Right-Alt, with or without Shift − e.g. for Caps).
Here's how it looks:

A: I find the Apple International US layout very good for this purpose, having all the accents available using dead keys, so I've implemented it with Microsoft Keyboard Layout creator like stansult suggested.
Then I came up with the problem of having only one "Alt" key usable, so I ended up remapping my Windows and Alt keys using ScanCodemap. This is a viable solution if you don't use the Windows key that often. One caveat of this method is, that you'll have to use Win+Tab instead of Alt+Tab from now on to switch between windows, it takes a couple of days to get used to that.
Windows Registry Editor Version 5.00

; 0x003a001d: Caps Lock (0x3a) -> Left Ctrl (0x1d)
; 0x0038e038: Left Alt (0xe05c) -> Right Alt (0x38)
; 0xe05b0038: Left Windows (0xe05b) -> Left Alt (0x38)
; 0xe05c0038: Right Windows (0xe05c) -> Left Alt (0x38)
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layout]
"Scancode Map"=hex:00,00,00,00,00,00,00,00,05,00,00,00,1d,00,3a,00,38,e0,38,00,38,00,5b,e0,38,00,5c,e0,00,00,00,00


text:
Q: Custom Authentication for cloud endpoints with own database user details I have gone through the google cloud endpoints documentation and find the below configuration there for custom authentication,
https://cloud.google.com/endpoints/docs/openapi/authenticating-users
I don't understand the below things,

*

*How do I configure My spring boot jwt authentication(username and password in database) service url here ?

2.What are the possible values for the below configurations in case of custom authentication
x-google-issuer: "issuer of the token"

x-google-jwks_uri: "url to the public key"

x-google-audiences: "YOUR-CLIENT-ID"

Can you provide a example for this If any one using this type of authentication?

A: There are some great resources in response to this existing StackOverflow question:
Google Cloud Endpoints custom authentication with App Engine Flexible (Node.js)
Don't let the specificity of the question deter you. Even though it was asked about AppEngine Flex with Node.js, the answer is language/environment agnostic.


text:
Q: python - Catching signals between sleep calls So, lets say I have this code:
import signal
from time import sleep

def signalHandler(sig, frame):
    print "signalHandler"
    while True:
        sleep(1)
        #print "Caught" # Uncomment this line, and you get multiple signals - commented, you don't.

signal.signal(signal.SIGINT, signalHandler)
while True:
    sleep(1)

As seen in the comment, if the print statement is uncommented, the code works normally, and the signal handler will catch any subsequent CTRL-C presses like it should. However, if left commented, another signal will never be caught.
Why is this? My guess is that consecutive sleep calls are mashed together, and control is never coming back up to python to catch a signal. Which it would have to do for a print statement. Can anyone shed any insight into this?

A: This is indeed strange!
I believe this is a subtle interaction between the internals of the Python generated bytecode and an anomaly present in Python 2.7 before.   Note two things:

*

*Your code works perfectly in Python 3 with or without the print statement.

*If you change the sleep inside the signal handler to "sleep(60)" you'll notice that it still works correctly if you hit Ctrl-C before the print is even reached! (This is what made me suspicious).

If you read Issue 12472 in the Python bug tracker, you'll see that Python inserts an internal call to Py_CheckSleep before the next instruction (in this case, your print), which causes the signal to be caught when the sleep is interrupted.  Without the print, the extra check does not occur.
According to the issue, this was fixed in Python 3 and greater, but not in earlier versions.


text:
Q: Deployment Target for iOS Apps As of 2019, I mean latest. What is the minimum deployment target I should set in Xcode? I set it as 12.1, hence I could not run on my I-Phone which is the iOS version 11.2. Help me on this.

A: There is no "should" for your minimum deployment target. It's a question of what audience you are intending to release to. Just specify the earliest system on which your app is to run. If you want it to run on iOS 11.2, specify 11.2 (or earlier).


text:
Q: what is in asyncio.get_event_loop(), how to register an event in the event loop the code is below , my question is:
1.what is in loop got by asyncio.get_event_loop().I thought that a loop is a place to put task in it, we need to add task in the loop first . is that correct?
2. in the code ,
   loop = asyncio.get_event_loop()
   get the loop at the beginning , but looks like nothing has been put into the loop yet.
import asyncio
import datetime
import time

def function_1(end_time, loop):
    print ("function_1 called")
    if (loop.time() + 1.0) < end_time:
        loop.call_later(1, function_2, end_time, loop)
else:
    loop.stop()

def function_2(end_time, loop):
    print ("function_2 called ")
    if (loop.time() + 1.0) < end_time:
        loop.call_later(1, function_3, end_time, loop)
    else:
    loop.stop()

def function_3(end_time, loop):
    print ("function_3 called")
    if (loop.time() + 1.0) < end_time:
        loop.call_later(1, function_1, end_time, loop)
    else:
        loop.stop()

def function_4(end_time, loop):
    print ("function_5 called")
    if (loop.time() + 1.0) < end_time:
        loop.call_later(1, function_4, end_time, loop)
    else:
        loop.stop()
loop = asyncio.get_event_loop()
end_loop = loop.time() + 9.0
loop.call_soon(function_1, end_loop, loop)
# loop.call_soon(function_4, end_loop, loop)
loop.run_forever()
loop.close()


text:
Q: Firebase Auth photoURL always returns null Trying to follow the Firebase doc to update the photoURL of users. However, when I update, it only returns null.
editProfilePicture(){
    const user = firebase.auth().currentUser;

    user.updateProfile({
      displayName: "Jane Q. User",
      photoURL: "https://example.com/jane-q-user/profile.jpg"
    }).then(function() {
      // Update successful.
    }).catch(function(error) {
      // An error happened.
    });
  }

I render the image using a component that takes the return of photoURL <ProfilePicture image={currentUser && currentUser.photoURL} />.
currentUser is const { currentUser } = firebase.auth(), and this works perfect for displayName..
What am I doing wrong?

A: if you using google auth it will works fine but if you using just email and password auth it couldn't return the user profil(null) because you just initialize email and password by your own, your app just borrow your email.


text:
Q: clang-format Pointer Alignment I need use clang-format to take my source code in a style. I try used the Linux kernel .clang-format, and take some modification in it.
But now one thing didn't come true:
/* This is clang-format result: */
struct one_name {
    int *   n1; /* Ummmm... */
    int     n2;
    double *p;
};

/* But I wanna this: */
struct one_name {
    int    *n1; /* The pointer is close to var name. */
    int     n2;
    double *p;
};

How to modify the .clang-format for the "int   *n1"?

A: I had found out the reason: The version of clang-format and LLVM is too low (6.0.0)!
If use 13.0.0 with the same .clang-format file, "PointerAlignment: Right" can give the good format!
With this command to check version, such as:
$ clang-format --version
clang-format version 13.0.0

A: Make sure .clang-format is in your project directory, and make sure use
clang-format -style=file yourCode.c

And your .clang-format should have a line like
---
PointerAlignment: Right

For more options, visit https://clang.llvm.org/docs/ClangFormatStyleOptions.html


text:
Q: Robot Framework - How to import SeleniumLibrary keywords implementation/documentation in eclipse I am new to robot framework and I am using eclipse. I also installed RED plugin.
I opened the demo project in eclipse. And opened resource.robot file.
Here's my question. When I Ctrl+click on "Login Page Should Be Open", I get redirected to implementation of the keyword.
Now, I want to do the same with "Open Browser", "Maximize Browser Window" etc
How can I do that?
The main difference between them is that the former is a user defined keyword while the latter is a SeleniumLibrary keyword.
Any help is appreciated. Thanks a lot.
*** Keywords ***
Open Browser To Login Page
    Open Browser    ${LOGIN URL}    ${BROWSER}    NONE    ${REMOTE URL}
    Maximize Browser Window
    Set Selenium Speed    ${DELAY}
    Login Page Should Be Open

Login Page Should Be Open
    Title Should Be    Login Page

A: Thanks everyone for the replies. The solution is to add robot nature (Right click on the project > Robot Framework > Add Robot Nature to the project and add the selenium library in the red.xml as shown below.
Add selenium library to red.xml

Ctrl+click on the 'Open Browser' keyword then you'll be redirected to implementation of the keyword

Note: I also installed PyDev plugin and setup Phyton Interpreter in eclipse


text:
Q: Code giving SEG FAULT only when the class is being derived!
I am unable to find out the bug in the below code which i had written[Not for any purpose though].

#include &lt iostream &gt
#include &lt cstdlib &gt

using namespace std;

class Base{
public:
        Base(){cout &lt&lt "Base class constructor" &lt&lt endl;}
        void funv() {};
        ~Base(){cout &lt&lt "Base class destructor" &lt&lt endl;} ;
};

class Derived:public Base{
public:
        char *ch;
        Derived():ch(new char[6]()){}
        ~Derived(){
                cout &lt&lt "before" &lt&lt endl;
                delete [] ch;
                ch = NULL;
                cout &lt&lt "after" &lt&lt endl;
        }
};

int main(){

        Derived * ptr = new Derived;

        //memcpy(ptr -> ch,"ar\0",4); // Works when class Derived is derved from base and also when not derived from base

        ptr -> ch = const_cast &lt char* &gt("ar0");  // Works only when class Derived is not derived from class Base

        cout &lt&lt ptr -> ch[1] &lt&lt endl;

        ptr -> funv();

        delete ptr;

        return 0;
}

I have commented on the suspected lines of the code.

I am using sun Studio 12.

A: This is an Undefined behavior. It will cause problem in any case, whether you derive it or not.
When you assign a const char* to a char* like below:
ptr -> ch = const_cast < char* >("ar0");

That means, you are assigning a character string which is defined in non-heap segment (mostly in data segment). One should only delete memory which was allocated on heap segment.
Also, above assignment statement is executed, it will leak memory pointed by ch earlier. One way to avoid such problem is to declare the variable as,
private: char* const ch;

As soon as you try assigning something to ch, it will give compilation error. So that it will make you write wrapper to assign ch and there you can take care of deallocation.

A: I think you have a serious problem with understanding the meaning of Undefine Behavior.
Undefined Behavior doesn't necessarily mean a segfault
sorry for shouting but this is a very importan point.
Undefined behavior means, like the name suggest, "undefined". This means that you don't know what is going to happen. Actually a segfault is the best thing that you can hope for... but unfortunately 90% of UB in C++ is just silent.
The application will run normally and will even give you the results you expect. Everything will be fine... until of course the demo day when in front of an hundred people the application will crash badly just for the fun of getting your stunned face on youtube.
Undefined behavior is one of the reasons for which learning C or C++ by experimentation is a bad idea. When you make an error in C++ the language is not going to help you... the silent assumption is basically that you will not make any error... and if you are learning the language this is of course a very difficult requirement to match.
Undefined behavior is also the reason for which putting too much hope in the test suite when writing in C or C++ is also a bad idea. In these languages (and in other languages where UB is present) it is a very dumb approach to write code without too much thinking (therefore letting bugs in) and then hoping to remove them later. While this idea of saving thinking time first and trading it with debugging time later is IMO a bad approach in general (the cost/effort of bug removal will always be higher), in languages that allow UB this is a true suicide because bugs can hide also behind non-deterministic behavior.
Clearly I'm not saying that testing is a bad idea... it's of course a great one (basically a must-have if you want to keep a refactoring possibility) but only if it's not used as an excuse to lower the attention you put when writing the code.
You should basically avoid to confuse what is an error (i.e. UB) with what is a crash (i.e. the segfault). Crash are friends... and you want to have as many possible crashes as you can, because a crash is a signal that an error is present. To add more possible crash points for example you should use assertions... a segfault is just an assertion automatically placed by the environment but you need more. When you have a crash then you know there is an error and you can start looking for it. Unfortunately when you don't have a crash it doesn't mean that there are no errors... it simply means that no bug fell in the traps you've prepared for them.
A piece of code can compile fine (zero errors and zero warnings), it can pass the whole test suite... but can still be at the same time incorrect. This is true of course even in higher level languages where it has been decided that the performance price to pay to avoid UB was worth runtime checks (e.g. Java) but an higher logical level. UB in C and C++ makes things a little harder because of non-determinism.
In your code UB is triggered because you are calling delete[] on a pointer that wasn't obtained with a call to new ... [] (a string literal). This may or may not of course generate a segfault.
Your code also has some other legal but very questionable parts:

*

*The base class destructor is not virtual. You are not destroying a derived object using a pointer to base, so this is legal, but none the less it's a bad idea. If a class is meant to be derived then the destructor should be virtual.

*The derived class defines a destructor, but no copy constructor and no assignment operator. These three methods should always go together: either you define none of them or you define (or at least declare) all three of them. The reason is that these three methods are automatically created by the compiler if they are not present and it's quite unlikely that the automatically generated code is correct in one case but not in the others. In your code for example if someone makes a copy of the derived object using Derived *der2 = new Derived(*der1); the pointer to the dynamically allocated memory will be just copied and possibly deallocated twice (once for each of the two objects destroyed); in case of an assignment with *der2 = *der1; instead you will have a potential double-deallocation in addition to a memory leak. It may make sense to forbid copy constructor and assigment for a class, but in this case the common idiom is to declare those methods private and leaving them not implemented (this will give a compile error if someone else tries to use them, and a link error if a method uses them by mistake).

A: memcpy(ptr -> ch,"ar\0",4);

memcpy copys the contents from source buffer to the destination buffer your pointer ptr->ch points to.
ptr -> ch = const_cast < char* >("ar0");

You're reassigning the value to the pointer itself. This is dangerous because you have no way to get the original buffer on heap anymore. That's a memory leak. Also, in your destructor you delete this pointer which now doesn't points to a buffer on heap. It's undefined.


text:
Q: Comparing numbers from one array with indexing of another array Javascript just wanted to know if something like this can be done and how exactly. My aim is to take all the numbers from one array and compare them with the indexes of another one, finally print the elements.
Example:
var myindex = new Array(2, 0);

var array1 = new Array("text", "apple", "sample")
var array2 = new array("book", "phone", "orange")

myindex.forEach(number => document.write(array1.indexOf(number)))

Expected result: the following will be printed: sample orange text book
First issue: All that is shown is the -1 error which means I think: no number in the array but there is one so I do not understand?
Second issue: I also need to implement array2 to work together with array1 so we can actually see the expected result as shown above. I would appreciate any help

A: You can simply loop through the index array and then use it's value:

var myIndex = [2,0];
var array1 = new Array("text", "apple", "sample");
 var array2 = new Array("book", "phone", "orange");

for (var i = 0; i < myIndex.length; i++){
  console.log(array1[myIndex[i]] + " " + array2[myIndex[i]]);
}

A: You could use an array for the data and check if the data at the given index exist. Then make the output.

var myindex = [2, 0],
    array = [["text", "apple", "sample"], ["book", "phone", "orange"]];

myindex.forEach(number => array[number] && console.log(array[number]));

A: You don't need indexOf here, which searches an array. You need to access the array via the index (square bracket notation) to get the value:

var myindex = new Array(2, 0);

var array1 = new Array("text", "apple", "sample")
var array2 = new Array("book", "phone", "orange")

myindex.forEach(number => console.log(array1[number], array2[number]));

NB: You had a typo in the array constructor: it needs to be Array(), not array(). Secondly, don't use document.write.

A: You just need to access the array elements with array[index] syntax.

var myIndexs = [2, 0];

var array1 = ["text", "apple", "sample", "book"];
var array2 = ["book", "phone", "orange", "text"];

myIndexs.forEach((index) => document.write(`${array1[index]} ${array2[index]} `));

Plus, use [] syntax to create arrays and not Array(): https://coderwall.com/p/h4xm0w/why-never-use-new-array-in-javascript
If you want the results in two lines, well it kind of depends on your use case, you just really want to write to the html, you can simply do it like this:

var myIndexs = [2, 0];

var array1 = ["text", "apple", "sample", "book"];
var array2 = ["book", "phone", "orange", "text"];

const results1 = [];
const results2 = [];

myIndexs.forEach((index) => {
  // Here you might want to validate if array1[index] exists
  results1.push(array1[index]);

  // Here you might want to validate if array2[index] exists
  results2.push(array2[index]);
});

document.write(`${results1}<br />${results2}`);

But, it might depend on your use case. I might want to create two different node targets in the html and write each of the results to different targets. You might just need the two array variables in javascript. You should not follow any of the code here blindly, you should adapt to your specific use case.

A: Just for some variety and for fun you may do like this;

var myIndex = new Array(2, 0),
     array1 = new Array("text", "apple", "sample"),
     array2 = new Array("book", "phone", "orange");
console.log.apply(console, myIndex.reduce((p,c) => p.concat(array1[c],array2[c]),[]));


text:
Q: prepared statement invalid parameter number Okay so I've been starting at this for an hour now, it says "Invalid parameter number: number of bound variables does not match number of tokens in..." Iv'e counted them out and they are right. Any ideas?
 $sql="insert into myTable (TicketID ,Priority, Status, Summary, Description, Category, Customer,
                AssignedGroup, AssignedTo, OpenedDate, ResolvedDate, ClosedDate, FinalDescription, RootCause, ResolutionCode)
               values(:tid,:pri,:stat,:summ,:descr,:cat,:cus,:assG,:assT,:opnDate,:resDate,:cloDate:,finDesc,:root,:resCode)";
        $stmt=$dbh->prepare($sql);

        $stmt->bindParam(':tid', $data[0]);
        $stmt->bindParam(':pri', $data[1]);
        $stmt->bindParam(':stat', $data[2]);
        $stmt->bindParam(':summ', $data[3]);
        $stmt->bindParam(':descr', $data[4]);
        $stmt->bindParam(':cat', $data[5]);
        $stmt->bindParam(':cus', $data[6]);
        $stmt->bindParam(':assG', $data[7]);
        $stmt->bindParam(':assT', $data[8]);
        $stmt->bindParam(':opnDate', $Odate);
        $stmt->bindParam(':resDate', $RDate);
        $stmt->bindParam(':cloDate', $CDate);
        $stmt->bindParam(':finDesc', $data[12]);
        $stmt->bindParam(':root', $data[13]);
        $stmt->bindParam(':resCode', $data[14]);

        try{
            $stmt->execute();
            $stmt->closeCursor();

A: You forgot : here in query
cloDate,:finDesc,
        ^ // here

A: Change this part:-
:cloDate:,finDesc

to
:cloDate,:finDesc


text:
Q: Set up Jenkins,Docker, Kubernetes ci/cd on Azure I want to create a CI/CD on Azure with Jenkins, Docker, Kubernetes, starting from simple.
I already went through the Voting-app tutorial Tutorial: Prepare application for Azure Container Service (AKS) Azure tutorial The tutorial covers the steps:

1 - Prepare application for AKS  2 - Create container registry ACS  3
  -Create Kubernetes cluster  4 - Run application

The application is working.
The next step I want to do, is to integrate Jenkins. I am following the tutorial Continuous deployment with Jenkins and Azure Container Service I couldn´t follow the tutorial because is too advanced to understand the commands from the files. For example, the way they deployed jenkins using the file deploy-jenkins-vm.sh
Instead of that, I went to the Marketplace on Azure and created "Jenkins" and via the Azure UI, set up the configuration. Jenkins is now running on localhost:8080
From another video tutorial Hands-on Docker, Jenkins CI/CD Azure  I shared the cluster kubeconfig to my remote jenkins host:

$ sudo scp ~/.kube/config
  anjenkins@jenkins9999.australiaeast.cloudapp.azure.com:/var/lib/jenkins/config

It worked.
Then, from the same video tutorial they run a bash file
#!/bin/bash
# Jenkins Bootstrap for ACS Kubernetes
set -x #echo on
wget https://raw.githubusercontent.com/mekenthompson/kubectl/master/kubectl -O ~/kubectl
chmod +x kubectl
sudo cp kubectl /usr/local/bin/kubectl
sudo mkdir /home/tomcat/.kube
sudo cp config /home/tomcat/.kube/config
sudo chown -R tomcat:tomcat /home/tomcat/.kube
sudo usermod -aG docker tomcat
sudo /opt/bitnami/ctlscript.sh restart
set +x #echo off

From the repository here. It didn´t work for me
+ chmod +x kubectl
+ sudo cp kubectl /usr/local/bin/kubectl
+ sudo mkdir /home/tomcat/.kube
mkdir: cannot create directory '/home/tomcat/.kube': No such file or directory
+ sudo cp config /home/tomcat/.kube/config
cp: cannot stat 'config': No such file or directory
+ sudo chown -R tomcat:tomcat /home/tomcat/.kube
chown: invalid user: 'tomcat:tomcat'
+ sudo usermod -aG docker tomcat
usermod: group 'docker' does not exist
+ sudo /opt/bitnami/ctlscript.sh restart
sudo: /opt/bitnami/ctlscript.sh: command not found
+ set +x

But my question is, what is the next step after I shared de kubeconfig to my jenkins remote host. I am just copying and pasting, but not knowing , what is happening
Form the tutorials, they seem to me, too advanced and I don´t know what is going on, or what exactly should be done.
From the Azure Voting tutorial they have another file, to set up Jenkins config-jenkins.sh, but as well I don´t know what needs to be done
What exactly I should do, Do you know other resources or links to follow.
I have already jenkins, an Azure Container Registry, Azure Container Service, and the voting app.

A: We're working on an open source project called Jenkins X which is a proposed sub project of the Jenkins foundation aimed at automating CI/CD on Kubernetes using Jenkins pipelines and GitOps for promotion across environments.
If you want to see how to automate CI/CD with multiple environments on Kubernetes using GitOps for promotion between environments and Preview Environments on Pull Requests you might wanna check out my recent talk on Jenkins X at DevOxx UK where I do a live demo of this on GKE. Though Jenkins X works on AWS, AKS and GKE and other kubernetes clusters too.


text:
Q: Select person in a table having a specific value but not having another value for same id I tried for hours and read many posts but I still can't figure out how to handle this request:
I have a table like this:
+------+------+------+
|PERSON|TRTYPE| ID   |
+------+------+------+
|JERRY | I    |   2  |
+------+------+------+
|JERRY | U    |   2  |
+------+------+------+
|TOM   | U    |   2  |
+------+------+------+
|SPIKE | I    |   3  |
+------+------+------+
|SPIKE | U    |   3  |
+------+------+------+

I would like to select the PERSON, ID that has a TRTYPE of U for an ID but he does not have a TRYPE of I for that same ID.
The output should be something like:
+------+------+
|PERSON| ID   |
+------+------+
|TOM   | U    |
+------+------+

As TOM is the only person who has performed a transtype of U on an ID on which he did not perform a TRTYPE of I

A: Use aggregation and having:
select person, id
from mytable
where trtype in ('I', 'U')
group by person, id
having min(trtype) = max(trtype) and min(trtype) = 'U'

A: You can use NOT EXISTS like in the below query
SELECT * FROM yourtable A WHERE A.TRTYPE ='U'
AND NOT EXISTS
(
SELECT 1 FROM yourtable T WHERE T.TRTYPE ='I'
AND T.PERSON=A.PERSON AND T.ID=A.ID
)

A: Assuming your table is called [table_1],
SELECT [PERSON], [ID] FROM [table_1] t1
WHERE (SELECT COUNT(*) FROM [table_1] t2 WHERE t2.[PERSON] = t1.[PERSON] AND t2.[TRTYPE] = 'I') = 0

A: You could use Common Table Expression to break your logic and acheive the result as follows
with cte as(select * from table where trptype in ('U'))
select * from cte where cte.id not in (select distinct cte.id from cte where cte.trptype in ('I'))


text:
Q: Multi SQL statements executed via ADO.NET command object I need to update a record in a table but it is possible that the record does not exist, so I would need to insert the record.
Below is a SQL statement that accomplished my goal by trying to update the record first and if it doesn't exist it performs an insert. What I am wondering if it can be executed directly via ADO.NET command object or does it need to go into a stored procedure.
UPDATE MyTable SET ReservationDate = @ReservationDate WHERE CustomerNumber = XXXX;
IF @@ROWCOUNT=0
  INSERT INTO MyTable (CustomerNumber , ReservationDate)
  VALUES (@CustomerNumber , @ReservationDate)

If I could execute it via the command object without a stored procedure it would mean one less dependency for deployment time (i.e. deploying the stored procedure).

A: The MERGE command in T-SQL works for just this scenario
string cmdText = @"MERGE MyTable T
                   USING (SELECT @CustomerNumber As CustomerNumber) as S
                   ON T.CustomerNumber = S.CustomerNumber
                   WHEN MATCHED UPDATE SET ReservationDate = @ReservationDate
                   WHEN NOT MATCHED INSERT INTO (CustomerNumber , ReservationDate)
                                    VALUES (@CustomerNumber , @ReservationDate)";

It is just one string of text wrapped for readability in more lines thanks to the verbatim character @
With MERGE you start defining your TARGET table (T), then you build a pseudotable called SOURCE (S) with the parameter that contains the value for the primary key field in TARGET. Now the two tables are JOINED ON the field CustomerNumber. The product of this join could be MATCHED or NOT MATCHED depending of the previous presence of the record in the TARGET table. The remainder of the query is probably self explanatory, just notice that in the two actions (UPDATE and INSERT) there is no need to repeat the MyTable name (it is the TARGET)
By the way, yes you could pass multiple commands to the SqlCommand separated by a semicolon


text:
Q: Retrofit call gives default values and not the values needed The problem that I have is when I do a retrofit call to my backend it knows that there are 4 objects but all the objects are having the default values instead of the correct values. When I do a call in postman it gave me the correct values so the problem is in my android code. Can somebody help ?
Below you find the code of my model.
class Breaks : Serializable{
@SerializedName("BreakId")
var breakId:Int = 0
@SerializedName("Player")
var player:String = ""
@SerializedName("MomentPlayed")
var momentPlayed:String = ""
@SerializedName("NumberPoints")
var numberPoints:Int = 0
@SerializedName("Opponent")
var opponent:String = ""
@SerializedName("TypeBreak")
var typeBreak:String = ""
@SerializedName("FrameId")
var frameId:Int? = 0

constructor(){}

constructor(breakId: Int, player: String, momentPlayed: String, numberPoints: Int, opponent: String, typeBreak: String, frameId: Int?) {
    this.breakId = breakId
    this.player = player
    this.momentPlayed = momentPlayed
    this.numberPoints = numberPoints
    this.opponent = opponent
    this.typeBreak = typeBreak
    this.frameId = frameId

}

constructor(breakId: Int,  player: String, momentPlayed: String, numberPoints: Int, opponent: String,  typeBreak: String) {
    this.breakId = breakId
    this.player = player
    this.momentPlayed = momentPlayed
    this.numberPoints = numberPoints
    this.opponent = opponent
    this.typeBreak = typeBreak

}

constructor(breakId: Int,  player: String, numberPoints: Int, opponent: String,  typeBreak: String) {
    this.breakId = breakId
    this.player = player
    this.numberPoints = numberPoints
    this.opponent = opponent
    this.typeBreak = typeBreak

}
fun getTotalOfPoints(): Int {
    return numberPoints
}

fun setTotalOfPoints(numberPoints: Int) {
    this.numberPoints = numberPoints
}

fun getTypeBreaks(): String {
    return typeBreak
}

fun setTypeBreaks(typeBreak: String) {
    this.typeBreak = typeBreak
}}

Below you can find the code where I do my retrofit call
        var call: Call<List<Breaks>>
    call = snookerApi.getBreaks()
    call.enqueue(object: Callback<List<Breaks>> {
        override fun onResponse(call: Call<List<Breaks>>, response: Response<List<Breaks>>) {
            val statusCode = response.code()
            if(statusCode == 200) {
                var Breaks = response.body()!!.toList()
                Log.d("","gelukt")
            }
        }
        override fun onFailure(call: Call<List<Breaks>>, t: Throwable) {
            Log.d("",t.toString())
        }
    })

Below you find the api call
    @GET("api/Breaks")
fun getBreaks(): Call<List<Breaks>>

Below you find what I need and what I get in postman
[
{
    "BreakId": 1,
    "Player": "Bart",
    "MomentPlayed": "2018-11-12T14:47:00",
    "NumberPoints": 49,
    "Opponent": "Dennis",
    "TypeBreak": "training",
    "FrameId": null
},
{
    "BreakId": 2,
    "Player": "Bart",
    "MomentPlayed": "2018-11-12T14:47:00",
    "NumberPoints": 49,
    "Opponent": "Dennis",
    "TypeBreak": "training",
    "FrameId": null
},
{
    "BreakId": 3,
    "Player": "Dennis",
    "MomentPlayed": "2018-11-12T14:47:00",
    "NumberPoints": 49,
    "Opponent": "Bart",
    "TypeBreak": "training",
    "FrameId": null
},
{
    "BreakId": 4,
    "Player": "Dennis",
    "MomentPlayed": "2018-11-12T14:47:00",
    "NumberPoints": 49,
    "Opponent": "Koen",
    "TypeBreak": "training",
    "FrameId": null
}

]

A: Solved the problem the @SerializedName needed to be @field:Json(name = "BreakId")


text:
Q: Simplifying/expanding the floor of a product Is there any way of simplifying or expanding the following expression:
$\lfloor ab\rfloor$
where $a$ and $b \in \mathbb{R}$? I know there exist formulae that allow simplifying the floor of a sum, or the floor of a quotient of two integers, but none that invlove the floor of a product. If simplifying is not possible, is there a way to expand it so that $a$ and $b$ are not "grouped" together within the floor function? Something like $\lfloor ab\rfloor = \lfloor a\rfloor \lfloor b\rfloor +...$


text:
Q: Getting a unique parameter off of client's device I need to create complete random numbers using a seed in JavaScript. I'm not using the built-in Math.random(), but rather something else that can take a seed and generate a random number based on that.
This solution is supposed to serve a situation in which two users log in at the same time to a website (it happens A LOT, and I'm getting a lot of users with identical IDs because of it). Math.random() isn't working for me, and I can't use timestamps because these also don't provide an accurate number (they're not being sampled every MS). I also don't want to use any ajax call in order to get an IP or something similar.
Is there anything anyone can think of that's either unique, or might be rare enough to use to create a good seed?
**EDIT: ** This is NOT a duplicate of the GUID generation question, because that one is still using Math.random(). I can't use that function anywhere in my code. I sometime have thousands of hits at more-or-less the exact same moment, and that's what screws up the random. It's also the reason why I need to find some attribute I can use as a seed.


text:
Q: URL Conditional config in htaccess My case is the following:
I have a file named mylogic.php. This file is called from two different URLs (/url1.php & /url2.php).
What I want to archive is to add some headers to the response only when mylogic.php is accessed from /url1.php.

Experts: Do you have a workaround to this issue?
THANKS in advance.

A: do you want to do this in your htaccess, or is something like
if( $_SERVER['REQUEST_URI'] == '/url1.php' ) header('WeirdStuff: x');

sufficient

A: $_SERVER['PHP_SELF'] contains the name of the main PHP script (i.e. /url1.php or /url2.php). You can test the value of this variable and send the header when it matches the URL you want. Something like:
if ($_SERVER['PHP_SELF'] == '/url1.php') {
    doSomething();
}


text:
Q: Docker compose failed build for scrapy-cluster I am running the docker quick-start  from the scrapy-cluster library. Everything works well when running docker-compose up -d in terms of redis, kafka and zookeeper images are successfully installed however, it gets to this line:
Use 'docker scan' to run Snyk tests against images to find vulnerabilities and learn how to fix them
Building crawler
[+] Building 3.3s (6/15)
 => [internal] load build definition from Dockerfile.py3                                                                                0.0s
 => => transferring dockerfile: 919B                                                                                0.0s
 => [internal] load .dockerignore                                                                                0.0s
 => => transferring context: 2B                                                                                0.0s
 => [internal] load metadata for docker.io/library/python:3.6                                                                                0.2s
 => CACHED [ 1/11] FROM docker.io/library/python:3.6@sha256:f8652afaf88c25f0d22354d547d892591067aa4026a7fa9a6819df9f300af6fc                                                      0.0s
 => [internal] load build context                                                                                0.0s
 => => transferring context: 184.10kB                                                                                0.0s
 => ERROR [ 2/11] RUN apt-get update && apt-get -y install   python-lxml   build-essential   libssl-dev   libffi-dev   python-dev   libxml2-dev   libxslt1-dev   && rm -rf /var/  3.0s
------
 > [ 2/11] RUN apt-get update && apt-get -y install   python-lxml   build-essential   libssl-dev   libffi-dev   python-dev   libxml2-dev   libxslt1-dev   && rm -rf /var/lib/apt/lists/*:
#5 0.238 Get:1 http://security.debian.org/debian-security bullseye-security InRelease [44.1 kB]
#5 0.241 Get:2 http://deb.debian.org/debian bullseye InRelease [116 kB]
#5 0.269 Get:3 http://deb.debian.org/debian bullseye-updates InRelease [39.4 kB]
#5 0.337 Get:4 http://security.debian.org/debian-security bullseye-security/main amd64 Packages [164 kB]
#5 0.402 Get:5 http://deb.debian.org/debian bullseye/main amd64 Packages [8182 kB]
#5 1.463 Get:6 http://deb.debian.org/debian bullseye-updates/main amd64 Packages [2592 B]
#5 2.142 Fetched 8548 kB in 2s (4326 kB/s)
#5 2.142 Reading package lists...
#5 2.492 Reading package lists...
#5 2.871 Building dependency tree...
#5 2.965 Reading state information...
#5 3.018 E: Unable to locate package python-lxml
------
executor failed running [/bin/sh -c apt-get update && apt-get -y install   python-lxml   build-essential   libssl-dev   libffi-dev   python-dev   libxml2-dev   libxslt1-dev   && rm -rf /var/lib/apt/lists/*]: exit code: 100
ERROR: Service 'crawler' failed to build : Build failed

Then it fails, perhaps these libraries are not in the requirements.txt file, and it is throwing the error. How do I correct this?


text:
Q: How to make Classes generated in build Serializable and Parcelable? I am trying to send List containing objects from Classes created during build.
and these classes are generated each time program builds.
so can't make these classes implement Serializable or Parcelable

How do i overcome this problem...!
saving json in preferences and then loading it in other class is not working as well as there is huge data.


text:
Q: Is it acceptable to call a function from a function is Node.js? I'm learning Node.js by converting an existing Rails project. It's taken some time to get my head around callbacks and the async nature of Node.
The first general attempt looked ok, my RoR functionality was replicated and general speed was much faster using Node.
Having watched the nodecast here I started wondering whether my creation went against all the Node principals.
I have some function which, depending on the results call other functions. Simple, if, else if, else logic.
What I'm trying to figure out is if it's OK to do this or whether I should using something like the async package.
One particular function looks like this:
  checkAuthorization: function(socket,callback) {
    client.hget(socket.mac, 'authorized', function(err, val) {
      callback(val);
      if (val == null) {
        checkExteralAuth(socket.mac, socket.serial, function(val) {
          data = JSON.parse(val)
          authorized = (data["live"] == 'yep') ? true : false
          setRedisHash(socket.mac, 'authorized', authorized);
        });
      };
    });
  }

Is there a mode "node" way of doing this?

A: Why wouldn't it be? Node.js is a JavaScript platform. It's perfectly acceptable to call functions inside functions in a functional programming language. You do it all the time.
That said, sometimes you might want to avoid simply calling the function, especially with callbacks. The way you're calling the function, referenced by callback, implies that unless that function was explicitly bound to some context (using bind), you're losing the context.
Instead, callback.apply(this, [val]); might be the preferred way of going about your business.
Another thing is that since you're passing a callback function to be called later on, you might want to seriously look into using async as much as possible. I don't have an awful lot of experience with node.js, but by its very nature you'll find yourself writing callbacks, handlers and just using general async trickery all over the place.
Having a package that makes that job a lot easier is always handy...

A: There isn't anything fundamentally un-node-ish in this code, most libraries you will see are written exactly like this.
However, when you're working on an application, which tends to grow rather quickly, you eventually run into what is called the "callback hell", where the level of nesting reaches a level where you can have dozens of nested anonymous function calls.
This quickly becomes unmaintainable, which is where control flow libraries come in. There are several of the, the most popular ones being async and q.
async can be dropped readily into any codebase to manage callback hell, q requires architecting your code to work as Promises, but results in generally nicer API.


text:
Q: 2 symbols arguments for tools in Python How to create arguments with 2 symbols
i know how to create -t, -u, -h but how to create arguments with 2 symbols like -db, -ab, etc
here is the code i create
opts, _ = getopt.getopt(sys.argv[1:], "t:u:h[db]", ["target=", "url=", 'help'])

A: The second and third arguments to getopt are the short options and the long options.  An option you specify in the short options string can only be one character long.  The long options can be longer, but they must be specified in the input with a prefix of --.  So you could define an option --db, but not an option -db.
For the sake of completeness, I should note that you don't have to use getopt.  You can parse the command line with your own software if you want.  If you did that, you could certainly support two-letter options.  It would just be more development work.


text:
Q: java division: Inconvertible types found: int What's wrong with this code
int numOfPrimes=pf.FindNumPrimes(10000);
Double frequency=((Double)numOfPrimes)/10000d;

Says

inconvertible types found   : int
  required: java.lang.Double        Double
  frequency=((Double)numOfPrimes)/10000d;

A: Don't cast from primitives to wrapper types. Use lower-case double. And you don't need any casting in this case - the compiler does that automatically. The above can be simplified to:
int numOfPrimes = ...;
double frequency = numOfPrimes / 10000d;

You should almost never mix primitives with wrappers. And always prefer primitives (if possible). Use Double.valueOf(..) for conversion if you need to.

A: You're trying to autobox an int to a Double object, which is invalid.
Try:
int numOfPrimes=pf.FindNumPrimes(10000);

Double frequency=((double)numOfPrimes)/10000d;

A: Double is not a primitive type (like int, long, byte, etc). It's a class type. You can convert between double and Double using autoboxing but not between int and Double.
You should either declare numOfPrimes as double or do the cast to a double instead of a Double
double numOfPrimes=pf.FindNumPrimes(10000);
Double frequency=((Double)numOfPrimes)/10000d;

or
int numOfPrimes=pf.FindNumPrimes(10000);
Double frequency=((double)numOfPrimes)/10000d;

or without unnecessary casts:
double numOfPrimes = pf.FindNumPrimes(10000);
Double frequency= numOfPrimes /10000d;

or
int numOfPrimes = 10;
Double frequency = numOfPrimes /10000d;


text:
Q: undefined reference to sin and exp in c I am trying to compile a bunch of different object files into an executable file using this command:
gcc -Wall -Ilib -lm -Itest/lib -o test/test_passwd test/test_cases/test_passwd.c build/tests/hills_quad_two.o build/tests/hills_blank_quad.o build/tests/climber.o build/tests/hills_double.o build/tests/hills_multi_var.o build/tests/test.o build/tests/hills_sin.o build/tests/hills_exp.o

and I am getting two errors:
/usr/bin/ld: build/tests/hills_sin.o: in function `hills_sin_function':
hills_sin.c:(.text+0x100): undefined reference to `sin'
/usr/bin/ld: hills_sin.c:(.text+0x11f): undefined reference to `sin'
/usr/bin/ld: build/tests/hills_exp.o: in function `hills_exp_function':
hills_exp.c:(.text+0x122): undefined reference to `exp'
/usr/bin/ld: hills_exp.c:(.text+0x1a0): undefined reference to `exp'
collect2: error: ld returned 1 exit status

I have linked the math library using -lm in the compilation command as well as using #include <math.h> in a header file. I'm not sure what I'm doing wrong that stops it from compiling. Thanks in advance for the help.


text:
Q: how to call knockout function in nested observable array I have a brand list and brands contains car list. Declared simple view model in knockout on http://jsfiddle.net/PZqEk/1/ . this.cars is undefined in removeCar function when clicking remove button. How to delete clicked car with best practice?
Html:

                        ()
                        <input data-bind="click: $root.removeCar" type="button" value="remove"/>

Javascript:
function RootModel()
{
    this.title = ko.observable("Dummy Title");
    this.brands = ko.observableArray();

    var b1 = new brandModel("Audi");
    b1.cars.push(new carModel("A3", 2005));
    b1.cars.push(new carModel("A6", 2005));

    var b2 = new brandModel("Volkswagen");
    b2.cars.push(new carModel("Golf", 2010));
    b2.cars.push(new carModel("Passat", 2008));
    b2.cars.push(new carModel("Polo", 2012));

    this.brands.push(b1);
    this.brands.push(b2);
}

function brandModel(name)
{
    this.nameOfBrand = ko.observable(name);
    this.cars = ko.observableArray();

    this.removeCar = function(car){
        this.cars.remove(car); // this.cars = undefined;
    }
}

function carModel(name, year){
    this.nameOfCar = ko.observable(name);
    this.yearOfCar = ko.observable(year);
}

ko.applyBindings(new RootModel());

Thanks

A: The problem is that you're accessing this from a function that is not called on the instance.  You'll need an alias.
function brandModel(name) {
    var self = this; // alias
    self.nameOfBrand = ko.observable(name);
    self.cars = ko.observableArray();

    self.removeCar = function(car) {
        self.cars.remove(car); // access through the alias instead
    }
}

A: Jeff is correct in that you should alias this (commonly by declaring self = this; at the top of a model), and I would recommend doing that for every Knockout application you make.
However, I did not notice that you were using this at first, and immediately tried this code:
<input data-bind="click: function(data, event) { $parent.removeCar(data); }" type="button" value="remove"/>

and as the only change to your fiddle, that worked.


text:
Q: SQL Query Search 2 tables Hi Im stuck trying to search two tables and getting the results I need I have one table with qualifications in with the users id's as well set out like this:
Table name: phpvms_airframe_qual
id    pilotid   airframe   icao
0       1001      name     tutr
1       1001      name     eufi
2       1002      name     tutr
3       1002      name     king
4       1001      name     a400

Table name: phpvms_aircraft
id    fullname   icao    registration
0       tutor    tutr        G-BXEX
1      typhoon   eufi        ZJ932
2       tutor    tutr        G-DXRT
3      kingair   king        ZZ990
4       atlas    a400        ZM400

What I need to do is get a list of aircraft but only show ones that the user has the qualification for. So user 1001 will show the following from the example:
id    fullname   icao    registration
0       tutor    tutr        G-BXEX
1      typhoon   eufi        ZJ932
2       tutor    tutr        G-DXRT
4       atlas    a400        ZM400

and 1002 will show the following:
id    fullname   icao    registration
0       tutor    tutr        G-BXEX
2       tutor    tutr        G-DXRT
3      kingair   king        ZZ990

I have tried:
SELECT * FROM `phpvms_aircraft` WHERE phpvms_aircraft.icao = (SELECT icao FROM `phpvms_airframe_qual` WHERE pilotid = '1001')

But I get errors any Ideas how to do this
Thanks

A: This should work but I have not been able to test it.  let me know if it doesn't and what errors come up.
SELECT * FROM phpvms_aircraft
    INNER JOIN phpvms_airframe_qual ON phpvms_airframe_qual.icao = phpvms_aircraft.icao
    WHERE phpvms_airframe_qual.pilot_id = 1001;

A: You can do an inner join to get this answer:
 select * from phpvms_aircraft inner p join phpvms_airframe_qual pq on p.icao = pq.icao where ...


text:
Q: Azure blob storage - controlling name when resource is downloaded We have thousands of files to store in Azure blob storage.  These files could be of any type, but PDF files, images, and Excel are the most common.  With the URI of the blob in an anchor tag, a user of our system can download a file directly from Azure to the user's computer.  All is good.
We would like to have the blob name be the name of the file itself, so when the user downloads the file, the original filename is intact.  However, we must account for inevitable filename collisions in the Container.  Using GUIDs for the blob name is a workable solution, but when the user clicks to download the file, they will get a filename as the GUID blob name (vs. the original filename).
Is there a way to use a GUID for the blob name, but when the user clicks to download the file, the returned file has the original filename?  I realize we can download the file to our server and stream a properly named file to the user, but we are trying to keep the load off our web server for file downloads.
So is there a configuration setting with a blob that would enable the file to be returned with the proper filename?  We can set a MIME type for a blob, and we were looking for a similar setting for the filename part.

A:
Is there a way to use a GUID for the blob name, but when the user
  clicks to download the file, the returned file has the original
  filename? I realize we can download the file to our server and stream
  a properly named file to the user, but we are trying to keep the load
  off our web server for file downloads.

You can use Content-Disposition property of the blob to achieve this. What you can do is set the name of the blob as GUID however set the content-disposition property of the blob as attachment; filename="original-file-name". If you want the file to  be always downloaded, you can permanently set this property. However if you want to only set this name when the file is downloaded, you can create a Shared Access Signature on the blob with Read permission and overwrite this header. I wrote about this in my blog sometime ago. From my blog post:

Assume a scenario where you want your users to download the files from
  your storage account but you wanted to give those files a user
  friendly name. Furthermore, you want your users to get prompted for
  saving the file instead of displaying the file in browser itself (say
  a PDF file opening up automatically in the browser only). To
  accomplish this, earlier you would need to first fetch the file from
  your blob storage on to your server and then write the data of that
  file in the response stream by setting "Content-Disposition" header.
  In fact, I spent a good part of last week implementing the same
  solution. Only if I had known that this feature is coming in storage
  itself:).
Now you don't need to do that. What you could do is specify a
  content-disposition property on the blob and set that as "attachment;
  filename=yourdesiredfilename" and when your user tries to access that
  through a browser, they will be presented with file download option.
Now you may ask, what if I have an image file which I want to show
  inline also and also as a downloadable item also. Very valid
  requirement. Well, the smart guys in the storage team has already
  thought about that :). Not only you can set content-disposition as a
  blob property but you can override this property in a SAS URL (more on
  it in a bit).


text:
Q: precalculus absolute value of imaginary numbers Question:
Let $z$ and $w$ be complex numbers such that $|2z - w| = 25$, $|z + 2w| = 5$, and $|z + w| = 2$. Find $|z|$.
Attempt at Solution:
Knowing that $w$ and $z$ are complex numbers is making what I'm solving for difficult to understand. Working without substituting the $a+bi$ thing in is giving me some "wait, what" moments.
I used the given hint "Use the identity $k \cdot \overline{k} = |k|^2$" with the given equations as follows:
$$(|2z - w| = 25)^2$$$$4z^2 - 4wz + w^2 = 625$$
Help would be greatly appreciated.
Thanks

A: That hint is wrong as written. If you square both sides of that equation then you get $$625 = |2z-w|^2 = (2z-w)(2\bar z-\bar w) = 4|z|^2+|w|^2 - 2(z\bar w+\bar zw) $$
Similarly squaring both sides of $|z+2w| = 5$ gives $$ 25 = (z+2w)(\bar z+2\bar w) = |z|^2+4|w|^2 +2(z\bar w+\bar z w)$$ and the third equation gives $$ 4 \ =(z+w)(\bar z+\bar w) = |z|^2+|w|^2+(z\bar w+\bar z w).$$
Now can you think of a way to combine these three equations to get $|z|$?
(Further hint: don't be thrown off by all the variables. As lulu mentioned in the comments, everything is in terms of three quantities: $|z|^2$, $|w|^2$ and $(z\bar w+\bar z w) $ which you can just rename $a$, $b$, and $c$ and solve for $a.$)


text:
Q: Receive API body POST by Python I have a problem with API POST, can you help me?
import requests
import json

url = 'http://xxx/api/getTotalPrice'

param = dict(itineraryType=1,
             departureAirportCode='HAN',
             destinationAirportCode='DLI',
             departureDate='2020-12-30T14:00',
             returnDate='2020-12-30T09:00',
             adult=1,
             children=1,
             infant=1
             )

resp = requests.post(url=url, params=param)
u_data = resp.json()
print(u_data)

I want to receive data from API POST. This is body API and this made error.
Here, this is error
C:\Users\Admin\PycharmProjects\untitled\venv\Scripts\python.exe C:/Users/Admin/PycharmProjects/untitled/venv/test.py
Traceback (most recent call last):
  File "C:\Users\Admin\PycharmProjects\untitled\venv\test.py", line 17, in <module>
    u_data = resp.json()
  File "C:\Users\Admin\PycharmProjects\untitled\venv\lib\site-packages\requests\models.py", line 900, in json
    return complexjson.loads(self.text, **kwargs)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Process finished with exit code 1

I can get data from POST API without body, but with body, I cannot.
Can you help to fix code?
Many thanks!
P/S:
Here value which I want to get
{
    "departureFlight": {
        "totalPrice": 1896000.0,
        "airlineCode": "VN"
    },
    "returnFlight": {
        "totalPrice": 3263800.0,
        "airlineCode": "VJ"
    }
}

A: OK, I have an answer.
data = {'itineraryType':1,'departureAirportCode':'HAN','destinationAirportCode':'DLI','departureDate':'2020-12-30T15:00','returnDate':'2020-12-30T09:00','adult':1,'children':1,'infant':1}
headers={'Content-type':'application/json', 'Accept':'application/json'}
resp = requests.post(url=url, json=data, headers=headers)
u_data = resp.json()
print(u_data)

change dict(...) to {...} and set headers.


text:
Q: kotlin / java sharedPreferences meaning in android studio What exactly does the sharedPreferences built in function mean in Kotlin / android studio? I've tried reading the documentation from the official android studio docs and would like a simple understanding on how I can use to share the data.

A: SharedPreferences in Kotlin/Java can be used to store data values of type (String, Int, Long, Float, Boolean etc) in the system's memory, so that even after the application terminates so that you can retrieve it later on.
Let's say you want save a String value,
// Declare a shared preference
val sharedPref = getSharedPreferences('MySharedPref', MODE_PRIVATE)

// Initial value
val doorState: String = "Opened"

editDoorState(doorState)
// So whenever the doorState changes, we can save it, so even if the application is
// terminated or killed and restarts again, the last edited value can be retrieved.
// This is commonly used to store a single data value.

// Function to save the doorstate change(of type String)
fun editDoorState(value: String) {
  val sharedPrefEditor = sharedPref.edit()

  // Where the 'doorState' is the SharedPreference Key.
  // To retrieve the value, key must be produced.
  sharedPrefEditor.putString('doorState', value)
  sharedPrefEditor.commit()
}

For more information, check out the official documentation from Android here.