text:
Q: Difference between OnClosing and Form_Closing or OnLoad and Form_Load I have a form in a VSTO addin.  It has two methods, OnClosing and Form_Closing.
What is the difference between these two?
I can't seem to figure it out with any of the docs.
Same goes for OnLoad and Form_Load.
Thanks
EDIT: Comment said that OnClosing is now OnFormClosing.  Well if that is the case what is there an OnFormLoad?  And does it really matter what it's called, considering I have to register the events anyway?
For example I have OnResize as well, are any of these methods being called?  I mean I never registered them anywhere. Like I did the Form_Load and Form_XXX functions.

A: This is the recommended pattern for implementing events.
Each Event Foo has a corresponding protected method OnFoo. The method is responsible for triggering the event. (By default the designer will create event handlers named ctrl_Foo).
This means that most of the time Event registration should be used, but there are some times when it may be required to override the OnFoo implementation. Do this only when it's required.
The fact that the project does both probably indicates a coding mispractice.

A: So this all comes about because you cannot call an event in any class other than the one that defined it.
So, for example, take this class Foo & a derived type FooChild:
public class Foo
{
    public event EventHandler Bar;
}

public class FooChild : Foo
{
    public void SomeMethod(object sender, EventArgs e)
    {
        var bar = this.Bar;
        if (bar != null)
        {
            bar(sender, e);
        }
    }
}

When this is compiled I get the error:

The event 'Foo.Bar' can only appear on the left hand side of += or -= (except when used from within the type 'Foo')

So, how do I raise the event from a child class?
We add a OnBar method to Foo.
public class Foo
{
    public event EventHandler Bar;

    protected virtual void OnBar(object sender, EventArgs e)
    {
        var bar = this.Bar;
        if (bar != null)
        {
            bar(sender, e);
        }
    }
}

Now, in FooChild it appears like I can access the event in two ways:
public class FooChild : Foo
{
    /* FIRST WAY */
    public FooChild()
    {
        this.Bar += BarHandler;
    }

    private void BarHandler(object sender, EventArgs e)
    {
        /* Do Stuff */
    }

    /* SECOND WAY */
    protected override void OnBar(object sender, EventArgs e)
    {
        base.OnBar(sender, e);
        /* Do Stuff */
    }
}

The first way is the way any code can attach to the event on Foo. Its semantics are that "the event has been fired and I'm responding to it".
The second way is slightly different. If it is implemented as above it is effectively the same as the normal handling method. But it can do something more powerful. Its semantics are "some code in the Foo class hierarchy has requested that the event should be fire, but I'll make the final decision if it will be." Here's some code that could do that:
public class FooChild : Foo
{
    protected bool _suppressBarEvent = true;

    protected override void OnBar(object sender, EventArgs e)
    {
        if (!_suppressBarEvent)
        {
            base.OnBar(sender, e);
        }
    }
}

So, in this example we have overridden whether the Bar event will be fired or not. This affects all of the event handlers that have attached.
That is the true purpose of the On### methods.

A: There are different methods which doing different jobs
OnLoad is method which triggers an event
Form_Load is "event handler", method which executes when event was triggered.


text:
Q: Buddhabrot Fractal I am trying to implement buddhabrot fractal. I can't understand one thing: all implementations I inspected pick random points on the image to calculate the path of the particle escaping. Why do they do this? Why not go over all pixels?
What purpose do the random points serve? More points make better pictures so I think going over all pixels makes the best picture - am I wrong here?
From my test data:
Working on 400x400 picture. So 160 000 pixels to iterate if i go all over.
Using random sampling,
Picture only starts to take shape after 1 million points. Good results show up around 1 billion random points which takes hours to compute.

A: Random sampling is better than grid sampling for two main reasons. First because grid sampling will introduce grid-like artifacts in the resulting image. Second is because grid sampling may not give you enough samples for a converged resulting image. If after completing a grid pass, you wanted more samples, you would need to make another pass with a slightly offset grid (so as not to resample the same points) or switch to a finer grid which may end up doing more work than is needed. Random sampling gives very smooth results and you can stop the process as soon as the image has converged or you are satisfied with the results.
I'm the inventor of the technique so you can trust me on this. :-)

A: The same holds for flame fractals: Buddha brot are about finding the "attractors",
so even if you start with a random point, it is assumed to quite quickly converge to these attracting curves. You typically avoid painting the first 10 pixels in the iteration or so anyways, so the starting point is not really relevant, BUT, to avoid doing the same computation twice, random sampling is much better. As mentioned, it eliminates the risk of artefacts.
But the most important feature of random sampling is that it has all levels of precision (in theory, at least). This is VERY important for fractals: they have details on all levels of precision, and hence require input from all levels as well.

A: While I am not 100% aware of what the exact reason would be, I would assume it has more to do with efficiency. If you are going to iterate through every single point multiple times, it's going to waste a lot of processing cycles to get a picture which may not look a whole lot better.  By doing random sampling you can reduce the amount work needed to be done - and given a large enough sample size still get a result that is difficult to "differentiate" from iterating over all the pixels (from a visual point of view).

A: This is possibly some kind of Monte-Carlo method so yes, going over all pixels would produce the perfect result but would be horribly time consuming.
Why don't you just try it out and see what happens?

A: Random sampling is used to get as close as possible to the exact solution, which in cases like this cannot be calculated exactly due to the statistical nature of the problem.
You can 'go over all pixels', but since every pixel is in fact some square region with dimensions dx * dy, you would only use num_x_pixels * num_y_pixels points for your calculation and get very grainy results.
Another way would be to use a very large resolution and scale down the render after the calculation. This would give some kind of 'systematic' render where every pixel of the final render is divided in equal amounts of sub pixels.

A: I realize this is an old post, but wanted to add my thoughts based on a current project.
The problem with tying your samples to pixels, like others said:

*

*Couples your sample grid to your view plane, making it difficult to do projections, zooms, etc

*Not enough fidelity. Random sampling is more efficient as everyone else said, so you need even more samples if you want to sample using a uniform grid

*You're much more likely to see grid artifacts at equivalent sample counts, whereas random sampling tends to just look grainy at low counts
However, I'm working on a GPU-accelerated version of buddhabrot, and ran into a couple issues specific to GPU code with random sampling:

*

*I've had issues with overhead/quality of PRNGs in GPU code where I need to generate thousands of samples in parallel

*Random sampling produces highly scattered traces, and the GPU really, really wants threads in a given block/warp to move together as much as possible. The performance difference for clustered vs scattered traces was extreme in my testing

*Hardware support in modern GPUs for efficient atomicAdd means writes to global memory don't bottleneck GPU buddhabrot nearly as much now

*Grid sampling makes it very easy to do a two-pass render, skipping blocks of sample points based on a low-res pass to find points that don't escape or don't ever touch a pixel in the view plane

Long story short, while the GPU technically has to do more work this way for equivalent quality, it's actually faster in practice AFAICT, and GPUs are so fast that re-rendering is often a matter of seconds/minutes instead of hours (or even milliseconds at lower resolution / quality levels, realtime buddhabrot is very cool)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Git checkout - switching back to HEAD I've been doing my project while at some point I discovered that one thing stopped working. I needed to look up the state of my code when it was working correctly, so I've decided to use git checkout (because I wanted to check-something-out). And so I've done
git checkout SHA

couple times while going back to point from which I can't go to HEAD, the output is following:
git checkout SHA-HEAD

error: Your local changes to the following files would be overwritten by checkout:
    [list of files]
Please, commit your changes or stash them before you can switch branches.
Aborting

I am pretty much sure I have NOT changed anything. The command
git checkout master

gives the same output.
Is there a way to go back to HEAD?
What is the safe way of "jumping over" history commits?

A: Short Answer
git reset --hard
git checkout HEAD

This removes any (undesired) changes and gets you back to the branch HEAD where you came from.

A: You can stash (save the changes in temporary place) then, back to master branch HEAD.
$ git add .
$ git stash
$ git checkout master

Note that some sites have changed the name of the default branch from "master" to "main" so you might have to use git checkout main instead.

Jump Over Commits Back and Forth:

*

*Go to a specific commit-sha.
  $ git checkout <commit-sha>

*If you have uncommitted changes here then, you can checkout to a new branch | Add | Commit | Push the current branch to the remote.
  # checkout a new branch, add, commit, push
  $ git checkout -b <branch-name>
  $ git add .
  $ git commit -m 'Commit message'
  $ git push origin HEAD          # push the current branch to remote

  $ git checkout master           # back to master branch now

*If you have changes in the specific commit and don't want to keep the changes, you can do stash or reset then checkout to master (or, any other branch).
  # stash
  $ git add -A
  $ git stash
  $ git checkout master

  # reset
  $ git reset --hard HEAD
  $ git checkout master

*After checking out a specific commit if you have no uncommitted change(s) then, just back to master or other branch.
  $ git status          # see the changes
  $ git checkout master

  # or, shortcut
  $ git checkout -      # back to the previous state


text:
Q: Keep referer mod_rewrite Please help with the following question.
There is domain1.com, domain2.com, domain3.com. With the help of organized htaccess redirects to domain.com. But in the apache logs for domain.com, I do not see the referer, since when domain1 or domain2 request came.
RewriteEngine on

RewriteBase /

RewriteCond %{HTTP_HOST} ^([^.]+)\.domain\.com?$ [NC]
RewriteRule ^$ http://domain.com/$1 [R=302,L]

RewriteCond %{HTTP_HOST} !^domain\.com$ [NC]
RewriteCond %{HTTP_HOST} !^rss\.domain1\.com$ [NC]
RewriteCond %{HTTP_HOST} !^contacts\.domain2\.com$ [NC]
RewriteRule ^(.*)$ http://domain.com/$1 [R=302,L]

RewriteCond %{HTTP_HOST} ^rss.domain1.com$
RewriteRule ^/?$ "http\:\/\/www\.google\.com" [R=302,L]

RewriteCond %{HTTP_HOST} ^contacts.domain2.com$
RewriteRule ^/?$ "https\:\/\/www\.google\.com" [R=301,L]

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^(.*)$ / [R=302,L]


text:
Q: Better way to select products that are related to ALL of the categories? I am trying to select products that are related to ALL of the categories, that has been "handed" to me.
The products are in the Product table and the relation to the categories are in the ProductCategoryRelation table.
The below code works, but I am not sure it is the fastest way to do it.
The 1,2,3 numbers are the category IDs.
SELECT *
FROM Product
WHERE (
    SELECT Count(*)
    FROM ProductCategoryRelation
    WHERE ProductCategoryRelation.CategoryId IN (1,2,3)
        AND ProductCategoryRelation.ProductId = Product.ProductId
    ) = 3

A: This might work for you, should perform better.
WITH CTE_ProductCount AS
(
    SELECT PC.ProductID
        , COUNT(PC.CategoryID) AS ProductCount
    FROM ProductCategoryRelation PC
    WHERE PC.CategoryID IN (1,2,3)
    GROUP BY PC.ProductID
    HAVING COUNT(PC.CategoryID) = 3
)
SELECT *
FROM Product
    INNER JOIN CTE_ProductCount PC ON PC.ProductID = Product.ProductID;


text:
Q: Does struts loads all action classes configured in struts-config file during server start up? This is my first post on any technical portal...
Kindly any one help me in understanding struts configurations a little deeper...
I have one doubt in struts 1.x ...
Does ActionServlet loads all action classes configured in struts-config.xml during server startup?
Actually, i have a struts application having almost 20 action classes configured in a single struts-config.xml file. Deployable in jboss 5.1.
Server taking a little extra time (around 2 mins) to get started with application deployed.
And iam not sure whether it is because of server taking time to load all classes or some thing else...
Kindly help me.
Also please suggest some good articles to learn struts internals.
Thanks.


