text:
Q: Cant find SDL.h - Windows, MingW, Cmake and SLD2 (in VSCode with CPP) I want to add SDL2 to a Cmake Project, using C++ in VSCode on Windows, but using Mingw64 from Msys2 (g++).
This is my current CMakeLists.txt:
cmake_minimum_required(VERSION 3.5)

project(TileGameStudio_Runtime LANGUAGES CXX)

set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

set(PROJ_SRC
    ${PROJECT_SOURCE_DIR}/src
)

add_subdirectory(${PROJECT_SOURCE_DIR}/SDL2)
include_directories(${PROJECT_SOURCE_DIR}/SDL2/include)

file(GLOB PROJECT_SOURCES CONFIGURE_DEPENDS
    ${PROJ_SRC}/*.cpp
)

set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${PROJECT_SOURCE_DIR}\\Game")
set(EXECUTABLE_OUTPUT_PATH "${PROJECT_SOURCE_DIR}\\Game")

# add the executable
add_executable(TileGameStudio_Runtime
    ${PROJECT_SOURCES}
)

target_link_libraries(TileGameStudio_Runtime PRIVATE
    SDL2-static
    SDL2main
)

set_target_properties(
    TileGameStudio_Runtime
    PROPERTIES
        OUTPUT_NAME "Game"
        SUFFIX ".exe"
)

This is my current Project Structure (img)
As you can see. i cloned the Repo from https://github.com/libsdl-org/SDL as a subdirectory to my Project. And this, i added via cmake add_subdirectory.
My Main.cpp is simply this:
#include <iostream>
#include <vector>
#include <string>
#include <SDL.h>

#ifdef main
# undef main
#endif /* main */

using namespace std;

int main(int argc, char *argv[]) {
    SDL_Window *win = NULL;
    SDL_Renderer *renderer = NULL;
    int posX = 100, posY = 100, width = 320, height = 240;

    SDL_Init(SDL_INIT_VIDEO);

    win = SDL_CreateWindow("Hello World", posX, posY, width, height, 0);

    renderer = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED);
    //================================================ Draw a Text
    //this opens a font style and sets a size
    TTF_Font* Sans = TTF_OpenFont("Sans.ttf", 24);
    // this is the color in rgb format,
    // maxing out all would give you the color white,
    // and it will be your text's color
    SDL_Color White = {255, 255, 255};

    // as TTF_RenderText_Solid could only be used on
    // SDL_Surface then you have to create the surface first
    SDL_Surface* surfaceMessage = TTF_RenderText_Solid(Sans, "put your text here", White);
    SDL_Texture* Message = SDL_CreateTextureFromSurface(renderer, surfaceMessage);
    SDL_Rect Message_rect; //create a rect
    Message_rect.x = 0;  //controls the rect's x coordinate
    Message_rect.y = 0; // controls the rect's y coordinte
    Message_rect.w = 100; // controls the width of the rect
    Message_rect.h = 100; // controls the height of the rect
    SDL_RenderCopy(renderer, Message, NULL, &Message_rect);
    //================================================ Draw a Text End

    while (1) {
        SDL_Event e;
        if (SDL_PollEvent(&e)) {
            if (e.type == SDL_QUIT) {
                break;
            }
        }
        SDL_RenderClear(renderer);
        SDL_RenderPresent(renderer);
    }

    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(win);

    SDL_Quit();

    return 0;
}

Which should create a Window.. and perhaps draw a text to it.
But, SDL.h can´t be found... so i can´t build the Stuff here..

A: I updated my CMakeLists.txt, cause i reinstalled the whole msys2 (since of a installation problem).
This is the new One:
cmake_minimum_required(VERSION 3.5)

project(TileGameStudio_Runtime LANGUAGES CXX)

set(CMAKE_CXX_FLAGS -v)
set(CMAKE_VERBOSE_MAKEFILE ON)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

set(PROJ_SRC
    ${PROJECT_SOURCE_DIR}/src
)

file(GLOB PROJECT_SOURCES CONFIGURE_DEPENDS
    ${PROJ_SRC}/*.cpp
)

set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${PROJECT_SOURCE_DIR}\\Game")
set(EXECUTABLE_OUTPUT_PATH "${PROJECT_SOURCE_DIR}\\Game")

INCLUDE(FindPkgConfig)
pkg_check_modules(SDL2 REQUIRED sdl2)
pkg_check_modules(SDL2_IMAGE REQUIRED SDL2_image)
pkg_check_modules(SDL2_TTF REQUIRED SDL2_ttf)
pkg_check_modules(SDL2_MIXER REQUIRED SDL2_mixer)

include_directories(
    ${SDL2_INCLUDE_DIRS}
    ${SDL2_IMAGE_INCLUDE_DIRS}
    ${SDL2_TTF_INCLUDE_DIRS}
    ${SDL2_MIXER_INCLUDE_DIRS}
)

link_directories (
    ${SDL2_LIBRARY_DIRS}
    ${SDL2_IMAGE_LIBRARY_DIRS}
    ${SDL2_TTF_LIBRARY_DIRS}
    ${SDL2_MIXER_LIBRARY_DIRS}
)

# add the executable
add_executable(TileGameStudio_Runtime
    ${PROJECT_SOURCES}
)

target_link_libraries (TileGameStudio_Runtime
    ${SDL2_LIBRARIES}
    ${SDL2_IMAGE_LIBRARIES}
    ${SDL2_TTF_LIBRARIES}
    ${SDL2_MIXER_LIBRARIES}
)

set_target_properties(
    TileGameStudio_Runtime
    PROPERTIES
        OUTPUT_NAME "Game"
        SUFFIX ".exe"
)

I installed the whole mingw64 toolchain and SDL2 via msys (under MingW64 Mode of msys2) now.
it still couldn´t find the SDL.h or SDL2/SDL.h
I checked the SDL2_Dir in the Cmake GUI.. and it has the correct Path to: "C:/msys64/mingw64/lib/cmake/SDL2"
EDIT:
I now changed the Main Folder of all my Projects (unreal, unity..etc) from "Game Design" to "Game_Design"..  Working like a Charm now...   Cause.. Spaces are evil..  very evil...
Thanks for your Help Trys :D   <3


text:
Q: React Apollo Testing is not working. Query data is always coming undefined I am getting loading state only and data as undefined in testing. I don't know why I am following everything in the given example. Please help.
Testing file. When i am waiting thsi line toexecute await wait(() => getByTestId('edit-category'));. It is giving response data of query as undefined.
Error: TypeError: Cannot read property 'getCategory' of undefined
Line 34 on editConatinerCategory.tsx => category={data!.getCategory!}
import React from 'react';
import gql from 'graphql-tag';
import { cleanup, wait } from 'react-testing-library';
import { customRender } from '../../../test-utils/customRender';
import { EditCategoryContainer } from './Container';

afterEach(() => {
  cleanup();
  console.error;
});
console.error = jest.fn();

const getCategoryMock = {
  request: {
    query: gql`
      query getCategory($id: Int!) {
        getCategory(id: $id) {
          id
          name
          active
          position
        }
      }
    `,
    variables: {
      id: 1
    }
  },
  result: {
    data: {
      getCategory: {
        id: 1,
        name: 'category',
        active: true,
        position: 1
      }
    }
  }
};

describe('create edit category module', () => {
  test('Rendering correct', async () => {
    const { container, debug, getByTestId } = customRender(<EditCategoryContainer />, [
      getCategoryMock
    ]);
    await wait(() => getByTestId('edit-category'));
    await wait(() => expect(container).toMatchSnapshot());
//Getting this TypeError: Cannot read property 'getCategory' of undefined. Because i am data as undefined from my query response

  });
});

CustomRender.tsx
import React from 'react';
import { render } from 'react-testing-library';
import { MockedProvider, MockedResponse } from 'react-apollo/test-utils';
import { Router, Switch } from 'react-router-dom';
import { createMemoryHistory } from 'history';

export const customRender = (
  node: JSX.Element | null,
  mocks?: MockedResponse[],
  {
    route = '/',
    history = createMemoryHistory({ initialEntries: [route] })
  } = {}
) => {
  return {
    history,
    ...render(
      <MockedProvider mocks={mocks} addTypename={false}>
        <Router history={history}>
          <Switch>{node}</Switch>
        </Router>
      </MockedProvider>
    )
  };
};

EditCategoryContainer.tsx
import React from 'react';
import { withRouter } from 'react-router';
import { Spin } from 'antd';
import {
  AddCategoryComponent,
  GetCategoryComponent
} from '../../../generated/graphql';
import { EditCategory } from './Edit';
import { LoadingComponent } from '../../../components/LoadingComponent';

export const EditCategoryContainer = withRouter(({ history, match }) => {
  const id: number = parseInt(match.params.id, 10);
  return (
    <GetCategoryComponent
      variables={{
        id
      }}
    >
      {({ data, loading: getCategoryLoading }) => {
        console.log(getCategoryLoading, 'getCategoryLoading');
        if (getCategoryLoading) {
          return <LoadingComponent />;
        }
        if (data && !data.getCategory) {
          return
Category not found!
;
        }
        console.log(data);
        return (
          <AddCategoryComponent>
            {(addCategory, { loading, error }) => {
              return (
                <EditCategory
                  data-testid="edit-category"
                  category={data!.getCategory!}
                  loading={loading || getCategoryLoading}
                  onSubmit={values => {
                    addCategory({ variables: values }).then(() => {
                      history.push('/dashboard/categories');
                    });
                  }}
                />
              );
            }}
          </AddCategoryComponent>
        );
      }}
    </GetCategoryComponent>
  );
});

Edit:
I tried @mikaelrs solution which is passed match. But it is not working. I also tried to pass id:1 as fixed. But it is still giving error.
 <GetCategoryComponent
      variables={{
        id:1
      }}
    >
...rest of code.
</GetCategoryComponent>

This is not working. My query without veriable is working fine. Mutation is also working fine. I am having only problem with this. When i have to pass like varible like this.

A: What I do to wait for the loading state of the MockedProvider to pass is to use the wait function from waait. This is actually what Apollo recommends as well.
So in your test you would do:
import React from 'react';
import gql from 'graphql-tag';
import { cleanup } from 'react-testing-library';
import wait from 'waait'

import { customRender } from '../../../test-utils/customRender';
import { EditCategoryContainer } from './Container';

afterEach(() => {
  cleanup();
});

const getCategoryMock = {
  request: {
    query: gql`
      query getCategory($id: Int!) {
        getCategory(id: $id) {
          id
          name
          active
          position
        }
      }
    `,
    variables: {
      id: 1
    }
  },
  result: {
    data: {
      getCategory: {
        id: 1,
        name: 'category',
        active: true,
        position: 1
      }
    }
  }
};

describe('create edit category module', () => {
  test('Rendering correct', async () => {
    const { container, debug } = customRender(<EditCategoryContainer />, [
      getCategoryMock
    ]);

    await wait(0);

    // Your loading state should be false after this, and your component should
    // get it's data from apollo for you to do any assertion you would like to
    // after this point. To see that the component is rendered with data invoke
    // the debug function from react-testing-library after this point

    debug();

    expect(container).toMatchSnapshot()
  });
});

Another solution is to use react-testing-librarys wait function to wait for an element that would be present after the loading state switches to true.
For instance
describe('create edit category module', () => {
  test('Rendering correct', async () => {
    const { container, debug, queryByText } = customRender(<EditCategoryContainer />, [
      getCategoryMock
    ]);

    await wait(()=> queryByText("Some Data"));

    // Your loading state should be false after this, and your component should
    // get it's data from apollo for you to do any assertion you would like to
    // after this point

    expect(container).toMatchSnapshot()
  });
});

A: I faced a similar issue. Here is how I resolved my issue.
First, wait for the query to resolve, as recommended by @mikaelrs and the docs:
await new Promise(resolve => setTimeout(resolve, 0));

After doing that, the loading property was false, but data was still undefined. I discovered that my mock result object was missing a property. Once I added that missing property to the mock result, the data was populated as expected.

redpajama_set_name: RedPajamaStackExchange


text:
Q: opencv image update in gtk for video streaming linux with C programming I am using opencv 1.0.0 and gtk2.0. I want to grab images continuously from a video stream. So far I have successfully been able to grab still image. This is non standard IP camera not VGA/USB /V4L one so need to know explicit method to refresh or update images continuously for video streaming!
GtkWidget *image;

...
...

IplImage*   bayerImage = NULL;
IplImage*   rgbImage = NULL;

...
...
...

cvCvtColor( bayerImage, rgbImage, CV_BayerBG2RGB );
// Usually opencv image is BGR, so we need to change it to RGB

pix = gdk_pixbuf_new_from_data ((guchar*)rgbImage->imageData,
                 GDK_COLORSPACE_RGB,
                 FALSE,
                rgbImage->depth,
                rgbImage->width,
                rgbImage->height,
                 (rgbImage->widthStep),
                  NULL,
                  NULL);
image = gtk_image_new_from_pixbuf (pix);

A: /* (c) 2010 Virgoptrex. Feel Free to use. Leave credits intact */

#include gtk/gtk.h

gint t=0;

     gboolean
     expose_event_callback (GtkWidget *widget, GdkEventExpose *event, gpointer data)
     {

     //g_object_ref_sink (widget->window);

     // gdk_drawable_ref (widget->window);

       gdk_draw_arc (widget->window,
                     widget->style->fg_gc[GTK_WIDGET_STATE (widget)],
                     TRUE,
                     0, 0, widget->allocation.width, widget->allocation.height,
                     0, 64 * 18*t);

      //gdk_drawable_unref (widget->window);

       return TRUE;
     }

static gboolean
time_handler(GtkWidget *widget)
{

 gtk_widget_queue_draw(GTK_WIDGET(widget));

  if (t<20)
  { t++; }
  else if (t >=20)
  { t=0; }

 printf("hello %d\n",t);
   return TRUE;

}

int main( int argc,
          char *argv[] )
{
    GtkWidget *window;
    GtkWidget *aspect_frame;
    GtkWidget *drawing_area;
    gtk_init (&argc, &argv);

    window = gtk_window_new (GTK_WINDOW_TOPLEVEL);

    gtk_window_set_title (GTK_WINDOW (window), "Aspect Frame");
    g_signal_connect (G_OBJECT (window), "destroy",
                  G_CALLBACK (gtk_main_quit), NULL);
    gtk_container_set_border_width (GTK_CONTAINER (window), 10);

    /* Create an aspect_frame and add it to our toplevel window */

    aspect_frame = gtk_aspect_frame_new ("2x1", /* label */
                                         0.5, /* center x */
                                         0.5, /* center y */
                                         2, /* xsize/ysize = 2 */
                                         FALSE /* ignore child's aspect */);

    gtk_container_add (GTK_CONTAINER (window), aspect_frame);
    gtk_widget_show (aspect_frame);

    /* Now add a child widget to the aspect frame */

    drawing_area = gtk_drawing_area_new ();

    /* Ask for a 200x200 window, but the AspectFrame will give us a 200x100
     * window since we are forcing a 2x1 aspect ratio */
    gtk_widget_set_size_request (drawing_area, 200, 200);
    gtk_container_add (GTK_CONTAINER (aspect_frame), drawing_area);
    gtk_widget_show (drawing_area);

     g_signal_connect (G_OBJECT (drawing_area), "expose_event",
                         G_CALLBACK (expose_event_callback), NULL);

    g_timeout_add(100, (GSourceFunc) time_handler, (gpointer)drawing_area);

    gtk_widget_show (window);
    gtk_main ();
    return 0;
}


text:
Q: Discord Api bot not joining the voice channel consistently I have made a bot that joins the voice channel whenever a discord member joins said channel,but sometimes when the member leaves and joins back i get the error that the bot is already connected,so i added the is_connected function to check if the bot is already conected before attempting to join.For some reason this fuction works only half the time,if i join and leave the call mutiple times eventually it just stops joining and it leaves no error code,it just stops.
This is the code:
@client.event
async def on_ready():

  print("Logged in as {0.user}".format(client))

@client.event
async def on_voice_state_update(member, before, after):

  if not before.channel and after.channel and member.id == 450333776485285919 or member.id==232855365082021890 or member.id==282234566066962433 or member.id==256759154524291074:

    channel = client.get_channel(988050675604803648)

    await is_connected()

@client.event
async def  is_connected():
    channel = client.get_channel(988050675604803648)
    voice_client=discord.utils.get(client.voice_clients)

    if(voice_client==None):

      await channel.connect()
    else:
      print("is connected:")

Did i use the function wrong?

A: you created an entire function for is_connected() which isn't entirely necessary. You need to use that event within the on_voice_state_update to check if the bot is already connected to that current voice channel.
@client.event
async def on_voice_state_update(member, before, after):

  if not before.channel and after.channel and member.id == 450333776485285919 or member.id==232855365082021890 or member.id==282234566066962433 or member.id==256759154524291074:

channel = client.get_channel(988050675604803648)

if client.voice.is_connected():
  return print("already connected")

await channel.connect()


text:
Q: Documentation of self-created function after having created an awesome :) function in Matlab, I want to add a documentation to this function, such that when the user enters
doc myfunction

