text:
Q: How convert a JSON string to Dictionary in Python? I already read different post regarding python conversion from str to dic but I still have problems and I can't convert my str in dictionary.
this is my original string:
{"faqId":1,"isPrivate":false,"question":"Question 1","answer":"# Hello world!!\r\n\r\n*   Proin elementum sollicitudin sodales.\r\n*   Nam id erat nec nibh dictum cursus.\r\n\r\n> In et urna eros. Fusce molestie, orci vel laoreet tempus, sem justo blandit magna, at volutpat velit lacus id turpis.  \r\n> Quisque malesuada sem at interdum congue. Aenean dapibus fermentum orci eu euismod.\r\n\r\n![](http://onehungrymind.com/wp-content/uploadspng)\r\n\r\n[This is an example link to nothing]()\r\n"},{"faqId":2,"isPrivate":false,"question":"Question 2","answer":"Dillinger\r\n=========\r\n\r\nDillinger is a cloud-enabled HTML5 Markdown editor.\r\n\r\n  - Type some Markdown text in the left window\r\n  - See the HTML in the right\r\n  - Magic\r\n\r\nMarkdown is a lightweight markup language based on the formatting conventions that people naturally use in email.  As [John Gruber] writes on the [Markdown site] [1]:\r\n\r\n> The overriding design goal for Markdown's\r\n> formatting syntax is to make it as readable \r\n> as possible. The idea is that a\r\n> Markdown-formatted document should be\r\n> publishable as-is, as plain text, without\r\n> looking like it's been marked up with tags\r\n> or formatting instructions.\r\n\r\nThis text you see here is *actually* written in Markdown! To get a feel for Markdown's syntax, type some text into the left window and watch the results in the right.  \r\n\r\nVersion\r\n----\r\n\r\n2.0\r\n\r\nTech\r\n-----------\r\n\r\nDillinger uses a number of open source projects to work properly:\r\n\r\n* [Ace Editor] - awesome web-based text editor\r\n* [Marked] - a super fast port of Markdown to JavaScript\r\n* [Twitter Bootstrap] - great UI boilerplate for modern web apps\r\n* [node.js] - evented I/O for the backend\r\n* [Express] - fast node.js network app framework [@tjholowaychuk]\r\n* [keymaster.js] - awesome keyboard handler lib by [@thomasfuchs]\r\n* [jQuery] - duh \r\n\r\nInstallation\r\n--------------\r\n\r\n```sh\r\ngit clone [git-repo-url] dillinger\r\ncd dillinger\r\nnpm i -d\r\nmkdir -p public/files/{md,html,pdf}\r\n```\r\n\r\n##### Configure Plugins. Instructions in following README.md files\r\n\r\n* plugins/dropbox/README.md\r\n* plugins/github/README.md\r\n* plugins/googledrive/README.md\r\n\r\n```sh\r\nnode app\r\n```\r\n\r\n\r\nLicense\r\n----\r\n\r\nMIT\r\n\r\n\r\n**Free Software, Hell Yeah!**\r\n\r\n[john gruber]:http://daringfireball.net/\r\n[@thomasfuchs]:http://twitter.com/thomasfuchs\r\n[1]:http://daringfireball.net/projects/markdown/\r\n[marked]:https://github.com/chjj/marked\r\n[Ace Editor]:http://ace.ajax.org\r\n[node.js]:http://nodejs.org\r\n[Twitter Bootstrap]:http://twitter.github.com/bootstrap/\r\n[keymaster.js]:https://github.com/madrobby/keymaster\r\n[jQuery]:http://jquery.com\r\n[@tjholowaychuk]:http://twitter.com/tjholowaychuk\r\n[express]:http://expressjs.com\r\n"},{"faqId":4,"isPrivate":false,"question":"Question 3","answer":"# Markdown Test\r\nThis is a link: [PDF link]"}

I try to tidy up a bit with
replace("false","False")
replace("true","True")
replace('"',"'")