text:
Q: OpenGL lighting working on iPhone 4/iPad, not on iPhone 3G I am having trouble with OpenGL 1.1 lighting.  My code works on the iPhone 4 but not the iPhone 3G.  Everything appears unlit (flat colours).  I don't have a 3GS so I can't find out if it works on that one or not.
Here is my lighting setup:
- (void)setupLighting
{
    const GLfloat           lightAmbient[] = {0.2, 0.2, 0.2, 1.0};
    const GLfloat           matAmbient[] = {0.6, 0.6, 0.6, 1.0};
    const GLfloat           matDiffuse[] = {1.0, 1.0, 1.0, 1.0};
    const GLfloat           matSpecular[] = {0.6, 0.6, 0.6, 0.1};
    const GLfloat           lightPosition[] = {0.0, 0.0, 0.0, 0.0};
    const GLfloat           lightShininess = 100.0;
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, matAmbient);
    glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, matDiffuse);
    glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, matSpecular);
    glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, lightShininess);
    glLightfv(GL_LIGHT0, GL_AMBIENT, lightAmbient);
    glLightfv(GL_LIGHT0, GL_POSITION, lightPosition);
    glShadeModel(GL_SMOOTH);
    NSLog(@"Lighting sorted");
}

I supply normal vectors and so on after that, which successfully renders on the newer iPhone... however, I would really like to support all three iPhones.  (It also works on the iPad).

A: Heh, to answer my own question (and provide info for anyone else with the same problem) there was a problem with the light position being (0, 0, 0, 0).  Setting it to (0, 0, -1.0, 0) fixed the problem and didn't disturb the lighting conditions on the other devices.  I still don't quite understand what I've done here, but I'm just glad I can provide compatibility to iPhone 3Gs...


text:
Q: 'IMG_Load' was not declared in this scope SDL 2 I'm trying to make an application with SDL and I would like to add an icon on my window but when I compile I get this error :
error: 'IMG_Load' was not declared in this scope
  SDL_Surface * icon_surface = IMG_Load(icon);
                                            ^

I'am using cmake and make for the compilation, here is the CMakeLists.txt
cmake_minimum_required (VERSION 2.6)

set(PROJECT_NAME "Engine")

project (${PROJECT_NAME})

SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c++0x")

if( CMAKE_SIZEOF_VOID_P EQUAL 8 )

    MESSAGE( "64 bits compiler detected" )
    SET( EX_PLATFORM 64 )
    SET( EX_PLATFORM_NAME "x64" )

    SET( EXECUTABLE_NAME ${PROJECT_NAME}-x64 )

else( CMAKE_SIZEOF_VOID_P EQUAL 8 )

    MESSAGE( "32 bits compiler detected" )
    SET( EX_PLATFORM 32 )
    SET( EX_PLATFORM_NAME "x86" )

    SET( EXECUTABLE_NAME ${PROJECT_NAME}-x86 )

endif( CMAKE_SIZEOF_VOID_P EQUAL 8 )

# The executable file will be generate in the bin/ directory
set(EXECUTABLE_OUTPUT_PATH bin/${CMAKE_BUILD_TYPE})

# All .h files are in the include/ directory
include_directories(
    ../include/
)

# All .cpp files are in the src/ directory
file(
    GLOB_RECURSE
    SOURCE_FILES
    ../src/*
)

add_executable(
    ${EXECUTABLE_NAME}
    ${HEADER_FILES}
    ${SOURCE_FILES}
)

target_link_libraries(
    ${EXECUTABLE_NAME}
    GL
    GLEW
    SDL2
)

and here the main.cpp
#include <stdio.h>
#include <stdlib.h>

#include <GL/glew.h>
#include <SDL2/SDL.h>
#include <glm/glm.hpp>

using namespace glm;
using namespace std;

SDL_Window * CreateWindow(
    const char * title,
    int x,
    int y,
    int w,
    int h,
    Uint32 flags,
    const char * icon
);

SDL_Renderer * CreateRenderer(
    SDL_Window * window,
    Uint32 flags,
    int r,
    int g,
    int b
);

void Init(Uint32 flags);

int main(void)
{

    Init(SDL_INIT_EVERYTHING);

    SDL_Window * window = CreateWindow("Prism", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, /*SDL_WINDOW_FULLSCREEN_DESKTOP*/ SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL, "../../assets/icon.png");

    SDL_Renderer * renderer = CreateRenderer(window, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC, 0, 0, 0);

    bool end = false;
    SDL_Event events;

    while(!end) {
        SDL_WaitEvent(&events);

        if(events.window.event == SDL_WINDOWEVENT_CLOSE)
            end = true;

        SDL_RenderClear(renderer); // On nettoie l'écran

        SDL_RenderPresent(renderer); // Et on effectue le rendu
    }

    SDL_DestroyWindow(window);

    SDL_Quit();

    return(EXIT_SUCCESS);
}

void Init(Uint32 flags){

    if(SDL_Init(flags) < 0){
        printf("Erreur lors de l'initialisation de la SDL : %s\n", SDL_GetError());
        exit(EXIT_FAILURE);
    }
}

SDL_Window * CreateWindow(const char * title, int x, int y, int w, int h, Uint32 flags, const char * icon)
{
    SDL_Window * window = SDL_CreateWindow(title, x, y, w, h, flags);

    if(window == NULL){
        printf("Erreur lors de la création de la fenêtre : %s\n", SDL_GetError());
        exit(EXIT_FAILURE);
    }

    SDL_Surface * icon_surface = IMG_Load(icon);

    if(icon_surface == NULL){
        printf("Erreur lors de la récupération de l'icone : %s\n", SDL_GetError());
        exit(EXIT_FAILURE);
    }

    SDL_SetWindowIcon(window, icon_surface);
    SDL_FreeSurface(icon_surface);

    SDL_ShowCursor(SDL_DISABLE);
    return window;
}

SDL_Renderer * CreateRenderer(SDL_Window * window, Uint32 flags, int r, int g, int b)
{
    SDL_Renderer * renderer = SDL_CreateRenderer(window, -1, flags);

    if(renderer == NULL){
        printf("Erreur lors de la création du renderer : %s\n", SDL_GetError());
        exit(EXIT_FAILURE);
    }

    if(SDL_SetRenderDrawColor(renderer, r, g, b, 255) < 0){
        printf("Erreur lors de la modification de la couleur de fond du renderer : %s\n", SDL_GetError());
        exit(EXIT_FAILURE);
    }

    return renderer;
}

I tried to add SDL_image.h in the include directory but I get an error because the compiler isn't able to find the SDL.h specified in the SDL_image.h...
Thank you for your helps !

A: Hmm... not sure, but maybe try this?
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>

Include both headers, in that order.

A: Aside from include <SDL2/SDL_image.h> as suggested by Justin Time, you would also have to supply the library (SDL2_image) to link against your executable in your cmake file, like so;
target_link_libraries(
    ${EXECUTABLE_NAME}
    GL
    GLEW
    SDL2
    SDL2_image
)

I just tested your code and it runs fine with above modification. Make sure your "../../assets/icon.png" is accessible to your executable. Hope that helps.

A: Ok
So I'm an idiot because I didn't install libsdl2-image-2.0-0... I looked at what you sent me Gestrong and I changed my CMakeList.txt to the following :
cmake_minimum_required (VERSION 2.6)

SET(PROJECT_NAME "Engine")

PROJECT(${PROJECT_NAME})

SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c++0x")

INCLUDE(FindPkgConfig)
INCLUDE(FindOpenGL REQUIRED)
INCLUDE(FindGLEW REQUIRED)
INCLUDE(FindSDL REQUIRED)

PKG_SEARCH_MODULE(SDL2 REQUIRED sdl2)
PKG_SEARCH_MODULE(SDL2IMAGE REQUIRED SDL2_image)

INCLUDE_DIRECTORIES(${OPENGL_INCLUDE_DIR})
INCLUDE_DIRECTORIES(${GLEW_INCLUDE_DIR})

SET(EXECUTABLE_OUTPUT_PATH bin/)

INCLUDE_DIRECTORIES(../include/)
INCLUDE_DIRECTORIES(${SDL2_INCLUDE_DIRS})
INCLUDE_DIRECTORIES(${SDL2IMAGE_INCLUDE_DIRS})