he gets a documentation window of my instructions on how to use this function.
I am not completely sure, whether this feature is available to functions shared on the mathworks file exchange only. Should this be the case, how can I then add a help text such that the user gets my instruction on how to use the function when he enters
help myfunction

?
I tried this.
However, my code (below) does not work.
When I enter
help my_boxplot

the command window prints 3 empty lines...
function y = my_boxplot(x);
% MY_BOXPLOT Plot a boxplot of a datatable with 2 columns.
%       The first column will be assigned to the x-axis, while the second
%       column will be assigned to the y axis.
%       REMARK: The dots displayed in the respective boxes are the means of
%       the corresponding range (whiskers).
%       the MEDIAN

Thank you for your time so far.


text:
Q: Changing bullet color for an unordered list with li:before? I just had one great solution on how to change the color of a bullet. The solution made note of another way.
"If you can't modify your HTML, you can either use list-style-image with a custom-colored dot, or use generated content (i.e. li:before) and color it accordingly (but watch out for list bullet position problems)."
Can someone explain this.
Thanks

A: This means that when you can only change the CSS and not the HTML, you can add contents with pure CSS.
In this example the unicode character \2022 which is   rendered as bullet is added before each list item and is colored red.
The CSS also hides any previous list item "marker" by the list-style-type: none; line above.


text:
Q: Dropdown in ASP.NET MVC 3 I am new to MVC so probably confused .  can somebody please explain me the dropdown in razor.my questions are-

*

*What is the difference in dropdownlist and dropdownlistfor

*how do i Pass ID column of my database  table as value and NAME column as text.

*How do i add "other" to the dropdownlist.

*how do i access the selectedlistitem in code behind.

if possible please explain with an example.

A: *

