text:
Q: Counting function for Fibonacci numbers Are there some results about "Fibonacci-counting function" - the function counting the number of Fibonacci numbers less than or equal to some real number x?

A: Thanks to all!   Maybe the answer is (achille hui's version): $$\pi_F(x)=\left\lfloor\log_{\phi}\sqrt{5} \ \left(\lfloor x\rfloor+\frac12\right)\right\rfloor, \ x\geq2 $$

A: The function $\pi_F(x)$ cannot have the form found in lesobrod's answer. The argument is too long for a comment, so I've made it into an 'answer', but of course it doesn't actually answer the original question.
Let $\widehat\varphi=-\frac1\varphi$, the other root of $x^2-x-1=0$. We know that $$F_n=\frac{\varphi^n-\widehat\varphi^n}{\sqrt5}\;,$$ so $$\log_\varphi\left(\sqrt5F_n+\widehat\varphi^n\right)=n\;.$$
Fix $a\in\Bbb R$, and consider the function
$$f(x)=\log_\varphi\left(\sqrt5x+a\right)\;.$$
If $a\le 0$, then $\left\lfloor f(F_{2n})\right\rfloor<2n$, since $\sqrt5F_{2n}+a<\sqrt5F_{2n}+\widehat\varphi^{2n}=\varphi^{2n}$. Thus, we may assume that $a>0$. Since $\widehat\varphi^n\to 0$ as $n\to\infty$,
$$\epsilon_n=\frac{a-\widehat\varphi^{2n}}{\sqrt5}>0$$
for all sufficiently large $n$.
Let $x=F_{2n}-\epsilon_n$; then $a-\sqrt5\epsilon_n=\widehat\varphi^{2n}$, and
$$2n=\log_\varphi\left(\sqrt5F_{2n}+\widehat\varphi^{2n}\right)=\log_\varphi\left(\sqrt5\left(F_{2n}-\epsilon_n\right)+a\right)=f(x)=\left\lfloor f(x)\right\rfloor\;,$$
but $\pi_F(x)\le 2n-1$, since $x<F_{2n}$.
For suitable values of $a$ such a function can agree with $\pi_F$ on $\Bbb Z^+$, but not on all of $\Bbb R^+$.


text:
Q: How to manage component states (loading, error, data) in React I have implemented the following code to fetch data and render a component if everything goes well along with checking loading, error states.
import { useEffect, useState } from "react";

function Posts() {
  const [posts, setPosts] = useState([]);
  const [loader, setLoader] = useState(false);
  const [error, setError] = useState({ status: false, message: "" });

  const fetchPosts = () => {
    setLoader(true);
    setTimeout(async () => {
      try {
        const response = await fetch(
          "https://jsonplaceholder.typicode.com/posts"
        );
        // throw new Error("Some error occured");
        const data = await response.json();
        if (data.error) {
           setError({ status: true, message: data.error });
        } else {
           setPosts(data);
        }
        setLoader(false);
      } catch (error) {
        console.log("error", error);
        setError({ status: true, message: error.message });
        setLoader(false);
      }
    }, 2000);
  };

  useEffect(() => {
    fetchPosts();
  }, []);

  if (loader) return
Loading...
;
  if (error.status) return
Error: {error.message}
;

  return (

Posts

      {posts.length === 0 &&
There are no posts
}
      {posts.length > 0 && (

          {posts.map((post) => (
            <Post post={post} key={post.id} />
          ))}

      )}

  );
}

export default Posts;

Is this the right way to handle loading, error and success states when fetching data? or is there a better and more elegant solution than repeating this for every component?

A: Instead of checking for data.error in the try block, you could check for response.ok; if it is true, call response.json(), otherwise throw an error.
Also move the setLoader call to the finally block to avoid the duplicate calls in try and catch blocks.
try {
    const response = await fetch(...);

    if (response.ok) {
       let data = await response.json();
       setPosts(data);
    } else {
       throw new Error(/* error message */);
    }

} catch (error) {
    console.log("error", error);
    setError({ status: true, message: error.message });
} finally {
    setLoader(false);
}

If you want to check for data.error property in a response, you can change the following if condition
if (response.ok) {

to
if (response.ok && !data.error) {

is there a better and more elegant solution than repeating this for
every component?

Make a custom hook to make the fetch request and use that in every component that needs to fetch data from the backend.
const useFetch = (apiUrl, initialValue) => {

   const [data, setData] = useState(initialValue);
   const [loader, setLoader] = useState(false);
   const [error, setError] = useState({ status: false, message: "" });

   useEffect(() => {
      async function fetchData = (url) => {
         setLoader(true);

         try {
            const response = await fetch(url);

            if (response.ok) {
               let responseData = await response.json();
               setData(responseData);
            } else {
               throw new Error(/* error message */);
            }

         } catch (error) {
            console.log("error", error);
            setError({ status: true, message: error.message });
         } finally {
            setLoader(false);
         }
      }

      fetchData(apiUrl);
   }, [apiUrl]);

   return [data, error, loader];
};

A: Your solution should be good enough to do, but, to me, I would prefer not to set timeout for getting data, and I will use .then and .catch for better readable and look cleaner to me
import { useEffect, useState } from "react";

function Posts() {
  const [posts, setPosts] = useState([]);
  const [loader, setLoader] = useState(false);
  const [error, setError] = useState({ status: false, message: "" });

  const fetchPosts = () => {
    fetch("https://jsonplaceholder.typicode.com/posts")
      .then(response => response.json())
      .then(data => {
        setPosts(data);
        setLoader(false);
      })
      .catch(error =>{
        console.log("error", error);
        setError({ status: true, message: error.message });
        setLoader(false);
      });
  };

  useEffect(() => {
    setLoader(true);
    fetchPosts();
  }, []);

  if (loader) return
Loading...
;
  if (error.status) return
Error: {error.message}
;

  return (

Posts

      {posts.length === 0 &&
There are no posts
}
      {posts.length > 0 && (

          {posts.map((post) => (
            <Post post={post} key={post.id} />
          ))}

      )}

  );
}

export default Posts;

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to convert element type to string in swift? I wanna get a key:value from a dict like this
var tmpDict = ["a":"1", "b":"2", "c":"3"]
var tmpString = "a1234"
print(tmpDict[tmpString.characters.first])

Here comes an error, something like tmpString.characters.first cannot convert to string, What can I do if I wanna call tmpDict[xxx], which "xxx" means the first character of tmpString.

A: You could use:
var tmpDict = ["a":"1", "b":"2", "c":"3"]
var tmpString = "a1234"
tmpDict[String(tmpString[tmpString.characters.startIndex])]

with tmpString.characters.startIndex you get the index of the first character of tmpString, then you use it to extract the first character, and finally convert this character to a String to access the dictionary.

A: Another way to do it is you can convert tmpString to Array and access it's first element this way:
tmpDict[String(Array(tmpString)[0])]  // "1"

Or you can use this extension:
extension String
{
    subscript(integerIndex: Int) -> Character
        {
            let index = advance(startIndex, integerIndex)
            return self[index]
    }

    subscript(integerRange: Range<Int>) -> String
        {
            let start = advance(startIndex, integerRange.startIndex)
            let end = advance(startIndex, integerRange.endIndex)
            let range = start..<end
            return self[range]
    }
}

var tmpDict = ["a":"1", "b":"2", "c":"3"]
var tmpString = "a1234"
print(tmpDict[String(tmpString[0])]!)  // "1"

For 2.0
extension String
{
    subscript(integerIndex: Int) -> Character {
        let index = startIndex.advancedBy(integerIndex)
        return self[index]
    }

    subscript(integerRange: Range<Int>) -> String {
        let start = startIndex.advancedBy(integerRange.startIndex)
        let end = startIndex.advancedBy(integerRange.endIndex)
        let range = start..<end
        return self[range]
    }
}


text:
Q: Why is recursion not working as expected in C I want to count numbers in int from user input from char to zero. This code make only 1 cycle. (Please help me understand what is wrong in second part.)
void count_down_from(int num);
int main()
{
    int start;
    char letter;
    printf("print letter to reduce to zero in ACSCII");
    scanf("%c", &letter);

    count_down_from(letter);
    return 0;
}

This part working not good:
 void count_down_from(int num)
    {
        if (num > 0)
        {
            --num;
            count_down_from;
            printf("%d\n", num);
        }
        else
            return;
    }
    }

What behaviour expected:
void count_down_from(int num)
{
    printf("%d\n", num);
    --num;
    if (num < 0)
        return;
    else
        count_down_from(num);
}

A: Missed (num) in function call in second block.

A: take a look at my modifications
void count_down_from(int num)
    {
        if (num >= 0) //need the >= operator to go down to zero not just 1
        {

            printf("%d\n", num);
            --num;
            count_down_from(num); //you need to send num to the call otherwise it won't be a recursive function
        }
        else
            return;
    }


text:
Q: Show linear Transformation $T:\mathbb{R}^n\rightarrow\mathbb{R}^m$ is one-to-one So I've been stuck on this question for some time now and I can't seem to get the ball rolling. It is clear to me that to prove either $T$ is onto or $S$ one-to-one, I must find whether if $n\geq m$. Nevertheless, I'm stumped on the next step to take to demonstrate this. Perhaps you might be able to help me out.
Let $A$ be an $m\times n$ matrix and $B$ be an $n\times m$ matrix.
Suppose $AB = I_{m}$, that is the $m\times m$ identity matrix.
Consider the linear transformation $T: \mathbb{R}^n \rightarrow \mathbb{R}^m$ and $S: \mathbb{R}^m\rightarrow \mathbb{R}^n$ respectively defined by $[T] = A$ and $[S]= B$.
(a) Show that $T:\mathbb{R}^n\rightarrow\mathbb{R}^m$ is onto.
(b) Show that $S:\mathbb{R}^m\rightarrow\mathbb{R}^n$ is one-to-one.

A: The fact that you are dealing with matrices can be ignored. This is one of those cases where it may be easier to just use what you know about linear transformations.
Hints:
$1).\ $ Show that in general, if $S:X\to Y$ is a linear transformation of vector spaces, then $S$ is injective if and only if $\text{ker}\ S=\{0\}.$ Now use this in the context of your problem to show that $S$ is injective.
$2).\ $ In the context of your problem, suppose $T$ is not onto. Then, there is a $y\in \mathbb R^m$ such that no $x\in \mathbb R^n$ satisfies $Tx=y.$ On the other hand, by hypothesis, $TSy=y.$

A: Welcome to MSE. Your problem is all related to solve linear systems. Note that, if $S$ is one-to-one, then $B X = 0$ has a unique solution $X = 0$, to this happens you may solve this system, for which values of n, m this system has a unique solution?  And if $T$ is onto, given $Y \in \mathbb{R}^{m}$, you have to find solutions for a linear system like $AX = Y$ with $X \in \mathbb{R}^{n}$. Again, to which values of $n, m$ you can solve a system like this? Do you know how to do this calculation?


text:
Q: Make Tab Layout Indicator smaller than the tab title Make small indicator for tab layout tabs. I have tried with tabIndicatorFullWidth but it only wraps up with the title of tab, I want to make it more smaller.
Example Image:

A: You can use custom indicator drawable for small indicator tabs.
like this>>
tab_layout_indicator.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:width="20dp"
        android:height="5dp"
        android:gravity="center">
        <shape android:shape="rectangle">
            <corners android:radius="5dp"/>
            <solid android:color="@color/green"></solid>

        </shape>
    </item>
</layer-list>