FILE(
    GLOB_RECURSE
    SOURCE_FILES
    ../src/*
)

ADD_EXECUTABLE(
    ${PROJECT_NAME}
    ${SOURCE_FILES}
)

TARGET_LINK_LIBRARIES(
    ${PROJECT_NAME}
    ${SDL2_LIBRARIES}
    ${SDL2IMAGE_LIBRARIES}
    ${OPENGL_LIBRARIES}
    ${GLEW_LIBRARIES}
)

I added #include <SDL2/SDL_image.h> in my code and now it WORKS :) thank you !


text:
Q: Multiple windows, Windows Universal I would like to have a second, (and more) windows for my windows universal app to run on a PC. But to my surprise this does not seem easy. In WPF for example I could add a new item to my project and select a window. In Universal, there is no "Window" in new items. I can declare an object of class windows.ui.xaml.window but I cannot instantiate it (there is no new) or show it. How do I launch another window? Thanks

A: There is a sample available on Microsoft's UWP GitHub repo which covers creating multiple views for your application. I can provide more information or help if you need it

A: Ended up finding something which is quite simple, takes a page by type, creates it and a window with it inside, and returns the page object created:
    async Task<Page> CreatePageWindowAsync(Type p)
    {
        CoreApplicationView newView = CoreApplication.CreateNewView();
        int newViewId = 0;
        Page pg = null;
        await newView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
        {
            Frame frame = new Frame();
            frame.Navigate(p, null);
            Window.Current.Content = frame;
            Window.Current.Activate();
            newViewId = ApplicationView.GetForCurrentView().Id;
            pg = frame.Content as Page;
        });
        bool viewShown = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(newViewId);
        return (pg);
    }


text:
Q: Auto complete when typing in drop down in Excel where list is filled using VBA I am using the below code to insert data into a drop down list from another sheet. This is achieved when the user selects a certain choice from another drop down list.
lstRow = Sheets("Data Sheet").Range("D" & Rows.Count).End(xlUp).Row
Sheets("Data Insert").Range("C3").Select
With Selection.Validation
    .Delete
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
    xlBetween, Formula1:="='Associated British Ports'!$G$7:$G" & lstRow
    .IgnoreBlank = False
    .InCellDropdown = True
    .InputTitle = ""
    .ErrorTitle = "Invalid Selection"
    .InputMessage = ""
    .ErrorMessage = _
    "Please select a user from the list or select New User as the configuration type."
    .ShowInput = True
    .ShowError = True
End With

I want to add in the function that when the user types in a few letters it searches through the list and eliminates anything that doesn't contain that.
I.E. say I have the below in the dropdown:
A Thomas
c Smith
f Graham
t Evans
s davids
B matthews
And the user types in "th"
The remaining values should be
A Thomas
c Smith
B matthews
Even a simplified version where the user must type in the name in the form of A Th.... To return A Thomas would be okay if the above is not doable.
I have seen this http://www.ozgrid.com/Excel/autocomplete-validation.htm and this Excel data validation with suggestions/autocomplete
but i dont think I'm not sure how to integrate this with the above code, or it is even possible!
Could anyone help me out please?
TIA :)

A: Here is my SAYT (Search As You Type) function. My form has a listbox control with a list of users and a textbox control that you can use to search the list.
Private Sub txtSearch_Change()
    Dim x As Integer

    lstUsers.ListIndex = -1
    For x = 0 To lstUsers.ListCount - 1
        lstUsers.ListIndex = x
        If InStr(1, LCase(lstUsers.Text), LCase(txtSearch.Text), vbTextCompare) > 0 _
        Or InStr(1, LCase(lstUsers.List(x, 1)), LCase(txtSearch.Text), vbTextCompare) > 0 _
        Then
            Exit Sub
        End If
    Next x
End Sub

Private Sub txtSearch_KeyPress(ByVal KeyAscii As msforms.ReturnInteger)
    If KeyAscii = 13 Then
        txtSearch.Text = lstUsers.Text
    End If
End Sub

As you type, the txtSearch_Change event fires with every keystroke, and it loops through the listbox values until it finds the first match and selects it. We also check the KeyPress event to see if the user pressed Enter (ASCII 13) to autocomplete the search. Mine is case insensitive (I LCase everything), but you could easily modify it to be case sensitive (or even add a checkbox so the user can select case sensitivity!)


text:
Q: Getting hash instead the actual value from excel in PowerShell I want to get data from a column in excel sheet. In my case it's the 3rd one. I use a for loop in order to scan all the cells and I have the following column :
1,724.87
1,560.00
18,109.61
64.37
4,898.22
1,784.47
43,430.30

When I use the WorkSheet.Cells.Item($x,3).Text function in the loop to get the content of each cell, I get the following :
1,724.87
1,560.00
#######
64.37
4,898.22
1,784.47
#######

The ####### can be seen in the .xls file when I open it in excel. When I expand the width of the column it shows the actual number again. So I assume that it reads it as it is. What can be done in order to get the actual number?

A: It seems that the issue with WorkSheet.Cells.Item($x,3).Text is that .Text will represent anything shown on the screen in the cell. In my case is #######
To show the actual value of the cell ,should be using WorkSheet.Cells.Item($x,3).Value2. More difference between .Value, .Value2 and .Text can be found in this post :
What is the difference between .text, .value, and .value2?


text:
Q: How to evaluate a string as a function with a function, and assign it to a variable? I have an object function1 which takes in another function0, and assign it to a variable:
val <- function1(function0)

I would like to wrap this into a string and then evaluate the assignment:
get(eval(paste0("val <- function1(function0)"))

but it says it cannot find the object. Is there a way to do this in R?

A: eval(parse(text = "val <- function1(function0)"))
get("val")

An example:
function0 <- function () "WhatIf"
function1 <- function (f) f()
eval(parse(text = "val <- function1(function0)"))
get("val")


text:
Q: Two foreach loops with same variable names break the order of elements Here is my code:
foreach($datawallright['adds'] as &$ad){
    $ad['img'] = get_ad_pic_url($this->em->getReference("models\MmAds",$ad['id']),'/crop_');
    $ad['description'] = ucfirst(strip_tags(html_entity_decode(mb_strtolower(str_replace(array("___","---"),"",$ad['description']), "UTF-8"))));
    $ad['titleurl'] = title_url($ad['title']);
}

foreach($datawallright['adds'] as $ad){

    $this->load->view("view_wallpage_add",array("ad"=>$ad,"isuserwall"=>$isuserwall));
}

I have two for loops going through the same array. The variables assigned in this two for loops are the same. The weird thing is when it iterates through the second for loop. The first n-1 element are correct, but in the place of the last element the element that is one before last appeares. I can do it all in one for loop. I can change the name of the variable $ad and then it works fine, but I want to know what happened.

A: What happened is that the first loop iterates by reference, so when the second attempts to assign "the current item" to $ad it actually updates your array contents in addition to updating $ad.
The simplest fix is to add an unset ($ad) immediately after the first foreach so that PHP will not consider the name $ad a reference from that point onward.
The need to do this (or else suffer from hidden updates to the reference later on) is one of the ugliest things that can bite you in PHP; personally I am very religious about appending an unset after iterating by reference, even if that's the last statement in a function.


text:
Q: KVM bridged network like in virtualbox I have a server with 3 NIC's with OpenSUSE 13.2 and KVM installed. I have installed Debian as guest.
My network is 192.168.88.0/24, DHCP server is at 192.168.88.1. Now I want my guest to also get a 192.168.88.x IP-address from the DHCP server. This behaviour is possible with VirtualBox using "Bridged networking".
I found this page about networking in KVM: http://www.linux-kvm.org/page/Networking. User Networking, private virtual bridge and public virtual bridge isn't what I want.
I instead used "Virtual network defualt: NAT". Now my VM is getting an IP, but 192.168.122.x.
How can I give the VM an IP in the same range as the host os, without loosing the IP of the host os?
Thanks!

A: You want the public bridge option. On your OpenSUSE KVM host the IP address moves from the physical NIC to the bridge interface and keeps it accessible on your 192.168.88.0/24 network and your Debian guest virtual NIC is connected through the bridge which also makes it attached to the same local network.
Using the NAT default means your Debian guest is effectively hidden behind the OpenSUSE KVM host and uses a private 192.168.122.0/24 network for any direct communication between each other but when communicating with other hosts on your network is NAT'd to whatever IP the OpenSUSE host has.

A: Some time ago I found out what I was doing wrong. I was creating the network in bridge in YAST, the configuration tool for OpenSUSE. However you should (of course..) create the network bridge in the virt-manager tool:

Inside this window I can configure everything I want. You can also configure the network interfaces themself


text:
Q: Azure fails release when zip file can't be located In my Azure release pipeline I have a task that extracts a zip file. But the zip file isn't always available. I've set my other tasks to continue when the zip extraction fails but the release status states: failed:

A: You can use conditions on a task: https://learn.microsoft.com/en-us/azure/devops/pipelines/process/conditions?view=azure-devops&tabs=yaml
if (Test-Path -path ***.zip) {
    Write-Host "##vso[task.setvariable variable=filesExists;]yes"
}

I'm using and(always(),variables['fileExists']) In a task I check if the zip files exist to set the value.


text:
Q: W8.1 Live SDK 5.6 - LiveAuthClient.InitializeAsync System.NullReferenceException I'm developing a Windows 8.1 App (XAML/C#) with MVVM Light.
I used to keep my LiveId inside the code just for debugging, but now it's time to do the LogIn.
Currently i'm stuck with this piece of code:
this.authClient = new LiveAuthClient();
LiveLoginResult loginResult = await this.authClient.InitializeAsync(scopes);

It keeps giving me the error:

An exception of type 'System.NullReferenceException' occurred in mscorlib.dll but was not handled in user code
Additional information: Object reference not set to an instance of an
  object.

Source Code:
    private static readonly string[] scopes =
            new string[] {
               "wl.signin",
               "wl.basic",
               "wl.offline_access"};

    private LiveAuthClient authClient;
    private LiveConnectClient liveClient;

    public DashboardView()
    {
        this.InitializeComponent();
    }

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);
        this.InitializePage();
    }

    private async void InitializePage()
    {
        this.authClient = new LiveAuthClient();
        LiveLoginResult loginResult = await this.authClient.InitializeAsync(scopes);
        if (loginResult.Status == LiveConnectSessionStatus.Connected)
        {
            if (this.authClient.CanLogout)
            {
                this.btnLogin.Content = "Sign Out";
            }
            else
            {
                this.btnLogin.Visibility = Visibility.Collapsed;
            }

            this.liveClient = new LiveConnectClient(loginResult.Session);
            this.GetMe();
        }
    }

    private async void btnLogin_Click(object sender, RoutedEventArgs e)
    {
        if (this.btnLogin.Content.ToString() == "Sign In")
        {
            LiveLoginResult loginResult = await this.authClient.LoginAsync(scopes);
            if (loginResult.Status == LiveConnectSessionStatus.Connected)
            {
                if (this.authClient.CanLogout)
                {
                    this.btnLogin.Content = "Sign Out";
                }
                else
                {
                    this.btnLogin.Visibility = Visibility.Collapsed;
                }

                this.liveClient = new LiveConnectClient(loginResult.Session);
                this.GetMe();
            }
        }
        else
        {
            this.authClient.Logout();
            this.btnLogin.Content = "Sign In";
        }
    }

    private async void GetMe()
    {
        Task<LiveOperationResult> task = this.liveClient.GetAsync("me");

        var result = await task;
        dynamic profile = result.Result;
    }

I even tried some different scopes and this was my last try.
Thanks in advance.

A: As far as i have noticed that problem occurred in my case when calling LiveAuthClient.LoginAsync through interface and/or class library. In order to solve the problem I have used mediator Messenger class from MVVMLight library to login from application entry project which is associated with the store. To associate app with the store follow this article http://www.codeproject.com/Articles/708863/Developer-Guide-to-Write-Windows-Store-App-usi .
My view models are in separate (portable) library and they reference contracts library which contains interfaces for services, in order to login without getting NullReferenceException create a message class.
This solution is for WP8.1, but as platforms are sharing same SDK, it should work. In sample code I am using Messenger and SimpleIoc from MVVM light.
Message class:
public class OneDriveLoginRequestMessage
{
    public Action CallbackAction { get; set; }
}

Register instance of your OneDriveClient (or however you are calling your wrapper) I am using MVVMLight's SimpleIoc
SimpleIoc.Default.Register(() => new OneDriveClient());

Inside App.xaml.cs file in method RootFrame_FirstNavigated add following code to login:
Messenger.Default.Register<OneDriveLoginRequestMessage>(this, async (msg) =>
{
    await SimpleIoc.Default.GetInstance<OneDriveClient>().Login();
    if (msg != null && msg.CallbackAction != null)
    {
        msg.CallbackAction();
    }
});

And finally to login from view model:
private void NavigateToOneDrivePage()
{
    MessengerInstance.Send(new OneDriveLoginRequestMessage
    {
        CallbackAction = async () =>
        {
            // after login continue here...
            var client = SimpleIoc.Default.GetInstance<OneDriveClient>();
        }
    });
}

I hope that solves your problem.
Best, M


text:
Q: Field injection works but constructor injection returns NullPointerException While looking at an existing Spring application, I stumbled upon a class with field injection, which we all know isn't recommended for various reasons. I have then decided to refactor it to make use of a more appropriate approach: constructor based DI.
Before refactoring
@Component
public class MaintenanceModeInterceptor implements HandlerInterceptor {

    private static final String MAINTENANCE_MODE_VIEW = "common/maintenanceMode";

    @Autowired
    private ApplicationObject applicationObject;

    public MaintenanceModeInterceptor() {
        // Required by Spring
    }
...
}

After refactoring
@Component
public class MaintenanceModeInterceptor implements HandlerInterceptor {

    private static final String MAINTENANCE_MODE_VIEW = "common/maintenanceMode";

    private ApplicationObject applicationObject;

    public MaintenanceModeInterceptor() {
        // Required by Spring
    }

    @Autowired
    public MaintenanceModeInterceptor(ApplicationObject applicationObject) {
        this.applicationObject = applicationObject;
    }
...
}

Maybe it is related to the fact that a default constructor is present. However, if I remove it, I end up having this exception:
Caused by: java.lang.NoSuchMethodError: my.application.web.interceptor.MaintenanceModeInterceptor: method <init>()V not found

So my understanding is that Spring requires a default constructor for interceptors.
Is there any way to achieve construtor based DI in this scenario?
Thank you.

A: I think you should remove the non @Autowired constructor and do perform a clean build on your project.


text:
Q: Prove that there is at least $1$ solution and finitely many solutions.
Fix an integer $n$ such that $n \geq 2$. Consider the system of equations
  $$\begin{cases}
a+b-c=n \\
a^2+b^2-c^2=n
\end{cases}$$
  in three variables $a,b,c\in\mathbb{Z}$.
  Prove that it has at least $1$ solution and finitely many solutions.

For example, for $n = 2$, it seems that the only solutions are $\left(1,1,0\right)$ and $\left(3,3,4\right)$, as found by the following python code:
def find(n, N):
    for a in range(-N, N+1):
        for b in range(-N, N+1):
            c = a + b - n
            if a**2 + b**2 - c**2 == n:
                print a, b, c

find(2, 25)

This question is probably one of the hardest I have attempted yet. I have tried to solve it but couldn't. Is there any way I could get help here?

A: For even $n$,
$$a=2n-1, b=\frac{3n}2, c=\frac{5n}2-1$$
is a solution, while for odd $n$,
$$a=2n, \space b=\frac{3n-1}2, \space c=\frac{5n-1}2$$
is one.
To prove that there are only finitely many solutions for a given $n\ge2$, we observe that
$$b-c=n-a, \space b^2-c^2=n-a^2$$
and hence $n-a|n-a^2$. Since $n-a|n^2-a^2$ it follows that $n-a|n^2-n$. Since $n \ge 2$, we have $n^2-n > 0$ and thus it has only finitely many integer devisors and thus only finitely many $a$ are possible. It remains to be shown that for each such $a$, only finitely many $b,c$ can exist.
$a=n$ is impossible, as that would imply $0|n^2-n$, which is impossible. So we get
$$b+c = \frac{b^2-c^2}{b-c} = \frac{n-a^2}{n-a}$$
Together with $b-c=n-a$ this gives exactly one solution $(b,c)$ in rationals, so at most one for integers, which concludes the proof. $\blacksquare$
These equations for $b-c$ and $b+c$ are also the way I found the special solutions given above. $n-a|n^2-n$ implies looking for divisors of $n^2-n$, where $n$ and $n-1$ obviously stand out. A little experimentation with signs lead to considering $a-n=n$ and $a-n=n-1$, and the equations for $b-c$ and $b+c$ then lead straightforward to the solutions.

A: Let's solve the system in General.
$$\left\{\!\begin{aligned}
&  a+b-c=n  \\
&  a^2+b^2-c^2=n
\end{aligned}\right. $$
Using a replacement... solve one equation. $c= a+b-n$
$$a^2+b^2-a^2-b^2-n^2-2ab+2(a+b)n=n$$
$$2(n-b)a=n(n-2b+1)$$
$$a=\frac{n(n-2b+1)}{2(n-b)}$$
There are $4$ solutions.
$1$ decision.
$$\frac{n}{(n-b)}=t$$
$$b=n\frac{(t-1)}{t}$$
We will decompose on multipliers. $n=kt$
$$b=k(t-1)$$
$2$ decision.
$$\frac{n}{(n-b)}=2t$$
$$b=\frac{n(2t-1)}{2t}$$
We will decompose on multipliers. $n=kt$
$$b=\frac{k(2t-1)}{2}$$
$3$ decision.
$$\frac{(n-2b+1)}{(n-b)}=t$$
We will decompose on multipliers. $n-1=k(t-2)$
$$b=n+k$$
$4$ decision.
$$\frac{(n-2b+1)}{(n-b)}=2t$$
We will decompose on multipliers. $n-1=2k(t-1)$
$$b=n+k$$
It can be seen that the solutions are related to the factorization of the number.  Means the number of decisions of course.


text:
Q: Which one is more efficient `Object(value)` or `value || {}` I want to make sure that some certain variable is always an Object (I know that aValue can either be an Object or undefined or null). I have the following options:
var mustBeObject = aValue || {};

or
var mustBeObject = Object(aValue);

Which is the two is more efficient and why?

A: If you want to guarantee that mustBeObject is an object regardless of what aValue is, but if aValue is an object, then you want to use the value of aValue, then you will need a little more code:
var mustBeObject = (aValue && typeof aValue === "object") ? aValue : {};

Or, if you want to make sure that aValue is not even an array or other type of non JS object, you need even further testing to make sure aValue is what you want it to be:
// make sure it's an object and not an array and not a DOM object
function isPlainObject(item) {
    return (
        !!item &&
        typeof item === "object" &&
        Object.prototype.toString.call(item) === "[object Object]" &&
        !item.nodeType
    );
}

var mustBeObject = isPlainObject(aValue) ? aValue : {};

These where written to make sure that mustBeObject is a JS object regardless of what aValue is initially.  If you know from your code that aValue is only just undefined or a valid object, then your first option:
var mustBeObject = aValue || {};

will certainly be faster than any of my above options, but your option only protects against a falsey value in aValue, not other types of non-falsey values that are not JS objects, so since you said that you needed to "make sure that some certain variable is always an Object", I figured you needed more tests than just what you had.

A jsperf test shows that the OR version is faster. Thanks to @Wander Nauta


text:
Q: React, CSS - Remove White Background at the end of the website in App.css I am relatively new to react and css. I am writing a react app. The code in my App.css is
.App {
    background-color: #f0f0f0;
    height: 100vh;
}

I hope that the #f0f0f0 background colour will cover my whole page. However, I can always scroll down the website a bit, and the scrolled down part has a white background.
But if I remove the height: 100vh part, the #f0f0f0 background will only cover until the end of the last  closing tag, and the rest white background is still there.
How do I get rid of the white background at the end of my page?
Thanks in advance!

A: Add this to your css file:
body {
  background-color: #f0f0f0
}

This will color the entire background of the page.


text:
Q: At login, brightness goes to minimum, fastly goes back to maximum and didn't change anymore I updated my ubuntu to 15:04 , but after que I can no longer reduce brightness. Even when I try with FN keys, the indicator varies, but the brightness doesn't change.
I've tried many ways to change the brightness, but nothing works. Seems like the video drivers doesn't response to command.
It may be helpful:
~$ ls /sys/class/backlight/
intel_backlight

20-intel.conf:
Section "Device"
    Identifier  "card0"
    Driver      "intel"
    Option      "Backlight"  "intel_backlight"
    BusID       "PCI:0:2:0"
EndSection

About my laptop:
~$ lspci -k | grep -EA2 'VGA|3D'

00:02.0 VGA compatible controller: Intel Corporation 3rd Gen Core
processor Graphics Controller (rev 09)
Subsystem: Holco Enterprise Co, Ltd/Shuttle Computer Device 2032
Kernel driver in use: i915

Graphics: Intel® Ivybridge Mobile
Model: Positivo Unique S1991i

A: Run in terminal
sudo -H gedit /usr/share/X11/xorg.conf.d/20-intel.conf

The editor will open. Post there this text
Section "Device"
        Identifier  "card0"
        Driver      "intel"
        Option      "Backlight"  "intel_backlight"
        BusID       "PCI:0:2:0"
EndSection

Save the file and reboot.


text:
Q: Command on Linux to tell is displayport over USB-C is supported I am running Linux and kernel 5.3 which has apparently had the DP Altmode supported for some time, but cannot get a monitor to work from an adapter cable.
Question:  what is a shell command that will tell me If I can expect the hardware and software to support DP Altmode over USB-C on this machine?


text:
Q: How can I monitor a router with a intern ssl certificate in Nagios? This ist my current setup:
Host config:
define host{

use     generic-host        ; Inherit default values from a template

host_name       A+A         ; The name we're giving to this host

alias       A+A Objektausstattung Router    ; A longer name associated with the host

address         https://87.139.203.190:444  ; IP address of the host

hostgroups      Router      ; Host groups this host is associated with

}

Service config:
define service{

use     generic-service     ; Inherit default values from a template

host_name       A+A

service_description HTTP

check_command   check_http

}

I´ll get this error from Nagios:

check_icmp: Failed to resolve https://87.139.203.190:444

What am I doing wrong here ?

A: Nagios tries to resolve to ip-address and port. Try ip-address only.
address         https://87.139.203.190  ; IP address of the host

A: Your host definition should only specify an IP address for the 'address'.  The URL is not an attribute of the host, but of the HTTP check your want to perform.
The Service definition specifies the check_command, which is in turn defined in the checkcommands.cfg file.  This will specify exactly what command is to be run, possibly using additional parameters passed.
You will probably want to pass the port number as a parameter, and that you are to use HTTPS.  How to do this will depend on your settings.  For example, you could use this in your checkcommands.cfg:
define command{
    command_name    check_https
    command_line    $USER1$/check_http -t 12 -H $HOSTADDRESS$ -f ok --ssl=1 -u "$ARG1$" -p "$ARG2$" -w $ARG3$ -c $ARG4$
    }

Then you could configure your service with a checkcommand thus:
check_command check_https!/!444!1!5

This would check for the url http://87.139.203.190:444/, giving a warning if it takes over 1s and a critical if it takes over 5s to complete.  TLSv1 would be used (else you might get a false positive on web servers with Poodle protection).


text:
Q: Repository method sets LiveData value inside Asynchronous Retrofit call When going through the official guide for the Android Architecture Components, in the section that explains the repository layer with a Retrofit request there is a piece of code I cannot seem to fully understand:
public class UserRepository {
    private Webservice webservice;
    // ...
    public LiveData<User> getUser(int userId) {
        // This is not an optimal implementation, we'll fix it below
        final MutableLiveData<User> data = new MutableLiveData<>();
        webservice.getUser(userId).enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                // error case is left out for brevity
                data.setValue(response.body());
            }
        });
        return data;
    }
}

At this stage we are initializing our LiveData object:
final MutableLiveData<User> data = new MutableLiveData<>();

Then in the retrofit asynchronous call, we set the value for that variable.
As this is an asynchronous call, wouldn't that method just return the data initialized but never with the value set?

A: You are correct that the LiveData instance will likely be returned from the method you show before the asynchronous network request completes.
This would be a problem if enqueuing a network request was not sufficient to prevent it from being eligible for garbage collection. Since this is not the case, the network request will continue to execute after you exit your method. Once the request completes, the value will be "fed into" the LiveData instance that you returned (this is what the call to setValue does), and observers of that instance will then be notified.

A: AFAIK, you will create a method in the ViewModel class, which will return the method you mentioned above from the repository, something like LiveData<User>getUser(). And because the Object returned from this function is wrapped in a LiveData you will be able to observe the changes in your Activity/Fragment:
 MyViewModel model = ViewModelProviders.of(this).get(MyViewModel.class);
    model.getUsers().observe(this, users -> {
        // update UI
    });

EDIT:
Obviously the answer by @stkent is much more precise and gives a clear reason why the code works.


text:
Q: Keyword struct before constructor name I was amazed when I saw that this code success compiled with MS Visual C++.
struct foo {
    struct foo(int i): value(i) {}
    int value;
};

What means keyword struct in such strange context?

A: In most contexts, you can use the elaborated type specifier struct foo, or equivalently class foo, instead of just the class name foo. This can be useful to resolve ambiguities:
struct foo {};  // Declares a type
foo foo;        // Declares a variable with the same name

foo bar;        // Error: "foo" refers to the variable
struct foo bar; // OK: "foo" explicitly refers to the class type

However, you can't use this form when declaring a constructor, so your compiler is wrong to accept that code. The specification for a constructor declaration (in C++11 12.1/1) only allows the class name itself, not an elaborated type specifier.
In general, you shouldn't be surprised when Visual C++ compiles all kinds of wonky code. It's notorious for its non-standard extensions to the language.


text:
Q: How to format the date and time into UTC format? I'm working in nodejs.
I have the input has date and time "1/6/2022, 2:49:22 AM".
need to convert the date and time to UTC format "2022-01-05T13:04:22.137Z".
please help me with the solution.
code:
let date =new Date().toLocaleString("en-US", { timeZone: "Pacific/Chatham" });
console.log(date);
how to convert this date and time "1/6/2022, 2:49:22 AM" into UTC format "2022-01-05T13:04:22.137Z".
kindly help me with the solution.

A: In javascript
var isoDateString = new Date().toISOString();
console.log(isoDateString);

The toUTCString() method returns a date object as a string, according to UTC.
Tip: The Universal Coordinated Time (UTC) is the time set by the World Time Standard.
Note: UTC time is the same as GMT time.
Source


text:
Q: Cannot save data --- Swift, IOS, Core data --- Thread 1: signal SIGABRT output:

2018-05-08 10:43:35.852689-0400 PatientRecord[37013:6040121] [error]
  error:  Failed to load model named PatientRecord CoreData: error:
  Failed to load model named PatientRecord 2018-05-08
  10:43:35.864686-0400 PatientRecord[37013:6040121] *** Terminating app
  due to uncaught exception 'NSInvalidArgumentException', reason:
  '+entityForName: nil is not a legal NSManagedObjectContext parameter
  searching for entity name 'Patient''

My breakpoints indicate that it crashes on: let entity = NSEntityDescription...
import UIKit
import CoreData

class CoreDataHandler: NSObject {

private class func getContext() -> NSManagedObjectContext{

    let appDelegate = UIApplication.shared.delegate as! AppDelegate

    return appDelegate.persistentContainer.viewContext

}

class func saveObject(onset: String, name: String, headache: String) -> Bool {

    let context = getContext()
    let entity = NSEntityDescription.entity(forEntityName: "Patient", in: context)
    let manageObject = NSManagedObject(entity: entity!, insertInto: context)

    manageObject.setValue(onset, forKey: "onset")
    manageObject.setValue(name, forKey: "name")
    manageObject.setValue(headache, forKey: "headache")

    do{
        try context.save()
        return true
    }catch{
        return false
    }
}

class func fetchObject() -> [Patient]? {
    let context = getContext()
    var patient:[Patient]? = nil
    do{
        patient = try context.fetch(Patient.fetchRequest())
        return patient
    }catch{
        return patient
    }
}

}

main class
import UIKit
//import CoreData

class AbdominalPainViewController: ViewController {

 var patient:[Patient]? = nil

override func viewDidLoad() {
    super.viewDidLoad()

    CoreDataHandler.saveObject(onset: "OnsetLabeltext", name: "PatientNLabelext", headache: "woo")

        patient = CoreDataHandler.fetchObject()

        for i in patient! {
            print(i.name!)
        }

}
}

Not sure what im doing wrong, this exact code works in a different project, with the same entity name. Thank you for your help :)
EDIT:

A: Pls try to prefix the class name in the Class field of the model entity inspector with the name of your module, just like this: "PatientRecord.Patient"
more info here stated

To configure a Swift subclass of NSManagedObject for use by a Core
  Data model entity, open the model entity inspector in Xcode, enter the
  class name into the Class field, and choose "Current Product Module"
  from the Module field drop-down list.


text:
Q: Probability of Picking the Same Password from a $k$ letter alphabet John and Mary both pick passwords at random from a $k$ letter alphabet.  There are up to $n$ letters allowed in the password.  Repetitions are allowed.  What is the probability that they pick the same password?
There are $\sum _{i=1}^{n}k^i$ possible passwords, and $\frac{1}{\sum _{i=1}^{n}k^i}$ probability of picking any particular password.
I'm not sure how to set the problem up from here.  I know that the answer is either John or Mary picks a password and then the probability of the other picking the same password is $\frac{1}{\sum _{i=1}^{n}k^i}$, but I'm not sure why.  I initially thought it would be $(\frac{1}{\sum _{i=1}^{n}k^i})^2$

A: The probability they both choose the first possible password is $\left(\frac{1}{\sum _{i=1}^{n}k^i}\right)^2$, the probability they both choose the second possible password is $\left(\frac{1}{\sum _{i=1}^{n}k^i}\right)^2$, etc.
Since these are mutually exclusive, you can add up the probabilities to find the overall probability they choose the same password. There are $\sum _{i=1}^{n}k^i$ cases with equal probability so this gives $$\left(\sum _{i=1}^{n}k^i\right)\left(\frac{1}{\sum _{i=1}^{n}k^i}\right)^2= \frac{1}{\sum _{i=1}^{n}k^i}.$$

A: Assume John picks his password first. You have computed the probability that Mary picks a specific password as $\frac1{\sum k^j}$. This is also the probability that Mary picks the specific password John happens to have picked.


text:
Q: Implement Click on a Chart I have a layout shown in the image. I want to Implement Click on all the rings separately i.e. 1, 2, 3, 4. How to do this? Please Help!!

A: It should look something like this.
public class CustomProgressBar extends ProgressBar {

    private boolean shouldHandleClick(float x, float y) {
        /*
         return true if click is within the ring

         For this to work you will have to calculate where exactly the ring is,
         then its just a matter of determining whether the click is inside the area or not.
         Might take some doing.
         */

    }

    // thanks to http://stackoverflow.com/questions/17831395/how-can-i-detect-a-click-in-an-ontouch-listener
    @Override
    public boolean onTouch(View v, MotionEvent event) {

        // this will check if its a click and calculate if it's within your area of interest.
        if (isAClick(startX, endX, startY, endY) && !shouldHandleClick(event.getX(),event.getY()))
            return false;

        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            startX = event.getX();
            startY = event.getY();
            break;
        case MotionEvent.ACTION_UP:
            float endX = event.getX();
            float endY = event.getY();
            if (isAClick(startX, endX, startY, endY)) {
                launchFullPhotoActivity(imageUrls);// WE HAVE A CLICK!!
            }
            break;
        default:
            return super.onTouch(v,event);
        }

        return true;
    }

    private boolean isAClick(float startX, float endX, float startY, float endY) {
        float differenceX = Math.abs(startX - endX);
        float differenceY = Math.abs(startY - endY);
        if (differenceX > CLICK_ACTION_THRESHHOLD/* =5 */ || differenceY > CLICK_ACTION_THRESHHOLD) {
            return false;
        }
        return true;
    }
}