So I got back:
{'faqId':1,'isPrivate':False,'question':'Question 1','answer':'# Hello world!!\r\n\r\n*   Proin elementum sollicitudin sodales.\r\n*   Nam id erat nec nibh dictum cursus.\r\n\r\n> In et urna eros. Fusce molestie, orci vel laoreet tempus, sem justo blandit magna, at volutpat velit lacus id turpis.  \r\n> Quisque malesuada sem at interdum congue. Aenean dapibus fermentum orci eu euismod.\r\n\r\n![](http://onehungrymind.com/wp-content/uploads.png)\r\n\r\n[This is an example link to nothing]()\r\n'},{'faqId':2,'isPrivate':False,'question':'Question 2','answer':'Dillinger\r\n=========\r\n\r\nDillinger is a cloud-enabled HTML5 Markdown editor.\r\n\r\n  - Type some Markdown text in the left window\r\n  - See the HTML in the right\r\n  - Magic\r\n\r\nMarkdown is a lightweight markup language based on the formatting conventions that people naturally use in email.  As [John Gruber] writes on the [Markdown site] [1]:\r\n\r\n> The overriding design goal for Markdown's\r\n> formatting syntax is to make it as readable \r\n> as possible. The idea is that a\r\n> Markdown-formatted document should be\r\n> publishable as-is, as plain text, without\r\n> looking like it's been marked up with tags\r\n> or formatting instructions.\r\n\r\nThis text you see here is *actually* written in Markdown! To get a feel for Markdown's syntax, type some text into the left window and watch the results in the right.  \r\n\r\nVersion\r\n----\r\n\r\n2.0\r\n\r\nTech\r\n-----------\r\n\r\nDillinger uses a number of open source projects to work properly:\r\n\r\n* [Ace Editor] - awesome web-based text editor\r\n* [Marked] - a super fast port of Markdown to JavaScript\r\n* [Twitter Bootstrap] - great UI boilerplate for modern web apps\r\n* [node.js] - evented I/O for the backend\r\n* [Express] - fast node.js network app framework [@tjholowaychuk]\r\n* [keymaster.js] - awesome keyboard handler lib by [@thomasfuchs]\r\n* [jQuery] - duh \r\n\r\nInstallation\r\n--------------\r\n\r\n```sh\r\ngit clone [git-repo-url] dillinger\r\ncd dillinger\r\nnpm i -d\r\nmkdir -p public/files/{md,html,pdf}\r\n```\r\n\r\n##### Configure Plugins. Instructions in following README.md files\r\n\r\n* plugins/dropbox/README.md\r\n* plugins/github/README.md\r\n* plugins/googledrive/README.md\r\n\r\n```sh\r\nnode app\r\n```\r\n\r\n\r\nLicense\r\n----\r\n\r\nMIT\r\n\r\n\r\n**Free Software, Hell Yeah!**\r\n\r\n[john gruber]:http://daringfireball.net/\r\n[@thomasfuchs]:http://twitter.com/thomasfuchs\r\n[1]:http://daringfireball.net/projects/markdown/\r\n[marked]:https://github.com/chjj/marked\r\n[Ace Editor]:http://ace.ajax.org\r\n[node.js]:http://nodejs.org\r\n[Twitter Bootstrap]:http://twitter.github.com/bootstrap/\r\n[keymaster.js]:https://github.com/madrobby/keymaster\r\n[jQuery]:http://jquery.com\r\n[@tjholowaychuk]:http://twitter.com/tjholowaychuk\r\n[express]:http://expressjs.com\r\n'},{'faqId':4,'isPrivate':False,'question':'Question 3','answer':'# Markdown Test\r\nThis is a link: [PDF link]'}

I'm trying different methods:
import json
json.loads(MY_STR)

import ast
ast.literal_eval(MY_STR)

etc...
but all of them give me back some kind of error, could you please help me?

A: Surround your original string with square brackets to make it a valid JSON string:
import json

valid_json_string = "[" + your_string + "]"  # or "[{0}]".format(your_string)
data = json.loads(valid_json_string)


text:
Q: Скрпит работает только для первого id  Мне нужно чтобы смена классов current, last и unactive происходила между двумя блоками. А у меня второй блок с id space1 остаётся всегда unactive, а смена классов происходит только в блоке с id space0.
PHP
     function viewImage($index, $text, $img, $style) {
        return "

" . $text . "

";
    }

JS

var Slider = {
    currentItem: function () {
        return document.querySelector(".slider-currentItem");
    },

    nextItem: function () {
        if (unactiveItems.length === 0)
            return null;

        return unactiveItems.shift();
    },

    lastItem: function () {
        return document.querySelector(".slider-lastItem");
    },

    unactiveItems: function () {
        var items = [];
        var nodes = document.querySelectorAll(".slider-unactiveItem");
        nodes.forEach(function(node) {
            items.push(node);
        });
        return items;
    },

    tornSlide: function() {
        if (currentItem) {
            currentItem.classList.remove("slider-currentItem");
            currentItem.classList.add("slider-lastItem");
        }

        lastItem = currentItem;

        currentItem = Slider.nextItem();
        console.log(currentItem);
        if (currentItem) {
            currentItem.classList.remove("slider-unactiveItem");
            currentItem.classList.add("slider-currentItem");
        }
    },

    hideLastItem: function() {
        if (!lastItem)
            return;

        lastItem.classList.remove("slider-lastItem");
        lastItem.classList.add("slider-unactiveItem");
        unactiveItems.push(lastItem);
        lastItem = null;
    },

    timeout: function () {
        tornCounter++;
        if (tornCounter > 10 && lastItem) {
            Slider.hideLastItem();
        }

        if (tornCounter > 40) {
            Slider.tornSlide();
            tornCounter = 0;
        }

        setTimeout("Slider.timeout()", 100);
    }
};

JSON
{
  "slide_1": {
     "name":"Jeans",
     "picture":"../slider/images/targets/2.jpeg"
  },
  "slide_2": {
     "name":"Men",
     "picture":"../slider/images/targets/3.jpeg"
  }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do i use string to get user Console Input Im working on a c++ programm which needs user text input per terminal as a variable
I have tried cin << input;
but text output is only shown as a 0
int input;
std::cin >> input;
std::cout << input;

I expected the text as output but i only got a 0

A: Integer can not take text as input. You need string in order to read text input form  user.
#include <iostream>
#include <string>
using namespace std;

int main()
{
   string text;
   cin>>text;
   cout<<text;
    return 0;
}

This program will  input text from  user. But cin extraction always consider white spaces as termination. For example cin in will only read "this" from "this is an apple string". In order to read complete string use getline() function. The above program can be written as
 #include <iostream>
#include <string>
using namespace std;

int main()
{
   string text;
   getline(cin,text); // will read white spaces to
   cout<<text;
    return 0;
}


text:
Q: How to tell if two 8-bit chars are gray codes in c++? The problem is to tell if two 8-bit chars are gray codes(differ only in 1 bit) in C++?
I found an elegant C++ solution:
bool isGray(char a, char b) {
    int m = a ^ b;
    return m != 0 && (m & (m - 1) & 0xff) == 0;
}

I was confused that what does the "& 0xff" do?

A: & 0xff extracts the 8 lowest bits from the resulting value, ignoring any higher ones.

A: It's wrong. The mistaken idea is that char is 8 bit.
It's also pointless. The presumed problem is that m can have more bits than char (true) so that "unnecessary" bits are masked off.
But m is sign-extended. That means the sign bit is copied to the higher bits. Now, when we're comparing x==0 we're checking whether all bits are zero, and with x & 0xff we're comparing if the lower 8 bits are zero. If the 8th bit of x is copied to all higher positions (by sign extension), then the two conditions are the same regardless of whether the copied bit was 0 or 1.


text:
Q: Compiling + linking a custom OS with Cygwin gcc: Unrecognized emulation mode: elf_i386 I have a bootloader written in assembly (boot.s) and a kernel written in c (kernel.c).
I also have some other files such as: linker.ld and grub.cfg but I have no clue how to use them...
My Problem:
If i run:
gcc -g -m32 -c -ffreestanding -o kernel.o kernel.c -lgcc
ld -melf_i386 -Tlinker.ld -nostdlib --nmagic -o kernel.elf kernel.o
objcopy -O binary kernel.elf kernel.bin

i get the Error: ld: Unrecognized emulation mode: elf_i386
PS.: Im using Windows 10 Pro 32Bit and also have VirtualBox installed (If this helps) for gcc im using cygwin.
kernel.c
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>

static const uint8_t COLOR_BLACK = 0;
static const uint8_t COLOR_BLUE = 1;
static const uint8_t COLOR_GREEN = 2;
static const uint8_t COLOR_CYAN = 3;
static const uint8_t COLOR_RED = 4;
static const uint8_t COLOR_MAGENTA = 5;
static const uint8_t COLOR_BROWN = 6;
static const uint8_t COLOR_LIGHT_GREY = 7;
static const uint8_t COLOR_DARK_GREY = 8;
static const uint8_t COLOR_LIGHT_BLUE = 9;
static const uint8_t COLOR_LIGHT_GREEN = 10;
static const uint8_t COLOR_LIGHT_CYAN = 11;
static const uint8_t COLOR_LIGHT_RED = 12;
static const uint8_t COLOR_LIGHT_MAGENTA = 13;
static const uint8_t COLOR_LIGHT_BROWN = 14;
static const uint8_t COLOR_WHITE = 15;

uint8_t make_color(uint8_t fg, uint8_t bg)
{
    return fg | bg << 4;
}

uint16_t make_vgaentry(char c, uint8_t color)
{
    uint16_t c16 = c;
    uint16_t color16 = color;
    return c16 | color16 << 8;
}

size_t strlen(const char* str)
{
    size_t ret = 0;
    while ( str[ret] != 0 )
        ret++;
    return ret;
}

static const size_t VGA_WIDTH = 80;
static const size_t VGA_HEIGHT = 24;

size_t terminal_row;
size_t terminal_column;
uint8_t terminal_color;
uint16_t* terminal_buffer;

void terminal_initialize()
{
    terminal_row = 0;
    terminal_column = 0;
    terminal_color = make_color(COLOR_LIGHT_GREY, COLOR_BLACK);
    terminal_buffer = (uint16_t*) 0xB8000;
    for ( size_t y = 0; y < VGA_HEIGHT; y++ )
        for ( size_t x = 0; x < VGA_WIDTH; x++ )
        {
            const size_t index = y * VGA_WIDTH + x;
            terminal_buffer[index] = make_vgaentry(' ', terminal_color);
        }
}

void terminal_setcolor(uint8_t color)
{
    terminal_color = color;
}

void terminal_putentryat(char c, uint8_t color, size_t x, size_t y)
{
    const size_t index = y * VGA_WIDTH + x;
    terminal_buffer[index] = make_vgaentry(c, color);
}

void terminal_putchar(char c)
{
    terminal_putentryat(c, terminal_color, terminal_column, terminal_row);
    if ( ++terminal_column == VGA_WIDTH )
    {
        terminal_column = 0;
        if ( ++terminal_row == VGA_HEIGHT )
        {
            terminal_row = 0;
        }
    }
}

void terminal_writestring(const char* data)
{
    size_t datalen = strlen(data);
    for ( size_t i = 0; i < datalen; i++ )
        terminal_putchar(data[i]);
}

void kmain()
{
    terminal_initialize();
    terminal_writestring("Starting mOS...\n\n");
    terminal_writestring("mOS Version alpha1 - Created by milan44\n");
}

boot.s
.set ALIGN,    1<<0
.set MEMINFO,  1<<1
.set FLAGS,    ALIGN | MEMINFO
.set MAGIC,    0x1BADB002
.set CHECKSUM, -(MAGIC + FLAGS)

.section .multiboot
.align 4
.long MAGIC
.long FLAGS
.long CHECKSUM

.section .bootstrap_stack
stack_bottom:
.skip 16384
stack_top:

.section .text
.global _start
_start:
    movl $stack_top, %esp

    call kmain

    cli
hang:
    hlt
    jmp hang

linker.ld
ENTRY(_start)

SECTIONS
{
    . = 1M;

    .text BLOCK(4K) : ALIGN(4K)
    {
        *(.multiboot)
        *(.text)
    }

    .rodata BLOCK(4K) : ALIGN(4K)
    {
        *(.rodata)
    }

    .data BLOCK(4K) : ALIGN(4K)
    {
        *(.data)
    }

    .bss BLOCK(4K) : ALIGN(4K)
    {
        *(COMMON)
        *(.bss)
        *(.bootstrap_stack)
    }
}

A: Use a Cross Compiler Tool Chain
I highly recommend you build a C cross compiler and tool chain that generates ELF objects. This breaks you from the nuances of host compilers and linkers. Default Cygwin GCC and LD have a number of differences from a generic ELF compiler and linker. The OSDev Wiki include information for building a cross compiler for Cygwin. I haven't personally built a cross compiler on Cygwin so can't say if the instructions are accurate for that environment.
Cygwin generates Windows PE32(32-bit) and PE32+ (64-bit) objects. This is why -melf_i386 doesn't work. Building an ELF cross compiler would allow you to use -melf_i386. You will need an ELF cross compiler in your case because the multiboot loaders require an ELF executable which Cywgin's GCC and LD can't generate.
Had you been using 64-bit Windows 10 you would have been able to do this under Windows Subsystem for Linux (WSL) since Ubuntu's GCC and LD will generate ELF exectuables by default.

If you don't want to use a Cross Compiler
Although pushing you to have a cross compiler is the right way to do this, there is a way to make it work with Cygwin.
Cygwin GCC (like other 32-bit Windows Compilers) will prepend an _ to the non-static functions that will be of globally visible scope. That means your kmain is actually _kmain.  Modify your boot.s to do call _kmain instead of call kmain. This applies to any C functions you call from assembly. Any functions you make available in assembly files to be accessed in C code will have to have an _ underscore added to them as well.
One big difference with Windows program is that the section names may be a bit different. rodata in Cygwin can be .rdata*. There may be a number of sections starting with rdata. You will have to account for this in your linker script:
ENTRY(_start)

SECTIONS
{
    . = 1M;

    .text BLOCK(4K) : ALIGN(4K)
    {
        *(.multiboot)
        *(.text*)
    }

    .rodata BLOCK(4K) : ALIGN(4K)
    {
        *(.rodata)
        *(.rdata*)    /* IMPORTANT - Windows uses rdata */
    }

    .data BLOCK(4K) : ALIGN(4K)
    {
        *(.data)
    }

    .bss BLOCK(4K) : ALIGN(4K)
    {
        *(COMMON)
        *(.bss)
        *(.bootstrap_stack)
    }
}

This makes a big difference given that if you don't properly deal with the rdata sections they may be placed before your Multiboot header possiblly causing it to be not seen by a Multiboot loader like GRUB. So this change is very important.
Your commands to build a file usable by a Multiboot compliant bootloader (or QEMU's -kernel option) is incorrect. Since LD can't output an ELF file you will need to have OBJCOPY to convert a PE32 executable to a 32-bit ELF executable. Your OBJCOPY command does the wrong thing. You convert to a binary file. Unfortunately the way your Multiboot header is written that doesn't work.
The commands to assemble and link your code, and to produce the final kernel.elf file that can be use by a Multiboot loader could look like:
gcc -g -m32 -c -ffreestanding -o kernel.o kernel.c
gcc -g -m32 -c -ffreestanding -o boot.o boot.s
ld -mi386pe -Tlinker.ld -nostdlib --nmagic -o kernel.pe kernel.o boot.o
objcopy -O elf32-i386 kernel.pe kernel.elf

Making a Bootable ISO/CD with Grub and your Kernel
This procedure is a bit tricky only in that Cygwin doesn't come with a grub-legacy package. To make a bootable ISO/CD image with Grub on it, you need to acquire the file stage2_eltorito. You can download a copy from this project.
You will have to run the Cygwin installer and install the package genisoimage
In the previous sections we built a file called kernel.elf. Now we have the components needed to build an ISO/CD image.
From the directory where you built kernel.elf we need to create a series of sub-directories. That can be done with:
mkdir -p iso/boot/grub

You need to copy the stage2_eltorito file and place it in iso/boot/grub directory. You will need to create the file menu.lst in iso/boot/grub as well.
iso/boot/grub/menu.lst :
default 0
timeout 0

title MyOS
# kernel ELF file.
kernel /boot/kernel.elf

The process above only has to be done once. This is enough to create a basic bootable ISO with Grub and our kernel.
Now the process of building the kernel, copying the file into the iso directory and generating the ISO/CD image can be done like this:
gcc -g -m32 -c -ffreestanding -o kernel.o kernel.c
gcc -g -m32 -c -ffreestanding -o boot.o boot.s
ld -mi386pe -Tlinker.ld -nostdlib --nmagic -o kernel.pe kernel.o boot.o
objcopy -O elf32-i386 kernel.pe kernel.elf
cp kernel.elf iso/boot
genisoimage -R -b boot/grub/stage2_eltorito -no-emul-boot \
    -boot-load-size 4 -boot-info-table -o myos.iso iso

The genisoimage command creates an ISO/CD called myos.iso . You can change the name to whatever you please by replacing myos.iso on the genisoimage command line with the name you prefer.
The myos.iso should be bootable from most hardware, virtual machines, and emulators as a simple CD image. When run with your kernel it should appear something like:

The image above is what I saw when I booted the ISO/CD in QEMU with the command:
qemu-system-i386 -cdrom myos.iso

You should see similar if you run it in VirtualBox as well.


text:
Q: How to link main.cpp, a.h and a.cpp? Forgive me if I'm doing something incredibly stupid, but I have 3 files:
main.cpp:
#include "a.h"

int main()
{
    return 0;
}

a.cpp:
#include "a.h"
//x = 0;

a.h:
#ifndef A_H
#define A_H

int x;

#endif // A_H

But it doesn't compile. I think x is being defined twice. What am I doing wrong? How to fix it?

A: x is defined in two translation units (because the defining header is included by two cpp files). Define it only once:
main.cpp:
#include "a.h"

int main()
{
    return 0;
}

a.cpp:
#include "a.h"
int x = 0;

a.h:
#ifndef A_H
#define A_H

extern int x;

#endif // A_H

A: You need to declare int x in a.cpp and extern int x in a.h.


text:
Q: Comparing GenericTypeDefinition of interfaces Simple code that I expect List<int>'s GenericTypeDefinition to contain a generic interface of ICollection<>. Yet I can't derive an acceptable type from List<int> which allows me to compare them properly.
using System;
using System.Collections.Generic;
using System.Linq;

public class Test
{
    public static void Main()
    {
        var a = typeof(List<int>);
        var b = typeof(ICollection<>);

        var r1 = a.GetGenericTypeDefinition().GetInterfaces();
        foreach (var x in r1)
        {
            Console.WriteLine(x);
        }
        Console.WriteLine();
        Console.WriteLine(b);
        Console.WriteLine();
        Console.WriteLine(r1.Any(x => x == b));
    }
}

Output
System.Collections.Generic.IEnumerable`1[T]
System.Collections.Generic.IReadOnlyList`1[T]
System.Collections.Generic.IReadOnlyCollection`1[T]
System.Collections.IEnumerable
System.Collections.Generic.IList`1[T]
System.Collections.Generic.ICollection`1[T]
System.Collections.ICollection
System.Collections.IList

System.Collections.Generic.ICollection`1[T]

False

I would have expected that r1 contained a type that was equal to b.
EDIT
Fixed, Jon Skeet gave me the right insight into what was happening.
using System;
using System.Collections.Generic;
using System.Linq;

public class Test
{
    public static void Main()
    {
        var a = typeof(List<int>);
        var b = typeof(ICollection<>);

        var r1 = a.GetInterfaces()
            .Where(x => x.IsGenericType)
            .Select(x => x.GetGenericTypeDefinition());

        foreach (var x in r1)
        {
            Console.WriteLine(x);
        }

        Console.WriteLine();
        Console.WriteLine(b);
        Console.WriteLine();
        Console.WriteLine(r1.Contains(b));

    }
}

Output
System.Collections.Generic.IEnumerable`1[T]
System.Collections.Generic.IReadOnlyList`1[T]
System.Collections.Generic.IReadOnlyCollection`1[T]
System.Collections.Generic.ICollection`1[T]
System.Collections.Generic.IList`1[T]

System.Collections.Generic.ICollection`1[T]

True

A: No, the generic type definition will refer to ICollection<T> specifically, where T is the type parameter for the IList<T>.
Imagine you had something like:
public class Foo<T1, T2> : IEnumerable<T1>, IComparable<T2>

The generic type definition contains all that information - it "knows" that it's specifically IEnumerable<T1> and IComparable<T2>, not IEnumerable<T2> and IComparable<T1> for example.
You can fix the check by getting the generic type definition for each of the interfaces implemented by the type:
Console.WriteLine(r1.Any(x => x.IsGenericType &&
                              x.GetGenericTypeDefinition()  == b));

A: Try below line..
 Console.WriteLine(r1.Any(x => x.Name == b.Name));

Instead of
Console.WriteLine(r1.Any(x => x == b));


text:
Q: How to change string output from basic color to random colors I am new to assembly and am trying to make a program that outputs the user string backwords. I also want to make it so anytime the user types something, it will output the reversed string in random colors. But I have no idea how to do this. Is it possible for someone to do this code for me or tell me where to modify the code? Thank you so much in advance.
INCLUDE Irvine32.inc

.data

stringInput byte 50 dup(0)

promptIn byte "Enter the string: ",0

.code

swaping MACRO a,b

XOR a,b

XOR b,a

XOR a,b

ENDM

strlen proc

push ebp

mov ebp, esp

push ebx

mov eax, 0

mov ebx, [ebp+8]

Counter:

cmp byte ptr [ebx + eax], 0

je Done

inc eax

jmp counter

Done:

pop ebx

mov esp, ebp

pop ebp

ret TYPE ebp

strlen endp

strrev proc

Push ebp

MOV ebp, esp

Push eax

Push ebx

Push ecx

Mov ebx, [ebp+8]

Mov ecx, [ebp+8]

push ebx

call strlen

ADD ecx, eax

SHR al,1

count: CMP al,0

JZ finished

MOV ah, byte PTR [ebx]

swaping ah, byte ptr [ecx-1]

MOV BYTE PTR [ebx], ah

INC ebx

DEC ecx

DEC al

JMP count

finished: POP ecx

POP ebx

POP eax

MOV esp, ebp

POP ebp

RET (TYPE ebp)*4

strrev ENDP

main proc

mov eax, 0

mov edx, offset promptIn

call writeString

mov edx, offset stringInput

mov ecx, 51

call readString

push edx

call strrev

call crlf

call writestring

call crlf

exit

main endp

end main


text:
Q: Python @app.route("/custom"), return page doesn't work I am using Pythonanywhere.com with Flask. I am using this code for the html:

        <form class="main_page" method="POST" action=".">

Aankomende Games Quiz

                    Jouw naam:
                    <input type="text" name="naam">

                    Welke game heeft géén multiplayer?
                    <select name="geen_multiplayer">
                        <option selected disabled>Maak een keuze</option>
                        <option>Red Dead Redemption 2</option>
                        <option>Destiny 2</option>
                        <option>South Park: The Fractured but Whole</option>
                        <option>FIFA 18</option>
                    </select>

                    Welke game is door Rockstar Games gemaakt?
                    <select name="gemaakt_rockstar">
                        <option selected disabled>Maak een keuze</option>
                        <option>Star Wars Battlefront II</option>
                        <option>The Elder Scrolls Online: Morrowind</option>
                        <option>Destiny 2</option>
                        <option>Red Dead Redemption 2</option>
                    </select>

                    Wat is géén shooter?
                    <select name="geen_shooter">
                        <option selected disabled>Maak een keuze</option>
                        <option>Red Dead Redemption 2</option>
                        <option>Destiny 2</option>
                        <option>Call of Duty: WWII</option>
                        <option>Star Wars Battlefront II</option>
                    </select>

                    Welke game wordt alleen op PS4 uitgebracht?
                    <select name="alleen_ps4">
                        <option selected disabled>Maak een keuze</option>
                        <option>MotoGP™17</option>
                        <option>Crash Bandicoot N. Sane Trilogy</option>
                        <option>Star Wars Battlefront II</option>
                        <option>Destiny 2</option>
                    </select>

                    Welke game heeft splitscreen?
                    <select name="heeft_splitscreen">
                        <option selected disabled>Maak een keuze</option>
                        <option>MotoGP™17</option>
                        <option>Dirt 4</option>
                        <option>Red Dead Redemption 2</option>
                        <option>The Elder Scrolls Online: Morrowind</option>
                    </select>

                    Welke game is door Codemasters gemaakt?
                    <select name="gemaakt_codemasters">
                        <option selected disabled>Maak een keuze</option>
                        <option>South Park: The Fractured but Whole</option>
                        <option>FIFA 18</option>
                        <option>Crash Bandicoot N. Sane Trilogy</option>
                        <option>Dirt 4</option>
                    </select>

                    Welke game speelt zich af in het wilde westen?
                    <select name="wilde_westen">
                        <option selected disabled>Maak een keuze</option>
                        <option>Dirt 4</option>
                        <option>Call of Duty: WWII</option>
                        <option>Red Dead Redemption 2</option>
                        <option>The Elder Scrolls Online: Morrowind</option>
                    </select>

                    Welke game heeft 'Sports' niét als genre
                    <select name="niet_sports">
                        <option selected disabled>Maak een keuze</option>
                        <option>FIFA 18</option>
                        <option>Dirt 4</option>
                        <option>Destiny 2</option>
                        <option>MotoGP™17</option>
                    </select>

                    Welke game is voor 18 jaar en ouder?
                    <select name="voor_18">
                        <option selected disabled>Maak een keuze</option>
                        <option>The Elder Scrolls Online: Morrowind</option>
                        <option>Star Wars Battlefront II</option>
                        <option>Destiny 2</option>
                        <option>Crash Bandicoot N. Sane Trilogy</option>
                    </select>

                    Welke game komt in september 2017 uit?
                    <select name="september_2017">
                        <option selected disabled>Maak een keuze</option>
                        <option>Red Dead Redemption 2</option>
                        <option>South Park: The Fractured but Whole</option>
                        <option>Call of Duty: WWII</option>
                        <option>FIFA 18</option>
                    </select>

                    <button type="submit" name="invoer" value="">Invoeren</button>

        </form>

I am using this python code:
@app.route("/quiz", methods=["GET", "POST"])

def quiz():

    if request.method == "GET":
        return render_template("quiz_page.html")

    score = 0

    if (request.form["geen_multiplayer"] == "South Park: The Fractured but Whole"):
        score += 1

    if (request.form["gemaakt_rockstar"] == "Red Dead Redemption 2"):
        score += 1

    if (request.form["geen_shooter"] == "Red Dead Redemption 2"):
        score += 1

    if (request.form["alleen_ps4"] == "Crash Bandicoot N. Sane Trilogy"):
        score += 1

    if (request.form["heeft_splitscreen"] == "MotoGP™17"):
        score += 1

    if (request.form["gemaakt_codemasters"] == "Dirt 4"):
        score += 1

    if (request.form["wilde_westen"] == "Red Dead Redemption 2"):
        score += 1

    if (request.form["niet_sports"] == "Destiny 2"):
        score += 1

    if (request.form["voor_18"] == "The Elder Scrolls Online: Morrowind"):
        score += 1

    if (request.form["september_2017"] == "FIFA 18"):
        score += 1

    if request.method == "POST":
        return render_template("quiz_page.html")

When I click on the submit button, it returns "Bad Request
The browser (or proxy) sent a request that this server could not understand." So this happends when I click on the button on my domainname.com/quiz. I noticed that when I clicked on the button, the "/quiz" behind the domain name dissapeard. What am I doing wrong?

A: Change action="." to action="#".
action="." causes the request to be sent to one level above the current url which is why /quiz disappear.


text:
Q: JavaScript/Nodejs : ajax POST request not passing object to backend I'm attempting to post a JSON object to my server, but when I console log req.body it shows an empty object. Here's my code:
var submitRecipe = () => {

    let recipe = {alias: null, description: null, instructions: null};
    recipe.alias = document.getElementById('alias').value;
    recipe.description = document.getElementById('description').value;
    recipe.instruction = document.getElementById('instructions').value;

    postRequest("/createrecipe", recipe, (xhr) => {
        console.log("Hello!" + JSON.parse(xhr.responseText));
    })
};
var postRequest = (url, data, callback = undefined) => {

    xhr.onreadystatechange = () => {
        //Call a function when the state changes.
        if(xhr.readyState == 4 && xhr.status == 200) {
            console.log("testing");
            return callback(200 , xhr.responseText);
        }else{
            return callback(400, xhr.responseText);
        }
    }
    xhr.open('POST', url)
    xhr.send(data);
}

Node
createRecipe = function(req, res){

    console.log(req.body);
}

I'm using express to transfer the server information, and I am using bodyParser.json(). From there, I just call the controller with the following:
express
var express = require("express");
var bodyParser = require("body-parser");

var server = express();

var recipeController = require("./controllers/recipeController");

server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: true}));