And Use this indicator to your xml layout file.
<com.google.android.material.tabs.TabLayout
                        android:id="@+id/tabs"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center"
                        app:tabIndicator="@drawable/tab_layout_indicator"
                        app:tabGravity="fill"
                        app:tabMode="scrollable"
                      ></com.google.android.material.tabs.TabLayout>


text:
Q: Android OpenGL ES 2.0 VBO I have spent a few days trying to get a VBO working on Android using OpenGL ES 2.0, but I just can't seem to get it to work.
Here is the code I am using:
/* The Android shader code */
private static final String[] androidVertexShaderCode = new String[] {
        "attribute vec4 vertexPosition;",
        "void main() {",
        "  gl_Position = vertexPosition;",
        "}" };

private static final String[] androidFragmentShaderCode = new String[] {
        "precision mediump float;",
        "uniform vec4 colour;",
        "void main() {",
        "  gl_FragColor = colour;",
        "}" };

/* The Android shader */
public Shader androidShader;

/* The constructor with the render mode and the
 * number of vertex values given */
public AndroidRenderer(int renderMode, int vertexValuesCount) {
    super(renderMode, vertexValuesCount);
    //Add this renderer to the list
    allRenderers.add(this);
    usage = GLES20.GL_STATIC_DRAW;
    //Setup the Android shader
    this.androidShader = new AndroidShader();
    this.androidShader.vertexShader = ShaderUtils.createShader(ArrayUtils.toStringList(androidVertexShaderCode), Shader.VERTEX_SHADER);
    this.androidShader.fragmentShader = ShaderUtils.createShader(ArrayUtils.toStringList(androidFragmentShaderCode), Shader.FRAGMENT_SHADER);
    this.androidShader.create();
}

/* The method used to setup the buffers,
 * assumes the vertices have already been set */
public void setupBuffers() {
    //Create the vertices buffer
    this.verticesBuffer = BufferUtils.createFlippedBuffer(this.verticesData);
    int[] vh = new int[1];
    GLES20.glGenBuffers(1, vh, 0);
    //Setup the vertices handle
    this.verticesHandle = vh[0];

    //Bind the vertices buffer and give OpenGL the data
    GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, this.verticesHandle);
    GLES20.glBufferData(GLES20.GL_ARRAY_BUFFER, Float.BYTES * verticesData.length, this.verticesBuffer, this.usage);
    GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, 0);

    //Check to see whether the normals have been set
    if (this.normalsData != null) {
        //Create the normals buffer
        this.normalsBuffer = BufferUtils.createFlippedBuffer(this.normalsData);
        int[] nh = new int[1];
        GLES20.glGenBuffers(1, nh, 0);
        //Setup the normals handle
        this.normalsHandle = nh[0];

        //Bind the normals buffer and give OpenGL the data
        GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, this.normalsHandle);
        GLES20.glBufferData(GLES20.GL_ARRAY_BUFFER, Float.BYTES * verticesData.length, this.normalsBuffer, this.usage);
        GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, 0);
    }

    //Check to see whether the colours have been set
    if (this.colourData!= null) {
        //Create the colours buffer
        this.coloursBuffer = BufferUtils.createFlippedBuffer(this.colourData);
        int[] ch = new int[1];
        GLES20.glGenBuffers(1, ch, 0);
        //Setup the colours handle
        this.coloursHandle = ch[0];

        //Bind the colours buffer and give OpenGL the data
        GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, this.coloursHandle);
        GLES20.glBufferData(GLES20.GL_ARRAY_BUFFER, Float.BYTES * colourData.length, this.coloursBuffer, this.usage);
        GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, 0);
    }

    //Check to see whether the texture coordinates have been set
    if (this.textureData != null) {
        //Create the texture coordinates buffer
        this.texturesBuffer = BufferUtils.createFlippedBuffer(this.textureData);
        int[] th = new int[1];
        GLES20.glGenBuffers(1, th, 0);
        //Setup the texture coordinates handle
        this.texturesHandle = th[0];

        //Bind the texture coordinates buffer and give OpenGL the data
        GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, this.texturesHandle);
        GLES20.glBufferData(GLES20.GL_ARRAY_BUFFER, Float.BYTES * textureData.length, this.texturesBuffer, this.usage);
        GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, 0);
    }
}

/* The method used to draw the object */
public void render() {
    this.androidShader.use();
    short[] indices = new short[this.verticesData.length];
    for (short a = 0; a < indices.length; a++)
        indices[a] = a;
    ShortBuffer indicesBuffer = BufferUtils.createFlippedBuffer(indices);
    //Enable the arrays as needed
    int vertexPositionAttribute = GLES20.glGetAttribLocation(this.androidShader.program, "vertexPosition");
    int normalAttribute = 0;
    int colourAttribute = 0;
    int texturesAttribute = 0;
    GLES20.glEnableVertexAttribArray(vertexPositionAttribute);
    GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, this.verticesHandle);
    GLES20.glVertexAttribPointer(vertexPositionAttribute, this.vertexValuesCount, GLES20.GL_FLOAT, false, 0, 0);
    if (this.normalsData != null) {
        GLES20.glEnableVertexAttribArray(normalAttribute);
        GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, this.normalsHandle);
        GLES20.glVertexAttribPointer(normalAttribute, 2, GLES20.GL_FLOAT, false, 0, 0);
    }
    if (this.colourData != null) {
        colourAttribute = GLES20.glGetAttribLocation(this.androidShader.program, "colour");
        Log.d("HELLO", "" + colourAttribute);
        GLES20.glEnableVertexAttribArray(colourAttribute);
        GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, this.coloursHandle);
        GLES20.glVertexAttribPointer(colourAttribute, this.colourValuesCount, GLES20.GL_FLOAT, false, 0, 0);
    }
    if (this.textureData != null) {
        GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, this.texturesHandle);
        GLES20.glEnableVertexAttribArray(texturesAttribute);
        GLES20.glVertexAttribPointer(texturesAttribute, this.textureValuesCount, GLES20.GL_FLOAT, false, 0, 0);
    }
    //Draw the arrays
    GLES20.glDrawElements(this.renderMode, indices.length, GLES20.GL_UNSIGNED_SHORT, indicesBuffer);
    //Disable the arrays as needed
    if (this.normalsData != null)
        GLES20.glDisableVertexAttribArray(normalAttribute);
    if (this.textureData != null)
        GLES20.glDisableVertexAttribArray(texturesAttribute);
    if (this.colourData != null)
        GLES20.glDisableVertexAttribArray(colourAttribute);
    GLES20.glDisableVertexAttribArray(vertexPositionAttribute);
    this.androidShader.stopUsing();
}

I haven't implemented the use of normal or textures at the moment, as I am just trying to draw a triangle where each vertex is a different color. I know that the shader should be working as I got this to work, rendering with only one color using the same shader, and vertices/colour data.
When I looked at LogCat, the message: : GL_INVALID_VALUE was being printed out. I then decided to print out the value of the colourAttribute found using glGetAttribLocation, and it turns out this was -1. Upon further research I found this: https://www.opengl.org/sdk/docs/man/html/glGetAttribLocation.xhtml, which states that the value of -1 is returned "If the named attribute variable is not an active attribute in the specified program object".
After searching Google, I haven't found a solution to the problem of the triangle not rendering, so would appreciate any help.
Thank you.

A: It seams that the stride of the vertexAttributePointer method is always 0. Which means you override the vertex positions within the vertex buffer with you color values.
GLES20.glVertexAttribPointer(colourAttribute, this.colourValuesCount, GLES20.GL_FLOAT, false, **0**, 0);

You have to increase that stride by an offset of the sum of the previous vertex attribute sizes. In your case 4 because of the vec4 of the vertexPosition vector.
The same applies later for the texture and normals.
Have a look here for the definition of glVertexAttribPointer: http://androidbook.com/akc/display?url=displaynoteimpurl&ownerUserId=android&reportId=4229
Additionally you can try to add a fixed color to the fragment shader eg:
gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);

So you avoid that the colorHandle has any influence to the rendering process.
Additionally try to avoid to use the IndexBuffer at first and not use the
glDrawElements(.. , ..)

method just use directly the vertexBufferObject with a
glDrawArrays(.., .., )

method.
If that works you can of course switch back to the IndexBuffer method.
UPDATE due to comment
I see another problem right now. You missed to link the shader and enable it using glLinkProgram and glUseProgram. Have a look here: Shader for Android OpenGL ES
This post shows you also how to output the compile errors of the shader program.


text:
Q: Filter multiple objects from array I'm trying to filter an array of objects where the filter is another array (of integers) which are values of properties of the first array. I've managed to make it work but I'm not sure if it's the best way. Since I'm a beginner in javascript, I'd appreciate any suggestions/improvements.
The items.json file contains an object with an array of objects. I want to filter all the objects (within that array) that have an id equal to the "ids" on the itemsids array.
code:
const itemsall = require('./items.json');

let itemsids = [1, 403, 3];

let filtereditems = [];

itemsids.forEach(id => {
  itemsall.items.forEach(item => {
    if (id === item.id) {
      filtereditems.push(item);
    }
  });
});

items.json (a small part of it)
{
    "items": [
        {
            "id": 0,
            "name": "Egg",
            "img": "http://www.serebii.net/pokemongo/items/egg.png"
        },
        {
            "id": 1,
            "name": "Pokeball",
            "img": "http://www.serebii.net/pokemongo/items/20pokeballs.png"
        },
        {
            "id": 2,
            "name": "Greatball",
            "img": "http://www.serebii.net/pokemongo/items/greatball.png"
        }
   ]
}

output: (expected)
[
    {
        "id": 0,
        "name": "Egg",
        "img": "http://www.serebii.net/pokemongo/items/egg.png"
    },
    {
        "id": 403,
        "name": "Cool Incense",
        "img": "http://www.serebii.net/pokemongo/items/incense.png"
    },
    {
        "id": 3,
        "name": "Ultraball",
        "img": "http://www.serebii.net/pokemongo/items/ultraball.png"
    }
]

Thanks!

A: You can use filter() and indexOf() to return filtered array.

var data = {
  "items": [{
    "id": 0,
    "name": "Egg",
    "img": "http://www.serebii.net/pokemongo/items/egg.png"
  }, {
    "id": 1,
    "name": "Pokeball",
    "img": "http://www.serebii.net/pokemongo/items/20pokeballs.png"
  }, {
    "id": 2,
    "name": "Greatball",
    "img": "http://www.serebii.net/pokemongo/items/greatball.png"
  }]
}
let itemsids = [1, 403, 3];

var result = data.items.filter(function(e) {
  return itemsids.indexOf(e.id) != -1
})

console.log(result)

With ES6/ES7 you can use includes() like this.
var result = data.items.filter((e) => itemsids.includes(e.id));


text:
Q: dotnet watch run doesn't seem to work on linux I am running Arch Linux and want to do some .NET 6 development.
I do have the .NET SDK and runtimes installed.
~/code/bejebeje feat/login-button ❯ dotnet --list-sdks
6.0.101 [/home/j/.dotnet/sdk]

~/code/bejebeje feat/login-button ❯ dotnet --list-runtimes
Microsoft.AspNetCore.App 6.0.1 [/home/j/.dotnet/shared/Microsoft.AspNetCore.App]
Microsoft.NETCore.App 6.0.1 [/home/j/.dotnet/shared/Microsoft.NETCore.App]

The project I'm in was recently updated to .NET 6 from .NET Core 5.
The project builds fine, and I can run it with:
~/code/bejebeje feat/login-button ❯ dotnet run --project Bejebeje.Mvc/Bejebeje.Mvc.csproj
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: https://localhost:5001
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
      Content root path: /home/j/code/bejebeje/Bejebeje.Mvc/