text:
Q: Express Sequelize and Passport.js authentication strategy not working I have the following authentication strategy for Express and Sequelize using passport.js:
var LocalStrategy = require('passport-local').Strategy;
var User = require('../../models').User;

module.exports = function (passport) {

    passport.use('register', new LocalStrategy({
            passReqToCallback: true,
            usernameField: 'email'
        }, function (req, email, password, done) {

            //var findOrCreateUser = function () {
            // find a user in Mongo with provided username
            User.findOrCreate({where: {email: email}}).spread(
                function (user, created) {
                    // In case of any error, return using the done method
                    //if (err) {
                    //    console.log('Error in SignUp: ' + err);
                    //    return done(err);
                    //}

                    if (email !== req.param('email-confirm')) {
                        console.log('Registration: Email address do not match');
                        return done(null, false, {message: 'Email addresses do not match'});
                    }

                    // already exists
                    if (user) {
                        console.log('User ' + email + ' is already registered.');
                        return done(null, false, {'message': 'The email ' + email + ' is already registered.'});
                    } else {

                        // if there is no user with that email
                        // create the user
                        var newUser = new User();

                        // set the user's local credentials
                        newUser.email = email;
                        newUser.password = password;

                        // save the user
                        newUser.save(function (err) {
                            if (err) {
                                console.log('Error in Saving user: ' + err);
                                throw err;
                            }
                            console.log('New user registration', newUser);
                            return done(null, newUser);
                        });
                    }
                });
            //};
            //// Delay the execution of findOrCreateUser and execute the method
            //// in the next tick of the event loop
            //process.nextTick(findOrCreateUser);
        })
    );

};