server.post("/createrecipe", recipeController.createRecipe);

The createRecipe function just console logs the information, but as stated before, req.body is an empty object. All tips are appreciated.

A: XHR expects your data to be encoded or packed in whatever way you expect it to be send unlike other library wrappers like jQuery or Angular Ajax wrapper functions.
Alsobody-parsermiddleware was not identifying the Content-type and was not activating for the required request.
Simply JSON.stringify your json data
data = JSON.stringify(data);

and add the application/json MIME type as xhr's content-type header.
xhr.setRequestHeader("content-type", "application/json");

Also, If you want to use url-encoded do the encoding of your data before attaching and add the corresponding header content type.
My full test code (for reference purposes):
Server (testServer.js):
var express = require("express");
var bodyParser = require("body-parser");

var server = express();

server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: true}));

server.post("/createrecipe", function(req, res){
    console.log(req.body);
    var resp = {server: "hello world", dataReceived: req.body};
    res.json(resp);
});

server.get("/", function(req, res){
    res.sendFile(__dirname + "/testClient.html");
})

server.listen(3000, function(){
    console.log("Server running");
})

Client (testClient.html):
<input type="text" id="alias" value="a">
<input type="text" id="description" value="b">
<input type="text" id="instructions" value="c">
<button onclick="submitRecipe()"> TEST</button>
<script>
var submitRecipe = () => {

    let recipe = {alias: null, description: null, instructions: null};
    recipe.alias = document.getElementById('alias').value;
    recipe.description = document.getElementById('description').value;
    recipe.instructions = document.getElementById('instructions').value;

    postRequest("/createrecipe", recipe, (status, xhr) => {
        var data = (JSON.parse(xhr.responseText));
        console.log(data.dataReceived);
    })
};
var postRequest = (url, dataObj, callback = undefined) => {
    //--------------Added line--------------------
    var data = JSON.stringify(dataObj);
    //--------------Added line--------------------
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = () => {
        //Call a function when the state changes.
        if(xhr.readyState == 4 && xhr.status == 200) {
            return callback(200 , xhr);
        }else if(xhr.status == 400){
            return callback(400, xhr);
        }
    }
    xhr.open('POST', url)
    //--------------Added line--------------------
    xhr.setRequestHeader("content-type", "application/json");
    //--------------Added line--------------------
    xhr.send(data);

}
</script>