However, if I wish to watch and use hot reload, I get the following:
~/code/bejebeje feat/login-button ❯ dotnet watch run --project Bejebeje.Mvc/Bejebeje.Mvc.csproj
watch : Hot reload enabled. For a list of supported edits, see https://aka.ms/dotnet/hot-reload. Press "Ctrl + R" to restart.
watch : Building...
  Determining projects to restore...
  All projects are up-to-date for restore.
  Bejebeje.Common -> /home/j/code/bejebeje/Bejebeje.Common/bin/Debug/net6.0/Bejebeje.Common.dll
  Bejebeje.Models -> /home/j/code/bejebeje/Bejebeje.Models/bin/Debug/net6.0/Bejebeje.Models.dll
  Bejebeje.Domain -> /home/j/code/bejebeje/Bejebeje.Domain/bin/Debug/net6.0/Bejebeje.Domain.dll
  Bejebeje.DataAccess -> /home/j/code/bejebeje/Bejebeje.DataAccess/bin/Debug/net6.0/Bejebeje.DataAccess.dll
  Bejebeje.Services -> /home/j/code/bejebeje/Bejebeje.Services/bin/Debug/net6.0/Bejebeje.Services.dll
  Bejebeje.Mvc -> /home/j/code/bejebeje/Bejebeje.Mvc/bin/Debug/net6.0/Bejebeje.Mvc.dll
watch : Started
A fatal error occurred. The required library libhostfxr.so could not be found.
If this is a self-contained application, that library should exist in [/home/j/code/bejebeje/Bejebeje.Mvc/bin/Debug/net6.0/].
If this is a framework-dependent application, install the runtime in the global location [/usr/share/dotnet] or use the DOTNET_ROOT environment variable to specify the runtime location or register the runtime location in [/etc/dotnet].

The .NET runtime can be found at:
  - https://aka.ms/dotnet-core-applaunch?missing_runtime=true&arch=x64&rid=arch-x64&apphost_version=6.0.1
watch : Exited with error code 131
watch : Waiting for a file to change before restarting dotnet...
watch : Building...
  Bejebeje.Common -> /home/j/code/bejebeje/Bejebeje.Common/bin/Debug/net6.0/Bejebeje.Common.dll
  Bejebeje.Domain -> /home/j/code/bejebeje/Bejebeje.Domain/bin/Debug/net6.0/Bejebeje.Domain.dll
  Bejebeje.Models -> /home/j/code/bejebeje/Bejebeje.Models/bin/Debug/net6.0/Bejebeje.Models.dll
  Bejebeje.DataAccess -> /home/j/code/bejebeje/Bejebeje.DataAccess/bin/Debug/net6.0/Bejebeje.DataAccess.dll
  Bejebeje.Services -> /home/j/code/bejebeje/Bejebeje.Services/bin/Debug/net6.0/Bejebeje.Services.dll
  Bejebeje.Mvc -> /home/j/code/bejebeje/Bejebeje.Mvc/bin/Debug/net6.0/Bejebeje.Mvc.dll
watch : Started
A fatal error occurred. The required library libhostfxr.so could not be found.
If this is a self-contained application, that library should exist in [/home/j/code/bejebeje/Bejebeje.Mvc/bin/Debug/net6.0/].
If this is a framework-dependent application, install the runtime in the global location [/usr/share/dotnet] or use the DOTNET_ROOT environment variable to specify the runtime location or register the runtime location in [/etc/dotnet].

The .NET runtime can be found at:
  - https://aka.ms/dotnet-core-applaunch?missing_runtime=true&arch=x64&rid=arch-x64&apphost_version=6.0.1
watch : Exited with error code 131
watch : Waiting for a file to change before restarting dotnet...
watch : Building...
  Bejebeje.Common -> /home/j/code/bejebeje/Bejebeje.Common/bin/Debug/net6.0/Bejebeje.Common.dll
  Bejebeje.Domain -> /home/j/code/bejebeje/Bejebeje.Domain/bin/Debug/net6.0/Bejebeje.Domain.dll
watch : Shutdown requested. Press Ctrl+C again to force exit.
Attempting to cancel the build...
  Bejebeje.Models -> /home/j/code/bejebeje/Bejebeje.Models/bin/Debug/net6.0/Bejebeje.Models.dll

That keeps on repeating until I hit Ctrl + C
Here's a screenshot too (for colour).
Am I doing something wrong? I thought dotnet watch was supposed to work on all platforms.


text:
Q: Something dongle-sized to enable wifi net connection to ethernet modem? I currently connect my laptop to the internet using an ethernet modem. I want to continue to do this most of the time, but occasionally to connect wirelessly, by plugging something as small as possible into the existing modem and then using my laptop, which is 802.11ac enabled, in another part of the house. I know I can get a wifi router and plug it into the ethernet modem, but instead of using one of those I want to use a bit of kit that's much smaller, dongle-sized if possible.
Would the following work?
1) Plug a male-RJ45-to-female-USB connector into the modem, and then
2) plug a male-USB wifi dongle into the said connector.
I'm hoping the answer is "yes", so that I can leave these two small pieces of kit plugged together and then just plug the RJ45 end (instead of the RJ45 cable) into the modem when I want to wander with the laptop.

A: Your best solution for keeping the whole setup physically small would be to get a small home gateway that includes the kind of broadband modem you need and has Wi-Fi AP (wireless router) functionality built in.
Or, if you really like your current broadband modem, buy a very small "travel router" type Wi-Fi AP and make a short Ethernet cable to connect it to the Ethernet port of the modem. Consider the TP-LINK TL-WR7xxN models, such as the TL-WR702N.
Here are some reasons why your dongle won't work:

*

*Your broadband modem almost certainly does not provide Power over Ethernet (PoE), so no pure dongle is possible; whatever device you get will have to have its own way to connect to power.

*There is no such thing as "a male-RJ45-to-female-USB connector". Part of this is because RJ-45 Males break too easily, so no one builds them into a captive cable. But there is no such thing as an Ethernet female-RJ-45-to-female-USB-A connector" either. If you've seen a device that looks like that, it's half of a matched set: a USB-over-Cat5 extender, which does proprietary signaling over the Cat5 cable, not Ethernet. So the device you may have seen wouldn't be able to talk to the Ethernet port on your broadband modem.

*There is no such thing as a generic USB-A host port (female) device that connects to Ethernet. USB can be used for tons of different things, and it would be very difficult to make a general-purpose Ethernet-connected USB host port, where people could buy any arbitrary USB device and connect it up to that Ethernet-connected host port device and have any hope of being able to share it on the network in any meaningful way. There are single-purpose boxes like USB print servers or NAS servers for sharing USB external hard drives, but no general-purpose "USB servers", and even if there were, your modem wouldn't be able to run the client software to connect to it. There are no single-purpose Ethernet-connected devices for sharing USB Wi-Fi dongles, and even if there were, again your modem wouldn't be able to run the client software to connect to it.

A: No, this won't work - for 2 reasons
1.  The WIFI settings won't be configured on the modem side.
2.  The modem side USB device is an AP Client, as is the computer, you need
    to talk to an AP device (unless your modem is very smart and can turn
    it into an AP - this is theoretically possible, but if your modem had
    the smarts to do it, it would not be a WIFI enabled router !)
Have you considered replacing your modem with a router with WIFI built in ?


text:
Q: Can't add reference to an F# PCL from a C# PCL
*

*Create C# Xamarin Forms app

*Add C# PCL

*Add F# PCL

*Try to add a reference from the C# PCL to the F# PCL

-> In the reference dialog you will see: Incompatible framework Definition:
:NETFramework=v4.5;Profile=Profile78)

Hints from other similar questions that are marked as solved do not work. E.g. adding the reference manually will fail to compile.
I don't know where to start to figure it out. Is it a compiler problem, a xamarin problem? I don't think it's the last one as it does not work with VS 2015 too.
Update 20.10.2016
Bugrequest and Gitrepo: https://bugzilla.xamarin.com/show_bug.cgi?id=44976

A: I wasn't able to reproduce this in Xamarin Studio. Based on what I tried and the screenshots, I am guessing that the F# PCL is a different profile target than the C# PCL. Double-check that the Targets are exactly the same and try again.

A: Jason Imison figured out a workaround:

*

*Even if F# was installed with VS the F# tools are required https://www.microsoft.com/en-us/download/details.aspx?id=48179

*Then it is possible to add a reference by using the assembly (not by project) and it will compile


text:
Q: Everything updated but still "! Use of \sortlist doesn't match its definition." I upgraded to a new CPU and installed windows all over. I then downloaded MikTeX 2.9 from the official website and Texmaker.
Biber I downloaded from sourceforge which downloads the file biber-cygwin64.tar.gz. After unzipping I copy the folder to my system drive and add it in Texmaker and set the path: .
Compiling files without bibliography files works just fine (I conclude MiKTeX and Texmaker work properly).
Compiling documents using references results in an error:
! Use of \sortlist doesn't match its definition.