The problem is that when I execute the code it fails to insert into the db with the following error:
Executing (fa4929e4-6b35-40ce-9e02-daf80af507e1): START TRANSACTION;
Executing (fa4929e4-6b35-40ce-9e02-daf80af507e1): SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
Executing (fa4929e4-6b35-40ce-9e02-daf80af507e1): SET autocommit = 1;
Executing (fa4929e4-6b35-40ce-9e02-daf80af507e1): SELECT "id", "email", "password", "lastLogin", "createdAt", "updatedAt", "deletedAt" FROM "Users" AS "User" WHERE ("User"."deletedAt" IS NULL AND "User"."email" = 'user@email.com') LIMIT 1;
Executing (fa4929e4-6b35-40ce-9e02-daf80af507e1): COMMIT;
Unhandled rejection TypeError: Object [object SequelizeInstance:User] has no method 'isModified'
    at sequelize.define.instanceMethods.save (/home/otis/Developer/Project/models/users.js:24:26)
    at Model.create (/home/otis/Developer/Project/node_modules/sequelize/lib/model.js:1735:6)
    at Object.<anonymous> (/home/otis/Developer/Project/node_modules/sequelize/lib/model.js:1837:17)
    at Object.tryCatcher (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/util.js:26:23)
    at Promise._settlePromiseFromHandler (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/promise.js:503:31)
    at Promise._settlePromiseAt (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/promise.js:577:18)
    at Async._drainQueue (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/async.js:128:12)
    at Async._drainQueues (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/async.js:133:10)
    at Async.drainQueues (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/async.js:15:14)
    at process._tickCallback (node.js:415:13)

I know it is during the user creation because if I get it to error with the same email address that all works. But if it starts to create a user it errors out, and the web page stalls.
Update: If I run it with just .find:
Executing (default): SELECT "id", "email", "password", "lastLogin", "createdAt", "updatedAt", "deletedAt" FROM "Users" AS "User" WHERE ("User"."deletedAt" IS NULL AND "User"."email" = 'user@email.com') LIMIT 1;
Unhandled rejection TypeError: expecting an array, a promise or a thenable

    See http://goo.gl/s8MMhc

    at PromiseArray.init [as _init] (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/promise_array.js:42:27)
    at Promise._settlePromiseAt (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/promise.js:575:21)
    at Promise._settlePromises (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/promise.js:693:14)
    at Async._drainQueue (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/async.js:123:16)
    at Async._drainQueues (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/async.js:133:10)
    at Async.drainQueues (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/async.js:15:14)
    at process._tickCallback (node.js:415:13)

Update: removed .spread:
Executing (default): SELECT "id", "email", "password", "lastLogin", "createdAt", "updatedAt", "deletedAt" FROM "Users" AS "User" WHERE ("User"."deletedAt" IS NULL AND "User"."email" = 'user@email.com') LIMIT 1;
express deprecated req.param(name): Use req.params, req.body, or req.query instead middlewares/authentication/registration-strategy.js:21:39
Unhandled rejection TypeError: object is not a function
    at null.<anonymous> (/home/otis/Developer/Project/middlewares/authentication/registration-strategy.js:35:39)
    at tryCatcher (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/util.js:26:23)
    at Promise._settlePromiseFromHandler (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/promise.js:503:31)
    at Promise._settlePromiseAt (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/promise.js:577:18)
    at Promise._settlePromises (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/promise.js:693:14)
    at Async._drainQueue (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/async.js:123:16)
    at Async._drainQueues (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/async.js:133:10)
    at Async.drainQueues (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/async.js:15:14)
    at process._tickCallback (node.js:415:13)