text:
Q: Input source for Logitech 750 keyboard not working as expected I have a Logitech 750 and until now I have been able to properly use it as my keyboard in my Macbook (same layout).
All of sudden (or at least I don't know what I have changed), for the key that I was able to type a back tick (`), now I can type this: §.
In my input source, I have US selected and I see this:

How can I use the backtick where § is located?
The physical layout of my Logitech 750 is this one:


text:
Q: How to find which control raised an event, while in so called event? Visual C# I am writing a C# program that takes in a bunch of parameters and does some transformations of data points and then draws them to screen.
On one of my forms I have a bunch of TextBoxes that I would all like to perform the same KeyPress event. Before I would just do a switch statement that would just take in the sender for the KeyPress event and compare it to all the TextBoxes. That method just doesn't seem very efficient to me as now I have 20+ TextBoxes.
What I would like to do is find which TextBox on the form sent the KeyPress event and get further information from that TextBox (IE its Text value, etc.). This would save me the trouble of having to do a huge switch with sender to see what TextBox it was equal too. But I have just been having the hardest time doing so.
I have looked through the System.Windows.Controls & System.Windows.Forms classes to see if I could find anything that would help me. What I was looking for was something that would let me see which control had focus. Maybe that was what I should have been searching for? I have also looked at what I can do with sender in the KeyPress event to see if I could figure out what TextBox raised the event and still no luck.
At this point I feel like I have confused myself more. Any help would be much appreciated.

A: There is a convention that the first parameter passed to the event handler is the control that sent the event, so you can cast it like this:
void myTextBox_EventHandler(object sender, EventArgs args)
{
    TextBox textBox = (TextBox)sender;
    ...
}

A: The sender approach should be fine. You can, however, cast:
TextBox txt = (TextBox) sender; // or "as" if you aren't sure.
                                // you can also just cast to Control for most
                                // common properties
// perhaps look at txt.Name, txt.Text, or txt.Tag

Note that there are scenarios where the sender isn't what you think, but this is the rarity, and mainly relates to event forwarding via code like:
public event EventHandler AcceptClick {
    add { acceptButton.Click += value;}
    remove { acceptButton.Click -= value;}
}

here, sender will be acceptButton, which you can't see. Normally this isn't a problem, though.

A: You can use tag property of control to differentiate multiple textboxes.
For this, First, you need to assign tag property for each textbox and in event method, you can access  tag property. suppose you want to assign multiple parameters then create a separate class with parameters as properties and assign the object of the class to tag property of textbox.
Hope, It helps

A: I think Marc and GraemeF's answers are great, but I'm going to add an answer (anyway) as an example of a slightly alternative approach. This approach reflects my "path of slack" :) programming philosophy. Note this example requires Linq.
My first goal would be to have a single variable of type TextBox available to hold the current active TextBox (or if that needed to be accessed from outside the Form, I'd make it accessible via a public property) : if I can get that, then I have an easy way to access the current active TextBox's current Text : just use the .Text property (no conversion required).
    //on the Form where the TextBoxes are : make into a Public Property
    // if you need to access this from outside the Form holding the TextBoxes
    // a Form-level variable
    private TextBox theActiveTB;

Then, on the Form, I'd make the Form Load event build a collection of the TextBoxes for me : and make sure they subscribed to the same 'KeyPress and 'Enter events :
   // on the Form where the TextBoxes are : a Form-level variable
    private List<TextBox> tbList;

    // build the list of TextBoxes and set the same 'Enter event for each of them
    // note the assumption that every TextBox on the Form is going to be handled
    // in exactly the same way : probably better to isolate them in a Panel in case
    // you have other TextBoxes for other purposes ; then you'd just use the same
    // code here to enumerate all the TextBoxes in the Panel
    private void Form1_Load(object sender, EventArgs e)
    {
         tbList =
         (
            from TextBox theTB in this.Controls.OfType<TextBox>()
            select theTB
         ).ToList();

         foreach (TextBox theTB in tbList)
         {
            theTB.KeyPress +=new KeyPressEventHandler(theTB_KeyPress);
            theTB.Enter +=new EventHandler(theTB_Enter);
         }
    }

    // so here's what the Enter event might look like :
    private void theTB_Enter(object sender, EventArgs e)
    {
        theActiveTB = (TextBox)sender;

        // reality check ...
        // Console.WriteLine("entering : " + theActiveTB.Name);
    }

    // so here's what the KeyPress event might look like :
    private void theTB_KeyPress(object sender, KeyPressEventArgs e)
    {
        // do what you need to do here

        // access the Text in the Textbox via 'theActiveTB

        // reality check
        // Console.WriteLine(theActiveTB.Name + " : " + e.KeyChar );
    }

Why bother to make List<TextBox> using Linq ? You could, after all, just loop through the Form (or a Panel, or whatever container) and check each control's type, and then, if it's a TextBox, assign the Event Handlers right on the spot. The reason why I chose to make a generic list of the TextBoxes is because : when I have a collection with a special shared identity, or purpose, or set of behaviors, it's often the case that I will want to do other things with its content as a "set" or "group."


text:
Q: Make a class depends on its own ports instead of injecting dependency interfaces I just have an idea about dependency management in Spring IOC environment that seems to be better than the typical approach, but I am not sure because I can't find any references or example out there that talk about it, though the idea is very simple. I will explain the idea comparing to the typical approach. Please help me see if the idea is valid and if it has some formal theoretical name or are there some books talking already about it.
Typical Approach
In typical Spring application, when class A has class B as a dependency, we would inject the interface of B into A. For example, let's say we have class ProductManager that depends on ProductService.
class ProductManager {
   private ProductService productService;
   public ProductManager(ProductService productService) {
      this.productService = productService;
   }

   public void foo() {
      ... // some logic
      // somewhere in this method
      String result = productService.bar1();
      ... // some logic
   }
}

interface ProductService {
   String bar1();
   void bar2();
}

class ProductServiceImpl implements ProductService {
   @Override
   public String bar1() { ... }

   @Override
   public void bar2() { ... }
}

@Configuration
public class ApplicationConfiguration {
   @Bean
   public ProductManager productManager(ProductService productService) {
      return new ProductManager(productService);
   }
}

@RunWith(SpringRunner.class)
@SpringBootTest
class ProductManagerTest {
   @Autowire
   private ProductManager classUnderTest;

   @MockBean
   private ProductService productService;

   public void testFoo() {
      when(productSerivce.bar1()).thenReturn("bar");
      // do the test
   }
}

In this approach, ProductManager directly depends on ProductService. It has some problems which I will explain in the last section.
My Idea
I want to make it that ProductManager and ProductService do not know each other completely. The ProductManager depends only on its own defined Port. We plug the ProductService#bar1() to the port in configuration class.
interface ProductManagerPort {
   String baz();
}

class ProductManager {
   private ProductManagerPort port;

   public ProductManager(ProductManagerPort port) {
      this.port = port;
   }

   public void foo() {
      ... // some logic
      // somewhere in this method
      String result = port.baz();
      ... // some logic
   }
}

// Notice we don't use interface anymore
class ProductService {
   public String bar1() { ... }
   public void bar2() { ... }
}

@Configuration
public class ApplicationConfiguration {
   @Bean
   public ProductManager productManager(ProductService productService) {
      // in more complex case, we can create an adaptor class instead of using a lambda
      return new ProductManager(() -> productService.bar1());
   }
}

class ProductManagerTest {
   @Test
   public void testFoo() {
      ProductManager classUnderTest = new ProductManager(this::mockBaz);
      // do the test
   }

   private String mockBaz() { return "bar"; }
}

The Differents
To explain why I come up with the idea, I will compare the two approaches in the following topics.
Dependency Decoupling
In the typical approach, ProductManager is tightly depending on ProductService. Even though the dependency is bound via an interface, it only helps to hide the implementation detail of ProductService from ProductManager, but the ProductManager still have to concern about how the ProductService works in general.
Suppose you assign 2 developers to write code for each class: John writes ProductManager and Marry takes care ProductService. both persons will have to agree on the interface before doing their own work. John has some assumption in mind how ProductService#bar1() works, and write the method ProductManager#foo() based on that assumption. When Marry found something new during implementation that affects the agreement, she notifies John. Then John has to rework to make his code support the new assumption.
In My Idea approach, ProductManager and ProductService are completely independent. ProductManager declares its own Port. John can keep his assumption in the Port without having to fear that Mary will find some problem during implementing the ProductService. Mary, in turn, does not have to fear that her changes of design will bother anyone.
To integrate ProductService into ProductManager, we can create ProductServiceToProductManagerPortAdaptor that implements ProductManagerPort. If there is some mismatch in John's and Mary's assumption, it will be adjusted in the adaptor. In the example code above, I use lambda for the adaptor to exemplify possible simplification of the adaptor.
Single Implementation Anti-Pattern
The typical approach requires us to make the ProductService an interface and put the implementation in ProductServiceImpl. We are forced to do so to avoid wiring dependencies with concrete classes.
In My Idea approach, we are free to that limitation because the wiring is done through the class's own ports. We can write a straight forward code using concrete class and use interfaces where a true abstraction is really needed.
Interface Segregation Principle

The interface-segregation principle (ISP) states that no client should be forced to depend on methods it does not use.

Wiring component to component is easy to violate this principle. For example, ProductManager only depends on ProductService#bar1() but it is forced to know about ProductService#bar2() just because they are packed within the same component. You have to read the implementation detail to be sure if ProductService#bar2() is used in ProductManager or not.
When writing test, in the typical approach, you are forced to use a mock framework to avoid unnecessary mocking unused method ProductService#bar2(). While in My Idea Approach, you are required to mock only as much as the ProductManager actually needs without using the mock framework.
Question
I want to encourage my team to use this pattern in our next project but I cannot find any references to support my idea. I am afraid that someone has already considered this idea and reject it due to some limitation.
Please share if you have experience using this pattern in your application or if there is a standard concept about it. I have looked into Hexagonal Architecture but it seems to be more about system architecture than a coding pattern.

A: You should manage dependencies not fight them.
If class A needs to send an email and class B can send emails then class A will depend on class B and no amount of abstraction and redirection is going to make it that relationship go away.
When you write:

In My Idea approach, ProductManager and ProductService are completely independent.

I'm afraid you are mistaken. The relationship is still there you just hide it behind some porcelain.
You will find that building and maintaining those ports and adapters will not be any simpler than the "traditional" solution so you will try to come up with a system that automatically generates those adapters. Maybe even utilize some domain specific language to define the ports? Congratulations, you just invented interfaces. What you will end up with will be a prime example of the inner platform effect:

The inner-platform effect is the tendency of software architects to create a system so customizable as to become a replica, and often a poor replica, of the software development platform they are using. This is generally inefficient and such systems are often considered to be examples of an anti-pattern.

A: You are not using objects right.
The "conventional" design you start from is to use a bunch of "Managers" and "Services" which basically have procedures that work with some data from somewhere else. In this typical design, there is no real (i.e. conceptual, i.e. business-relevant) relation between these things, they are purely technical. So you are not using dependencies at all for anything valuable, therefore (understandably) you want to hide them completely.
Better designs use dependencies as part of their story. Dependencies are just another tool to tell the reader some business-relevant information, some connection or relation to help her better understand the software. In these designs, there is obviously no hurry to hide these dependencies, since they are part of the application.
So the problem is you are not using dependencies, you are just forced to have them. Which leads to your technical solution to hide them even more.

A: As far as the mechanism of dependency injection goes, both of these are pretty much the same thing; the only difference is how you go about it. That is, both of these are a form of dependency injection. But there is (likely) an important difference in semantics.
Generally, you want to combine dependency injection with dependency inversion. There, you have two components1 and an abstraction of some sort that both of the other two components depend on. (BTW, the abstraction doesn't have to be represented by an interface). This abstraction needs to represent some generalization of different possible dependency implementations. There is no general prescription on how to design this abstraction, as this depends on your understanding of the domain (and it may change as the application evolves). But it needs to be based on relatively stable concepts (it should change less often then the components that depend on it), and it needs to be workable (an abstraction is no good if it's not technically feasible - e.g., results in unacceptably poor performance).
Now, the key difference between the two cases that you've shown is how this abstraction is conceptualized. In the first case, the expectation is that different dependency implementations can all be effectively expressed & realized through the bar1() and bar2() methods. In the second case, the abstraction supposes that dependencies can be effectively expressed & realized through the baz() method. That's the important bit; weather you use inheritance or a wrapper is a secondary concern.
Which one of the abstractions is better depends entirely on which one of these two works better for the domain you are trying to model (and within the context of the tools and languages you are using). That's something you and your team will have to think about. You may also want to postpone that decision until your understanding of this part of the domain (and of the change patterns in this part of the code) becomes greater; you don't want to lock yourself into a wrong abstraction.
A side note: In the first approach, the ProductService interface, at least at first glance, doesn't really provide an abstraction of ProductServiceImpl, as both of them have an identical set of methods. I suspect that's part of the reason you dislike it. But consider this; if ProductServiceImpl is your only example of a ProductService implementation so far, you may be at a point where you lack enough information to come up with a useful abstraction, so you may want to wait to see how the code will change (and if it'll change at all), and what will other implementations look like. On the other hand, it could turn out that the all the changes will be happening behind the ProductServiceImpl class (so, in its own internal details, or in its own dependencies), i.e., the software will grow "behind" that class. In that case, you may even decide to scrap the ProductService interface entirely, and use the ProductServiceImpl class as the abstraction instead.

1 I use the term here in a general, loose sense - just some piece of code

A: The structure of your two approaches is practically the same, but you approached the design process differently – and that difference matters.
In the first solution, the interface describes the full capabilities of the "default" implementation.  That makes it look like an almost useless indirection. As you've correctly noted this also makes it easy to accidentally violate the ISP and to add unwanted coupling to the system. However, such approaches have fairly good tooling support.
In your second solution, your interfaces were guided by how the object will be used. That's how it should be and how OOP works best. It's not quite how Java works best, so you have to introduce adapter classes. In your cases these adapters are invisible through the use of lambdas or method references, but that only works for single-method interfaces.
Usage-guided interface definitions occur in a number of places:

*

*You've already noticed that in the Hexagonal/Onion/Clean Architecture, dependencies flow inward so that interfaces are defined at the point of use, not the point of implementation. While this is an architecture-level pattern, the same principles hold on a small scale.

*Programming by Wishful Thinking is a small-scale variant of this: we solve a problem top-down by breaking it down into smaller, easier parts. Let's write the code as if a solution to that smaller problem already exists. Later, somehow implement the required functionality. If we need some object, we can first write the interface to denote what we require from the object, and later see how that object can be provided. This technique was popularized by SICP.

*TDD also ties in to this. A TDD practicioner iteratively tries to write the simplest possible test that could fail, write the simplest possible code to make it pass, then refactors the solution into a suitable design. At each of these steps, expressing the solution in terms of a yet-to-be-implemented interface can often be the simplest approach. Which I can then flesh out during the next TDD iteration.

*The object system of some languages is well-suited for adapting existing types to new interfaces, e.g. Go or Rust.
Such interfaces or design approaches help keep each piece of code small and simple, and keep interfaces relevant to the context in which they are used. However, such approaches tend to produce many more objects that each do very little actual work. This can also hurt maintainability, especially in a language like Java where supporting declarations typically get their own file. It is also possible to go overboard and declare an interface for every single method that you would call. That is no longer useful.
So it is probably best to apply such strategies when:

*

*dependencies cross domain or system boundaries (e.g. interfaces that represent external systems, functionality provided by third party libraries)

*the using code needs to be exceptionally clear and simple (usage-guided interfaces make the using code more self-documenting)

*the software has detailed tests (e.g. is developed with TDD, and wants to mock other functions)

*the code is not written in Java or C#

But most importantly:

*

*the code doesn't want to hard-code certain decisions (e.g. so that business rules can be swapped via the strategy pattern)


text:
Q: When Using Reverse Proxy, Backend Server Does 301 Back to The Proxy Server or Changes URL As a learning exercise in order to understand more about reverse proxy. I decided to use my private cloud server as a reverse proxy server and try to bypass corporate firewall (when I am at work) to allow myself to access gmail.
I have came up with the following Proxy configuration (please dont mind the square brackets):

SSLProxyEngine on
ProxyRequests Off
ProxyVia Off

[Proxy *]
    Order deny,allow
    Deny from all
    Allow from xxx.xxx.xxx
[/Proxy]

ProxyPreserveHost On

ProxyPass /qqq https://www.google.com/accounts/ServiceLogin?service=mail
ProxyPassReverse /qqq https://www.google.com/accounts/ServiceLogin?service=mail

ProxyPass /qqqqq http://mail.google.com/mail
ProxyPassReverse /qqqqq http://mail.google.com/mail

The outcomes of the above configuration as follows:

*

*When I navigate to myserver.com/qqq, the backend server (Google) simply changes URL and redirects me to google.com. Although I have "ProxyPreserveHost On"

*When I navigate to myserver.com/qqqqq, Google does 301 back to my proxy server, which redirects me again to Google and I end up in the loop.
I have read a number of posts here at stackoverflow, but could not extract any helpful info from them:
https://stackoverflow.com/questions/5277107/apache-reverse-proxy-changes-url
https://stackoverflow.com/questions/6385638/proxy-pass-follow-redirect-on-server
https://stackoverflow.com/questions/1144286/how-to-tell-apache-in-reverse-proxy-mode-to-intercept-or-trap-302-responses-fro
My questions here are:

*

*How to prevent Google from changing the URL, and instead transparently display content

*What can I do in order not end up in 301 loop between my proxy server and Google
If you think I have missed/omitted/misunderstand something, please do let me know
Thank you,
Alex

A: I have done that by the following code. You can try it...
    ProxyPreserveHost On
    <Proxy *>
            AddDefaultCharset off
            Order deny,allow
            Deny from all
          Allow from all
    </Proxy>

            ProxyPass /google http://www.google.com/
            ProxyHTMLURLMap http://www.google.com /google

    <Location /google>
            ProxyPassReverse /
            ProxyHTMLInterp On
            ProxyHTMLURLMap  /      /google
            RequestHeader    unset  Accept-Encoding
    </Location>


text:
Q: i2c over 1m shielded multi-core cable with 0.5A load at the same cable is possible? I'm using an I2c sensor (Time of flight, VL6180X breakout board with voltage regulator onboard) at the end of a 1M cable. An arduino controls it.
As I2c was not meant to be far away from the PCB and the MCU, I used a 6 core shielded wire to connect the sensor to the Arduino Leonardo. I grounded one side of the cable mesh to the sensor. I'm using an USB 8 pin plug to connect the cable to the arduino control box.
I also added two 10k Pull-ups from the SDA and SCL lines to 5V, close to the MCU.
But, in the same cable I use the two other cores for powering a 2W led, at 500-600mA max. (4 cores for the sensor - 5V, GND, SCL and SDA and 2 for the led driver).
The sensor works normally when the led is off, 100% of the times. But when I turn the led on, mostly when the pwm duty is close to med-max, it makes the sensor fail almost everytime.
Am I adding capacitance to the whole cable when the led is on? Why does it happen? I measured the 5V VIN to the sensor with a multimeter and it doesn't change with the led on or off.
Is there a workaround for it? Having I2c working normally in a cable where 0.5A load is applied? Is there another type of cable that would make it work?
I could make the cables separate, but it wouldn't be the best option for me, for I would need more connectors, and a bulkier setup.
Edit: For testing purposes, I separated the cables. One for the led and another one for the sensor, on the same connector. It works much better, but it's not a solution I'd like to use for good....
Thanks for reading!

A: The best solution to a problem like this would be to put a small MCU at the sensor, and then send back something like a UART data stream via a differential transmitter.  Something like an ATtiny would work well.
Additionally, it would be good to do the PWM switching at the location of the LEDs, and to bypass the supply for that with plenty of capacitance there, to try to keep the current through the supply lines mostly DC - eg, the long wires would carry the average current while the current pulses would stay local.  You could also consider using a higher voltage supply, and using a regulator at the point of load and/or putting your LEDs in series to reduce the overall current.
In terms of what you can do right now, in addition to the suggestions in comments, you could try much smaller pull-up resistor.  10K is marginally too large for even an on-board situation.  Hopefully you are benefitting from pullups already on the Arduino.  If you look with a scope, too weak a pull-up would mean an RC character to the signal rise, while too strong a pull-up would mean that the signal never really gets to ground.
Its unclear if your application would permit it, but if you could disable the LEDs while taking a reading that would likely solve your problem.

A: A distinct idea: Graham Stevenson's question about the I2C clock rate prompted a thought that it's not the clock rate which makes the system suspectible to induced noise, but rather the chance that a current spike happens during the I2C signalling itself.
So what if you were to coordinate the I2C and your 490 Hz PWM, such that the PWM on/off transitions happened during word-gaps in the I2C when you could actively clamp the I2C lines low, while the actual I2C signalling was confined to the portion of the PWM where the LED was steady powered or especially unpowered?  When the I2C lines are low they are in a lower impedance state and less susceptible to coupling: at an extreme, you could even use an additional line to activate some FET's to clamp the lines to ground at the device end, or split the processor's view of I2C into a set of sense lines and a lines to drive far-end FET's.
It would be tricky, you'd probably need to bit-bang both (or at least implement at low level), but the timing can probably work unless you need nearly a full range of duty cycle variation.
And it raises questions about if the pulsing of your LEDs needs to be something specific to get the desired sensor result (though it's never been clear how your LED actually interacts with the sensor)
I don't like this as much as engineering a more sound system, but it might be a software hack that could save your current hardware.

A: I did a similar implementation a year ago. I used a VEML030 light sensor that was on a PCB and communicated with another PCB through I2C. On my experience, you would need level shifters to amplify the voltage on the cables, if not, you are risking the operation of the sensor. True that if you turn off the LED, the sensor will read properly, however, when you power on the LED you are taking energy from the power line. Using level shifters is not trivial, I used SN74LVC1T45DBVR from Texas Instruments, though when you connect it to your PCB, be very careful with how you route everything.
I have seen that other people have suggested other solutions so, I would recommend you considering this option as one of the last bullets.
Hope this help!

A: Thanks for all feedback,  ideas and support! They were really helpful!
I manage to solve the problem by:
Lowering the values of the pull-ups on the SDA and SLC close to the arduino (470 ohms each)
And I used a thin Cat6A cable - less than 4mm diameter - (with 28 awg twisted pairs inside and no shielding), instead of my previous 6 core wire with shielding.
I wired one twisted pair with the SDA and 5V, another pair with SCL and GND, another pair with both wires together to the led cathode and the last pair with both wires together to the Led´s anode.
With this cable, at 1.5m length, the sensor works flawlessly everytime, at all led pwm levels. Never hangs anymore!
I know there are many other options, but in my case, for this cable length I need, this was a really simple workaround, that proved to work perfectly in my setup!
Thanks for all the help and input!
Regards!


text:
Q: JavaFX Button hover scaling I started learning about JavaFX effects, but I can't seem to find any relevant information on button scalling on hover.
I'm guessing it could be done by either JavaFX code with the Scale transition or with CSS.
In CSS I have found a way to grow button's on mouse hover, but I don't know how to implement it to JavaFX.
Here is the grow hover effect in pure css code for html:
.hvr-grow {
    display: inline-block;
    vertical-align: middle;
    transform: translateZ(0);
    box-shadow: 0 0 1px rgba(0, 0, 0, 0);
    backface-visibility: hidden;
    -moz-osx-font-smoothing: grayscale;
    transition-duration: 0.3s;
    transition-property: transform;
}

.hvr-grow:hover,
.hvr-grow:focus,
.hvr-grow:active {
    transform: scale(1.1);
}

How could I transform that css code into fx-css code? Is css code the same as fx-css code? (meaning do i just have to put "-fx-[buttonID]"in front and thats it?)
If there is any information reguarding CSS animations and stuff like that for JavaFX css, I would like to know.
Could you please help me with this task?

A: Node has a -fx-scale-x, -fx-scale-y and an -fx-scale-z CSS property, which have the default value of 1. Node is the superclass of Button therefore these properties are inherited.
To apply it to any button on hover in your application, add this css selectpr to your stylesheet:
.button:hover {
    -fx-scale-x: 1.1;
    -fx-scale-y: 1.1;
    -fx-scale-z: 1.1;
}

To see what CSS styles the different controls have you can check the linked guide and you can also check the default stylesheet for JavaFX 8 (modena.css).
To learn about how to style your application with CSS, you can check this tutorial.


text:
Q: SwiftUI: EnvironmentObject loads only the first time in my current project I work with an EnvironmentObject but I have a very strange bug, maybe someone can help.
First the code:
Model:
class Daten: ObservableObject{

@Published var intervallInsgesamt: Double = UserDefaults.standard.double(forKey: Keys.intervallInsgesamt){
    didSet{
        UserDefaults.standard.set(self.intervallInsgesamt, forKey: Keys.intervallInsgesamt)
    }
}

@Published var pauseInsgesamt: Double = UserDefaults.standard.double(forKey: Keys.pauseInsgesamt ){
    didSet{
        UserDefaults.standard.set(self.pauseInsgesamt, forKey: Keys.pauseInsgesamt)
    }
}
...
}

First View:
@EnvironmentObject var daten: Daten

var body: some View {
    NavigationView{
        GeometryReader { geometry in
            VStack{
                ScrollView(showsIndicators: false){
                    ...
                }

               //IMPORTANT START
                NavigationLink(destination: TrainingView().environmentObject(daten)){ //!!!
                    Text("Start")
                        .styleButton()
                 }
               //IMPORTANT END
            }
        }
    }

}

Second View (TraingsView):
struct TrainingView: View {

@EnvironmentObject var daten: Daten

@State private var isRunning = false
@State private var to: CGFloat = 0

@State private var insgesamt = 0.0
@State private var minuten = 0
@State private var sekunden = 0
@State private var durchgang = 1

@State private var timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

@State private var zähl = 0

@State private var color = Color.red

@State private var übung = 0

@State private var momentaneÜbung = ""
@State private var nächsteÜbung = ""

@State private var teilerTo = 0

var body: some View {
    ZStack{
        VStack{
            ...
            }
            HStack(spacing: 50){

                Button(action:{

                    isRunning = true
                    Sounds.playSounds(soundfile: "sound.wav")

                }) {
                    Text("Start")
                }

                Button(action:{
                    isRunning = false
                    Sounds.playSounds(soundfile: "sound.wav")
                }) {
                    Text("Stop")
                }
            }
        }
    }
    .onReceive(timer) { _ in
        if isRunning{
            if insgesamt > 0{
                print("1. Durchgang: \(durchgang), Übung: \(übung), momenaten: \(momentaneÜbung), nächste: \(nächsteÜbung)")
                insgesamt -= 1.0
                minuten = Int(insgesamt/60)
                sekunden = Int(insgesamt.truncatingRemainder(dividingBy: 60))
                zähl += 1

                withAnimation(.default) {
                    to = CGFloat(Double(zähl) / Double(teilerTo))

                }
            }else{
                ... stuff that should run when insgesamt <= 0 but is not important for my problem
            }
        }
    }
    .onAppear {
        teilerTo = Int(daten.intervallInsgesamt)
        print("Teiler: \(teilerTo)")
        insgesamt = daten.intervallInsgesamt

        minuten = Int(insgesamt/60)
        sekunden = Int(insgesamt.truncatingRemainder(dividingBy: 60))

        if !daten.übungen.isEmpty{
            momentaneÜbung = daten.übungen[übung].name
            if übung+1 < daten.übungen.count{
                nächsteÜbung = "Pause"
            }else{
                nächsteÜbung = "Nächster Durchgang"
            }
        }
    }
}
}

NOW THE PROBLEM:
When I start the app, set the different times, go to the TrainingsView, everything works fine. Then I go back to the first View(change the times or not, it doesn't matter) and go back to the TraingsView. Now nothing works! It doesn't find the EnvironmentObject anymore. I don't know why because the first time it did. Does somebody know why?
(An other problem I is, that print() doesn't work. I can't see the things that should print out. I don't know if that is important...)
Thanks in advance!

A: In your root view, you should declare your object as an observable object:
@ObservableObject var daten = Daten()

then you should use a .environmentObject() modifier on top of your first View:
// pass the daten object that was declared as observable object here
.environmentObject(daten)

from now on, on other descendant views, you can get your model by declaring it as an environment object:
@EnvironmentObject var daten: Daten
// gives you the same old daten model


text:
Q: I am new to Celery and Django,How can i store all results from the celery response in a single text file here im calling the celery task, and after compleating every task i want to store the results in a single text file
views.py
urls=["https//:.....com,https//:.....com,etc.."]
for i in urls:
   r=process.delay(i)

tasks.py
@app.task
def process(url):
    r = requests.get(url, allow_redirects=True)
    return r


text:
Q: Promise's reject is throwing Error in angular 2/4 I have defined a async validator function like this.
static shouldBeUnique(control: AbstractControl): Promise<ValidationErrors | null> {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if (control.value === 'some_text') {
                resolve({ shouldBeUnique: true });
            }
            reject(null);
        }, 2000);
    });
}