which has been documented before in this forum (stack exchange does not let me post any additional links but you find searching for "Error "Use of \sortlist doesn't match its definition. \sortlist{"")
I fail to solve the problem by updating the individual components as suggested in the other stackexchange post. MiKTeX packages cannot be updates as there are not updates available:

and the biber version cannot be outdated since I just downloaded it a couple of minutes ago. The same document works just fine on my laptop, where I use Texmaker as well.
Anyone any idea on how to fix this?? I would really appreciate any help!

EDIT 1:
After updating the MiKTeX packages on my laptop I get the same error message. So it seems to be related to the biblatex package in MiKTeX.

EDIT 2:
Using a mini-example as suggested, I can move one step further.
\documentclass{article}
\usepackage{biblatex}
\addbibresource{biblio.bib}
\begin{document}
 b
\parencite{Archarya.2016}
\cite{Archarya.2016}
\printbibliography \end{document}

Quick build works, but the second step (running BibTex) results in a new error:
Process started
This is BibTeX, Version 0.99d (MiKTeX 2.9.6210 64-bit) The top-level auxiliary file: newtest.aux I found no \citation commands---while reading file newtest.aux I found no \bibdata command---while reading file newtest.aux I found no \bibstyle command---while reading file newtest.aux (There were 3 error messages)
Process exited with error(s)

Most likely because my path under Bib(la)tex in Texmaker is not correct (in that I reference to the sourceforge file and not what it really should be)

A: You should never install Biber or biblatex manually from SourceForge or any other source, unless you know exactly what you are doing and you have a good reason to do so.
If you are running MikTeX, there is hardly ever a reason to do a manual install.
So you should

*

*Remove the manual installation of Biber you got from SourceForge.

*Check that biblatex and Biber are installed in MikTeX.

*

*If not, install the corresponding packages.

*If you have the biber package installed, but you overwrote it with your manual install you may have to uninstall and then reinstall it.

*Make an update. (With both the User version of MikTeX update and the Admin version. To be sure, run each wizard twice.)

Then you need to ensure that you actually run Biber.

*Biblatex with Biber: Configuring my editor to avoid undefined citations
If you still have problems with your document, delete the auxiliary files and try to recompile from a clean directory. Refer also to Troubleshooting for biber.


text:
Q: How to fix cannot convert value of type Result, Error> to closure result type Result Swift I'm trying to map over Swift's Result type to produce a new Result of a different type but it isn't type checking, and is throwing the error:
error: cannot convert value of type Result<ParseSuccess<B>, ParseError> to closure result type Result<Success, Failure>
I've tried using a switch on the result and matching on the .success and .failure but I get a similar type checking error. I've also tried specifying the input and return types explicitly with no luck.
I've  replicated the code in other languages I'm a little more familiar with (F# and Kotlin) and it seems to type check there.
The swift compiler shows a sqiggly under this line:
return self.apply(input).map { result in ParseSuccess(transform(result.data), result.input) }
Where am I going wrong with this code?
import Foundation

class ParseError : Error {
    let err: String
    init(_ err: String) {
        self.err = err
    }
}

class ParseSuccess<A> {
    let data: A
    let input: Substring

    init(_ data: A, _ input: Substring) {
        self.data = data
        self.input = input
    }
}

class Parser<A> {
    let fn: (Substring) -> Result<ParseSuccess<A>, ParseError>

    init(_ fn: @escaping (Substring) -> Result<ParseSuccess<A>, ParseError>) {
        self.fn = fn
    }

    func apply(_ input: Substring) -> Result<ParseSuccess<A>, ParseError> {
        return self.fn(input)
    }

    func map<B>(_ transform: @escaping (A) -> B) -> Parser<B> {
        return Parser { (input) in
            return self.apply(input).map { result in
 ParseSuccess(transform(result.data), result.input) }
        }
    }
}

For what it's worth, I'm sure this is probably not the best way to start writing a parser combinator, but I've gotten caught up in trying to figure out where I went wrong here!
Thank you

A: It's a weird behaviour of the unqualified used of Paraser in the line return Parser {. When a generic type is mentioned in its unqualified form, within the body of the generic type's declaration, the type parameters are inferred to be unchanged. For example, a function on Array<T> can return simply Array, and the T is implied to be the same as the value of T for self. Needless to say, I'm not a huge fan of this behaviour.
Changing it to return Parser<B> { ... solves the issue.

Here's how I found the issue. When working with generics errors, I always try to insert a ton of type annotations to "pin down" the data types, to confirm that the compiler and me are on the same page.
I first wrote:
func map<B>(_ transform: @escaping (A) -> B) -> Parser<B> {
    return Parser { (input) in
        return self.apply(input).map { result in
            let newData: ParseSuccess<B> = transform(result.data)
            return ParseSuccess(newData, result.input)
        }
    }
}

At which point the error changed to:
Untitled 2.swift:32:10: error: cannot convert return expression of type 'Parser<A>' to return type 'Parser<B>'
                return Parser { (input) in
                       ^~~~~~~~~~~~~~~~~~~~


text:
Q: Disable menu items programmatically I am working on a Desktop app with the Netbeans RCP. I have a number of menu items that are beeing added to the menu through annotations in the TopComponents.
I would like to be able to disable several of these menu items, depending on the access rights of the logged user.

A: One way to do this in the NetBeans Platform is to register a Presenter.Menu in the menu:
@ActionID(id = "com.company.MyPresenter", category = "Edit")
@ActionRegistration(displayName = "com.company.Bundle#CTL_MyPresenter")
@ActionReference(path = "Menu/Edit", position = 1)
public class MyPresenter implements Presenter.Menu {

    @Override
    public JMenuItem getMenuPresenter() {
        // return menu item from your ACL'd registry
    }
}

When you register a Presenter.Menu in the menu the getMenuPresenter() method is called by the platform to get the actual JMenuItem that is added to the menu.
Normally you would just construct a JMenuItem here but since you need to be able to get a hold of it in other parts of the application you'll need to keep some kind of registry of your menu items so that you'll be retrieving the same instance.
One way to do this is to register all of your ACL'd menu items as a ServiceProvider. In this way you can Lookup all of them when you need to enable/disable them.
A ServiceProvider interface:
public interface ControllableMenuItem {

    void setEnabled(boolean enabled);

    JMenuItem getMenuItem();
}

A ControllableMenuItem implementation registered as a ServiceProvider:
@ServiceProvider(service = ControllableMenuItem.class)
public class MyMenuItem implements ControllableMenuItem {

    private JMenuItem menuItem;

    @Override
    public void setEnabled(boolean enabled) {
        getMenuItem().setEnabled(enabled);
    }

    @Override
    public JMenuItem getMenuItem() {
        if (menuItem == null) {
            menuItem = new JMenuItem(new MyAction());
        }
        return menuItem;
    }
}

Now you can Lookup all of the ControllableMenuItems when you need to enable/disable them:
Collection<? extends ControllableMenuItem> menuItems =
    Lookup.getDefault().lookupAll(ControllableMenuItem.class);
for (ControllableMenuItem item : menuItems) {
    item.setEnabled(isAuthorized());
}

However there's one more piece for this to work properly. You need a way to guarantee that the Presenter.Menu is getting the same instance that the Lookup is getting. One way to do this - admittedly not very elegant - is to register the MenuItem as a @ServiceProvider for itself and look this up in getMenuPresenter():
// replaces the above annotation of MyMenuItem
@ServiceProviders(value = {
    @ServiceProvider(service = ControllableMenuItem.class),
    @ServiceProvider(service = MyMenuItem.class)
})
public class MyMenuItem implements ControllableMenuItem {...}

public class MyPresenter implements Presenter.Menu {

    @Override
    public JMenuItem getMenuPresenter() {
        MyMenuItem myMenuItem = Lookup.getDefault().lookup(MyMenuItem.class);
        return myMenuItem.getMenuItem();
    }
}

In this way you are guaranteed to get the same instance whenever you Lookup your ControllableMenuItems.
This is only one way of doing this. The point here is that you need to have a mechanism in place to get the same instances of all of your ACL'd menu items when you need to disable them.
Another approach to controlling what menu items actually make it into the menu system is to create separate modules for each level of access and simply disable modules when users aren't authorized for a particular group of functionality. This is beneficial in many respects and is one of the strengths of using a modular system.

A: *

*see Oracle tutorial How to Use Menus, run code examples

*use Xxx.setEnabled(false) for JMenu, JMenuItem, JRadioButtonMenuItem and JCheckBoxMenuItem


text:
Q: Basic Automated Test of a Javascript Browser Library I am using Webpack to build a webapp that is designed for the browser.
After my build process I have two files: index.html and app.bundle.js
To my dismay I have found that the although the development Webpack configuration works the production configuration does not because of errors during minification.
I am looking for the most basic way to run a test that does the following:

*

*Opens the index.html file (which contains <script defer="defer" src="app.bundle.js"> and sees if there are any errors when the script contained in app.bundle.js runs

That is it.
I need a full Browser environment (requestianimationframe, fetch, etc.)
I have tried JSDOM and I get Error: Uncaught [ReferenceError: fetch is not defined] which looks like it has a bunch of issues, and then there are a tremendous amount of overlapping libraries and tools like Phantom.js Zombie.js Pupeteer, headless-chrome etc. and I honestly can't figure out how to just open my app. I have tried to explore all of these tools but they are all complicated.
Ideally I wouldn't have to create a local webserver, but I'd be fine with that if this is what is required.

A: The 'best' way to do this IMHO, would be to have a full test environment that mirrors your production environment that you can deploy to and then run tests against, using a framework like WebdriverIO or Playwright. But that can be prohibitively expensive and requires a fair amount of devops work.
Your second best option is probably to configure a local webserver on whatever machine you run your tests on and spin up Selenium or Puppeteer tests there. Leveraging a framework like WebdriverIO or Playwright a basic sanity check test shouldn't take more than an hour or two to set up.


text:
Q: Determine if $f_n(x)=\frac{1-x}{1+x^n}$ converges uniformly on $[0,2]$ I want to determine the uniform convergence of the family of functions $f_n:[0,2]\to\mathbb{R}$ defined by
$$
f_n(x)=\frac{1-x}{1+x^n}.
$$
My attempt

*

*Limit of $f_n$
Let $f$ be the limit of $f_n$, then
$$
f(x)=\begin{cases}
1-x,& 0\le x <1\\
0,&1\le x\le 2
\end{cases}.
$$
$f$ is continuous on $[0,1]$, but not differentiable at $x=1$.

*

*Inequalities about $|f_n(x)-f(x)|$
We know that
$$
|f_n(x)-f(x)| = \begin{cases}
\frac{(1-x)x^n}{1+x^n},&0\le x<1\\
\frac{x-1}{1+x^n},&1\le x\le 2
\end{cases}.
$$
If $0\le x<1$,
$$
|f_n(x)-f(x)|=\frac{(1-x)x^n}{1+x^n} \le (1-x)x^n,
$$
and $(1-x)x^n$ has the maximum $\frac{1}{n}\left(1-\frac{1}{n+1}\right)^{n+1}$ at $x=\frac{n}{n+1}$. Also, if $1\le x\le 2$, then
$$
|f_n(x)-f(x)|=\frac{x-1}{1+x^n}\le \frac{x-1}{x^n}
$$
and $\frac{x-1}{x^n}$ has the maximum $\frac{n-2}{(n-1)^2}\left(1-\frac{1}{n-1}\right)^{n-1}$ at $x=\frac{n}{n-1}$. Thus we obtain
\begin{align}
|f_n(x)-f(x)| &\le \max\left\{\frac{1}{n}\left(1-\frac{1}{n+1}\right)^{n+1},\frac{n-2}{(n-1)^2}\left(1-\frac{1}{n-1}\right)^{n-1}\right\}\\
&\le \frac{1}{n-1}
\end{align}
for $n\ge 2$.

*

*Conclusion

For $\epsilon > 0$, there is $N\in\mathbb{N}$ such that $\frac{1}{N}<\epsilon$ by Archimedian property. Then, for any $n\in\mathbb{N}\setminus\{1\}$ and $x\in [0,2]$, if $n > N$, then
$$
|f_n(x)-f(x)|\le \frac{1}{n-1}\le \frac{1}{N} <\epsilon.
$$
Therefore $f_n$ uniformly converges on $[0,2]$.
"Solution" $f_n$ does not converge uniformly, since $f_n$ is differentiable but $f$ is not differentiable at $x=1$.
However, I think the solution is wrong. For example, $f_n(x)=\frac{\sin nx}{\sqrt{n}}$ converges uniformly on $\mathbb{R}$, whereas $f_n'(x)=\sqrt{n}\cos nx$ does not pointwisely converge. According to Sequence of differentiable functions, there is a sequence of differentiable functions which uniformly converges to a non-differentiable function.
Question Is my attempt correct? If so, is there an easier method to solve the problem?

A: Your argument is correct. The sequence converges uniformly. The "solution" is wrong. It is not true in general that a uniformly convergent sequence of differentiable functions converges to a differentiable function. An additional assumption is needed. For example, if we know that at some point $x_0$ the sequence of derivatives $f_n'(x_0)$ tends to $f'(x_0)$, then it is true. But not in general.

A: If the $f_n$ are differentiable and converge uniformly to $f$, then $f$ need not be differentiable (see Wikipedia).
Your pointwise limit is correct! You also correctly bounded $\|f_n-f\|_\infty$ for $0\le x\le 1$ and for $1\le x\le 2$. Thus, your conclusion that the the convergence is uniform holds.

A: Another method (using very elementary inequalities): let $\epsilon >0$. Then, for $ 1-\epsilon <x\leq 1$ we have $|f_n(x)-(1-x)| \leq |1-x| \leq \epsilon$. For $x \leq 1-\epsilon $ we have $|f_n(x)-(1-x)| \leq \frac {x^{n}}{1+x^{n}} \leq (1-\epsilon)^{n} \to 0$. For $1 \leq x \leq 1+\epsilon$ we get $|f_n(x)|\leq \epsilon$.  I will leave the case $1+\epsilon \leq x \leq 2$ to you. [Use the fact that $\frac 1 {(1+\epsilon)^{n}} \to 0$.


text:
Q: nginx custom root for certain addresses I have installed nginx to my VPN. And I'm a very beginner with that so it might be a stupid mistake but I was unable to figure our or google it.
What I'm trying to do and keep failing in it is set the root folder for certain addresses. For example:
mydomain.com/websiteone/ will have root folder in /var/www/websiteone/public/ and
mydomain.com/websitetwo/ in /var/www/websitetwo/public/
Im using Laravel that why I need to do that.
Here is the confing and what I was attempting in different variations.
server {
    listen 80 default_server;
    listen [::]:80 default_server;

    root /var/www;

    index index.html index.php index.htm;

    location /websiteone/ {
        root /var/www/websiteone/public/;
        try_files $uri $uri/ 404;
    }

    location /websitetwo/ {
        root /var/www/websitetwo/public/;
        try_files $uri $uri/ 404;
    }
}

A: No need for alias or anything fancy as long as URL dir path matches to actual directory names of your two Laravel instances (see below).
Also, Laravel has a typical "front controller" URL pattern, which means URLs that do not exist should be bootstrapped through its index.php. So:
server {
    listen 80 default_server;
    listen [::]:80 default_server;

    root /var/www;

    index index.html index.php index.htm;

    location /websiteone/ {
        root /var/www/websiteone/;
        try_files /public$uri /public$uri/ /public/index.php$is_args$args;
    }

    location /websitetwo/ {
        root /var/www/websitetwo/;
        try_files /public$uri /public$uri/ /public/index.php$is_args$args;
    }
}


text:
Q: Mocha executes irrelevant file before test file In my express app, I'm trying unit testing using Mocha for an independent util class. When kicking off the mocha tests, something strange happened.
Mocha somehow launches the express app before tests.
Since the file that initiates the app is not referenced from any test suite, I think it's weird that Mocha reaches out to it.
Here's my folder structure:
/dist
/index.ts <-- server launching script
/util
  / util.ts <-- independent util class
  / util.test.ts <-- tests for util.ts
/package.json

In package.json I define something like:
"test:unit": "mocha --require source-map-support/register 'dist/**/*.test.js'"

And when I run it, the log output is something like:
> my-project@1.0.0 test:unit
> mocha --require source-map-support/register 'dist/**/*.test.js'

info: server started

  Util class
    ✔ Test case 1 (64ms)
    ✔ Test case 2 (62ms)
    ✔ Test case 3 (122ms)

  3 passing (258ms)

info: server listening on port 3333

(And Mocha never exits!!!!)

Currently, the --exit flag makes it possible to forcefully quit the tests after finishing. But it's still a mystery why Mocha behaves like this. Does anyone know the reason? Any answers would be appreciated.


text:
Q: How do hide the x-axis serifs in chart.js 2? How do I hide the x-axis serifs in chart.js 2 ?
And remove all paddings around of chart?

var barChartEl = document.getElementById("barChart");
    var barChart = new Chart(barChartEl, {
        type: 'bar',
        data: {
            labels: ["2012 г.", "2013 г.", "2014 г.", "2015 г."],
            datasets: [{
                data: [542, 34127, 39797, 51450]
            }]
        },
        options: {
            scales: {
                yAxes: [{
                    ticks: {
                        display: false
                    }
                }]
            }
        }
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.bundle.js"></script>
<canvas id="barChart" width="400" height="200"></canvas>

A: resolve:
scales: {
    xAxes: [{
        gridLines: {
         tickMarkLength: 0
                    }
                }]
            }


text:
Q: possible to run/call a function in a batch file directly from cmd? How can I run/call one function which is in a batch file directly from cmd?
I have this test.bat file which contains some function and I want to call/run one of the function without running the whole file. Is it possible?
@echo off
:plus
set /p input1=first input:
set /p input2=second input:
set /a n1=input1
set /a n2=input2
set /a ans=%n1%+%n2%
echo %input1%+%input2% = %ans%

REM goto :eof
:sub
set /p input1=first input:
set /p input2=second input:
set /a n1=input1
set /a n2=input2
set /a ans=%n1%-%n2%
echo %input1% - %input2% = %ans%

REM goto :eof
:mul
set /p input1=first input:
set /p input2=second input:
set /a n1=input1
set /a n2=input2
set /a ans=%n1%*%n2%
echo %input1% * %input2% = %ans%
goto :eof

A: I am guessing you want something like this?
(Please note, you could change call :%~1 to goto :%~1 if you want to still access labels, sucj as goto :eof
@echo off

:: This portion will use the paramter sent from cmd window.
call :%~1
goto :eof

:plus
echo Welcome to additions (n+n=n)
set /p input1=first input:
set /p input2=second input:
set /a n1=input1
set /a n2=input2
set /a ans=%n1%+%n2%
echo %input1%+%input2% = %ans%
goto :eof

:sub
echo Welcome to subtractions (n-n=n)
set /p input1=first input:
set /p input2=second input:
set /a n1=input1
set /a n2=input2
set /a ans=%n1%-%n2%
echo %input1% - %input2% = %ans%
goto :eof

:mul
echo Welcome to muptiplications (n*n=n)
set /p input1=first input:
set /p input2=second input:
set /a n1=input1
set /a n2=input2
set /a ans=%n1%*%n2%
echo %input1% * %input2% = %ans%

:eof
pause

To then use it, open cmd and type (assuming your file is called mybat.cmd:
mybat.cmd mul

Which will in turn in the batch call the label :mul
The fact that we use %~1 instead of %1 is that it can then also be run as:
mybat.cmd "mul"

Which will have the exact same result.
Here is a screenshot of this exact script as I tested it.

Just as a side note, you could also use set /p to prompt user what to run, then simply call the label accordingly. you then just have to run the batch file and not having to run it from cmd each time.

A: After the most general way Gerhard mentioned which I would personally simplify it as follows:
@echo off

if "%1" == "" (echo The file was either run regardless or from cmd without arguments. & exit /b 1)

:: This portion will use the paramter sent from cmd window.
call :%~1
goto :END

:plus
echo Welcome to additions (n+n=n)
set /p "input1=first input: "
set /p "input2=second input: "
set /a "ans=input1+input2"
echo %input1% + %input2% = %ans%

:sub
echo Welcome to subtractions (n-n=n)
set /p "input1=first input: "
set /p "input2=second input: "
set /a "ans=input1-input2""
echo %input1% - %input2% = %ans%

:mul
echo Welcome to muptiplications (n*n=n)
set /p "input1=first input: "
set /p "input2=second input: "
set /a "ans=input1*input2"
echo %input1% * %input2% = %ans%

:END
pause
exit /b 0

which I think it is much sorter, there is another way to do that:

*

*Create a batch file named additions.bat which will have the content:

@call yourfile.bat "plus"

*

*Create a batch file named subtractions.bat which will have the content:

@call yourfile.bat "sub"

*

*Create a batch file named muptiplications.bat which will have the content:

@call yourfile.bat "mul"

It will be much easier I think to just double-click the correct batch file and you will have what you want.


text:
Q: Why do I get I/O error 32 even though the file isn't open in any other program? I'm trying to write a line to a text file in Delphi 7 with the code below, but it gave this error:
"Raised Exception Class EInOutError with 'I/O error 32'"
AssignFile(trackertxt, 'tracker.txt');
ReWrite(trackertxt);
WriteLn(trackertxt, 'left'+':'+':');
CloseFile(trackertxt);

It's not being used by any other application, yet it still gives error 32.
(Also need it to overwrite the current content in the text file).

A: this is a simple example on how to write a simple text file
source of example is - http://www.delphibasics.co.uk/RTL.asp?Name=TextFile
code:
var
  myFile : TextFile;
  text   : string;

begin
  // Try to open the Test.txt file for writing to
  AssignFile(myFile, 'Test.txt');
  ReWrite(myFile);

  // Write a couple of well known words to this file
  WriteLn(myFile, 'Hello World');

  // Close the file
  CloseFile(myFile);

  // Reopen the file for reading
  Reset(myFile);

  // Display the file contents
  while not Eof(myFile) do
  begin
    ReadLn(myFile, text);
    ShowMessage(text);
  end;

  // Close the file for the last time
  CloseFile(myFile);
end;

if the file is locked by another process, or already locked by the current process(as Remy Lebeau pointed out) then you get an error as described here http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/delphivclwin32/SysUtils_EInOutError.html

32  Sharing violation

that means that another process is using that file, and you can not save your changes until that process is done using the same file.
the following code taken from this website http://www.swissdelphicenter.ch/torry/showcode.php?id=104 shows you how to verify if a file is already in use:
function IsFileInUse(FileName: TFileName): Boolean;
var
  HFileRes: HFILE;
begin
  Result := False;
  if not FileExists(FileName) then Exit;
  HFileRes := CreateFile(PChar(FileName),
                         GENERIC_READ or GENERIC_WRITE,
                         0,
                         nil,
                         OPEN_EXISTING,
                         FILE_ATTRIBUTE_NORMAL,
                         0);
  Result := (HFileRes = INVALID_HANDLE_VALUE);
  if not Result then
    CloseHandle(HFileRes);
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  if IsFileInUse('c:\Programs\delphi6\bin\delphi32.exe') then //here you need to change this with the path to the file you want to edit/write/etc
    ShowMessage('File is in use.');
  else
    ShowMessage('File not in use.');
end;

A: The code in your question will replace all content in the file with the text 'left::'. That part of your code is fine.
I/O error 32 is a sharing violation. The file is locked in a way that prevents your code writing to the file. Either another process, or even your own process has a lock on the file. The system doesn't lie. The file is already open somewhere which is why your code fails with error 32.
I think it most likely that your own program is the guilty party. Look at all the places in the code where you open that file. Do you have two or more file variables that are attached to that file? Are you 100% sure that you never open the file with one file variable whilst it is already open with another variable?


text:
Q: Excel VBA: Indexing a collection of SpecialCells I've noticed that if you apply the SpecialCells method to a range, and then index the elements of the resulting collection, what is returned are all the elements of the original range, not of the new range based on the SpecialCells criteria.
Sub test()

    Dim i As Range

    Selection.SpecialCells(xlCellTypeConstants).Select

    For Each i In Selection
        Debug.Print i
    Next

End Sub

For example, if you run the above code based on a range consisting of a constant, followed by a formula, followed by a constant, and then check the elements of Selection in the Immediate window you get the values: 1, 2, 3 (see image below).
However, if you iterate through the Selection, the values 1 and 3 are returned, as expected (again, see image below). Does anyone know why the returned values differ in each case?

A:
Situations to Test Collection in B1:B3 :

*

*1,2,3.

*1 =2, 3.

*1, =a1+a2, 3.
Sub TestofCollection()
  Dim Collection1 As Collection
   Dim n As Integer
    Dim x As Integer

   Set Collection1 = New Collection

   n = 1

  On Error Resume Next
     For Each Cell In Range("B1:B3")
        Collection1.Add n, CStr(Cell.Value)
        n = n + 1
    Next Cell
 On Error GoTo 0

 For x = 1 To Collection1.Count
    Range("C" & x).Value = Collection1.Item(x)
 Next x

End Sub


text:
Q: Return value int& I have a code like this.
#include <iostream>
using namespace std;

int c=0;
int& abc()
{
    c++;
    return c;
}

int main()
{
    cout << c << endl;
    int f = abc();
    cout << c << " " << f << endl;
    f++;
    cout << c << " " << f << endl;
}

The output I am getting is
0
1 1
1 2

Now the function abc returns an integer reference. So the statement int f=abc(); should point integers f and c to the same address. But why the statement f++ is not affecting the value of c?

A: int &f = abc();

Because your f is not a reference.It just a variable that be assigned a value of c.You should write it look like above.

A: That's because while abc() returns an int by reference, f doesn't "grab" this reference, but rather grabs the value the returned reference points to. If you want f to grab the reference, you need to define it as a reference type.
Do it like this:
#include <iostream>
using namespace std;

int c=0;
int& abc()
{
    c++;
    return c;
}

int main()
{
    cout << c << endl;
    int &f = abc();
    cout << c << " " << f << endl;
    f++;
    cout << c << " " << f << endl;
}

A: int f = abc();
^^^ // This type is 'int' not 'int&'

You're type for f is int which is no the same as int& and results in creating a copy. Therefore, instead of f being a reference to c it is a separate and distinct value that is initialized to the same value as stored in c when it is returned from abc.

A: Yes abc() returns a reference. But f is just an integer variable. Therefore whatint f=abc() does is assigning the value of c to f.
When you call f++ it only change the f variables value. It does not change the value of c. because f is not a pointer.

A: In following code: int f = abc() f is a copy of the value of c, these two values are distinct. When you perform ++f you are incrementing the copy f which will have no effect on c. When you do the following: int &f = abc() you are creating a reference variable f which is bound to the value of c and hence as f is an alias for the variable c, any changes made to f are made to c.


text:
Q: How to loop the jquery call more effectively instead of looping multiple times Using the below piece of logic we are trying to loop the records which are in DB suppose if I have 1000 rows then it is getting iterated 1000 times where it is taking more time instead of doing this how can I make it simpler and achieve the results quickly
 for (var row in db) {
            if (db.hasOwnProperty(row)) {
                if (currentid == db[row].actualid)
                    optionsHtmlString += '<option value="' + db[row].MemberId + '" selected="selected" title="' + db[row].FullName + '">' + db[row].FullName + '</option>';
                else
                    optionsHtmlString += '<option value="' + db[row].MemberId + '" title="' + db[row].FullName + '">' + db[row].FullName + '</option>';
            }
        }


text:
Q: cuda context creation and resource association in runtime API applications I want to understand how a cuda context is created and associated with a kernel in cuda runtime API applications?
I know it is done under the hood by driver APIs. But I would like to understand the timeline of the creation.
For a start I know cudaRegisterFatBinary is the first cuda api call made and it registers a fatbin file with the runtime. It is followed by a handful of cuda function registration APIs which call cuModuleLoad in the driver layer. But then if my Cuda runtime API application invokes cudaMalloc how is the pointer provided to this function associated with the context, which I believe should have been created beforehand. How does one get a handle to this already created context and associate the future runtime API calls with it? Please demystify the internal workings.
To quote NVIDIA's documentation on this

CUDA Runtime API calls operate on the CUDA Driver API CUcontext which
  is bound to the current host thread.
If there exists no CUDA Driver API CUcontext bound to the current
  thread at the time of a CUDA Runtime API call which requires a
  CUcontext then the CUDA Runtime will implicitly create a new CUcontext
  before executing the call.
If the CUDA Runtime creates a CUcontext then the CUcontext will be
  created using the parameters specified by the CUDA Runtime API
  functions cudaSetDevice, cudaSetValidDevices, cudaSetDeviceFlags,
  cudaGLSetGLDevice, cudaD3D9SetDirect3DDevice,
  cudaD3D10SetDirect3DDevice, and cudaD3D11SetDirect3DDevice. Note that
  these functions will fail with cudaErrorSetOnActiveProcess if they are
  called when a CUcontext is bound to the current host thread.
The lifetime of a CUcontext is managed by a reference counting
  mechanism. The reference count of a CUcontext is initially set to 0,
  and is incremented by cuCtxAttach and decremented by cuCtxDetach.
If a CUcontext is created by the CUDA Runtime, then the CUDA runtime
  will decrement the reference count of that CUcontext in the function
  cudaThreadExit. If a CUcontext is created by the CUDA Driver API (or
  is created by a separate instance of the CUDA Runtime API library),
  then the CUDA Runtime will not increment or decrement the reference
  count of that CUcontext.
All CUDA Runtime API state (e.g, global variables' addresses and
  values) travels with its underlying CUcontext. In particular, if a
  CUcontext is moved from one thread to another (using cuCtxPopCurrent
  and cuCtxPushCurrent) then all CUDA Runtime API state will move to
  that thread as well.

But what I don't understand is how does cuda runtime create the context? what API calls are used for this? Does the  nvcc compiler insert some API calls to do this at compile time or is this done entirely at runtime? If the former is true what run time APIs are used for this context management? It the later is true how exactly is it done ?
If a context is associated with a host thread, how do we get access to this context? Is it automatically associated with all the variables and pointer references dealt with by the  thread?
how ultimately is a module loading done in the context?

A: The CUDA runtime maintains a global list of modules to load, and adds to that list every time a DLL or .so that uses the CUDA runtime is loaded into the process.  But the modules are not actually loaded until a device is created.
Context creation and initialization is done "lazily" by the CUDA runtime -- every time you call a function like cudaMemcpy(), it checks to see whether CUDA has been initialized, and if it hasn't, it creates a context (on the device previously specified by cudaSetDevice(), or the default device if cudaSetDevice() was never called) and loads all the modules.  The context is associated with that CPU thread from then on, until it's changed by cudaSetDevice().
You can use context/thread management functions from the driver API, such as cuCtxPopCurrent()/cuCtxPushCurrent(), to use the context from a different thread.
You can call cudaFree(0); to force this lazy initialization to occur.
I'd strongly advise doing so at application initialization time, to avoid race conditions and undefined behavior.  Go ahead and enumerate and initialize the devices as early as possible in your app; once that is done, in CUDA 4.0 you can call cudaSetDevice() from any CPU thread and it will select the corresponding context that was created by your initialization code.


text:
Q: In a commutative ring $R$, $I+J =R$ for every non-zero ideal $J$ with $J\ne I$. Can I conclude that $I$ is principal? In a commutative with unity ring $R$ there is an ideal $I$ for which $I+J=R$ for every non-zero ideal $J$ and $J$ is not equal to $I$. Then I know $I$ must be maximal, but can I conclude $I=Rt$ for a $t$ contained in $I$?

A: Take $t \in I$, $t \neq 0$ (if such a $t$ does not exist, then $I = \{0\} = R \cdot 0$). You have either $I = Rt$ (then you are done) or you have $I \neq Rt$, in which case you get $I = I + Rt = R = R\cdot 1$.


text:
Q: How to dynamically create new todo list page with user inputs submitted from form I am building  a To-Do-List program in html, css and js.
I want a new project window to appear, containing the user's project name and description after the user clicks the submit button on the form after add project button is clicked.
However I don't see the values for inputName nor inputDescription. What am I doing wrong?
live code : (https://codepen.io/nolimitz71/pen/QWmBpPm?editors=1010)
JS:
const cancelButton = document.getElementById("cancel");
const projectForm = document.getElementById("projectForm");
const newPage = document.querySelector('.add-project');
const inputName = document.getElementById('project-name');
const inputDescription = document.getElementById('project-description');
const examplePage = document.querySelector(".example-page");
const createdContainer = document.createElement("div");
const projectHolder = document.querySelector(".item-placement");
const createdProject = document.createElement("button");
const container = document.querySelector(".body");

/*Controlling new Project form Open and Close*/
const closeProject = () => {
    projectForm.style.display = "none";
};
const openProject = () => {
    projectForm.style.display = "block";
};

newPage.addEventListener("click", openProject);

cancelButton.addEventListener("click", closeProject);

const subProjects = (() => {
    createdProject.setAttribute("id","change");
    createdProject.innerHTML =
    `
    <ion-icon name="checkmark-circle-outline"></ion-icon>
    ${inputName.value}
    `
    projectHolder.appendChild(createdProject);
})();

const LoadProject = (() => {
    createdContainer.setAttribute("id",'new-subpage');
    createdContainer.setAttribute("data-tab-content", "");
    container.appendChild(createdContainer);

    const paraName = document.createElement('p');
    paraName.textContent= inputName.value;
    paraName.classList.add("new-paragraph");
    createdContainer.appendChild(paraName);

    const paraDesc = document.createElement('p');
    paraDesc.textContent= inputDescription.value;
    paraDesc.classList.add('new-description');
    createdContainer.appendChild(paraDesc);

    const newTasks = document.createElement('button');
    newTasks.textContent = "Add Task!"
    newTasks.classList.add("new-btn");
    createdContainer.appendChild(newTasks);

    const defaultTask = document.createElement("div");
    defaultTask.classList.add("item");
    defaultTask.innerHTML= `
    <input class = "check" type="checkbox">

Default Task

       <ion-icon class = "black" name="pencil-outline"></ion-icon>
       <ion-icon class = "black"name="trash-outline"></ion-icon>

`
    createdContainer.appendChild(defaultTask);
})();

addPage.addEventListener("click", () => {
    examplePage.style.display = "none";
    createdContainer.style.display = "block";
})

export {closeProject, LoadProject, openProject};


text:
Q: Key - Values with JQuery autocomplete plugin Is the standard JQuery autocomplete able to get key-values instead of only keys or only values.
Forexample userIds and username.
1 - Roel Veldhuizen
2 - Pino Jansen
3 - Afred van Buren

Where the userId is the saved value but the username is the search value and the value which is showed to the user.
Current code:
<script>
                    <!--
                    $(document).ready(function() {
                        $("#creatorUserId").autocomplete("Gateway.php?action=UserAction&subAction=suggest");
                    });
                    -->
                    </script>
<input type="text" name="creatorUserId" id="creatorUserId" value="3" size="40" />

A: Check example on the offisial site: Remote JSONP datasource.
There you can find that JS objects are binded to autcomplete and you can use any property of this object. In your case you need to format objects with name and value and use value when you need.


text:
Q: Is there a console scroll lock in IntelliJ? I've recently moved from Eclipse to IntelliJ and one feature I'm missing (or maybe just can't find) is the console scroll lock i.e. stop refocusing on the latest console entry.
Is this possible in IntelliJ? I'm using v9 Ultimate edition.

A: It depends where your cursor is. Just click on the part you want to be scroll locked.

A: Just adding to this for google reasons - clicking at the bottom is hard when the console is still scrolling, it's a bit of a race - but control-end (or cmd-end on mac) also did it!

A: To unlock the scrolling just press "Enter" key inside of console window.

A: To unlock the scrollbar, click on the last line (should be blank) of the console.

A: To Unlock the scroll lock on intelliJ 14 (probably earlier as well) on OSX its
fn + cmd + right cursor.

A: In PyCharm 2017, there is a "Scroll to the end" button in the "Console" tab of the Debug window.
Disabling it stops the auto scroll on output.


text:
Q: How can I make these formulas work with google forms so they reproduce into new entries? I am trying to make a form that has these formulas do calculations for each entry. How to I make it so they do it for new entries?
=IF(AND(E2="Stfyc",G2<41),G2*0.49,IF(AND(E2="Stfyc",and(G2>40,G2<71)),G2*0.65,if(and(E2="Stfyc",and(G2>70,G2<101)),G2*0.77,if(and(E2="Stfyc",100<G2),0.94*G2,if(and(E2<>"Stfyc",G2<41),G2*1.2,if(and(E2<>"Stfyc",and(G2>40,G2<71)),1.45*G2,if(and(E2<>"Stfyc",and(G2>70,G2<101)),G2*1.8,if(and(E2<>"Stfyc",100<G2),2.1*G2))))))))

=IF(H2="30A",0,if(H2="2x30A",17,if(H2="50A",17,if(H2="2x50A",30,if(H2="100A",30,"")))))

=if(N2="","",N2-L2)

=if(O2="","",(J2+K2)*O2)

A: You need to use the special formula "arrayformula" that will allow you to set the formula on the first row of your document and it will be repeated for all the beneth rows.
here an exemple with the formula =if(N2="","",N2-L2)
With array formula it will be like: =arrayformula(if(N2:N="","",N2:N-L2:L))
the first 2 formulas you gave are a bit more complicated to encapsulate in an arrayformula (try to use named range for that)


text:
Q: JQuery Ajax / PHP Post - No Return I am trying to get a html page with jquery ajax to connect to an online database and return true or false if a query returns true or false.
Here is the code for the index.html file (This is running on my local pc in wamp)
The Query/Ajax Code:

And the Form...
<form id="ContactForm" onsubmit="return submitForm();">
    Username: <input id="username" type="text" name="username" value="" />

    Password: <input id="password" type="text" name="password" value="" />

    <input type="submit" name="submit" value="Submit" />

</form>

Now, here is the code on the server side...This file I''ve uploaded to the server where the database is resident:
<?php

  if(isset($_POST['username'])) {

      $username = $_POST['username'];
      $password = md5($_POST['password']);

      $con=mysqli_connect("localhost","dbuser","pass","myDatabase"); //Server Online

    if (mysqli_connect_errno())
      {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }

    $result = mysqli_query($con, "SELECT * FROM tblusers WHERE username='".$username."'");

     if ($result->num_rows) {

      echo "right login !!";

         } else {

         echo 'wrong login';

       }

     mysqli_close($con);

    }

?>

The problem is that nothing is returned on the html page (callback) ...
In other words.. this line:
$('#ContactForm').find('.form_result').html(response);

is not being called.
I've checked the console log and it returns 200 OK and the posts is actually submitted BUT nothing is returned to the page.
Any ideas what could be going wrong?

A: Try changing the following lines of code:
if($result->num_rows > 0){
    echo "right login !!";
} else{
    echo 'wrong login';
}

And then edit your AJAX to look like this (adding dataType: 'html')
$.ajax({type:'POST',
  url: 'http://mywebsite.com/test/index.php',
  data:$('#ContactForm').serialize(),
  dataType: 'html', //or dataType: 'text'
  success: function(response) {
       $('#ContactForm').find('.form_result').html(response);
  }
});

A: Try to change the if statement with:
if($result->num_rows > 0){

  echo "right login !!";

     } else {

     echo 'wrong login';

   }

A: Try using json_encode() on your 'right login' and 'wrong login' strings

A: On local pc with wamp for exemple, debugger may add debugging info in your php response. Then, statut is ok (200) but you response is not json parsable. Try to add a
 error: function (xhr, status, error) {
            var err = eval("(" + xhr.responseText + ")");
            alert(err.Message);
        }

in your ajax and you ll see that response contain debugging infos...


text:
Q: How to group jQuery functionality with grouped elements? My document contains grouped elements and with those elements comes functionality. I would like to be able to take this group of elements and their interaction with each other and place it wherever on the page when possible.
When I try to do this, my current jQuery code tries to change elements of one group while the other group is being interacted with. How do I keep these groups and their functionality seperated but able to use the same piece of jQuery functionality (preventing having to write double funcitonality)?
This is my code:

//If value of Dropdown 1 has been changed, do the following:
$( ".dd-first-check" ).change(function() {
  var selectedValue = $(".dd-first-check").val();

  //If the selected option has a value assigned to it, execute the following:
  if(selectedValue)
  {
    //$("#Dropdown1-error").hide();
    $( "#Dropdown1-error" ).addClass( "d-none" );
    $(".dd-second-check option").show();
    //Do something else
    //alert(selectedValue);
  }

}).trigger( "change" );

//Whenever Dropdown 2 has been clicked and Dropdown 1 value has not yet been set, show validation error:
$(".dd-second-check").click(function() {
 //If the selected option does not have a value assigned to it, execute the following:
  if(!$(".dd-first-check").val())
  {
   //Show validation message:
    //$("#Dropdown1-error").show();
    $( "#Dropdown1-error" ).removeClass( "d-none" );
    $(this).blur().focus();
  }
});

//Don't allow Dropdown 2 value to change when Dropdown 1 does not contain a selected value
//(this prevents "wrong" data from being send when DOM is manually edited on client side):
$( ".dd-second-check" ).change(function(e) {
  if(!$(".dd-first-check").val())
  {
    alert("No option was selected in previous dropdown.");

    //TO DO: Still requires some code
    //e.preventDefault;
  }
});
.dd-second-check option
{
  display: none;
}

.dd-group-1
{
  background-color: green;
}

.dd-group-2
{
  background-color: red;
}
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/>

<form>

          Group 1 Dropdown 1:
          <select class="form-control dd-first-check dd-group-1">
            <option disabled selected="selected">Choose an option...</option>
            <option value="1">Please load in more options...</option>
            <option value="2">Example option 2</option>
            <option value="3">Example option 3</option>
            <option value="4">Example option 4</option>
            <option value="5">Example option 5</option>
          </select>

            Dropdown 1 field is required.

          Group 1 Dropdown 2:
          <select id="group-1" class="form-control dd-second-check dd-group-1">
            <option disabled selected="selected">Choose an option...</option>
            <option>Please load in more options...</option>
          </select>

          Group 2 Dropdown 1:
          <select class="form-control dd-first-check dd-group-2">
            <option disabled selected="selected">Choose an option...</option>
            <option value="1">Please load in more options...</option>
            <option value="2">Example option 2</option>
            <option value="3">Example option 3</option>
            <option value="4">Example option 4</option>
            <option value="5">Example option 5</option>
          </select>

            Dropdown 1 field is required.

          Group 2 Dropdown 2:
          <select class="form-control dd-second-check dd-group-2">
            <option disabled selected="selected">Choose an option...</option>
            <option>Please load in more options...</option>
          </select>

</form>

Whenever I click the last dropdown element from the second group, jQuery will be executed for the validation element with that ID. So I need to get the ID of the validation element that belongs to that group. Is there a way I could make a relation between elements like this happen and make sure that the groups won't interact with each other whilst keeping the functionality of the first two drop down elements?
My goal is reusability.

A: I modified your fiddle to look for the element within a parent group and to use classes rather than id's for you error spans. The rows have an additional class called group.
This is used to find the current item's parent with a class of group.  That parent is then searched for the second element.
You need to ensure that you are only looking within the group

//If value of Dropdown 1 has been changed, do the following:
$( ".dd-first-check" ).change(function() {
  var selectedValue = $(this).val();
  //Get the parent group element
  var $group = $(this).parents('.group');
  //If the selected option has a value assigned to it, execute the following:
  if(selectedValue)
  {
    //$("#Dropdown1-error").hide();
    $group.find( ".dropdown-error" ).addClass( "d-none" );
    $group.find(".dd-second-check option").show();
    //Do something else
    //alert(selectedValue);
  }

}).trigger( "change" );

//Whenever Dropdown 2 has been clicked and Dropdown 1 value has not yet been set, show validation error:
$(".dd-second-check").click(function() {
  //Get the parent group element
  var $group = $(this).parents('.group');
 //If the selected option does not have a value assigned to it, execute the following:
  if(!$group.find(".dd-first-check").val())
  {
   //Show validation message:
    //$("#Dropdown1-error").show();
    $group.find( ".dropdown-error" ).removeClass( "d-none" );
    $(this).blur().focus();
  }
});

//Don't allow Dropdown 2 value to change when Dropdown 1 does not contain a selected value
//(this prevents "wrong" data from being send when DOM is manually edited on client side):
$( ".dd-second-check" ).change(function(e) {
  //Get the parent group element
  var $group = $(this).parents('.group');
  if(!$group.find(".dd-first-check").val())
  {
    alert("No option was selected in previous dropdown.");

    //TO DO: Still requires some code
    //e.preventDefault;
  }
});
.dd-second-check option
{
  display: none;
}

.dd-group-1
{
  background-color: green;
}

.dd-group-2
{
  background-color: red;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>

<form>

          Group 1 Dropdown 1:
          <select class="form-control dd-first-check dd-group-1">
            <option disabled selected="selected">Choose an option...</option>
            <option value="1">Please load in more options...</option>
            <option value="2">Example option 2</option>
            <option value="3">Example option 3</option>
            <option value="4">Example option 4</option>
            <option value="5">Example option 5</option>
          </select>

            Dropdown 1 field is required.

          Group 1 Dropdown 2:
          <select id="group-1" class="form-control dd-second-check dd-group-1">
            <option disabled selected="selected">Choose an option...</option>
            <option>Please load in more options...</option>
          </select>

          Group 2 Dropdown 1:
          <select class="form-control dd-first-check dd-group-2">
            <option disabled selected="selected">Choose an option...</option>
            <option value="1">Please load in more options...</option>
            <option value="2">Example option 2</option>
            <option value="3">Example option 3</option>
            <option value="4">Example option 4</option>
            <option value="5">Example option 5</option>
          </select>

            Dropdown 1 field is required.

          Group 2 Dropdown 2:
          <select class="form-control dd-second-check dd-group-2">
            <option disabled selected="selected">Choose an option...</option>
            <option>Please load in more options...</option>
          </select>

</form>


text:
Q: Veritasium - Firing bullet in block - along center and away from center This question is about this video on YouTube, in which a bullet is fired vertically into the center of a wooden block from below, sending the block up into the air. Next, a bullet is fired vertically but off-center into a similar block from below, again causing the block to rise into the air, but simultaneously to rotate. The video asks for a prediction as to which block will rise higher.
Please post your guess/prediction/solution along with answer or in comments.
My first guess was that air friction decreases when object is rotating, but now I think that's not the reason.
Someone please shed some light on this.
EDIT
Is it possible that the first bullet went deeper inside the first block and thus the first block had lesser kinetic energy than expected?

A: Here is the mathematical treatment of this experiment. A block of mass $m_{block}$ is at rest when struck by a bullet of mass $m_{bullet}$ traveling with $v_{bullet}$ at a distance $x$ from the center of the block.
If the impact is perfectly plastic then the linear velocity of the block at the impact point should equal the velocity of the bullet after the impact. If the momentum transferred from the bullet to the block is $J$ then the change in speed for the bullet during the impact is
$$ \Delta v_{bullet} = - \frac{J}{m_{bullet}} $$
The same momentum $J$ affects the block by imparting linear and angular velocity at the center of gravity of
$$ \begin{aligned} \Delta v_{block} & = \frac{J}{m_{block}}
\\ \Delta \omega_{block} & = \frac{x\, J}{I_{block}} \end{aligned} $$
where $I_{block}$ is the mass moment of inertia of the block.
For a purely plastic contact setting the final relative speed equal to zero means
$$ \begin{aligned}
 \Delta v_{block} + x \, \Delta \omega_{block} & = v_{bullet} + \Delta v_{bullet} \\
  \frac{J}{m_{block}} + \frac{x^2\, J}{I_{block}} & = v_{bullet} - \frac{J}{m_{bullet}}
\end{aligned} $$
which is solved for:
 $$   J  = \frac{v_{bullet}}{ \frac{1}{m_{bullet}} + \frac{1}{m_{block}} + \frac{x^2}{I_{block}} } $$
Now for the trick. The combined center of gravity is at $x_{cg} = x \frac{  m_{bullet}} { m_{block} +m_{bullet} } $ so the take off speed of the new cg is
$$ \begin{aligned}
   v_{cg} & = \Delta v_{block} + x_{cg} \Delta \omega_{block} \\
          & =  \frac{J}{m_{block}} + x \left( \frac{  m_{bullet}} { m_{block} +m_{bullet} } \right) \frac{x\, J}{I_{block}} \\
   v_{cg} & =\left( \frac{  m_{bullet}} { m_{block} +m_{bullet} } \right) v_{bullet}
\end{aligned} $$
The above expression means that the take of speed (and hence the height) of the cg of the combined block and bullet does not depend on the impact location $x$.

A: The system needs to conserve momentum. In both cases, the momentum is whatever m*v is for the bullet. Since it's the same in both cases, the bullet and block have the same vertical velocity.
Mechanical energy is not conserved. The reason the block hit on the side has more kinetic energy is that the bullet converted less of its kinetic energy into heat upon impact. We would find that this bullet penetrated less far into the block.

A: Maybe I think I got it.
You cannot apply mechanical energy conservation to an inelastic collision, which is happening when the bullet is getting stuck into the block.
So in the first case the bullet is losing more mechanical energy by being fired into the center of the block than the second case, so when they reach the same height the block in the second case has more mechanical energy(because it must have lost lesser energy).
The fact that they will go to the same height is fairly simple to prove, by momentum conservation which can be applied for any kind of collision, elastic or inelastic.
The bullet has the same momentum initially in both cases, and the mass of the final system(Block + bullet) is same in both the cases so we get the same initial linear velocity for both cases, which implies they will both go to the same height.

A: The answer is: less
Some amount of the momentum (energy) transferred results in
spin of the block, so less momentum (energy) is left for the
rise.
WRT thw idea that off-center hit will transfer more/less
momentum: nonsense!
The time needed to stop the bullet in the block is much
shorter than any movement of the block.
That is why that arrangement is called "ballistic".
The original version is a wooden Block (or a chest filled with
cotton or wet clay) hinged as a pendulum bob.
This is the traditional equipment used to measure momentum
of rifle bullets depicted in every basic mechanics textbook.
http://hyperphysics.phy-astr.gsu.edu/hbase/balpen.html
https://www.google.de/search?q=ballistic+pendulum&tbm=isch&tbo=u&source=univ&sa=X&ei=CxAeUtirOoeZhQfn94DADw&sqi=2&ved=0CDQQsAQ&biw=1338&bih=911

A: I was thinking the same thing you were: spinning reduced the air resistance. Since the spinning trick helps bullets travel faster with barrels that have riffling.
A lot of people are considering that it is probably that the block hit dead center because by hitting the block dead-center the collision was supposedly more inelastic.
Although I am going to be honest here and claim that there argument makes sense, I have a suggestion for testing both explanations:
1) Conduct a similar experiment but instead of using a wooden block use a material that will have a more elastic collision. If the results are slightly different it probably was due to heat loss. If not air-resistance was the cause.
2) Conduct a similar experiment with a wooden block but in a vacuum, [I don't know where one can find a vacuum as large other than space, but no matter]. If they travel the same distance then it was due to energy loss in heat, otherwise air-resistance.


text:
Q: How to change background-color of body with checkbox with pure CSS (if it's possible) I have a check-box, and want to change the background-color of body when that is checked, with pseudo-class ":checked". Is there any way to do this? I'll be thankful for any answer;

        <input id = "night" type = "checkbox">
        Night

#night:checked {
    background-color: #242729;
}

A: using jquery you can do it like this
    $('#night').change(function(){
      let color = $(this).is(':checked') ? 'black' : 'white';
      $('body').css('background-color', color);
    });

I don't know how to do in pure css, sorry

A: You can achieve this with pure css like so,
<input type="checkbox" id="cb_1" value="cb_val" name="cb_name">

     my checkbox text

With this css,
label { background-color:#333; color:#FFF; }

input[type="checkbox"]:checked + label {
    background: brown;
}

Keep in mind
The label has to be after the checkbox so you will need to style it around more to keep the same look you had.
Here is an option of styling it more to have the same appearance as you wanted, New fiddle. THIS DOES NOT involve positioning anything absolute, just some trickery.

A: If you are trying to do it with the body tag then it is not possible with Pure CSS. But you can if you will create a different "body" and "+" selector. You can check this link for an example
<input id="night" type="checkbox" hidden>

  Click to Switch Mode

Good luck and cheers!


text:
Q: WPF C# Roulette Game I want to create roulette game in WPF C# below mentioned code is working properly but I want to  stop wheel after 3 second but I am not getting the way to do it. Kindly help me out with same
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="WpfApplication2.MainWindow" Title="MainWindow" WindowState="Maximized">
<Canvas>
    <Canvas.Background>
        <ImageBrush ImageSource="Image/Background.jpg" AlignmentX="Right" AlignmentY="Bottom" Stretch="None"/>
    </Canvas.Background>
    <Ellipse Height="250" Width="250" Margin="200,100,-200,-100">
        <Ellipse.Fill>
            <ImageBrush x:Name="p2" ImageSource="Image/p2.png"/>
        </Ellipse.Fill>
        <Ellipse.RenderTransform>
            <RotateTransform x:Name="TransRotate11" CenterX="125" CenterY="125"/>
        </Ellipse.RenderTransform>
        <Ellipse.Triggers>
            <EventTrigger RoutedEvent="Image.Loaded">
                <BeginStoryboard>
                    <Storyboard x:Uid="s1" TargetProperty="Angle" RepeatBehavior="Forever">
                        <DoubleAnimation By="360" Duration="0:0:0.1" Storyboard.TargetName="TransRotate11" Storyboard.TargetProperty="Angle" FillBehavior="Stop"/>
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
        </Ellipse.Triggers>
    </Ellipse>
</Canvas>

A: If the duration of the animation is 0.1 seconds and you want it to run for 3 seconds, why not simply set its RepeatBehavior to 30 times:
<Storyboard x:Uid="s1">
    <DoubleAnimation Storyboard.TargetName="TransRotate11"
                     Storyboard.TargetProperty="Angle"
                     By="360" Duration="0:0:0.1"
                     RepeatBehavior="30x" FillBehavior="Stop" />
</Storyboard>


text:
Q: Convert Office 365 classic team site template id (STS#0) to modern site template id (STS#3) In SharePoint Online, I have a classic team site. I know the steps to convert the look and feel to modern UI using modern site pages. However, the template id of the actual site i.e. "STS#0" is not changed.
Is there a way to convert the template id from "STS#0" to "STS#3" using PowerShell or any other method?
Thanks in advance.

A: Based on my research, you can not change site template of an existing SharePoint site, it is by design.
We suggest that you can go to the Microsoft Tech Community to submit a feedback.
Reference:

*

*Change site template of an existing site collection


text:
Q: Matching large regular expression gives stack overflow error I'm trying to match a long string with below regular expression
100(\\n|\\r\\n)13(\\n|\\r\\n)150(\\n|\\r\\n)17((\\n|\\r\\n)205(\\n|\\r\\n)206((\\n|\\r\\n)209){1,7}((\\n|\\r\\n)300){1,4}((\\n|\\r\\n)107){0,1}){1,9999}(\\n|\\r\\n)109(\\n|\\r\\n)

But every time I am getting

stack over flow
  error.

I've googled alot and seen most of the time that people say it happens due to recursion.
I couldn't understand what it means here. Could any one explain
what recursion error is here
and
at what point it starts happening in regular expressions?
Second, what I can do with my regular expression to avoid this error?


text:
Q: Why my .bat file for deleting these files does not work? I'm trying to create a .bat file for deleting all the files with the extensions .aux, .log, .gz from a given folder. In the command line window it works but when I run the .bat file nothing happens. I'm getting crazy with it. Can anyone take a look at it:
echo off
erase /q "desktop\teste\*.log"
erase /q "desktop\teste\*.gz"
erase /q "desktop\teste\*.aux"
exit

Why doesn't it work?

A: are you sure you are in the same directory with your bat file as where you are in cmd?


text:
Q: How to migrate from Oracle Exadata X4-2 database to BigQuery?
*

*What are the migration considerations that should be taken?

*Is it better to have a new data model prepared beforehand fo BigQuery? Or move the data As-Is data model to bigquery first and then change the data model

*Any key considerations to make

*Any migration templates that can be used

*Any other key suggestions please indicate as well

A: *

*for a one off migration, you can output Oracle tables to Cloud Storage (as csv, avro or parquet) and then perform an import from Cloud Storage.  This can be wrapped up within a script using the BigQuery API and can make use of Cloud Composure if there is a need to orchestrate the load.  There are also several tools that can assist such as DataPrep and Data Flow, but each come at a cost and a learning curve.

*To make use of BigQuery is it is likely that you'll want to remodel, rather then reuse Oracles schema.

*You really need to understand the data you are starting with, the BigQuery environment that will support your business need going forward and size and complexity of the migration.  Take a look at this Oracle to BigQuery migration guide

*Migrations tend to be business/ data specific, so no templates that I am aware of

*Understand your data well and restructure to make use of BigQuery strengths (such as nested and repeated data).  Make sure you utilise partitions and clusters to suit your business querying need. Avoid the need for joins where you can.  Shift design consideration away from storage cost and towards query data structure and query optimisation for performance and query cost benefit


text:
Q: Como Autollenar las cajas de texto, desde su numero de identificacion "DNI" en PHP Y MYSQL como puedo autocompletar los campos Nombre y Apellido, una vez que se halla escrito el numero de documento relacionado al usuario, la idea es que se valide si existe este Nro de documento en la base de datos, luego autocompletar automaticamente y luego poder insertar el E-mail el cual es el objetivo, para poder agregarlo a la informacion del usuario.
el DNI es = al Nro de documento.
Adjunto imagen y codigo:

<?php

include("con_db.php");

if (isset($_POST['register'])) {
    if (strlen($_POST['dni']) >= 1 && strlen($_POST['nombre']) >= 1 && strlen($_POST['apellido']) >= 1 && strlen($_POST['email']) >= 1) {
        $dni = trim($_POST['dni']);
        $nombre = trim($_POST['nombre']);
        $apellido = trim($_POST['apellido']);
        $email = trim($_POST['email']);
        $fecha = date("d/m/y");
        //$consulta = "INSERT INTO registro(dni, nombre, apellido, email, fecha) VALUES ('$dni','$nombre','$apellido','$email','$fecha')";

        $consulta = "UPDATE registro SET nombre='$nombre', apellido='$apellido', email='$email' WHERE dni='$dni'";
        $resultado = mysqli_query($conex,$consulta);
        if ($resultado) {
            ?>

¡Actualisaste tus Datos Corecctamente!

           <?php
        } else {
            ?>

¡Ups ha ocurrido un error!

           <?php
        }
        }else {
            ?>

¡Por favor complete los campos!

           <?php
            }

}

?>

A: Puedes usar para lo que quieres ajax. En el momento en que cambies de input, puedes hacer una llamada a una función de ajax que recoja el valor del dni introducido en el primer input, esto hará una llamada a una función php que ejecutará una consulta a la db con ese dni, el cual, si todo está bien relacionado en la db, debería de extraer los datos el usuario.
Posteriormente, si la respuesta ha sido satisfactoria, podrías con jquery extraer los datos de tu respuesta y setearlos en los inputs correspondientes.
Sería algo como esto:
$.ajax(
   url: "tu ruta o archivo.php",
   Method:"post o get" en este caso sería una petición get,
   Data: {"dni" : $("#idInput o clase").val(),
   success: function(response) {
      Setea response.valor dentro de tu input
   },
   Error: function(response) {
     Captura el error y haz algo con el, por ejemplo un alert
   }
);

Php:
Crear función que ejecute una query y reciba el DNI del ajax
Más o. Menos este sería el pseudocodigo que deberías hacer. Siento no ser de más ayuda, estoy desde el móvil y por eso no puedo hacer mucho más xD. Espero te haya guiado.
Suerte y un saludo