A: The sequelize model is not a constructor (i.e. you can't call new).
http://docs.sequelizejs.com/en/latest/api/model/
Use it as a factory, either by calling build, which returns a new, unsaved instance, or calling create which returns a promise that resolves with a saved instance


text:
Q: Xcode SwiftUI: mathematical equations / crypto profit calculator I want to make me an app, where I can calculate the profit that I make out of Crypto-investments. It's written in Xcode SwiftUI.
I don't know how to code the equations. Here is my mathematical equation:
Amount = 10€, Price on purchase date = 12.000€, Price on sale date = 20.000€

*

*60€ / 12.000€ = 0.005 BTC

*0.005 BTC * 20.000€ = 100€

*100€-60€=40€

How do I transform this into code?
Here is my code:

 //Gewinnrechner
struct GewinnView: View {
    @State private var anlage: String = ""
    @State private var kauf: String = ""
    @State private var verkauf: String = ""
    @State private var ergebnis: String = ""

    var body: some View {
        NavigationView {
            Form {
                Section(header: Text("Anlagebetrag")) {
                    TextField("Anlagebetrag in EUR", text: $anlage)
                        .keyboardType(.decimalPad)
                        }

                Section(header: Text("Kaufkurs in EUR pro Stück")) {
                    TextField("Kaufkurs in EUR", text: $kauf)
                        .keyboardType(.decimalPad)
                        }

                Section(header: Text("Verkaufskurs in EUR pro Stück")) {
                    TextField("Verkaufskurs in EUR", text: $verkauf)
                        .keyboardType(.decimalPad)
                        }

                Section(header: Text("Ergebnis")) {
                    Text("\(anlage + kauf)€")
                    }

            }
            .navigationTitle("Gewinnrechner")
        }
    }
}

There is this test equation in 37: It won't add the "anlage" to the "kauf". It simply writes it down after the first var. E. q.: anlage = 5 and kauf = 7. It wont add it like 5 + 7 = 12. It just makes this: 5 + 7 = 57.

A: It is about changing String to Double here a working way:

struct GewinnView: View {

    @State private var anlage: String = String()
    @State private var kauf: String = String()
    @State private var verkauf: String = String()

    @State private var anlageDouble: Double = Double()
    @State private var kaufDouble: Double = Double()
    @State private var ergebnis: Double = Double()

    var body: some View {

        NavigationView {

            Form {
                Section(header: Text("Anlagebetrag")) { TextField("Anlagebetrag in EUR", text: $anlage) }

                Section(header: Text("Kaufkurs in EUR pro Stück")) { TextField("Kaufkurs in EUR", text: $kauf) }

                Section(header: Text("Verkaufskurs in EUR pro Stück")) { TextField("Verkaufskurs in EUR", text: $verkauf) }

                Section(header: Text("Ergebnis")) { Text(ergebnis.description + "€") }

            }
            .navigationTitle("Gewinnrechner")
        }
        .keyboardType(.decimalPad)
        .onChange(of: anlage) { newValue in

            if let unwrappedDouble: Double = Double(newValue) {

                anlageDouble = unwrappedDouble
                ergebnis = unwrappedDouble + kaufDouble

            }

        }
        .onChange(of: kauf) { newValue in

            if let unwrappedDouble: Double = Double(newValue) {

                kaufDouble = unwrappedDouble
                ergebnis = anlageDouble + unwrappedDouble

            }

        }
    }
}


text:
Q: Can be a Schmidt Decomposition Written in this Form? The Schmidt Decomposition of a state $|\Psi_{AB}\rangle = \sum C_{ij}|i_A\rangle |j_B\rangle$ can be written in this form $|\Psi_{AB}\rangle = \sum \lambda_k|k_A\rangle |k_B\rangle$ where $\lambda_k$ are the Schmidt coefficints. I was reading a manuscrip provided online, written by an expert in this field, and he wrote the Schmidt Decomposition of $|\Psi_{AB}\rangle$ in this way:
$|\Psi_{AB}\rangle = (U_A \otimes U_B ) (|\Psi _A\rangle \otimes |\Psi _B\rangle$) where $U_{A,B}$ are unitary matrices.
How can it be written in this way?


text:
Q: Why this code has findDOMNode warning first time open the dialog? Always got this error when the first time open this dialog:

Warning: findDOMNode is deprecated in StrictMode. findDOMNode was
  passed an instance of Transition which is inside StrictMode. Instead,
  add a ref directly to the element you want to reference

import React, { Component } from "react";
import {Button, Modal, Form} from "react-bootstrap";

class ClusterBar extends Component {
    state = { show: false, clusterName: '', clusterConfigure: '' };

    handleClose = () => this.setState({show: false});
    handleShow = () => this.setState({show: true});
    handleSave = () => {
        this.setState({show: false});
        console.log(this.state.clusterName, this.state.clusterConfigure);
    }

    handleClusterNameChange = (event) => {
        this.setState({clusterName: event.target.value});
    }
    handleClusterConfigureChange = (event) => {
        this.setState({clusterConfigure: event.target.value});
    }

    render() {
        return(
            <>
            <div className="list-group">
                <Button className="list-group-item list-group-item-action">cluster One</Button>
                <Button className="list-group-item list-group-item-action">cluster Two</Button>
                <Button className="list-group-item list-group-item-action">cluster Three</Button>
                <Button className="list-group-item list-group-item-action" onClick={this.handleShow}>+</Button>
            </div>
            <Modal show={this.state.show} onHide={this.handleClose}>
            <Modal.Header closeButton>
                <Modal.Title>Add a cluster</Modal.Title>
            </Modal.Header>
            <Modal.Body>
            <Form>
                <Form.Group controlId="formClusterName">
                    <Form.Label>Cluster Name</Form.Label>
                    <Form.Control type="text" onChange={this.handleClusterNameChange} />
                </Form.Group>

                <Form.Group controlId="formClusterConfigure">
                    <Form.Label>Connnection Configure</Form.Label>
                    <Form.Control as="textarea" rows="3" onChange={this.handleClusterConfigureChange} />
                </Form.Group>
            </Form>
            </Modal.Body>
            <Modal.Footer>
                <Button variant="secondary" onClick={this.handleClose}>
                Cancel
                </Button>
                <Button variant="primary" onClick={this.handleSave}>
                Save
                </Button>
            </Modal.Footer>
            </Modal>
            </>
        )
    }
}

export default ClusterBar


text:
Q: Why did Frank Drake choose these math equations for the Voyager Golden Record? Not sure this belongs in this or some other community, but one of the images on the golden record is a brief snapshot of our decimal system and then a few math examples. Here is the image in question:
http://webodysseum.com/wp-content/uploads/2012/06/Voyager-Golden-Record-Pictures-03.gif
Is there a reason he chose these values to show how we do arithmetic? Does is introduce concepts that other equations would lack? Just curious... also I might get a tattoo of this so I'd like to know more about the background of it first. Thank you!

A: At a guess, $2+3=5$ is the simplest non-confusing sum: $2+2=4$ is confusable with multiplication. $1+2=3$ is confusable with an ordering, as is $1+1=2$. It looks like all of the digits are used in the calculations, too.

A: Part of the answer can be found in this passage from Drake's chapter, "The Foundations of the Voyager Record," in Murmurs of Earth, a popular book edited by Carl Sagan which came out at around the time of the Voyager launchings:

"About this time [1961] Lingua Cosmica, a book on interstellar
  codes, was published by Hans Freudenthal, a Yale mathematician.  It
  contained an ingenious method to construct a language by utilizing
  simple mathematics to establish simple rules and concepts.  For
  example, an equation such as $2+3=5$ and another equation such as
  $4+5=9$ can be used to establish the meaning of the plus sign and the
  equal sign....  Freudenthal showed that by using such
  mathematical equations one could develop quite a sophisticated
  language -- in fact even an ability in the end to express emotion."

The book by Freudenthal that Drakes cites is actually titled Lincos: Design of a Language for Cosmic Intercourse Part I.  ("Lincos" is a contraction of "Lingua Cosmica.")  Freudenthal's book is in the tradition of Russell and Whitehead's Principia Mathematica, with pages and pages of logical impenetralia.  There is no Part II.
Incidentally, there is a fun 1961 essay, Extraterrestrial Linguistics, by Solomon Golomb of polyomino fame.  Here's an excerpt (with an interpolated "[more]" to make sense of one of the sentences):

"[I]t is probably rank terrestrial provincialism to expect others to
  attach the same importance to pi that we do.  Even in our own
  mathematics, such constants as e and log 2 are considered [more]
  important, and the exaggerated role of pi stems largely from the
  Greeks' undue efforts attempting to square the circle....
"My own recommendation is the prime sequence $2, 3, 5, 7, 11, 13, 17, 19, 23,\ldots$, with a long period to prove the non-accidental nature
  of the signal.  It isn't so much that I'm sure these
  Extra-terrestrials would recognize the primes; but if they don't,
  they must be dull fellows, and I would just as soon uot [sic] get
  acquainted."


text:
Q: How to create binary matrix given indices in tensorflow Suppose I have a tf tensor with indices for two samples:
x = [[2,3,5], [5,7,5]]

I would like to create a tensor with a certain shape (samples, 10), where the indices of each sample in x are set to 1 and the rest to 0 like this:
output = [[0, 0, 1, 1, 0, 1, 0, 0, 0, 0],
          [0, 0, 0, 0, 0, 1, 0, 1, 0, 0]]

What is the best way to do this, without creating a lot of intermediary matrices?
The closest I got was using tf.scatter_nd, but I couldn't figure out how to transform x and the updates correctly, except manually adding additional information like this:
>>> tf.cast(tf.scatter_nd([[0,2], [0,3], [0,5], [1,5], [1,7], [1,5]], [1, 1, 1, 1, 1, 1] ,
[2, 10]) > 0, dtype="int64")
<tf.Tensor: id=1191, shape=(2, 10), dtype=int64, numpy=
array([[0, 0, 1, 1, 0, 1, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 1, 0, 1, 0, 0]])>

Also, this approach will aggregate duplicate indices at first, which makes an intermediary boolean matrix necessary. (This I could live with though, the main problem is getting from x to a matrix with shape (samples, 10) where non-existent indices are 0 for each sample.)
Thanks for any help! :)

A: I found a solution (tensorflow 2.2.0):
class BinarizeSequence(tf.keras.layers.Layer):
    """
    Transforms an integer sequence into a binary representation
    with shape (samples, vocab_size).

    Example:
    In: [[2,3,5], [5,7,5]]
    Out: [[0, 0, 1, 1, 0, 1, 0, 0, 0, 0],
          [0, 0, 0, 0, 0, 1, 0, 1, 0, 0]]

    By default the output is returned as SparseTensor.
    Use dense_output=True if you need a dense representation.
    """

    def __init__(self, vocab_size, dense_output=False, **kwargs):
        super(BinarizeSequence, self).__init__(**kwargs)
        self.vocab_size = vocab_size
        self.dense_output = dense_output

    def get_config(self):
        config = super().get_config().copy()
        config.update(
            {"vocab_size": self.vocab_size, "dense_output": self.dense_output}
        )
        return config

    def call(self, x, mask=None):
        # create indices for binarized representation
        x = tf.cast(x, dtype=tf.int32)
        x_1d = tf.reshape(x, [-1])
        sample_dim = tf.repeat(
            tf.range(tf.shape(x)[0], dtype=tf.int32), tf.shape(x)[1]
        )
        indices = tf.transpose(tf.stack([sample_dim, x_1d]))

        # only keep unique indices
        # (see https://stackoverflow.com/a/42245425/979377)
        indices64 = tf.bitcast(indices, type=tf.int64)
        unique64, idx = tf.unique(indices64)
        unique_indices = tf.bitcast(unique64, type=tf.int32)

        # build binarized representation
        updates = tf.ones(tf.shape(unique_indices)[0])
        output_shape = [tf.shape(x)[0], self.vocab_size]
        if self.dense_output:
            output = tf.scatter_nd(unique_indices, updates, output_shape)
        else:
            output = tf.sparse.SparseTensor(
                tf.cast(unique_indices, tf.int64), updates, output_shape
            )
        return output