Its throwing below error (may be on reject)

Cannot read property 'ngOriginalError' of null

How to get rid of this error?
Thanks
Plnkr : https://embed.plnkr.co/VSHXGKiMGUWEhy8neyXU/

A: Generally if you reject a Promise you should better reject it with an Error
reject(new Error('User is not vikash (whatever descriptive message what went wrong)'));

EDIT Since you are trying to implement async validator you need to resolve a Promise with null not to reject it to indicate validation was ok.
static shouldBeUnique(control: AbstractControl): Promise<ValidationErrors | null> {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if (control.value === 'some_text') {
              resolve({ shouldBeUnique: true });
            } else {
              resolve(null); // resolve
            }
        }, 2000);
    });
}

Demo

A: In angular form validation, when the field is valid you should pass null. It's a little bit confusing but that's how it goes. You can read more about here and here.
I'm attaching plunker I've forked from you. I've only changed that null will be return when the filed is valid, and ValidationErrors when it's invalid.
Also to be more clear about the filed validation status Iv'e added to the html the errors object of the filed.
https://embed.plnkr.co/t0gniM/
@Component({
  selector: 'my-app',
  template: `

Hello {{name}}

      Please open developer console to chek the exception

      Type anything and click anywhere other than the textbox

      <form [formGroup]="formObj">
      <input type="text" id="username" formControlName="username" placeholder="Username" />
      {{formObj.controls['username'].errors|json}}

      </form>

  `,
})
export class App {
  name:string;
  shouldBeUnique(control:AbstractControl):Promise<ValidationErrors|null>{
    return new Promise((resolve, reject) => {
            setTimeout(() => {
                if (control.value === 'vikash') {
                  console.log('---matched--');
                    resolve(null);
                }else{
                resolve({ shouldBeUnique: true });
                }
            }, 1000);
        });
  }