*DropDownList is generated by code like this:
@Html.DropDownList("PersonId", new SelectList(Model.People, "Id", "Text");
On the other hand, DropDownListFor is generated like this:
@Html.DropDownListFor(m => m.PersonId, new SelectList(Model.People, "Id", "Text")
Problem with DropDownList is that it has a magic string and if you decide to refactor the model later on, there's a high change you'll forget to change the magic string too.

*You could do a LINQ query like this:
var datalist = New SelectList(from x in _peopleService
                              select new SelectListItem { Text = x.Name, Value = x.Id});
If you don't have a service or an ORM between it you need to apply it to your situation, but you can generate a list like that.

*After nr 2, you can
datalist.Add(new SelectListItem() { Text = "Other", Value = "-1"});
Also you have to put that datalist in your viewmodel/model that is passed to the View, so you can generate a selectlist item with that. In this case you could just do:
@Html.DropDownListFor(x => x.PersonId, Model.PersonList);
if you stored the list as PersonList in Model.

*In your Viewmodel (Well, model in mvc) you have a property where the selected item will be stored, look at the 1st question - In this instance the selected item's id will be stored in the PersonId property.


text:
Q: Play a Lottie / Bodymovin animation on scroll on an HTML web page I have been searching multiple forums looking for a solution to this problem- I am trying to code multiple lottie animations to play when each animation enters the browser window on an HTML web page. Does anyone have a working solution?
I have tried a solution using Waypoint.js but unfortunately I could not get any more than one animation to play with that approach. If anyone knows of a way to get Lottie and Waypoint to play nicely together I would appreciate any suggestions.
I am open to any script suggestions even if they require that I load dependencies to make them work. Any help would be greatly appreciated. Also, I should note that I am brand new to Lottie and I am an animator so please leave detailed explanations as I am a beginner with javascript.

A: After creating an animation, use anim.goToAndStop(0) to pause it:
const animData = ... // Let's pretend that you loaded this from a .json file
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.className = 'myAnimation';

// Create the animation
const anim = lottie.loadAnimation({
  renderer: 'canvas',
  loop: true,
  autoplay: false,
  rendererSettings: {
    context: ctx,
    scaleMode: 'noScale',
    clearCanvas: true,
  },
  animationData: animData,
});

// Go to the first frame and pause
anim.goToAndStop(0);

Then, you can use something like OnScreen (https://github.com/silvestreh/onScreen) to detect when the animation is visible:
import OnScreen from 'onscreen';
const os = new OnScreen();

os.on('enter', '.myAnimation', (element, event) => {
    anim.play(); // If animation becomes visible, play it
});

os.on('leave', '.myAnimation', (element, event) => {
    anim.goToAndStop(0); // If animation goes off screen, reset it
});

The above applies to a single animation, but with some minor tweaking, it could be extended to multiple animations.

A: Here a simple solution:
var container = document.getElementById('graph_ani');
      animData = bodymovin.loadAnimation({
          container: container,
          renderer: 'svg',
          autoplay: false,
          loop: false,
          path : 'graph.json'
      });
var animationStart = 0;
$(window).scroll(function(){
    animData.playSegments([animationStart,animationStart+1], true);
    animationStart++;
}

Could use some work to only play when visible and play on scrolldown and reverse on scroll up but works pretty well for a quick snippet.


text:
Q: JBoss HTTP Status 403 - Access is denied - JBWEB000123: Access to the specified resource has been forbidden
JBWEB000065: HTTP Status 403 - Access is denied
JBWEB000309: type JBWEB000067: Status report
JBWEB000068: message Access is denied
JBWEB000069: description JBWEB000123: Access to the specified resource
  has been forbidden.
JBoss Web/7.5.7.Final-redhat-1

in PostMan app I Got this:

        <title>JBoss Web/7.5.7.Final-redhat-1 - JBWEB000064: Error report</title>

JBWEB000065: HTTP Status 403 - Access is denied

            JBWEB000309: type JBWEB000067: Status report

            JBWEB000068: message
            Access is denied

            JBWEB000069: description
            JBWEB000123: Access to the specified resource has been forbidden.

JBoss Web/7.5.7.Final-redhat-1


text:
Q: Azure Cognitive Search - Index and Deletes I setup a demo instance of Azure Search with the web front end app.
One thing I have noticed is that even after I remove a document from Blob storage and the indexer runs again, the deleted document and its contents are still stored in the index.  How can I remove the document's contents from the index without deleting and recreating the index?
Here is the link to my GitHub repository for the template for this environment…  https://github.com/jcbendernh/Azure-Search-Ignite-2018-Demo
Any insight that you can provide is extremely appreciated.

A: In order to get a document to be removed from your index by the indexer when it is no longer in the data source, you need to define a data deletion detection policy in your indexer.
There are two different approaches:
1. By defining a column that defines which fields are supposed to be deleted from your data source (SoftDeleteColumnDeletionDetectionPolicy)
2. Or by using the new native soft delete support in blob storage (NativeBlobSoftDeleteDeletionDetectionPolicy)
Both of these approaches are documented at https://learn.microsoft.com/en-us/azure/search/search-howto-indexing-azure-blob-storage#incremental-indexing-and-deletion-detection
Thanks,
-Luis Cabrera (Azure Search PM)


text:
Q: Why does mysqli_query return an error? $q = "INSERT INTO customers (username, email, pass, first_name, last_name) VALUES ('$u', '$e','"  .  password_hash($p, PASSWORD_BCRYPT) .  "', '$fn', '$ln)";

$r = mysqli_query($dbc, $q);

The structure of customers table.
id int(10) UNSIGNED AUTO_INCREMENT
username    varchar(45)
email index     varchar(80)
first_name  varchar(20)
last_name   varchar(40)
pass        varchar(255)
date_created    timestamp   CURRENT_TIMESTAMP
type    enum('member', 'administer')

Then, mysqli_affected_rows($dbc) returns -1.
Tell me what is a problem.

A: In the last value to insert you have missed a '.
$q = "INSERT INTO customers (username, email, pass, first_name, last_name) VALUES ('$u', '$e','"  .  password_hash($p, PASSWORD_BCRYPT) .  "', '$fn', '$ln)";

Try using this one
$q = "INSERT INTO customers (username, email, pass, first_name, last_name) VALUES ('$u', '$e','"  .  password_hash($p, PASSWORD_BCRYPT) .  "', '$fn', '$ln')";


text:
Q: Dagger and Kotlin. Dagger doesn't generate component classes I'm new with kotlin and Dagger. I have a little problem that I do not how to solve and I don't find a solution.
So this is what I have:
@Module
class AppModule (app: Application) {
    private var application: Application;

    init {
        this.application = app;
    }

    @Provides fun provideApplication(): Application? {
        return application;
    }

    @Provides fun provideResources(): Resources? {
        return application.resources;
    }
}

@Singleton
@Component(modules =  arrayOf(AppModule::class))
interface AppComponent: AppComponentBase {

    public class Initializer {
        private constructor(){}

        companion object {
            fun Init(app: Application): AppComponent? {
                return DaggerAppComponent.builder().appModule(AppModule(app)).build()
            }
        }
    }
}

AppComponentBase: This interface contain all the methods needed by this component.
Now, the problem is that this DaggerAppComponent class is not generated by Dagger if I do this DaggerAppComponent.builder().appModule(AppModule(app)).build() invocation within the companion object.
If a invoke the same line any were by the companion object dagger generate de class without any problem.
An other thing I did look for a solution was create an other different class with the same structure, and importe the DaggerAppComponent as internal object, and I the same result happened.
I don't what to have the initialization of the component outside. So, there any other alternative solution, or what am I doing wrong?.

A: This issue can be fixed with the bellow change which is different from original answer
Following will also work well to fix this issue
with plugins
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'

and dependencies
implementation "com.google.dagger:dagger:$dagger_version"
implementation "com.google.dagger:dagger-android:$dagger_version"
implementation "com.google.dagger:dagger-android-support:$dagger_version"
kapt "com.google.dagger:dagger-compiler:$dagger_version"
kapt "com.google.dagger:dagger-android-processor:$dagger_version"

For reference check out this Gist

A: I don't know when this change happened, but on 1.1.2 of the Kotlin gradle plugin you replace this (in your module's build.gradle):
kapt {
    generateStubs = true
}

with this:
apply plugin: 'kotlin-kapt'

and then make sure to replace dependencies that use annotationProcessor with kapt.
For example, the old way would be to use:
annotationProcessor (
    'some.library:one:1.0'
    ...
    'some.library.n:n.0'
)

and now you use:
kapt (
    'some.library:one:1.0'
    ...
    'some.library.n:n.0'
)

A: UPDATE FOR KOTLIN 1.1.4
generateStubs does not work anymore. Feel free to make a build with the latest Kotlin and it would tell you in the Messages section of Android Studio that it is not necessary anymore. Here's an up-to-date list of dependencies for Dagger2 for Android and Kotlin
apply plugin: 'kotlin-kapt'

//...
// Other Gradle stuff
//...

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:1.1.4-3"

    compile 'com.google.dagger:dagger-android:2.12'
    kapt 'com.google.dagger:dagger-android-processor:2.12'
    compileOnly 'com.google.dagger:dagger:2.12'
    kapt 'com.google.dagger:dagger-compiler:2.12'
}

A: You need to have the kapt processor in build.gradle:
kapt {
    generateStubs = true
}

dependencies {
    ...
    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    compile 'com.google.dagger:dagger:2.0.2'
    kapt 'com.google.dagger:dagger-compiler:2.0.2'
    ...
}

This extension will generate the code for dagger.
Additionally, for newer gradle versions, you can also apply the plugin in your build.gradle:
apply plugin: 'kotlin-kapt'

dependencies {
    ...
    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    compile 'com.google.dagger:dagger:2.0.2'
    kapt 'com.google.dagger:dagger-compiler:2.0.2'
    ...
}

You can check this project for reference

A: Use these dependencies if you are using kotlin as the primary language for android application development
// Dagger dependencies
def dagger_version = "2.44"
implementation "com.google.dagger:dagger:$dagger_version"
kapt "com.google.dagger:dagger-compiler:$dagger_version"
implementation "com.google.dagger:dagger-android:$dagger_version"
implementation "com.google.dagger:dagger-android-support:$dagger_version" // if you use the support libraries
kapt "com.google.dagger:dagger-android-processor:$dagger_version"

A: My case must be some exclusion rule in Dagger's implementation
com.mycompany.native -> Dagger doesn't generate code
com.mycompany.other -> Dagger generates code
I wasted quite some time on this :-( I hope it helps someone else!

A: Sorry, I didn't create a new issue, but decided to answer under similar questions, because maybe someone find it useful!
I faced to ridiculous issue! «Make Project» do not generate dagger files. They are generated while preparing run your App! But I was trying to solve problem for hours and didn't think of simple trying to click Run..)))
So, maybe you faced to the same problem:
Neither «Sync Project with Gradle» nor «Clean» and «Build Project» help generate dagger files.
-> Then just Run your App!
After the first Run App my Dagger started generated files if I click Make Project.

A: If u have problem withe DaggerComponent, You should add
apply plugin: 'kotlin-kapt'

kapt {
    generateStubs = true
}

to build.gradleit will generate kotlin code for dagger 2 otherwise project will only build on Rebuild


text:
Q: uk.co.mmscomputing.device.twain.TwainIOException : Cannot load Twain Source Manager hi every one i was using uk.co.mmscomputing.device lib to scan images on my computer 32 bit but when i switched the project to another computer using 64bit system
i got this error =(
uk.co.mmscomputing.device.twain.TwainIOException: Cannot load Twain Source Manager.
at uk.co.mmscomputing.device.twain.jtwain.getSourceManager(jtwain.java:126)
at uk.co.mmscomputing.device.twain.jtwain.select(jtwain.java:154)
at uk.co.mmscomputing.device.twain.TwainScanner.select(TwainScanner.java:25)
at scan.TwainAppletExample.actionPerformed(TwainAppletExample.java:81)
at java.awt.Button.processActionEvent(Button.java:392)
at java.awt.Button.processEvent(Button.java:360)
at java.awt.Component.dispatchEventImpl(Component.java:4630)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

i searched all the day but with no result. thanks for ur answers

A: The possible cause of the issue is that you don't have 64-bit TWAIN DSM on the machine. Try running your application as 32 bit and test again.

A: Download TWAINDSM.DLL for 64bit and put it in C:/windows/system32


text:
Q: Static method vs object method which is better in such code sample public class VerifyFactory {

    private static final VerifyFactory INSTANCE = new VerifyFactory();

    private VerifyFactory() {
    }

    public static VerifyFactory getInstance() {
        return INSTANCE;
    }

    public Verifiable getVerifyForEntryConference(ServerOperations serverOperations, String logPath,
         language);
    }

    public Verifiable getVerifyForEntryTone(ServerOperations serverOperations, String logPath,

    }

    }

public class VerifyFactory {

    public static Verifiable getVerifyForEntryConference(ServerOperations serverOperations, String logPath,
         language);
    }

    public static Verifiable getVerifyForEntryTone(ServerOperations serverOperations, String logPath,

    }

    }

static method vs object method which is better in such code sample.

A: "static method vs object method which is better" well it depends on the purpose of your usage.
If you want your method to be called up only after an instance of the class (containing that method) has been created, then you should define that method as non-static
And if you want to call your method without creating an instance of the class, then you should define your method as static

A: Object method is much better than static but it depend on method and requirements. i generally used static when it is not possible to create object before method call. and if your class has some instance variable then use object methods. you can't use class instance variables in static method.
object methods are specific to objects but static methods are not.
So if your method is not interfering with instance variables then  you can make them static.
you can check this Ques. also : Difference between Static methods and Instance methods


text:
Q: How to execute a PHP script asynchronously using Ajax on button click? A simple question which I have tried to resolve for a dozen of hours and am still stuck. I am fairly new to PHP/Javascript, so it may seem a bit stupid, but I can't do that on my own. Sorry for my English, it's not my native.
I have a local web server, MySQL database and a form named index.php, which is displayed in my Chrome tab when the server is running. There is a button on the form, which is supposed to insert some info in the database asynchronously, i.e. without page reloading. Google says that in order to do so, I have to use Ajax. So I do the following:
1) I place an Ajax function on the "onClick" event of the button placed on the form;
2) I place the PHP "insertion script" into the "Submit" function, which I place either in index.php, or separate file submit.php, which contains only the "insertion script";
3) And when I click the button, nothing happens. Literally nothing. But, if I place some JavaScript operator into the Ajax function itself (for example, a simple "alert("something")"), it works, and the alert is displayed in the browser.
So, the goal is: use some Ajax function to execute a PHP script which has to be placed somewhere and should be called with Ajax, and to be executed without page reloading. Any help would be greatly appreciated.

A: I am just giving the hint how to do it.Because i don't know which scenario your using this.you can change the code based on your requirement
html
<form id="form-search" method="post" action="<?php echo
  $_SERVER['PHP_SELF'];?>">
    <input type="email" name="email" type="email" id="email" required/>

 <input type="submit" value="submit" id="save" class="submit" />

this ajax method
//make sure you have to load the jquery library here
 $(document).on('click','#save',function(e) {
   e.preventDefault();
  var data = $("#form-search").serialize();
  $.ajax({
         data: data,
         type: "post",
         url: "insert.php",
         success: function(data){
              alert("Data Save: " + data);
         }
});
 });

Insert.php
<?php
    if($_POST['email']!=""))
    {
    //make create connection variable here
    $con = mysqli_connect("localhost","my_user","my_password","my_db");
    $email=$_POST['email'];
    $sql="INSERT INTO tablename (email) VALUES ('$email')";
    $result=mysqli_query($con,$sql);
    if($result){
    echo "You have been successfully inserted.";
    }else{
        echo "not inserted";
    }
   }
    ?>