text:
Q: Extract Package question: Not present \Sectionformat statement is extracted I use the solution shown here (thanks to Mike Renfro!) to extract a synopsis from my LaTeX documents. Sadly I am struggling with the output of the headings. Basically the problem is that the extract packages extracts commands that are not present in the document.
\section{section}

gets
\section[section]{\Sectionformat {section}{1}}

which gives an compile error.
Here is a MWE of the code
\documentclass{article}
\usepackage{tocbasic}
\usepackage{afterpage}
\usepackage{pdflscape}
\usepackage{eso-pic} %exact placement of figures
\usepackage[below]{placeins} %prevents floats of getting over a FloatBarrier
\usepackage{pdftexcmds}
\usepackage[font+=footnotesize]{subcaption}
%%%%%%% This is for extracting synopses %%%%%%%
%% see stackexchange
\usepackage{verbatim}
\let\synopsis\comment \let\endsynopsis\endcomment
% Extract synopsis environments, \section commands, and \tableofcontents
% commands into a separate synopsis.tex file. In that file, a synopsis
% environment will be a simple semantic environment with no extra decoration.
\usepackage[active,generate=synopsis, extract-env={synopsis},
extract-cmd={section,subsection,subsubsection}, %extract on section, subsection and sub subsection level
extract-cmdline={tableofcontents}
]{extract}
\begin{extract}
\newenvironment{synopsis}{}{}
\end{extract}

  \usepackage[hidelinks,pdfa,pdfencoding=auto,pdfusetitle,hypertexnames=false]{hyperref}
%,hypertexnames=false

%%%%%%

\begin{document}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{introduction} \begin{synopsis} Some text \end{synopsis} Main
text

\end{document}

and this is the output
%%
%% This is file, `synopsis.tex',
%% generated with the extract package.
%%
%% Generated on :  2016/01/11,19:26
%% From source  :  mwesynopsis.tex
%% Using options:  active,generate=synopsis,extract-env={synopsis},extract-cmd={section,subsection,subsubsection},extract-cmdline={tableofcontents}
%%
\documentclass{article}
\newenvironment{synopsis}{}{}

\begin{document}

\section[introduction]{\Sectionformat {introduction}{1}}

\begin{synopsis}
Some text
\end{synopsis}

\end{document}

I get an compilation error for
\section[introduction]{\Sectionformat {introduction}{1}}

compiling with XeTeX
! Undefined control sequence.
<argument> \Sectionformat
                          {introduction}{1}
l.14 ...duction]{\Sectionformat {introduction}{1}}

The control sequence at the end of the top line
of your error message was never \def'ed. If you have
misspelled it (e.g., `\hobx'), type `I' and the correct
spelling (e.g., `I\hbox'). Otherwise just continue,
and I'll forget about whatever was undefined.

Any hints how to get rid of this error are warmly welcome

A: \Sectionformat is from the hyperref package. So if you make sure you include it in the synopsis document with the extract* environment, things should work correctly. If you need other packages in the synopsis, add them to the extract* environment as well.
You should also avoid adding text on a line after a synopsis, as that text will be ignored (your original document only had "text", not "main text" in the body).
\documentclass{article}
\usepackage{verbatim}
\let\synopsis\comment \let\endsynopsis\endcomment
\usepackage[active,
generate=synopsis,
extract-env={synopsis},
extract-cmd={section,subsection,subsubsection},
extract-cmdline={tableofcontents}
]{extract}
\usepackage{tocbasic}
\usepackage{afterpage}
\usepackage{pdflscape}
\usepackage{eso-pic}
\usepackage[below]{placeins}
\usepackage{pdftexcmds}
\usepackage[font+=footnotesize]{subcaption}
\begin{extract*}
\usepackage[hidelinks,pdfa,pdfencoding=auto,pdfusetitle,hypertexnames=false]{hyperref}
\end{extract*}
\begin{extract}
\newenvironment{synopsis}{}{}
\end{extract}

\begin{document}
\section{introduction}
\begin{synopsis} Some text \end{synopsis}
Main text
\end{document}


text:
Q: Fake dynamic files in Makefile I want to run pocketlint on all **/*.js files.
.PHONY: lint_js2

LINT_JS = $(wildcard static/js/*.js static/js/**/*.js)
LINT_JS_TARGETS = $(addprefix lint__,$(LINT_JS))

#.PHONY: $(LINT_JS_TARGETS)

lint_js2: $(LINT_JS_TARGETS)
    echo $<

lint__%: %
    pocketlint $<

However, I get this error:
make: *** No rule to make target `lint__static/js/ad_list.js', needed by `lint_js2'.  Stop.

*

*Why lint__static/js/ad_list.js is not captured by lint__%?

*If I uncomment second .PHONY, it echoes lint__static/js/ad_list.js, but does not invoke pocketlint static/js/ad_list.js. Why?

If my approach is wrong, what would be the right approach? Since tasks are independent, I would appreciate if make -j50 would do what I am expecting.
Thanks!

A: It's not clear what is intended: does pocketlint write a file named lint__static/js/ad_list.js, or is that really a phony filename?  Anyway...

*

*Reread the second paragraph of How Patterns Match:

When the target pattern does not contain a slash (and it usually does not), directory names in the file names are removed from the file name before it is compared with the target prefix and suffix. After the comparison of the file name to the target pattern, the directory names, along with the slash that ends them, are added on to the prerequisite file names generated from the pattern rule's prerequisite patterns and the file name.

In short, % generally matches just a filename, not a pathname with slashes in it.  So lint__static/js/ad_list.js is not captured because actually it is only ad_list.js that is being matched against lint__%.
If you can arrange it so that the output files from pocketlint are static/js/lint__ad_list.js etc, then this could be made to work:
LINT_JS_TARGETS = $(foreach f,$(LINT_JS),$(dir $f)lint__$(notdir $f))

lint__%: %
    pocketlint $<

Alternatively you can make % match pathnames by having the target pattern be a pathname (containing a slash):
LINT_JS_TARGETS = $(addprefix linted/,$(LINT_JS))

linted/%: %
    pocketlint $<

This time % = static/js/ad_list.js does match the pattern rule.
In either case, you're going to have to have pocketlint produce output (if indeed it produces output) named differently than lint__static/*.

*Implicit rule search is suppressed for phony targets (see Phony Targets, paragraph 5).  So the rule involving pocketlint is never considered when lint__static/js/ad_list.js is phony.
It's not obvious why the result is Nothing to be done for (phony) lint__static/js/ad_list.js rather than No rule to make target lint__static/js/ad_list.js, but I wouldn't lose sleep over it!


text:
Q: Can I integrate with Power bi, or Tableau and create dashboards on them and display the dashboards to my clients? I'm searching if I can use tool like tableau or power bi to create dashboards fast and display it to the clients in my system
The data cannot be shared publicly
I searched and found the Power BI and Tableau embedded
Didn't use it, and want to know more cause I'm comparing between creating the dashboards manually or using this solution
But need to know if someone used it before, what's the limitations, value, and the pricing,
Thanks in advance


text:
Q: Мерцание меню при закрытии Не могу разобраться, почему происходит мерцание элементов меню при закрытии, на долю секунды меню становится видным перед самым закрытием

const burger = document.querySelector('.header__burger-menu');
const burgerMenu = document.querySelector('.header__menu');
const body = document.body;

burger.addEventListener('click', () => {
  burger.classList.toggle('header__burger-menu_active');
  burgerMenu.classList.toggle('header__menu_active');
  body.classList.toggle('lock');
});
body {
  background: #e5e5e5;
}

body.lock {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  overflow: hidden;
}

.ul-reset {
  list-style: none;
}

.btn-reset {
  border: none;
  cursor: pointer;
  background: transparent;
}

.header {
  display: flex;
  align-items: center;
  width: 100%;
  height: 100px;
  background: #fff;
  box-shadow: 0 5px 40px rgba(0, 0, 0, 0.1);
}

.header__burger-menu {
  margin-right: 50px;
  position: relative;
  top: 0;
  display: inline-flex;
  width: 30px;
  height: 23px;
  z-index: 110;
}

.header__burger-menu::before,
.header__burger-menu::after {
  content: '';
  position: absolute;
  left: 0;
  width: 100%;
  height: 3px;
  background: #000;
  transition: .2s ease-in;
}

.header__burger-menu::before {
  top: 0;
}

.header__burger-menu::after {
  bottom: 0;
}

.header__burger-menu .header__burger-menu-line {
  position: absolute;
  top: 10px;
  left: 0;
  width: 100%;
  height: 3px;
  background: #000;
}

.header__menu {
  position: fixed;
  height: 0;
  top: 0;
  left: 0;
  width: 420px;
  opacity: 0;
  background-color: #fbfbfb;
  overflow: auto;
  transition: opacity .2s linear, height .2s linear;
}

.header__menu-list-item:not(:last-child) {
  margin: 0 0 50px;
}

.header__menu_active {
  opacity: 1;
  height: 768px;
  z-index: 100;
  transition: opacity .2s linear, height .2s linear;
}

.header__burger-menu_active .header__burger-menu-line {
  transform: scale(0);
}

.header__burger-menu_active::before {
  transform: rotate(45deg);
  top: 11px;
}

.header__burger-menu_active::after {
  transform: rotate(-45deg);
  bottom: 9px;
}

.header__menu_active .header__menu-list {
  flex-direction: column;
  padding: 50px;
}

  <button class="btn-reset header__burger-menu" aria-label="открыть меню">

      </button>

        О нас

        Проекты

        Этапы

        Отзывы

        Контакты

A: Проблема в этом параметре было overflow: auto; сменил на overflow: hidden;
Добавил @media screen and (max-height: 400px) and (orientation: landscape) под мобильную версию.

const burger = document.querySelector('.header__burger-menu');
const burgerMenu = document.querySelector('.header__menu');
const body = document.body;

burger.addEventListener('click', () => {
  burger.classList.toggle('header__burger-menu_active');
  burgerMenu.classList.toggle('header__menu_active');
  body.classList.toggle('lock');
});
body {
  background: #e5e5e5;
}

body.lock {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  overflow: hidden;
}

.ul-reset {
  list-style: none;
}

.btn-reset {
  border: none;
  cursor: pointer;
  background: transparent;
}

.header {
  display: flex;
  align-items: center;
  width: 100%;
  height: 100px;
  background: #fff;
  box-shadow: 0 5px 40px rgba(0, 0, 0, 0.1);
}

.header__burger-menu {
  margin-right: 50px;
  position: relative;
  top: 0;
  display: inline-flex;
  width: 30px;
  height: 23px;
  z-index: 110;
}

.header__burger-menu::before,
.header__burger-menu::after {
  content: '';
  position: absolute;
  left: 0;
  width: 100%;
  height: 3px;
  background: #000;
  transition: .2s ease-in;
}

.header__burger-menu::before {
  top: 0;
}

.header__burger-menu::after {
  bottom: 0;
}

.header__burger-menu .header__burger-menu-line {
  position: absolute;
  top: 10px;
  left: 0;
  width: 100%;
  height: 3px;
  background: #000;
}

.header__menu {
  position: fixed;
  height: 0;
  top: 0;
  left: 0;
  width: 420px;
  opacity: 0;
  background-color: #fbfbfb;
  overflow: hidden; /* изменено */
  transition: opacity .2s linear, height .2s linear;
}

/* Под мобильные экраны в горизонтальном положении не выше 400px*/
@media screen and (max-height: 400px) and (orientation: landscape) {
  .header__menu {
    overflow: auto;
  }
}

.header__menu-list-item:not(:last-child) {
  margin: 0 0 50px;
}

.header__menu_active {
  opacity: 1;
  height: 768px;
  z-index: 100;
  transition: opacity .2s linear, height .2s linear;
}

.header__burger-menu_active .header__burger-menu-line {
  transform: scale(0);
}

.header__burger-menu_active::before {
  transform: rotate(45deg);
  top: 11px;
}

.header__burger-menu_active::after {
  transform: rotate(-45deg);
  bottom: 9px;
}

.header__menu_active .header__menu-list {
  flex-direction: column;
  padding: 50px;
}

  <button class="btn-reset header__burger-menu" aria-label="открыть меню">

      </button>

        О нас

        Проекты

        Этапы

        Отзывы

        Контакты


text:
Q: How to sign using new keyvault client from azure.security.keyvault I recently started to replace the old Azure KeyVault client from the Microsoft.Azure.KeyVaultnamespace with the newer one in Azure.Security.KeyVault.
This works without any issues when getting secrets and certificates, but I am not sure how to sign anymore
How do I sign using the new keyvault client?

A: Did you check Azure SDK Azure.Security.KeyVault.Keys package on github?
Example code from that source:
SignResult rsaSignDataResult = rsaCryptoClient.SignData(SignatureAlgorithm.RS256, data);
Debug.WriteLine($"Signed data using the algorithm {rsaSignDataResult.Algorithm}, with key {rsaSignDataResult.KeyId}. The resulting signature is {Convert.ToBase64String(rsaSignDataResult.Signature)}");

A: For azure key vault, we need to create a signature from a digest using the specified key.
So, you could refer to the below code to sign some arbitrary data and verify the signatures using the CryptographyClient with both the EC and RSA keys we created.
byte[] digest = null;

using (HashAlgorithm hashAlgo = SHA256.Create())
{
    digest = hashAlgo.ComputeHash(data);
}

SignResult rsaSignResult = rsaCryptoClient.Sign(SignatureAlgorithm.RS256, digest);

If you want to sign certificate you could refer to this article.


text:
Q: Three.js shadows not working properly I was trying to learn about shadows in Three.js and I found this nice example in jsfiddle.
However I am not able to understand why, when I lower the y of light to like 65, that is:
light.position.set( 20, 65, 0 );

the shadow disappears completely.
Meanwhile, everything above 70 is perfectly fine and the shadow is cast. Like always, I am probably missing something obvious, but I really cannot see what can be preventing the light from making that shadow.

A: This is happening because shadows will only be cast by and onto objects inside the frustrum of the light.shadowCamera; in this case, the default light.shadowCameraNear appears to be set to about 50, so the frustrum begins too far from the light source, and when the light's position.y is at 65 the bar isn't included. When the light's position.y is 70, the closest edge of the shadowCamera frustrum moves up to include the bar, and the shadow is cast properly.
You can fix this by setting light.shadowCameraNear to a smaller number. In that fiddle, uncomment the line:
light.shadowCameraNear = 1;

and the shadow will appear no matter how low you move the light.

A: You can try:
light.shadowCameraVisible = true;

To see the position and direction of the light on screen this will help you to understand what is changing.
Hope it helps :)