  formObj = new FormGroup({
    username: new FormControl('', [
      Validators.required
    ], [
      this.shouldBeUnique
      ])
  });
  constructor() {
    this.name = `Angular! v${VERSION.full}`
  }

}

@NgModule({
  imports: [ BrowserModule,FormsModule,ReactiveFormsModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

Hopes it's help's.


text:
Q: Cannot connect to internet in release build apk I've created an Android application. I tested it in debug mode and works completely fine. But when I tried to release build the apk, it's not connecting to the internet at all. I used Google sign in and firebase.
AndroidManifest.xml
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.REAL_GET_TASKS " />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    ....

build.gradle
plugins {
    id 'com.android.application'
    id 'com.google.gms.google-services'
}

android {
    compileSdkVersion 31
    buildToolsVersion "31.0.0"

    defaultConfig {
        applicationId "com.defenderstudio.geeksjob"
        minSdkVersion 21
        targetSdkVersion 31
        versionCode 1
        versionName '1.0'
        multiDexEnabled true

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            shrinkResources false
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    buildFeatures {
        viewBinding true
    }
}
...

A: If you were you not able to login using Google sign in, you have to put your Release SHA1 (from Google play or firbase console and your apk generated) key in google firebase console and then download and replace Json File and you'll be able to login.


text:
Q: Preordering on a set I am given a definition which states that a 'preodering on a set is a relation that is reflexive and transitive.'
Show that a relation $\leq$ defined on $\mathbb{C}$ by $z_1 \leq z_2$ iff $|z_1| = |z_2|$ is a preodering on $\mathbb{C}$.
I must be missing something here because clearly for any $z \in \mathbb{C}$ we have $|z| = |z|$ and if $z_1 \leq z_2$ and $z_2 \leq z_3$ then that implies that $|z_1| = |z_2| = |z_3|$ which means that $z_1 \leq z_3$.  I must be reading the question wrong surely.  What am I missing?

A: Yup, as presented you have verified both reflexivity and transitivity for $\le$ on $\Bbb C$, and they follow from the same properties as in the equality relation itself. Sometimes it really just is that simple!

Mostly posting this so this question can be finally considered to have an answer and thus be removed from the unanswered queue. Made it Community Wiki since I have nothing much of substance to add.


text:
Q: What is alternative of attributes? Attributes helps us use class dependant values instead of instances and they help us carry some values without strong relation with our classes. But i found some restrictions on attributes. We are not able to change these values on runtime. So i am looking a way to use similiar concept to attributes as we have seen many example configure classes by fluent apis instead of attributes. Do you know such a ready library ? What is an alternative to use attribute concept for avoiding attribute restrictions ?

A: Actually in some cases you can tweak attributes at runtime - for example via TypeDescriptor - but this only affects ComponentModel usage, not reflection usage. You can also write the attribute itself to do things like resx lookup for i18n purposes.
But other options:

*

*maybe a static property, perhaps following a naming convention

*a separate object model that talks about the types - a meta-model, so to speak

*a configuration file or similar

Any will work; which is best depends on exactly what you have in mind.

A: A good replacement of attribute in a plug-in architecture could be using smart naming conventions.

A: Perhaps I am missing something, but can't you just add properties with a public setter to your custom attributes? I just tried this on a implementation where I use attributes, and I am able to change this property at runtime without any problems.
Which values do you want to change?


text:
Q: How to get weekly count in SQL? I'm trying to get the count by each week from a table to show Weekly report, which shows the total per week number (Week 1, Week 2 .... Week54).
This is my SQL:
 select DATEPART(week, CAST([submissionDate] as date)) as [weeks],sum(qty)
 as [Zen Usage] FROM [zicucfbu_MIS].[dbo].[FileUploadDetails] where [route]
 like 'ZENIT_WS%' and DATEPART(week, CAST([submissionDate] as date)) =
 DATEPART(week, cast(GETDATE() as date))
 and year(CAST([submissionDate] as date)) = year(cast(GETDATE() as date))
 group by DATEPART(week, CAST([submissionDate] as date))  order by weeks

But with this SQL I'm only getting the current week total count. I  would appreciate most if anyone could help me to show the total count by each week.
Thanks in advance.

A: Your where clause has a condition that explicitly limits the results to the current week:
DATEPART(week, CAST([submissionDate] as date)) =
DATEPART(week, cast(GETDATE() as date))

Just remove it and you should be fine.


text:
Q: Modbus floating point conversion I am using Arduino modbus library for measuring string current using hall sensor.Here library downloaded.Modbus library .I have sensor data in floating value & the library store the value in integer format.
question :

*

*how can save the sensor value into integer format

*How can assign user defined address. start address like 4000h instead of 0000H

code
#include <avr/wdt.h>
#include"glob.h"
//#define ID   1
void Device_ID_Reading()
{
  for(row=0;row<9;row++)
  {
    digitalWrite(SO_enable,array1[row][0]);
    digitalWrite(S1_enable,array1[row][1]);
    digitalWrite(S2_enable,array1[row][2]);
    Status_Out[row]=digitalRead(Read_IDstatus);
    Device_ID =1*Status_Out[0]+2*Status_Out[1]+4*Status_Out[2]+8*Status_Out[3]+16*Status_Out[4]+32*Status_Out[5]+64*Status_Out[6]+128*Status_Out[7];
    Serial.print("Device_ID");
    Serial.print(row);
    Serial.print(":\t");
    Serial.println(Device_ID);

  }
}

int8_t state = 0;
Modbus slave(Device_ID, 0, 0);
unsigned long tempus;
// data array for modbus network sharing
uint16_t au16data[30];

void Take_Reading()
{
  for(row=0;row<9;row++)
  {
    //  int k=(8*array[row][0]+4*array[row][1]+2*array[row][2]+1*array[row][3]);
    //   digitalWrite(Enablepin,array[row][0]);
    digitalWrite(SO_enable,array1[row][1]);
    digitalWrite(S1_enable,array1[row][2]);
    digitalWrite(S2_enable,array1[row][3]);
    //delay(100);
    Sensor_Value0=analogRead(A0);
    Sensor_Value1=analogRead(A5);
    Mux1_array[row]=(Sensor_Value0 * ARDUINO_ANALOG_SCALING);
    Mux2_array[row]=(Sensor_Value1 * ARDUINO_ANALOG_SCALING);

    Current_Value1[row]=  (Mux1_array[row]*35.1428571429)-87.6571428571;
    Current_Value2[row]=  (Mux2_array[row]*35.1428571429)-87.6571428571;
    Current_Value3[row]=(Mux3_array[row]*35.1428571429)-87.6571428571;

  }
}
void setup()
{
  wdt_enable(WDTO_8S);
  slave.begin( 9600 );
  tempus = millis() + 100;
  pinMode(3,OUTPUT);
  pinMode(SO_enable, OUTPUT) ;// pin can enable/disable using digital IO 7 of arduino
  pinMode(S1_enable, OUTPUT) ;// pin can enable/disable using digital IO 6 of arduino
  pinMode(S2_enable, OUTPUT) ;// pin can enable/disable using digital IO 5 of arduino
  //  pinMode(Enablepin, OUTPUT) ;// pin can enable/disable using digital IO 4 of arduino
  pinMode(A0, INPUT) ;
  pinMode(A1, INPUT) ;
  pinMode(A2,INPUT);
  //  Serial.begin(9600);
}
void loop()
{
  digitalWrite(3,HIGH);
  // wdt_reset();
  Take_Reading();
  Device_ID_Reading();
  state = slave.poll( au16data,30 );
  if (state > 4) {
    tempus = millis() + 50;
    digitalWrite(13, HIGH);
  }
  if (millis() > tempus) digitalWrite(13, LOW );

  Modbus_call();

}
void Modbus_call()
{

  /*reading of coil where i can succefully read value*/
  au16data[1]=(int)(100*Current_Value1[0]);
  au16data[2]=(int)(100*Current_Value1[1]);
  au16data[3]=(int)(100*Current_Value1[3]);
  au16data[4]=(int)(100*Current_Value1[4]);
  au16data[5]=(int)(100*Current_Value1[5]);
  au16data[6]=(int)(100*Current_Value1[6]);
  au16data[7]=(int)(100*Current_Value1[7]);
  au16data[8]=(int)(100*Current_Value1[8]);
  au16data[9]=(int)(100*Current_Value2[0]);
  au16data[10]=(int)(100*Current_Value2[1]);
  au16data[11]=(int)(100*Current_Value2[2]);
  au16data[12]=(int)(100*Current_Value2[3]);
  au16data[16]=(int)(100*Current_Value2[4]);
  au16data[17]=(int)(100*Current_Value2[5]);
  au16data[18]=(int)(100*Current_Value2[6]);
  au16data[19]=(int)(100*Current_Value2[7]);
  uint16_t calcCRC( au16data[15]);
  au16data[13] = slave.getInCnt();
  au16data[14] = slave.getOutCnt();
  au16data[15] = slave.getErrCnt();

}

Is there any other library where i can use the floating point directly.

A: Modbus as a protocol does not directly support floats. However you can put float data into adjacent registers. Use type punning to put the float data into your registers and pull it out on the other side.
union Pun {float f; uint32_t u;};

void encodeFloat(uint16_t *regs, float x)
{
    union Pun pun;

    pun.f = x;
    regs[0] = (pun.u >> 16) & 0xFFFFU;
    regs[1] = pun.u & 0xFFFFU;
}

float decodeFloat(const uint16_t *regs)
{
    union Pun pun;

    pun.u = ((uint32_t)regs[0] << 16) | regs[1];
    return pun.f;
}

You would use it like so:
void Modbus_call()
{
    /*reading of coil where i can succefully read value*/
    encodeFloat(&au16data[ 0],  Current_Value1[0]);
    encodeFloat(&au16data[ 2],  Current_Value1[1]);
    encodeFloat(&au16data[ 4],  Current_Value1[2]);
    /* And so on... */
}


text:
Q: Django fields styling (e.g. for help_text argument position , or validation messages or ...) in template I have this code:
class CreateListing(forms.Form):
image = forms.CharField(label="Image URL", required=False, max_length=16384, help_text="Optional")

Result is

But is not nice UI arrangement. I want be same the↓:

In Form Fields Documentation:

The help_textarguments is wrapped in <span> element which is placed after <br> one.
How setting Help_text final UI be same I want above? With grace arrangement.
Or this code:
bidStarting = forms.IntegerField(
        label="Starting Bid",
        min_value=1,
        widget=forms.TextInput(attrs={'placeholder': 'Dollars'})
    )

After enter number 0 in bidStarting Integer field (In template form and submitting the form), running this code:
return render(request, "auctions/index.html",{
                'form': CreateListing(request.POST)
            })

The result is:

But hard defining the validation message is generated for each element?
Or I prefer some addition styling same as border-color Red.
How can styling Django form elements in validation or initialization?


text:
Q: Building VTK in Visual studio 2008 Windows 64 bit I built and configured VTK using cmake in visual studio according to the link below:

http://vtkblog.blogspot.com/2007/04/install-build-vtk-from-source-in-visual.html

But I get linking errors as below:

1>vtk_minimal.obj : error LNK2019: unresolved external symbol "public: static class vtkInteractorStyleTrackballCamera * __cdecl vtkInteractorStyleTrackballCamera::New(void)" (?New@vtkInteractorStyleTrackballCamera@@SAPAV1@XZ) referenced in function _main
  1>vtk_minimal.obj : error LNK2019: unresolved external symbol "public: void __thiscall vtkRenderWindowInteractor::SetRenderWindow(class vtkRenderWindow *)" (?SetRenderWindow@vtkRenderWindowInteractor@@QAEXPAVvtkRenderWindow@@@Z) referenced in function _main
  1>vtk_minimal.obj : error LNK2019: unresolved external symbol "public: static class vtkRenderWindowInteractor * __cdecl vtkRenderWindowInteractor::New(void)" (?New@vtkRenderWindowInteractor@@SAPAV1@XZ) referenced in function _main
  1>vtk_minimal.obj : error LNK2019: unresolved external symbol "public: static class vtkRenderWindow * __cdecl vtkRenderWindow::New(void)" (?New@vtkRenderWindow@@SAPAV1@XZ) referenced in function _main
  1>vtk_minimal.obj : error LNK2019: unresolved external symbol "public: void __thiscall vtkRenderer::AddActor(class vtkProp *)" (?AddActor@vtkRenderer@@QAEXPAVvtkProp@@@Z) referenced in function _main
  1>vtk_minimal.obj : error LNK2019: unresolved external symbol "public: static class vtkRenderer * __cdecl vtkRenderer::New(void)" (?New@vtkRenderer@@SAPAV1@XZ) referenced in function _main
  1>vtk_minimal.obj : error LNK2019: unresolved external symbol "public: static class vtkActor * __cdecl vtkActor::New(void)" (?New@vtkActor@@SAPAV1@XZ) referenced in function _main
  1>vtk_minimal.obj : error LNK2019: unresolved external symbol "public: static class vtkPolyDataMapper * __cdecl vtkPolyDataMapper::New(void)" (?New@vtkPolyDataMapper@@SAPAV1@XZ) referenced in function _main
  1>vtk_minimal.obj : error LNK2019: unresolved external symbol "public: static class vtkConeSource * __cdecl vtkConeSource::New(void)" (?New@vtkConeSource@@SAPAV1@XZ) referenced in function _main
  1>vtk_minimal.obj : error LNK2019: unresolved external symbol "public: class vtkAlgorithmOutput * __thiscall vtkAlgorithm::GetOutputPort(int)" (?GetOutputPort@vtkAlgorithm@@QAEPAVvtkAlgorithmOutput@@H@Z) referenced in function "public: class vtkAlgorithmOutput * __thiscall vtkAlgorithm::GetOutputPort(void)" (?GetOutputPort@vtkAlgorithm@@QAEPAVvtkAlgorithmOutput@@XZ)
  1>Debug/../bin/vtk_minimal_d.exe : fatal error LNK1120: 10 unresolved externals

Please help me.

A: You should be using CMake to configure VTK before building. Here are some instructions: http://www.vtk.org/Wiki/VTK/Building/Windows


text:
Q: Why ChainSaw cannot display logger name? I am using the latest ChainSaw developer snapshot
I'm trying get logs from a file with logs in pattern :
[%d] [%t] [%c] [%m]%n

and I don't know why it doesn't work - whole log is read as %m. When I use pattern without %c every log is displayed correctly.

A: Try this pattern instead
[TIMESTAMP] [THREAD] [LOGGER] [MESSAGE]
(I'm assuming your logs also have those "[]", otherwise remove them)


text:
Q: How to implement infinite ajax scroll pagination in Laravel I want to use infinite ajax scroll pagination for my blog, but unfortunately I do not have a result!? I still get this error message : server not responding...
Below the code used.
controller:
$posts =Post::paginate(5);
if ($request->ajax()) {
    $view = view('user.list.data', compact('posts'))->render();
    return response()->json(['html'=>$view]);
}
return view('user.list.page', compact('posts');

view:

Liste poste

        @include('user.list.data')

view data:
@foreach($posts as $post)

        {{ $post->title }}

{{ $post->description }}

        <button class="btn btn-success">Read More</button>

@endforeach


text:
Q: Node: How to read file? I want to read a file and return is as a response to GET request
This is what I am doing
app.get('/', function (request, response) {
    fs.readFileSync('./index.html', 'utf8', function (err, data) {
        if (err) {
            return 'some issue on reading file';
        }
        var buffer = new Buffer(data, 'utf8');
        console.log(buffer.toString());
        response.send(buffer.toString());
    });
});

index.html is
hello world!

When I load page localhost:5000, the page spins and nothing happens, what is I am doing incorrect here
I am newbie to Node.

A: You're using the synchronous version of the readFile method. If that's what you intended, don't pass it a callback. It returns a string (if you pass an encoding):
app.get('/', function (request, response) {
    response.send(fs.readFileSync('./index.html', 'utf8'));
});

Alternatively (and generally more appropriately) you can use the asynchronous method (and get rid of the encoding, since you appear to be expecting a Buffer):
app.get('/', function (request, response) {
    fs.readFile('./index.html', { encoding: 'utf8' }, function (err, data) {
        // In here, `data` is a string containing the contents of the file
    });
});


text:
Q: C Programming Struct #include<stdio.h>
#include<string.h>

struct s {
    char ch[20];
    float a;
};

int main()
{
    struct s p[10];
    int i;
    for(i=0;i<10;i++)
    {
        scanf("%s%f",p[i].ch,p[i].a);
    }
}

What is wrong with this code?
Its giving runtime error.
What's the problem?

A: Most of the errors come from this line.
scanf("%s%f",p[i].ch,p[i].a);

You should use the address of p[i].a, and also restrict the numbers of chars to write in p[i].ch.
scanf( "%19s%f", p[i].ch, &p[i].a );

A: I haven't touched C code for a while but shouldn't it be something like
scanf("%s%f",p[i].ch,&(p[i].a));

(You have to give the memory address of the variables to the scanf function.)

A: I think the problem is in the p[i].a parameter;
use &p[i].a instead.

A: At the line:
scanf("%s%f", p[i].ch, p[i].a);

You are using p[i].a as a float* (pointer), while it's a float. You're invoking undefined behavior. You probably wanted to do it like this:
scanf("%s%f", p[i].ch, &p[i].a);

A: Change your code like this:
#include <stdio.h>
#include <string.h>
struct s {
    char ch[20];
    float a;
};

int main(){
    struct s p[10];
    int i;
    for(i=0;i<10;i++){
        scanf("%s%f",p[i].ch, &p[i].a);
    }
}

Note that variable a is a float type; you need to pass its memory address when using scanf.


text:
Q: how to make column width responsive to content Jsgrid I am JSGrid to show data in a grid. however jsgrid column is not adjusting to the values. I don't want the fixed width of columns and if i dont give width the data overflow the next column as shown
.
i found work around solution mentioned here auto adjust columns
 .jsgrid-header-cell,
    .jsgrid-cell {
                    overflow: hidden;
                }

but the problem is i dont want to hide the overflow data in the header and somehow wrap the values in data columns . any solution or workaround

A: I don't need to do anything, just set width: "100%" in your datagrid and the width in the columns you should use the minimum value you want, using the minimum value jsgrid will do the horizontal scroll automaticly.
See this image


text:
Q: Measurable extended real valued functions. I am trying to prove the following lemma:
An extended real valued function $f:X\to\bar{\mathbb{R}}$ is measurable if and only if the sets $A = \{x\in X\mid f(x) = +\infty\}, B = \{x\in X\mid f(x) = -\infty\}\in \mathbb{F}$ and the function $g(x) = \begin{cases}f(x)& x\notin A\cup B\\0 & x\in A\cup B\end{cases}$ is measurable. $\mathbb{F}$ is the $\sigma$-algebra on $X$.
Assuming that $f$ is measurable, I'm trying to show that the function $g$ is measurable. I'm thinking that $\forall\alpha\in\mathbb{R}$ the set $\{x\in X\mid g(x) > \alpha\} = \{x\in X\mid f(x)>\alpha\}\cup\{x\in X\mid 0>\alpha\}$. Now since $f$ is measurable, then the set $\{x\in X\mid f(x)>\alpha\}\in\mathbb{F}$.
For the set $C = \{x\in X\mid 0>\alpha\}$ if $\alpha < 0$ then $C = X\in\mathbb{F}$ and if $\alpha\geq 0$, then $C = \emptyset\in\mathbb{F}$
I'm not sure if this proof is correct, especially writing out $\{x\in X\mid g(x) > \alpha\} = \{x\in X\mid f(x)>\alpha\}\cup\{x\in X\mid 0>\alpha\}$. I would love if someone could clarify this for me

A: Maybe you forgot intersecting $A\cup B$ or $(A\cup B)^C$ in the calculation of $\{x\in X\mid g(x) > \alpha\}$.
Take the following sketch as example:

for any $\alpha \in \Bbb{R}$, as from the figure, the set $\{x \in X| -\infty < f(x) \leq \alpha\}$ is disjoint with $\{x \in X| g(x) > \alpha\}$.

Here is the original answer with a proof:
Since here the definition of measurable function is not given in the question, I am following the definition in Real Analysis by H.L. Royden, 4th.
Take any $\alpha$ in $\Bbb{R}$, denote $U_\alpha$ to be the set $\{x\in X\mid g(x) > \alpha\}$.
If $\alpha \geq 0$, then for any $x \in A \cup B$, $x \notin U_\alpha$ for $g(x) = 0 \leq \alpha$. And for any $x \notin A \cup B$, $x \in U_\alpha$ if and only if $f(x) > \alpha$.
Similarly, if $\alpha < 0$, then for any $x \in A \cup B$, $x \in U_\alpha$ for $g(x) = 0 > \alpha$. And for any $x \notin A \cup B$, $x \in U_\alpha$ if and only if $f(x) > \alpha$.
Hence:
$$
U_\alpha = \{x\in X\mid g(x) > \alpha\} \\
\begin{aligned}
=\begin{cases}
(A\cup B)^C \cap \{x\in X\mid f(x)>\alpha\} \text{ if $\alpha \geq 0$}\\
((A\cup B)^C \cap \{x\in X\mid f(x)>\alpha\}) \cup (A \cup B)\text{ if $\alpha < 0$}
\end{cases}
\end{aligned}
$$
For both cases, $U_\alpha$ is measurable. Hence $g$ is measurable.


text:
Q: Git Tower - how to overwrite master with a previous commit Somehow I've created a git mess where the latest commit is wrong but the previous commit is right.
I tried to revert to the previous commit in Tower (right click) but that created some kind of merge which didn't fix the issue and now things look messier than ever.
I've created a new branch from the commit I know to be correct and have tested it and everything looks great.
Question: is it possible to simply replace the master branch with this new branch?
I obviously want to avoid creating an even bigger mess so would like to know if this is possible or if this is even a good idea? All the search results look scary as I don't fully understand what they're going to do.
For the life of me I don't know what went wrong as the repo only contained one branch.

A: OK, so if you you'd like to replace master with a commit in Tower/Github, here's what worked for me:

*

*Click on the master branch and find the commit you're going to use to replace master

*Right click and choose "Create new branch from ..."

*Name the branch 'master-new'

*Publish this branch to github

*Login to github and click the settings button to administer the repo

*Make sure 'Options' is selected in the left subnav

*Under the repository name field, find the 'Defaualt' dropdown menu

*Change the default to 'master-new'

*We do this becauase you can't delete the branch Github uses as the default

*Back in Tower, 'master-new' should be checked out - if not, checkout master-new

*Delete your local 'master' branch

*Now go to the remotes/origin area in the left sidebar

*Right click the master branch and choose 'Delete origin/master'

*Right click your local 'master-new' branch and rename it to 'master'

*Do the exact same thing to the remote 'master-new' branch

Now you've migrated master over to a new branch locally and on the remote.


text:
Q: Search for a file by filename and file contents in unix I would like to search for a file in a unix/unix-like system that has a filename matching a regular expression and has contents matching a regular expression.
For example, find files recursively in the path /hello/there such that the filename matches "*.gradle" and file contents matches "*module*".
This search should bring back a hit for a file named build.gradle with the contents sometext-module-somemoretext
Thanks in advance, an example would be helpful.
EDIT: what I have already tried has been requested
I have tried: find /hello/there -type f -name '*.gradle' -exec grep 'module' {} \; which gives me something close to the answer I am after, but doesn't print the file name.

A: from @anubhava 's answer
find /hello/there -type f -name '*.gradle' -exec grep -l 'module' {} \;
I was missing the -l flag for grep that displays the file name and path.


text:
Q: Does deleting superclass call destructor of it's fields? I have the following code:
template<class T>
class List<T> {
    class Node{
        T data;
        Node * next;
        ...
    };
    Node * head;
    ...
    ~List() {/*iterating through all nodes and deleting them*/}
    ...
};

template<class T>
class Tree<T> {
    class Node {
        Node * next;
        ...
        T key;
        List<int> internal_list;
    };
    destroy_node(Node * x) { delete x; }
};

Does destroy_node(Node * x) call the destructor of the List<T> class or do I need to call it explicitly?

A: Yes.
A class's destructor always calls all sub-objects' destructors, in the reverse order of construction.
It does not matter whether they are virtual base-classes, normal base-classes or member sub-objects for the above to hold.
(virtual base-classes are always constructed and destructed directly by the most-derived-class, never by a base-class.
And if you destroy an object through a pointer neither of most-derive type, nor possessing a virtual dtor, all bets are off anyway.)

A: When a class is destructed, the destructors of all its non-pointer members are called automatically. For any members that are pointers to objects dynamically allocated with new/new[], or memory blocks dynamically allocated with a memory function, you have to free them yourself using delete/delete[] or appropriate memory function, respectively.
So yes, in this example, destroying a Node instance will destruct its internal_list member automatically.