text:
Q: SVG filter simulate blending mode I'm trying to simulate mix-blend-mode:exclusion blending mode with only SVG filters. The docs say exclusion is a substraction of darker color from lighter, in other words, greater color component value minus smaller color component value.
Is there any way to simulate this logic using SVG filters?
The original image is:

The filtered image would be:

The color to exclude is #3a0339
I'm bringing some code snippets for your convenience:

svg {
  width: 0;
  height: 0;
}
.myFilter {
  filter: url(#myFilter);
}
<svg>
<defs>
<filter id="myFilter" x="0" y="0" width="100%" height="100%">
  <feFlood result="fill" flood-color="#3a0339" flood-opacity="1">
  </feFlood>
<feComposite operator="arithmetic" in="SourceGraphic" in2="fill" k1="0" k2="0.5" k3="0.5" k4="0"/>
 </filter>
</defs>
</svg>

A: The Filter Effects module updated the definition of <feBlend>.  In addition to the values of mode defined in the SVG 1.1 spec, you can now use all of the extra modes defined by the Compositing and Blending specification.
That includes "exclusion", so as long as you are in a browser environment, you can actually do what you want quite easily.  The following works in Firefox and Chrome. I haven't checked any other browsers.

svg {
  width: 0;
  height: 0;
}
.myFilter {
  filter: url(#myFilter);
}
.myFilter2 {
  mix-blend-mode: exclusion;
}
.mix-bg {
  background-color: #3a0339;
  display: inline-block;
}
.mix-bg IMG {
  display: block;
}
<svg>
  <defs>
    <filter id="myFilter" x="0" y="0" width="100%" height="100%"
            color-interpolation-filters="sRGB">
      <feFlood flood-color="#3a0339" result="flood"/>
      <feBlend mode="exclusion" in="flood" in2="SourceGraphic"/>
    </filter>
  </defs>
</svg>


text:
Q: Save a python 3.x dictionary to JSON The solution suggested in this answer allows saving a dict into json. For instance:
import json
with open('data.json', 'wb') as fp:
    json.dump(data, fp)

However, this doesn't work with 3.x. I get the following error:
TypeError: 'str' does not support the buffer interface

According to this answer, the solution is some sort of cast; but I don't manage to do it for a dictionary. What's the right way to save a dict to json using python 3.x?

A: remove the b:
with open('data.json', 'w') as fp:
    json.dump(data, fp)

json.dump
The json module always produces str objects, not bytes objects. Therefore, fp.write() must support str input.


text:
Q: Filtering data issue in React native I am getting response from server, but, I have to display last 5 indexes of data. So, I tried to do with some logic like if indexes is greater than 4, Then do filter. ReturnsData has the response.
But, The data is not persistent always, Some times that data is only 1 or 2 indexes, So, my logic getting wrong and UI showing empty, Even I tried to set else condition in react native, But, nothing working.
    someAction = () => {
          let lastFiveYearsData = [];
          if (ReturnsData.length > 4) {
            lastFiveYearsData = ReturnsData.sort((a, b) => a.year - b.year);
             filteredArray = lastFiveYearsData.slice(Math.max(lastFiveYearsData.length - 5, 1));
          } else {
            this.filteredArray = ReturnsData;
          }

        filteredArray.map((item, index) => {
            //do some work here
            }
}
    console.log ('filteredArray', filteredArray)

filteredArray showing undefined
Even I tried with set state which is not working and showing undefined filteredArray this is global defined.
How to fix this?

A: In your else condition you are assigning the data to the this.filteredArray instead of filteredArray.


text:
Q: "'ViewData' is not declared." when using MVC4 Razor Views in Class Library Looking the various different suggestions and recommendations, like this this I can't get working Razor Views in the Class Library. Non of the System.Web.Mvc.WebViewPage properties are accessable, even if it's configured as a page Base Type. Here is my web.config in the Class Library:
<configuration>
<configSections>
<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">

</sectionGroup>
</configSections>

<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
  <namespaces>
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Optimization"/>
    <add namespace="System.Web.Routing" />
  </namespaces>
</pages>
</system.web.webPages.razor>

<system.web>
<compilation targetFramework="4.0">
  <assemblies>
    <add assembly="System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
  </assemblies>
</compilation>
</system.web>

</configuration>

Any ideas what else could be missing?


text:
Q: How to make the setup.exe from a VS2010 Setup Project ask for Admin Privileges? I have a problem which I guessed would be really simple to solve... but duh.
I'm deploying a .NET application with VS2010. I have a C# Windows Forms project and a Deployment Project. I need the installer to run with admin privileges because the app is installed for all users and an entry to the registry is made.
When starting the setup.exe I'm not prompted for privilege elevation. The installer will just start and suggest to install to Program Files (x86) which is good. After clicking next the installer runs and finished with a success message. Which is basically a lie because it did not successfully install. Instead it puts the apps exe directly to C:\.
How can I make the installer ask for admin privileges. Or do I have to rely on my customer to right click the setup and select "Run as Admin" which is very error prone?
Clarifications about my setup:

*

*In the File System view of the setup project I added (among other things) "Primary Output from project01 (Active)" and "Build Outputs from project01 (Active) to "Application Folder". I also added a shortcut to "Primary Output" into "User's Programs Menu\CompanyName\ProgramName".

*In the Registry View I added an entry to HKEY_CLASSES_ROOT because I need to register an url handler.

I also modified the setup's settings: I set InstallAllUsers to True because it is supposed to do so.
When I build and start the setup.exe by double clicking (or by selecting Install from the project's context menu) I always get the same result: The installer runs without asking for admin privileges, ask for an install location (which I leave at the default C:\Program Files(x86)\Company\ProgramName) and then procedes after clicking Next. As a result, the exe is put directly in C:\ and the shortcut created of course points into Nirvana.
If I run the setup.exe manually as Administrator things work fine. But this cannot seriously be the way to go.
So how can I tell the setup to always run as Admin?

A: I think this is a perfectly valid question, is a real problem, and has an actual explanation.
I recently ran across this problem.  In my case, the cause is that the  AlwaysInstallElevated policy was set on the computer through GPO.  The policy was set to 1 in the per-machine policy and 0 in the per-user policy.  These policies can be manually set to reproduce the effect it has on MSI installers
Using msexec /log install.log /i Deploy.msi, I had a setup log and there were strings in it like this:
MSI (s) (A4:8C) [13:00:42:885]: Ignoring disallowed property TARGETDIR
MSI (s) (A4:8C) [13:00:42:885]: Ignoring disallowed property VSDNETURLMSG
MSI (s) (A4:8C) [13:00:42:885]: Ignoring disallowed property VSDNETMSG

It seems that Visual Studio does not set the SecureCustomProperties in the MSI correctly and post processing of some sort is needed.  I think that moving to WiX may be a better long term solution instead.
A blog post on MSDN is what I found that helped me find the root cause to this problem.

A: I've come across the same issue as you, and have found a good enough solution for it. So it might work for you too. The solution is documented here:
VS2010 Setup Project - Run As Administrator
I will re-iterate the solution briefly here. Basically, you need to manually edit the setup project file (.vdproj) and the following property to TRUE:
"MsiBootstrapper"
{
    ...
    "RequiresElevation" = "11:TRUE"
}

A:
When starting the setup.exe I'm not prompted for privilege elevation.

This is the normal behavior. The boostrapper doesn't need elevation.

Which is basically a lie because it did not successfully install.
  Instead it puts the apps exe directly to C:.

So it did install your application, but in the wrong location. This is not related to elevation. In the File System editor in your setup project where did you add your application files? Did you add them in "Application Folder"?

How can I make the installer ask for admin privileges.

A MSI package installed for all users automatically prompts for elevation when clicking Install button. If it doesn't elevate automatically and installs in a per-machine location (like C:), the installation fails and nothing is copied on the target machine.


text:
Q: Отображение hex C-строки (cout << hex << int(char)) C++ Есть функция, которая выводит  hex C-строку, может есть более правильный способ?
void outHexByCout(const char * cha, int len)
{
    for (size_t i = 0; i < len; ++i)
    {
        cout  << setw(2) << setfill('0') << hex << static_cast<uShort>(cha[i]) << " ";
    }
    cout << endl;
}

Пример вывода:

00 1f ff80 00 00 00 03 ffac 00 15 5b 30 33 2d 32 38 20 32 31 3a 35 37
  3a 31 30 3a 31 30 30 5d 00

Что нужно:

00 1F 80 00 00 00 03 AC 00 15 5B 30 33 2D 32 38 20 32 31 3A 32 31 3A
  30 30 3A 31 30 30 5D 00

Почему приписывает ff?
Например, вот эту строчку получил

ff80 00 00 00

таким образом:
...
writeSESS(128);
...
        void writeSESS(uint32_t ses)const
        {
            // const char* m_buffer
            memcpy(const_cast<char*>(m_buffer + 2, (char*)&ses, sizeof(uint32_t));
        }

A: Ваш компилятор в соответствии с установленными опциями рассматривает тип char аналогично типу signed char, поэтому при приведении типов знаковый бит объекта распространяется на старшие биты результирующего выражения.
Сравните.
#include <iostream>
#include <iomanip>

int main()
{
    char c = '\x80';

    std::cout << std::hex << static_cast<unsigned short>( c )  << std::endl;
    std::cout << std::hex << static_cast<unsigned short>( static_cast<unsigned char>( c ) )  << std::endl;

    return 0;
}

Вывод программы
ff80
80

Вам надо сначала объект типа char преобразовывать в объект типа unsigned char, а лишь затем в тип unsigned short или short


text:
Q: How can I load singleton class properties? I'am making a game, where I want to use Settings singleton class. I've got this sample of code from internet. But have a problem with loading this class. Can't understand how can I load these properties after saving.
class Settings: NSObject, NSCoding {

static let DocumentDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first!
static let ArchiveURL = DocumentDirectory.appendingPathComponent("settings")

static let shared = Settings()

var level: Int = 1
var moves: Int = 0
var music: Bool = true

override init() {
    super.init()
}

required init?(coder aDecoder: NSCoder) {
    level = aDecoder.decodeInteger(forKey: SNames.CurrentLevelSName)
    music = aDecoder.decodeBool(forKey: SNames.MusicSName)
}

func encode(with aCoder: NSCoder) {
    aCoder.encode(level, forKey: SNames.CurrentLevelSName)
    aCoder.encode(music, forKey: SNames.MusicSName)
}

func loadGame() -> Settings? {
    return NSKeyedUnarchiver.unarchiveObject(withFile: Settings.ArchiveURL.path) as? Settings
}

func save() {
    let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(self, toFile: Settings.ArchiveURL.path)
    if !isSuccessfulSave {
        print("Failed to save Settings...")
    }
}

}

A: You have to do a if let to get the settings and then you can access the level, moves and other properties. Heres some code.
if let settings = Settings.shared.loadGame() {
    print(settings.level)
}

This will load the settings and print the level.


text:
Q: Helping identifying a common mode choke Seeking help to identify the following common mode choke. The best guess is it a part from Sumida Corporation.

This part is from a refrigerator.
Any of the following information is greatly appreciated

*

*Datasheet

*Manufacture

*Specification

Based on research it was assumed that following part might have similar specification. Currently not too sure.

*

*SU9HD-40006 from Kemet

Following are results form searches.

*

*Results from google search

*Results from Digikey search

*PZ-UU10.5-Series 0.5~50mH Common Mode Choke Line Filter Common Mode Inductor

*UU Series Common Mode Chokes


text:
Q: Есть ли способ получить данные о текущей подключенной сети Wi-Fi? Я хотел бы получить информацию о текущей сети Wi-Fi через python, но как это можно реализовать?
Я хочу получить данные о имени сети и ее скорости, при чем выполнять это только на Windows

A: Попробуйте
https://alastairs-place.net/projects/netifaces/
Вроде бы появилась версия и для Windows (сам не пробовал, но смотрим на сайт https://pypi.org/project/netifaces/)
Или еще вариант (для Windows) https://pypi.org/project/ifaddr/
Со "скорость интернета" есть нюансы. Для того, что-бы посчитать реальную скорость надо что-то прочесть из интернета, определить объем прочитанного и поделить на время выполнения закачки. В принципе, все программы определяющие скорость так и работают. Поэтому можно это довольно просто написать самому.
Или использовать АPI каких-либо готовых пакетов измерения. И первое, что приходит в голову, конечно, speedtest. У него есть свой открытый API, до которого можно добраться (windows - только 64 битная):
https://www.speedtest.net/apps/cli
https://xn--90aeniddllys.xn--p1ai/pyatiminutka-python-test-skorosti-interneta-v-5-strok/


text:
Q: show loading bar when parent component pass data to and render child component. React.JS I am loading a child component on parent component in React.js. With a click on the button, data will be pass to child component through props, and child component will map through that data and render on screen. I am getting data from localstorage and processing its data structure to child component.
But, the issue is when I click on the button and data is being passed and rendered, the button is shown and after the child component is rendered that shows up. I need the loading spinner when I click on the button and it disappears and shows the actual component.
I have tried methods like loading: false in the state but to no avail.
Thanks for your help
import ShowPatientAppointments from './ShowPatientAppointments.component';

class PatientAppointmnent extends Component {
    state = {
        doctorSlots: null,
        timingSlot: null,
        bookDay: null,
        bookTime: null,
        hasTiming: false,
    }

    getSlots = () => {
        let slot = [];
        let time = [];

        for (let i=0; i< localStorage.length; i++) {
            let key = localStorage.key(i);
            let value = JSON.parse(localStorage[key]);
            slot.push(key);
            time.push(value);

            this.setState({doctorSlots: slot, timingSlot: time});
        }
        console.log(this.state.doctorSlots, this.state.timingSlot);
    }

    render() {
        const { doctorSlots, timingSlot, hasTiming } = this.state;
        return(

                <button onClick={this.getSlots} className='button'>Show me dates</button>

                {doctorSlots === null ?

 : <PatientSelectDay props={doctorSlots} timing={timingSlot} getTimings={this.getTiming} />}

        )
    }
}

export default PatientAppointmnent;

class PatientSelectDay extends Component {
state = {
      options: [...this.props.props].map(obj => {
        return {value: `${obj}`, label: `${obj}`}
      }),
      timingOptions: [...this.props.timing],
      open_id: [],
      part_id: '',
      doctorDay: 'day',
      doctorTiming: 'timing',
  }

  changeSingleHandler = e => {
    this.setState({ part_id: e ? e.value : '' });
  };

  changeHandler = e => {
    let add = this.state.open_id;
    add.push(e.map(x => x.value));
    this.setState({ open_id: e ? add : [] });
  };

  saveState = (option) => {
...save selected options
  }

  render() {
    const {options, timingOptions} = this.state;
    return (

          {options.map((option, index) => {
                const timing = timingOptions[index].map(obj => {
                  return {value: `${obj}`, label: `${obj}`}});
                return(

                  <Select
                    name="open_id"
                    value={option}
                    onChange={this.changeSingleHandler}
                    options={option}
                    className='select'
                  />
                  <Select
                    name="open_id"
                    value={this.state.open_id}
                    onChange={this.changeHandler}
                    options={timing}
                    className='select'
                  />
            <button onClick={() => this.saveState(option)} className='button-left'>Select Days</button>

            )
  })}

          )
    }
  }
export default PatientSelectDay;

A: You need to update your code adding a loading state variable.
class PatientAppointmnent extends Component {
    state = {
        doctorSlots: null,
        timingSlot: null,
        bookDay: null,
        bookTime: null,
        hasTiming: false,
        loading: false
    }

    getSlots = () => {
        let slot = [];
        let time = [];

        this.setState({
          loading: true
        })

        for (let i=0; i< localStorage.length; i++) {
            let key = localStorage.key(i);
            let value = JSON.parse(localStorage[key]);
            slot.push(key);
            time.push(value);

            this.setState({doctorSlots: slot, timingSlot: time, loading: false});
        }
        console.log(this.state.doctorSlots, this.state.timingSlot);
    }

    renderButton = () => {
            const { doctorSlots, timingSlot, loading } = this.state;
        if(doctorSlots === null && timingSlot === null) {
        return

          {loading ?
Loading...
 : <button onClick={this.getSlots} className='button'>Show me dates</button>}

      }
      return null;
    }

    render() {
        const { doctorSlots, timingSlot, hasTiming, loading } = this.state;
        return(

                {this.renderButton()}
                {doctorSlots === null ?

 : <PatientSelectDay props={doctorSlots} timing={timingSlot} getTimings={this.getTiming} />}

        )
    }
}

export default PatientAppointmnent;

class PatientSelectDay extends Component {
state = {
      options: [...this.props.props].map(obj => {
        return {value: `${obj}`, label: `${obj}`}
      }),
      timingOptions: [...this.props.timing],
      open_id: [],
      part_id: '',
      doctorDay: 'day',
      doctorTiming: 'timing',
  }

  changeSingleHandler = e => {
    this.setState({ part_id: e ? e.value : '' });
  };

  changeHandler = e => {
    let add = this.state.open_id;
    add.push(e.map(x => x.value));
    this.setState({ open_id: e ? add : [] });
  };

  saveState = (option) => {
...save selected options
  }

  render() {
    const {options, timingOptions} = this.state;
    return (

          {options.map((option, index) => {
                const timing = timingOptions[index].map(obj => {
                  return {value: `${obj}`, label: `${obj}`}});
                return(

                  <Select
                    name="open_id"
                    value={option}
                    onChange={this.changeSingleHandler}
                    options={option}
                    className='select'
                  />
                  <Select
                    name="open_id"
                    value={this.state.open_id}
                    onChange={this.changeHandler}
                    options={timing}
                    className='select'
                  />
            <button onClick={() => this.saveState(option)} className='button-left'>Select Days</button>

            )
  })}

          )
    }
  }
export default PatientSelectDay;


text:
Q: AngularJS orderby integer field not working properly I just took the simplest demo from http://docs.angularjs.org/api/ng.filter:orderBy  and just change the value of age to have different number of digit. It stop working as it expected. Its ordering like "string" not as "integer" value. How should i change it so that it order by age like integer value?
Plunkr demo is here
http://plnkr.co/edit/pzgiIYrki7jUZdVaTMt9?p=preview
Codes are:
function Ctrl($scope) {
  $scope.friends =
      [{name:'John', phone:'555-1212', age:'2352345'},
       {name:'Mary', phone:'555-9876', age:'4235243'},
       {name:'Mike', phone:'555-4321', age:'241'},
       {name:'Adam', phone:'555-5678', age:'34325'},
       {name:'Julie', phone:'555-8765', age:'1234'}]
  $scope.predicate = '-age';
}

<!doctype html>

Sorting predicate = {{predicate}}; reverse = {{reverse}}

  [ unsorted ]

      Name
          (^)
      Phone Number
      Age

      {{friend.name}}
      {{friend.phone}}
      {{friend.age}}

A: you have to convert age to type Number to make to orderBy to work as it should.
Add to your controller to sort String age as float:
   angular.forEach($scope.friends, function (friend) {
    friend.age = parseFloat(friend.age);
   });

It should work,
See PLunker

A: I know is a little late for this answer, but in the newest version of Angular, you can use a function as the orderBy's predicate (https://docs.angularjs.org/api/ng/filter/orderBy).
In this case, add to the controller a function like next
$scope.orderByFunction = function(friend){
    return parseInt(friend.age);
};

and change the predicate in the orderBy filter
ng-repeat="friend in friends | orderBy:orderByFunction:reverse"

This will do the trick!

A: You just have to remove quotes in age variable because it's an integer, not a string:
  $scope.friends =
      [{name:'John', phone:'555-1212', age:2352345},
       {name:'Mary', phone:'555-9876', age:4235243},
       {name:'Mike', phone:'555-4321', age:241},
       {name:'Adam', phone:'555-5678', age:34325},
       {name:'Julie', phone:'555-8765', age:1234}]

A: AngularJs have in built functionalities to sort the values.But before sorting float values we need to convert the values to float using the parseFloat() javavscript function .
http://hubpages.com/technology/How-to-sort-table-content-filter-table-data-and-add-pagination-using-Angular-JS

A: Changing your predicate to the following will also work:
Age

A: Add JSON_NUMERIC_CHECK code while converting array into json.
json_encode($anyarray,JSON_NUMERIC_CHECK);


text:
Q: Styling individual features in a GeoJSON layer I have managed to display a GeoJSON layer with multiple polygons (~150) in a Leaflet map in SharePoint.
I would like to style different features in this GeoJSON layer according to  a colour stored within a column in this GeoJSON layer, called "color".
So far the output is only diplaying by default: "blue"
// Polygons coloured
      $.getJSON("../XX/XX/XX/polygons.geojson",function(data){
        polygons = L.geoJSON(data, {
                style:function(feature) {
                switch (feature.properties.color)
                },
        onEachFeature: function(feature, layer) {
               layer.bindPopup(feature.properties.name);
    }
        });

 layercontrol.addOverlay(polygons, 'POLYGONS');

 document.getElementById('mapid').style.opacity = 1;

 });

I could style the features indivdually like I started in the following script but I dont think it is the most adequate solution since I have more than 100 polygons.
/ polygons
      $.getJSON("../SiteAssets/webparts/Data/WOAs_WGS84.geojson",function    (data){
         woas2 = L.geoJSON(data, {
                        style: function(feature) {
                switch (feature.properties.name) {
                case 'polygon 1: return {color: #00FF7F", opacity:0.7};
                case 'polygon 2:   return {color: "#c917dc", opacity:0.7};
                case 'polygon 3:   return {color: "#FF0000", opacity:0.7};
                case 'polygon 4':   return {color: "#a9fb3a", opacity:0.7};
                case 'polygon 5:   return {color: "#4169E1", opacity:0.7};

and so on
...
                case 'polygon 150 ':   return {color: " #C0C0C0", opacity:0.7};
         },
               onEachFeature: function(feature, layer) {
               layer.bindPopup(feature.properties.name);
         }
         });

            layercontrol.addOverlay(polygons, 'POLYGONS');

               });

A: Leaflet's choropleth example  is an excellent place to understand coloring by attributes. I didn't change the example much - just followed your sample.
// color by attribute.
woas2 = L.geoJSON(data, {
          style: function(feature) {
            d = feature.properties.colorByAttr;
            return d > 1000 ? {color: '#00FF7F', opacity:0.7} :
              d > 500  ? {color: '#BD0026', opacity:0.7} :
              d > 200  ? {color: '#E31A1C', opacity:0.7} :
                         {color: '#FFEDA0', opacity:0.7};
           },

Assigning random colors can also be achieved by creating a function that returns a random color or creating a pre defined array of colors and assigning the colors simillar to your method, though serially instead of 'by name'.


text:
Q: What is "di:waypoint " in BPMN? I've been reading on the XML structure of BPMN files and I have understood everything expect the use of di:waypoint . Can anyone explain me what it is used for?
Here is a small xml of a bpmn file:
<?xml version="1.0" encoding="UTF-8"?>
<definitions id="Definition">
  <process processType="Private" isExecutable="true" id="Minimal" name="Minimal Process" >

 <!-- nodes -->
    <startEvent id="_1" name="StartProcess" />
    <scriptTask id="_2" name="Hello" >
      <script>System.out.println("Hello World");</script>
    </scriptTask>
    <endEvent id="_3" name="EndProcess" >
        <terminateEventDefinition/>
    </endEvent>

    <!-- connections -->
    <sequenceFlow id="_1-_2" sourceRef="_1" targetRef="_2" />
    <sequenceFlow id="_2-_3" sourceRef="_2" targetRef="_3" />

  </process>

  <bpmndi:BPMNDiagram>
    <bpmndi:BPMNPlane bpmnElement="Minimal" >
      <bpmndi:BPMNShape bpmnElement="_1" >
        <dc:Bounds x="15" y="91" width="48" height="48" />
      </bpmndi:BPMNShape>
      <bpmndi:BPMNShape bpmnElement="_2" >
        <dc:Bounds x="95" y="88" width="83" height="48" />
      </bpmndi:BPMNShape>
      <bpmndi:BPMNShape bpmnElement="_3" >
        <dc:Bounds x="258" y="86" width="48" height="48" />
      </bpmndi:BPMNShape>
      <bpmndi:BPMNEdge bpmnElement="_1-_2" >
        <di:waypoint x="39" y="115" />
        <di:waypoint x="75" y="46" />
        <di:waypoint x="136" y="112" />
      </bpmndi:BPMNEdge>
      <bpmndi:BPMNEdge bpmnElement="_2-_3" >
        <di:waypoint x="136" y="112" />
        <di:waypoint x="240" y="240" />
        <di:waypoint x="282" y="110" />
      </bpmndi:BPMNEdge>
    </bpmndi:BPMNPlane>
  </bpmndi:BPMNDiagram>

</definitions>

A: The BPMN 2.0 specification (find the pdf here: http://www.omg.org/spec/BPMN/2.0/PDF/) describes it as follows:

An edge is often depicted as a line with 2 or more points (i.e., one
  or more connected line segments) in the coordinate system, called
  waypoints. The first point typically intersects with the edge's
  source, while the last point typically intersects with the edge's
  target. Any points in between establish a route for the line to
  traverse in the diagram.

The "edges" are in your case the BPMN sequence flows in between the start event and the script task, and in between the script task and the end event.


text:
Q: Affine (or Stein) tubular neighbourhood theorem Fix an embedding $X\subset Y$ of smooth complex affine varieties, or Stein manifolds.
I would guess that in general there is no analytic neighbourhood $X\subset U\subset Y$ with a holomorphic retraction $U\to X$. But does anyone know a counterexample? (If not, a proof of the existence of $U$?)

A: My original interest in this problem was the following question.
Given a holomorphic bundle $E$ on an affine/Stein scheme $X$ inside any scheme/analytic space $Y$ of finite embedding dimension, is it the restriction of a bundle on a Stein neighbourhood $U\subset Y$ of $X$?
Smooth case. If $X$ and $Y$ are both smooth, then Corollary 1 in Siu's paper now gives this, by pulling $E$ back along the holomorphic retraction.
Reduced case. If $X$ and $Y$ are only reduced then Mohan Ramachandran's comment below solves this. In more detail: $Y$ admits a triangulation with $X$ as a subcomplex, so there is an open neighbourhood $U'$ of $X$ which is a retract, giving a continuous (not usually holomorphic) projection $\pi:U'\to X$.
Now by Siu's theorem there is a Stein neighbourhood $X\subset U\subset U'$ on which we have the topological bundle $\pi^*E|_U$. By Grauert's Oka principle there is a holomorphic structure on this which restricts to the given one on $\pi^*E|_X=E$.
$X$ nonreduced. Here we apply the above result to $E|_{X^{red}}$ to get a bundle $\widetilde E$ on $U\subset Y$ with $\widetilde E|_{X^{red}}\cong E|_{X^{red}}$. But I think this means $\widetilde E|_X\cong E$ since there is at most one extension of $E|_{X^{red}}$ from $X^{red}$ to $X$ when $X$ is Stein.
$Y$ nonreduced. Finally for general $Y$ we may assume it is Stein by replacing it by Siu's Stein neighbourhood of $X^{red}$. Then we can embed in some $\mathbb C^N$, find a holomorphic extension $\widetilde E$ there, then restrict back to $Y$.
So thanks to Richard Lärkäng and Mohan Ramachandran I think the result is probably true. Surely there's a reference for it somewhere?

A: A theorem of Siu says there in fact exists such a retraction, see Corollary 1 in
Every Stein Subvariety Admits a Stein Neighborhood, Inventiones math. 38, 89-100 (1976).


text:
Q: React JS update classes when useState is updated I am trying to make a carousel slider in react. Now am I checking the state and if the state is 2 for example add the tailwind class -left-1/3. Now that is working all fine. But only I have to click twice before it adds the first switch case. Does anyone know if there is a way (maybe with useEffect) to update or reload when the stae is getting updated?
const Hero = () => {
  const [sliderIndex, setSliderIndex] = useState(1);
  const [sliderClass, setSliderClass] = useState("-left-0");

  console.log(sliderIndex);
  const nextSlide = () => {
    setSliderIndex(sliderIndex + 1);
    console.log("onclick", sliderIndex);

    switch (sliderIndex) {
      case 1:
        setSliderClass("-left-0");
        break;
      case 2:
        setSliderClass(`-left-1/${dataSlider.length}`);
        break;
      case 3:
        setSliderClass(`-left-2/${dataSlider.length}`);
        break;
    }
    if (sliderIndex >= dataSlider.length) {
      setSliderIndex(1);
    }
  };
  const prevSlide = () => {
    console.log("onclick", sliderIndex);

    setSliderIndex(sliderIndex - 1);
    switch (sliderIndex) {
      case 1:
        setSliderClass("-left-0");
        break;
      case 2:
        setSliderClass(`-left-1/${dataSlider.length}`);
        break;
      case 3:
        setSliderClass(`-left-2/${dataSlider.length}`);
        break;
    }
    if (sliderIndex < 2) {
      setSliderIndex(3);
    }
  };

  useEffect(() => {
    console.log("change");
  }, [sliderIndex]);

  return (

        {dataSlider.map((obj, index) => {
          return (
            <>
              <div
                className={`${sliderClass} transition-all duration-700 relative w-full h-full`}
              >
                <img
                  // layout="fill"
                  // objectFit="cover"
                  src={`/sliderImg${index + 1}.jpg`}
                  alt={obj.aboutImg}
                  className={`  object-cover  transition-all  duration-1000 h-full w-full`}
                />

                    {obj.title}

{obj.text}

                  <Link href={obj.btnHref}>
                    <button className=" px-8 py-4 text-white rounded active:scale-[0.98] hover:scale-[1.02] transition-transform bg-primary ">
                      {obj.btnText}
                    </button>
                  </Link>

            </>
          );
        })}
        <button
          onClick={prevSlide}
          className="absolute md:pl-[18px] pl-[9px] rounded md:w-12 md:h-12 w-8 h-8 z-10 active:scale-[0.98] hover:scale-[1.02] transition-transform cursor-pointer top-0 bottom-0 left-0 mt-auto mb-auto ml-4 md:ml-20 bg-white"
        >
          <svg
            width="10"
            height="19"
            viewBox="0 0 10 19"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
          >
            <rect
              width="12.368"
              height="1.76686"
              transform="matrix(0.707425 0.706788 -0.707425 0.706788 1.25 8.18359)"
              fill="#111731"
            />
            <rect
              width="12.368"
              height="1.76686"
              transform="matrix(-0.707425 0.706788 -0.707425 -0.706788 10 1.92017)"
              fill="#111731"
            />
          </svg>
        </button>
        <button
          onClick={nextSlide}
          className="absolute md:pl-[18px] rotate-180 pl-[9px] rounded md:w-12 md:h-12 w-8 h-8 z-10 active:scale-[0.98] hover:scale-[1.02] transition-transfom cursor-pointer top-0 bottom-0 right-0 mt-auto mb-auto mr-4 md:mr-20 bg-white"
        >
          <svg
            width="10"
            height="19"
            viewBox="0 0 10 19"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
          >
            <rect
              width="12.368"
              height="1.76686"
              transform="matrix(0.707425 0.706788 -0.707425 0.706788 1.25 8.18359)"
              fill="#111731"
            />
            <rect
              width="12.368"
              height="1.76686"
              transform="matrix(-0.707425 0.706788 -0.707425 -0.706788 10 1.92017)"
              fill="#111731"
            />
          </svg>
        </button>

  );
};

export default Hero;```

A: @yainspan is correct in his comment. To explain with a bit of code:
Try to avoid calling setState willy-nilly. I've removed an unnecessary call in this version of prevSlide():
const prevSlide = () => {
    console.log("onclick", sliderIndex);
    let tempIndex = sliderIndex -1;
    if (tempIndex < 2) {
       setSliderIndex(3);
    }else{
       setSliderIndex(tempIndex);
    }
};

I've also remove the switch statement as, as yainspan suggests, you can just use sliderIndex to determine what class to add (you'll have to expand on the simplified version here but hopefully the logic is clear):
<div
    className={`${sliderIndex === 0 ? '-left-0' : sliderIndex === 1 ? '-left-1' : sliderIndex === 2 ? '-left-2' : '' }transition-all duration-700 relative w-full h-full`}
          >


text:
Q: How can I fix the "Error connecting with login URI" exception I get when adding events to Google Calendar? I use the following code in Java. It works well and it adds events into Google Calendar. But in Android it gives the Exception Error connecting with login URI. Can anyone help me to solve this?
CalendarService myService = new CalendarService("calendarTest");
String userName = "mytest.test@gmail.com";
String userPassword = "xxxxxxx";

// Create the necessary URL objects.
try {
    metafeedUrl = new URL(METAFEED_URL_BASE + userName);
    eventFeedUrl = new URL(METAFEED_URL_BASE + userName
        + EVENT_FEED_URL_SUFFIX);
} catch (MalformedURLException e) {
    // Bad URL
    strbuf.append(e.getMessage());
    System.err.println("Uh oh - you've got an invalid URL.");
    e.printStackTrace();
    return;
}

try
{
    myService.setUserCredentials(userName, userPassword);
    // Demonstrate creating a single-occurrence event.
    CalendarEventEntry singleEvent = createSingleEvent(myService,"Event Title", "Event Description ");
    System.out.println("Successfully created event " +singleEvent.getTitle().getPlainText() );

    // Demonstrate creating a quick add event.
    CalendarEventEntry quickAddEvent = createQuickAddEvent(myService,"Tennis with me June 22 3pm-3:30pm");
    System.out.println("Successfully created quick add event "       + quickAddEvent.getTitle().getPlainText());

}
// catch.......

A: This needs internet-access to add something  to the calendar, right?
So you need to give your app the permission for internet access. Try adding this right before the closing tag of AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>


text:
Q: Modded Minecraft server with the mods messed up I made a Modded Minecraft server (hosted on my Computer) and the only mod it has is Lord of the Rings.
However, it is like the mod isn't there, I can't spawn anything in on Not Enough Items and I can't place or use anything. I can see the items on the Inventory and Creative GUI but in the game its impossible.
I did try the mod on a single player world, which worked.
I followed multiple YouTube videos, I checked the Forge versions (1.7.10) (and all the Forge versions inside 1.7.10) they are all identical.
It's not a permission issue, and I am an OP. It's the client saying to the server that this doesn't exist so I'm deleting it, but, it does exist. and within that, I don't know why it is doing that.

A:
It's the client saying to the server that this doesn't exist so I'm deleting it, but, it does exist. and within that, I don't know why it is doing that.

It's exactly the opposite. If the items show up in NEI and creative, but can not be put into the game world, that means that the server has no clue about the mod, but the client does.
Here's an illustration of what happens when you try to get a mod item:

CLIENT: Hey, SERVER, I want to have [ITEM].
SERVER: [ITEM]? What are you talking about, CLIENT? There is no such thing as [ITEM]. I'll remove whatever it is that you think you are holding.

I suggest you re-install the forge server and the mods on it.

*

*Go to the Forge website and download the installer (not the universal .jar!).

*Run the Forge installer and select "Install Server"

*Go to the installation directory and run forge-1.7.10-10.13.4.1614-1.7.10-universal.jar, set the eula=true, and then run it again.

*Place all server-side mods into the newly created mods folder.

A: I think you may have to many mods on your sever this can make your game act up a bit try removing a mod off that world and see if it works it worked for me.


text:
Q: Express.js application bug causes Route.post() requires a callback function but got a [object Undefined] error I am working on a blogging application (click the link to see the GitHub repo) with Express, EJS and MongoDB.
I am trying to introduce an add post image feature with Multer. Being quite new to Express, I run into trouble.
In utils\imageupload.js I have added:
const multer = require("multer");

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
            cb(null, './uploads/images')
    },
    filename: function (req, file, cb) {
            cb(null, file.fieldname + '-' + Date.now() + '.png')
    }
});

exports.upload = multer({ storage: storage }).single('postimage');

I import and use that in my dashboard routes file:
const imageUploader = require('../../utils/validation.js');

//more code

// Add Post
router.post('/post/add', imageUploader.upload, validator.addPostCheck, dashboardController.addPost);

//more code

In the controller I have (among others):
exports.addPost = (req, res, next) => {

    upload(req, res, function(err) {
        if (err) {
            console.log("There was an error uploading the image.");
        } else {
            res.sendStatus(200);
        }
    })

    var form = {
        titleholder: req.body.title,
        excerptholder: req.body.excerpt,
        bodyholder: req.body.body
    };

    const errors = validationResult(req);

    const post = new Post();

    post.title = req.body.title;
    post.short_description = req.body.excerpt
    post.full_text = req.body.body;

    if (!errors.isEmpty()) {
        req.flash('danger', errors.array())
        res.render('admin/addpost', {
            layout: 'admin/layout',
            website_name: 'MEAN Blog',
            page_heading: 'Dashboard',
            page_subheading: 'Add New Post',
            form: form
        });
    } else {
        post.save(function(err) {
            if (err) {
                console.log(err);
                return;
            } else {
                req.flash('success', "The post was successfully added");
                req.session.save(() => res.redirect('/dashboard'));
            }
        });
    }
}

As long as the line imageUploader.upload is in the controller, the entire application just crashes, with the error: Route.post() requires a callback function but got a [object Undefined] error.
What am I doing wrong?

A: You have the following line:
const imageUploader = require('../../utils/validation.js');

validation.js does not export upload which you are using here:
// Add Post
router.post('/post/add', imageUploader.upload, validator.addPostCheck, dashboardController.addPost);

Changing the import to
const imageUploader = require('../../utils/imageupload.js');

should fix the problem.
Regarding the problem in the admin dashboard-controller: Since you've already called the multer upload, you can remove it in addPost, req should now contain the uploaded file.
exports.addPost = (req, res, next) => {
    // removed the upload code
    var form = {
            titleholder: req.body.title,
            excerptholder: req.body.excerpt,
            bodyholder: req.body.body
    };
    ...


text:
Q: Is there a way to denormalize data in the resultset of an Oracle SQL query I have table Students as follows:
SNO    NAME   SUBJECT   MARKS
-----------------------------
1      HARWI   HINDI     75
2      SHWETA  ENGLISH   80
3      RUDRA   MATHS     90
4      HARWI   MATHS     60
5      MANVI   GK        89
6      RUDRA   HINDI     98
7      SHWETA  MATHS     67

I need output like this:
1   HARWI     HINDI   75
              MATHS   60
2   MANVI     GK      89
3   RUDRA     HINDI   98
              MATHS   90
4   SHWETA    ENGLISH 80
              MATHS   67

I DO NOT WANT TO USE concatenation operator ||
Are there standard functions in Oracle which can help me achieve this result set?

A: Use window functions row_number() and dense_rank():
with cte as (
  select s.*, row_number() over (partition by name order by marks desc) as rn
  from students s
)
select
  case when c.rn > 1 then null else dense_rank() over (order by c.name) end as rn,
  case when c.rn > 1 then null else name end as name,
  subject, marks
from cte c
order by c.name, c.rn

See the demo.
Results:
>   RN | NAME   | SUBJECT | MARKS
> ---: | :----- | :------ | ----:
>    1 | HARWI  | HINDI   |    75
>      |        | MATHS   |    60
>    2 | MANVI  | GK      |    89
>    3 | RUDRA  | HINDI   |    98
>      |        | MATHS   |    90
>    4 | SHWETA | ENGLISH |    80
>      |        | MATHS   |    67

A: You can use analytical function as following:
select case when lag(name) over(partition by name order by marks) is null then dr end as sno,
case when lag(name) over(partition by name order by marks) is null then name end as name,
subject,
marks
from (
  select t.*, dense_rank() over (order by t.name desc) as dr
  from students t -- dense rank is used to give numbers to the student - sno
)
order by dr;

Cheers!!


text:
Q: Contar registros en Query - ORACLE Tengo una consulta muy simple que no logro acomodar, anexo mi query:
SELECT
    PE.SCHD_ID AS OFERTA,
    PA.DESCRIPTION AS DESCRIPCION,
    PE.STUD_ID,
    PS.FNAME AS NOMBRE,
    PS.LNAME,
    PO.ORG_ID,
    PO.ORG_DESC,
    PF.ACCT_ID,
    PA.ACT_CPNT_ID,
    PA.TOTAL_LEARNING_COST as "Costo Oferta",
    PA.CLOSED_DATE,
    NULL AS PRORRATEO
FROM PA_ENROLL_SEAT         PE
INNER JOIN PA_SCHED         PA
    ON PE.SCHD_ID=PA.SCHD_ID
INNER JOIN PA_STUDENT       PS
    ON PS.STUD_ID=PE.STUD_ID
INNER JOIN PA_ORG           PO
    ON PO.ORG_ID=PS.ORG_ID
INNER JOIN PA_ORG_FIN_ACCT  PF
    ON PF.ORG_ID=PO.ORG_ID
WHERE PA.SCHD_ID='86010'

Ésta consulta al ejecutarla, me arroja 3 registros, lo cual está excelente, pero necesito que en el último campo el cual llamo como  "NULL AS PRORRATEO", necesito que me cuente la cantidad de registros (3) entre el total de "Costo Oferta" que en esta caso es un costo de $20,000.
En teoría el campo de PRORRATEO requiero que me realice la división del total del costo oferta (20,000) entre la cantidad de registros que mando llamar en mi consulta (3)  y en dicho campo me pueda mostrar 6,666.66 lo equivalente a
 20,000 / 3.
HELP no soy muy buena en esto aún =(

A: Para obtener el Costo Oferta por SCHD_ID entiendo yo, lo más sencillo es hacer esto:
SELECT  SCHD_ID,
        SUM(TOTAL_LEARNING_COST) as "Total_Costo_Oferta",
        FROM PA_SCHED
        WHERE SCHD_ID = '86010'
        GROUP BY SCHD_ID

Si quitamos el WHERE, te permitiría hacer una consulta más amplia si hiciera falta. Este total puede incorporarse a tu consulta para llegar a un prorateo rudimentario:
SELECT  PE.SCHD_ID AS OFERTA,
        PA.DESCRIPTION AS DESCRIPCION,
        PE.STUD_ID,
        PS.FNAME AS NOMBRE,
        PS.LNAME,
        PO.ORG_ID,
        PO.ORG_DESC,
        PF.ACCT_ID,
        PA.ACT_CPNT_ID,
        PA.TOTAL_LEARNING_COST as "Costo Oferta",
        PA.CLOSED_DATE,
        T.Total_Costo_Oferta / PA.TOTAL_LEARNING_COST as 'PRORRATEO'
        FROM PA_ENROLL_SEAT PE
        INNER JOIN PA_SCHED PA
            ON PE.SCHD_ID=PA.SCHD_ID
        INNER JOIN PA_STUDENT PS
            ON PS.STUD_ID=PE.STUD_ID
        INNER JOIN PA_ORG PO
            ON PO.ORG_ID=PS.ORG_ID
        INNER JOIN PA_ORG_FIN_ACCT  PF
            ON PF.ORG_ID=PO.ORG_ID
        INNER JOIN (
             SELECT  SCHD_ID,
                     SUM(TOTAL_LEARNING_COST) as "Total_Costo_Oferta",
                     FROM PA_SCHED
                     WHERE SCHD_ID = '86010'
                     GROUP BY SCHD_ID
           ) T
           ON T.SCHD_ID = PA.SCHD_ID
        WHERE PA.SCHD_ID = '86010'

Digo un prorrateo rudimentario, por que tienes un problema con los decimales períodicos o infinitos, dónde por mas precisión que le des a la variable, la suma de los prorrateos no te dará exactamente 1. Habitualmente lo que se suele hacer, si tuvieras la posibilidad de usar una tabla intermedia, es ajustar el valor más alto para que la suma total de 1.


text:
Q: Why does Chrome add extra html to my page? I have a snippet of code that looks like this in my html document:

    Request ID :

....

When i open it up in Chrome and inspect the
 element, this is what is shown:

    Request ID :

....

It has in fact, added another identical  tag under the first p.
However, if i select 'view page source', the HTML code shown is identical to that in my file.
Why would Chrome add the extra  into the HTML?
Note: I am aware that name is an invalid attribute for an  however this is how bookmarks are represented in HTML when converting from docx to this format so im sticking with it.

A:  is not a self-closing tag. It's invalid to use  (instead of ) in HTML (and inadvisable in XHTML for compatibility).

    Request ID :


text:
Q: How to group by one field when the other field rows are different I have the result set i am looking for, but now i am trying to trouble the rows by Order ID, but i am having a hard time figuring out how to do this. The other fields for the duplicate Order ID are different so i am unsure how to group them, so it will only show one Order ID, even though the other fields are different. See below for the code and the output. When looking at the input just notice that there are Order ID's that are the same and i need to consolidate those into one row, even though the other fields are slightly different.
WITH CTE as(
    Select
        [Order Details].[Order ID],
        SUM(Quantity * [Rental(PLTR)1]) as [Sum of all ProductID]
    FROM [Order Details]
    join Products ON [Order Details].[Product ID] = Products.[Product ID] AND
        [Order Details].location = Products.location
    WHERE [Order Details].Location = 'OC'
    group by [Order Details].[Order ID]
)
SELECT
    [Order Details].[Order ID],
    [Order Details].[Product ID],
    P.[Sum of all ProductID],
    OrigSalesman,
    Enterby,
    Months,
    Quantity
from [Order Details]
join CTE as p on p.[Order ID] = [Order Details].[Order ID]
join Orders ON Orders.[Order ID] = [Order Details].[Order ID]
join [Job Name ID] ON [Orders].[Job Name ID] = [Job Name ID].[Job Name ID]
wHERE [Order Details].[Product ID] = '3367'
order by [Order Details].[Order ID]

Here is the output:
Order ID / Product ID / Sum of all ProductID / OrigSalesman / Enterby / Months / Quantity

38119   3367    275 Susan DeMarchi  144 12  1
38119   3367    275 Susan DeMarchi  144 12  2
38119   3367    275 Susan DeMarchi  144 12  8
38119   3367    275 Susan DeMarchi  144 12  1
38301   3367    80  Susan DeMarchi  91  12  1
47476   3367    830 House Sale  25  6   1
47997   3367    0   House Sale  277 6   1
48760   3367    0   Don P. C. Carpentier    270 6   1
48761   3367    0   Don P. C. Carpentier    270 6   1
48762   3367    0   Don P. C. Carpentier    270 6   1
48763   3367    0   Don P. C. Carpentier    270 6   1
48880   3367    0   Roger Riley 270 12  1
51411   3367    0   House Sale  270 12  1
52444   3367    0   Susan DeMarchi  277 6   1
53280   3367    0   Roger Riley 25  6   1
59408   3367    90  Susan DeMarchi  25  6   1
59714   3367    75  Eddie Salti 453 1   13
60327   3367    1052    Susan DeMarchi  18  10  1
60394   3367    170 Susan DeMarchi  25  16  1
62687   3367    235 Susan DeMarchi  663 12  1
62776   3367    40  Susan DeMarchi  73  10  1
62876   3367    40  Susan DeMarchi  663 10  1
62894   3367    62.5    Susan DeMarchi  73  12  1
62898   3367    130 Susan DeMarchi  73  12  1
62915   3367    0   House Sale  270 6   1
62971   3367    84  Susan DeMarchi  663 12  1
62994   3367    363 Susan DeMarchi  663 14  1
62999   3367    75  Susan DeMarchi  663 12  1
63248   3367    62.5    Susan DeMarchi  663 12  1
63252   3367    130 Susan DeMarchi  663 12  1
63562   3367    0   House Sale  33  12  1
63894   3367    527.5   Susan DeMarchi  663 8   2
63975   3367    220 Susan DeMarchi  663 12  6
63982   3367    95  Susan DeMarchi  663 12  6
63984   3367    95  Susan DeMarchi  663 12  6
63985   3367    40  Susan DeMarchi  663 12  6
63986   3367    100 Susan DeMarchi  663 12  6
63987   3367    80  Susan DeMarchi  663 12  6
64269   3367    190 Susan DeMarchi  663 8   2
64269   3367    190 Susan DeMarchi  663 8   2
64643   3367    89  Susan DeMarchi  663 10  4

A: Remove Order Details from the outer query and move filter by Product ID inside the CTE. That's it.


text:
Q: Add trailing slash wit url excluding some urls I have used the following rule to add trailing slash with url and its working fine
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_URI} !(.*)/$
  RewriteRule ^(.*)$ https://www.myexamplesite.com/$1/ [L,R=301]

I want to exclude some admin urls and some ajax urls so that they dont permanent redirect, I tried with following code but its not working
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_URI} !get-ajax
  RewriteCond %{REQUEST_URI} !admin
  RewriteCond %{REQUEST_URI} !(.*)/$
  RewriteRule ^(.*)$ https://www.myexamplesite.com/$1/ [L,R=301]

There are some more urls I want to exclude from trailing slash ( means they can be loaded with or without trailing slash )
Above code works only for one url like get-ajax but not for all, there will be some more urls I will exclude form trailing slash.
Is there a way to do this ?


text:
Q: Google OAuth Client with Angular/Ionic: How do I find the redirect_uri? I have an Ionic2 app that I would like to add GooglePlus Authentication to.
I get the following error:

As far as I understand, it's because I have not set up a redirect_uri.
Question
What redirect_uri (Authorized redirect URIs) should I use for an Ionic2 app? Where do I find it?

The following works with Facebook login.

UPDATE
Following these instructions, I changed the REVERSED_CLIENT_ID to the following format:
"com.googleusercontent.apps.uniqueId"

So I think I have made progress.
I now get the following error in iOS:

From reading here, this means that the credentials should not be created for a Web Application here. But if I create it for iOS, how will this work for Android?  Or does Android not make use of these credentials anyway?
For Android, when I try to log in, I just get an exception with an undefined error message.
So I have two questions please:

*

*Do I need to create iOS client ID here instead of a Web application?

*How do I configure or debug this for Android?

UPDATE
For iOS I added an iOS Client Id and changed my REVERSED CLIENT ID to match, and like with Android, it prompted me to sign into my Google Account. So that looks like further progress.
However, once I sign in, like with Android now I get an exception with the message as undefined. In the Xcode console, however, I do get the following:

com.google.HTTPStatus error 400.

Following these, I have now created credentials for both iOS and Android.

I have configured Android and iOS IDs in the new IDs.
I get an exception with the message as undefined on both Android and iOS.
UPDATE
Got it working for iOS.  The webClientId option when you call login must not be the reversed client id, but rather the client id.
        GooglePlus.login({
            'webClientId': 'xxxxx.apps.googleusercontent.com',
            'offline': true
        }).then(googleData => {

Now to figure out why Android doesn't work.
In Android, I now get error = 12501 (which is a result of something wrong with my Keystore I think).
UPDATE
I generate the Keystore. As per these instructions, I copy the SHA1 to the Signing-certificate fingerprint. But still get error = 12501.

A: As you got iOS working, here is solution for Android.
Build APK of your app and then run this command-
keytool -list -printcert -jarfile app.apk

The output will reveal the Signature, Certificate fingerprints (MD5, SHA1 and SHA256) and Extensions of the APK.
Copy the SHA1 to the Signing-certificate fingerprint while creating client ID for android


text:
Q: Magento 2:ERROR: Front controller reached 100 router match iterations I got error when trying to do like this extention
http://inchoo.net/magento-2/routing-in-magento-2/
it work ok but when I add a foreach to check the url, I got error

Front controller reached 100 router match iterations
  #0 [internal function]: Magento\Framework\App\FrontController->dispatch(Object(Magento\Framework\App\Request\Http))


text:
Q: Change menu name Odoo9 I'm inherit project module, how in my custom module in .xml view change menu title from Project to Project 1234
Original code from project menu:
 <!-- Top menu item -->
 <menuitem name="Project"
   id="base.menu_main_pm"
   groups="group_project_manager,group_project_user"
   icon="fa-calendar"
   web_icon="project,static/description/icon.png"
   sequence="50"/>

A: Use this:
<record model="ir.ui.menu" id="base.menu_main_pm">
  <field name="name">Project 1234</field>
</record>


text:
Q: Local variable error in "if" statement (Java) import java.util.Scanner;
import java.util.Random;
import static java.lang.System.out;

class TestingStuf {
    enum tooWhat {tooHigh, tooLow, justRight};

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        Random myRandom = new Random();

        tooWhat guess;

        out.println("Pick a number between 1 and 10.");
        int userGuess = keyboard.nextInt();
        int randomNumber = myRandom.nextInt(10) + 1;

        if (userGuess < randomNumber) {
            guess = tooWhat.tooLow;
        }else if (userGuess > randomNumber) {
            guess = tooWhat.tooHigh;
        }else if (userGuess == randomNumber) {
            guess = tooWhat.justRight;
        }

        out.println("Your guess is:");

        if (guess == tooWhat.tooLow) {
            out.println("Too low.");

        }else if (guess == tooWhat.tooHigh) {
            out.println("Too high.");

        }else if (guess == tooWhat.justRight) {
            out.println("Correct!");

        }

            keyboard.close();
    }
}

In my code I have an error in the second set of "if" statements that says The "local variable guess may not have been initialized" even though in the previous "if" statement I give the "guess" variable a value that is dependent on the user input. What am I doing wrong?

A: If you look at your code, it seems like there's a path through the if...else if...else if where guess is never initialized. That's what the compiler is warning you about, because code subsequent to that expects that guess will definitely have a value.
Although we, as humans, know that your three conditions are mutually-exclusive, the compiler isn't quite as smart as we are. Just make your final one an else rather than an else if (...):
if (userGuess < randomNumber) {
    guess = tooWhat.tooLow;
}else if (userGuess > randomNumber) {
    guess = tooWhat.tooHigh;
}else { // *** No `if`
    guess = tooWhat.justRight;
}

A: Change your last if else statement to an else statement
 if (userGuess < randomNumber) {
        guess = tooWhat.tooLow;
    }else if (userGuess > randomNumber) {
        guess = tooWhat.tooHigh;
    }else
        guess = tooWhat.justRight;

That way the compiler knows that there is no possibility that guess stays uninitialized.

A: Compiler isn't sure if variable guess shall ever be provided a value based on just going through if..else if..else..if ladder. If compiler were to evaluate values for each of these ladder steps it would be able to find that out but that would be an overkill for the compiler. Going by the code, replacing last else if with else shall resolve your issue.


text:
Q: htaccess - allow certain parameters but redirect to 404 if other query string Following problem:
I have a form on a page and want to allow certain parameters to enable form value overwriting. But if there is a questionmark in the url without any of the parameter I want to redirect to the 404 page.
But my regex doesn't work very well...
RewriteCond %{QUERY_STRING} !^(a=.*|b=.*|c=.*)
RewriteRule ^subfolder/(.*)$ - [R=404,L,NC]

But now my page only shows up if a parameter is set. http://example.com/subfolder/ does not work, but http://example.com/subfolder/?a=whatever works. I only want a redirect if there is a question mark without any my parameters. How to do that?

A: You can use this rule:
RewriteCond %{QUERY_STRING} .
RewriteCond %{QUERY_STRING} !(^|&)(a|b|c)= [NC]
RewriteRule ^subfolder/(.*)$ - [R=404,L,NC]

First condition RewriteCond %{QUERY_STRING} . makes sure that QUERY_STRING is non-empty.


text:
Q: php: converting from cp1251 to utf8 I have a problem converting a string from cp1251 to utf8...
I need to get some names from database and those names are in cp1251(i'm not the one who made that database, so I can't edit it, but I know for sure that these names are cp1251)...
The name in database is this - "Р?нтернет РІ цифрах"
I'm converting it to utf8 using iconv function like this:

iconv("UTF-8", "CP1251//IGNORE", $name)

and what I have in the result is this - "�?нтернет в цифрах"(it's Russian), but the first two symbols are not correct... it should be "Интернет в цифрах"...
So the final thing that I have to do is somehow change these two symbols "�?" to russian letter "И"... and I really don't know how to do that... I've tried to use preg_replace, but it doesn't work...or I'm not using it correctly.
And I'm sorry for Russian letters, it is really hard to explain what I need without showing them.

A: The first letter comes out incorrect because one of the bytes needed to store the UTF-8 encoding of И (0x98 to be exact) is not used in CP1251. If the database has replaced the 98 byte by a question mark you have to change it back before using iconv:
$name = str_replace("\xD0\x3F", "\xD0\x98", $name);
echo iconv("UTF-8", "CP1251//IGNORE", $name);

A: use this:
mb_convert_encoding($model->text, 'cp1252', 'utf8')

A: Try this:
function cp1251_to_utf8($s){
           $c209 = chr(209); $c208 = chr(208); $c129 = chr(129);
           for($i=0; $i<strlen($s); $i++)    {
               $c=ord($s[$i]);
               if ($c>=192 and $c<=239) $t.=$c208.chr($c-48);
               elseif ($c>239) $t.=$c209.chr($c-112);
               elseif ($c==184) $t.=$c209.$c209;
               elseif ($c==168)    $t.=$c208.$c129;
               else $t.=$s[$i];
           }
           return $t;
       }