text:
Q: Fastlane Getting Freeze at Running script '[CP] Embed Pods Frameworks' With azure Pipeline Using Fastlane with azure pipeline Build getting a freeze at Running script '[CP] Embed Pods Frameworks we aren't able to do further action on the build as it gets stuck on given a run script
Error:https://ibb.co/qFbqqfz
Also, raise the same query at https://github.com/fastlane/fastlane/issues/15290

A: Alright after some digging I've found the solution. My CI server was Travis, not Azure though.
With this setup you need to stop using Automatic code signing and select the match provisioning profile in your project settings.
Modify your Fastfile as follows:
before_all do |lane, options|
    ENV["MATCH_KEYCHAIN_NAME"] = "travis-ci"
    ENV["MATCH_KEYCHAIN_PASSWORD"] = ENV["MATCH_KEYCHAIN_NAME"]
end

Insert create_keychain before calling sync_code_signing (a.k.a match).
create_keychain(
    name: ENV["MATCH_KEYCHAIN_NAME"],
    password: ENV["MATCH_KEYCHAIN_PASSWORD"],
    default_keychain: true,
    unlock: true,
    timeout: 3600,
    add_to_search_list: true
)
sync_code_signing(
    readonly: true,
    keychain_name: ENV["MATCH_KEYCHAIN_NAME"],
    keychain_password: ENV["MATCH_KEYCHAIN_PASSWORD"]
)

Finally, remove the keychain with delete_keychain whenever appropriate, e.g. at the end of the lane.
Enjoy :)


text:
Q: Message Board with answers selecting from SQL Server database with proper order I have message board table in SQL Server, and I need to query board entries with replies in specific order. New board entries at the top, but new answers at the bottom of each board entry.
Original data in the table:
ID  AnswerToID
---------------
095 NULL
096 NULL
097 NULL
098 095
099 NULL
100 099
101 099
102 095
103 NULL
104 103

I need this query result:
ID  AnswerToID
-------------------------
103 NULL
104 103  - answer to 103
099 NULL
101 099  - answer to 99
100 099  - answer to 99
097 NULL
096 NULL
095 NULL
102 095  - answer to 95
098 095  - answer to 95

Is there any simple SQL query for this?
The result query will be used by Entity Framework, so maybe there is a simpler way (LINQ) than pure SQL.

A: Your last result entry (096 NULL) seems out of place. Shouln't it be after 097 NULL?
IAC, try something like this:
BoardMessages
    .OrderByDescending(b => b.AnswerToId == null ? b.ID : b.AnswerToId)
    .ThenBy(b => b.AnswerToId == null ? 0 : b.AnswerToId);

A: For a pure SQL solution you could do the following (the ndx column is for display purposes only and can be removed from the production instance)
select * ,
 concat(isnull(AnswerID,ID),'.',(9999-isnull(ID,AnswerID))) as ndx
 from board
 order by concat(isnull(AnswerID,ID),'.',(9999-isnull(ID,AnswerID))) desc

which produces a result as follows
ID      AnswerID        content         ndx
103     (null)          (null)          103.9896
104     103             answer to 103   103.9895
099     (null)          (null)          099.9900
100     099             answer to 99    099.9899
101     099             answer to 99    099.9898
096     (null)          (null)          096.9903
095     (null)          (null)          095.9904
098     095             answer to 95    095.9901
102     095             answer to 95    095.9897


text:
Q: Segfault when testing the intersection with geos in parallel I am using GEOS's C API to manage geometry in a parallel simulator: I need to ensure that the objects stay inside a constrained area.
To that end when my object makes a step, I check whether the line between its previous and current position intersects the border of the environment (environment_manager_->get_border(), which returns a const GEOSPreparedGeometry*).
The code is running in parallel with several OpenMP threads. I initialized GEOS before starting the simulation through
initGEOS_r(notice, log_and_exit);
context_handler_ = GEOS_init_r();

so I have only one handler for all threads.
When running the simulation with several threads the code crashes inside env_intersect with a segfault if I do not wrap GEOSPreparedIntersects_r in a critical section.
bool SpaceManager::env_intersect(const GEOSGeometry * line) const
{
    bool intersect;
    // #pragma omp critical // adding prevents segfault
    // {
        intersect = GEOSPreparedIntersects_r(
            context_handler_, environment_manager_->get_border(), line);
    // }
    return intersect;
}

Could someone point me to what I'm doing wrong? Is it the initialization of GEOS that needs to be done differently to work with OpenMP? Does it come from the fact that environment_manager_ is a unique_ptr? None of those?

Backtrace of segfault gives:
Thread 19 "python" received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x7fffd63da700 (LWP 4374)]
0x00007ffff78816b2 in tcache_get () from /usr/lib/libc.so.6
(gdb) bt
#0  0x00007ffff78816b2 in tcache_get () at /usr/lib/libc.so.6
#1  0x00007ffff5dbf0a9 in operator new(unsigned long) (sz=sz@entry=32)
    at /build/gcc-multilib/src/gcc/libstdc++-v3/libsupc++/new_op.cc:50
#2  0x00007fffc8468273 in geos::geom::LineString::computeEnvelopeInternal() const (this=0x555555f10170) at LineString.cpp:278
#3  0x00007fffc845b95f in geos::geom::Geometry::getEnvelopeInternal() const (this=0x555555f10180) at Geometry.cpp:276
#4  0x00007fffc84612ad in geos::geom::GeometryCollection::computeEnvelopeInternal() const (this=0x555555f15980) at GeometryCollection.cpp:257
#5  0x00007fffc845b95f in geos::geom::Geometry::getEnvelopeInternal() const (this=0x555555f15998) at Geometry.cpp:276
#6  0x00007ffff53cea66 in geos::geom::prep::BasicPreparedGeometry::envelopesIntersect(geos::geom::Geometry const*) const () at /usr/lib/libgeos-3.6.2.so
#7  0x00007ffff53cef82 in geos::geom::prep::PreparedLineString::intersects(geos::geom::Geometry const*) const () at /usr/lib/libgeos-3.6.2.so
#8  0x00007ffff5907380 in GEOSPreparedIntersects_r ()
    at /usr/lib/libgeos_c.so.1
#9  0x00007ffff61d7938 in growth::SpaceManager::env_intersect(GEOSGeom_t const*) const (this=0x555555fb3b78, line=0x7fff7c045c20)

[EDIT] making one const GEOSPreparedGeometry* copy of the environment per OMP thread and accessing only the thread specific copy successfully prevents the segfault in the absence of the critical section. The code becomes:
intersect = GEOSPreparedIntersects_r(
        context_handler_, environment_manager_->get_border(omp_id), line);

where environment_manager_->get_border(omp_id) returns the thread-specific const GEOSPreparedGeometry*. This means that the problem came from the concurrent access to the shared data when I was previously using a single pointer. This seems weird since the function is supposed to be thread safe...

A: Apparently thread-safe implementation is not ready yet (see mailing list exchange).
I solved the problem by using a copy of the global environment geometry on each thread (this obviously also allows fully concurrent tests).


text:
Q: What context to use in Multi activity android app? I'm badly confused and hope to get your help understanding this concept.
I have an app with 3 activities, splash, login and main and the main activity is a multi fragment drawer activity that uses sqlite.
In my fragments i need to use context many places. I used to have a static context in my main activity defined and passed that around but in another questions someone suggested not to use static context to avoid leaks and i took the advice.
I had to change a few things and got things working. I use getapplicationcontext() but now my application now consistently crashes. The crashes are more prominent when the app is put in background.
My question is, which activity's context should i be using to start with? Splash? Login or main?  How would you get access to the context in resume?
Thanks

A: If you are in A fragment you can use getActivity() to access its container activity context.
If you are try to access activity context from an adapter class or dialog, you must pass the activity context to the constructor of the adapter class or dialog
If you are in an activity you can use this or yourActivity.this as per the situation.
For example
1)If you want to access activity context from onResume() or onCreate() you can simply use this.
2)If you are try to access activity context from an inner class like retrofit call then you must use yourActivity.this for activiy context