text:
Q: How can I access contents of a SharePoint repo without downloading contents to my computer? OK so I will probably butcher some terminology but bear with me...
Our organization in transitioning to the Microsoft infrastructure. One thing that was done was backup to SharePoint of a NAS backup drive. What I am trying to figure out is how I access the contents of that backup without having to download massive files to my computer.
For example, suppose there was a folder on the backup drive called Foo that had large files bar.zip and baz.pptx in it. In the past I could mount the drive as a logical drive, say Z:, and I could then open a console or PowerShell window and do things like cd z:\Foo and dir z:\Foo\baz.zip. Or I could open baz.pptx in PowerPoint without having to copy it first to my local drive c:
Now the folder has been copied to SharePoint. I can access the location through my browser via the right URL, but can I do operations like the above from a PowerShell window without having to first make a local copy of the contents? In other words, I want to explore contents of the repo using console commands and scripts rather than by clicking around in the browser.
If this can be done, is there a good guide you can recommend? TIA

A: You can map a SharePoint folder to a drive letter, with some preparations.

*

*Add your SharePoint base URL to "Trusted Sites":
Run Internet Options > Security tab > Trusted Sites > Sites.

*In the Services applet, ensure that the WebClient service is running.
You may set it to start automatically.

*You may now map a drive-letter to the SharePoint folder via Explorer's
Map Network Drive, or using the net use command:
   net use T: \\poshlab2.sharepoint.com@SSL\sites\ITOps /persistent:yes

For extensive details with screenshots, see the article
How to Map a SharePoint Drive.


text:
Q: How to give the illusion of rotation to a moving ball  //draw method
 draw() {
     //draw the ball
     ctx.beginPath();
     ctx.arc(this.xPos, this.yPos, this.radius, 0, 2 * Math.PI), false;
     ctx.moveTo(this.xPos, this.yPos);
     var i;
     //use a for loop
     for (i = 1; i < 8; i++) {
         var x = this.radius * Math.cos(i * 2 / 7 * Math.PI) + this.xPos;
         var y = this.radius * Math.sin(i * 2 / 7 * Math.PI) + this.yPos;
         ctx.lineTo(x, y);
         ctx.moveTo(this.xPos, this.yPos);
     }

     ctx.lineTo(this.xPos, this.yPos);
     ctx.fillStyle = "rgba(125, 125, 125, 1)";
     ctx.strokeStyle = "red";
     ctx.fill();
     ctx.stroke();
 }

I'm completely new to graphics programming, and I am wondering how I could use a rotate method to shift all the lines in the circle (created by the draw method) by a fixed amount of radians as it moves
here is an image of the output:

A: There are more efficient ways to go about this, but they would require things like webgl or webgpu so just to get what you want going:
This is the 2D rotation matrix:

Add a theta parameter to your draw method and outside of the draw parameter increment it by a small amount like 0.001 on each iteration of a loop (remember to clear your canvas before drawing).
Then inside of your method, calculate the center C of your circle. The formula to rotate ANY shape round its centroid C'is:
R(theta) * (S - C) + C

Where S is the set of all points in your shape and R(theta) is the rotation matrix evaluated at theta.
In other words, for every pair of (x, y) coordinates in the cartwheel, you first subtract the center, then you multiply the resulting vector <x, y> by the rotation matrix FROM THE LEFT (R * V), the final vector <x', y'> represents the rotated shape.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Import Excel file into rally How can, I import excel file into rally and update features of existing features.
The Excel consists of multi selection options.
Please share the approach as I am new to work on rally using ExtJS ?
I have created a App which uploads excel file further approach would be appreciated.

A: You can either use the excel add-in for bulk creating data, or import excel files directly from the portfolio items page with this menu:


text:
Q: ASP.Net links won't disable if done during postback I'm still fairly new to ASP.Net, so forgive me if this is a stupid question.
On page load I'm displaying a progress meter after which I do a post back in order to handle the actual loading of the page.  During the post back, based on certain criteria I'm disabling certain links on the page.  However, the links won't disable.  I noticed that if I force the links to disable the first time in (through debug) that the links disable just fine.  However, I don't have the data I need at that time in order to make the decision to disable.
Code Behind
If (Not IsCallback) Then
    pnlLoading.Visible = True
    pnlQuote1.Visible = False
Else
    pnlLoading.Visible = False
    pnlQuote1.Visible = True
    <Load data from DB and web service>
    <Build page>
    If (<Some Criteria>) Then
        somelink.Disable = True
    End If
End If

JavaScript
if (document.getElementById('pnlQuote1') === null) {
    ob_post.post(null, 'PerformRating', ratingResult);
}

ob_post.post is an obout js function that does a normal postback and then follows up with a call to the server method named by the second param. then followed by the call to a JavaScript method named by the third param.  The first parameter is the page to post back to.  A value of null posts back to the current page.
The post back is working fine.  All methods are called in the correct order.  The code that gives me trouble is under the code behind in bold.  (somelink.disabled = True does not actually disable the link)  Again, if I debug and force the disabling of the link to happen the first time in, it disables.  Does anyone know what I might do to get around this?
Thanks,
GRB

A: Your code example is using the IsCallBack check, while the question text talks about the IsPostback Check.   I'd verify that you're using Page.IsPostBack in your code to turn off the links.


text:
Q: How to extract small part of the email body in Outlook using Python? I am trying to automate the extraction of information from the body of standard mails in my outlook.
I need to extract following info:

*

*code

*number1

*number3

And then transfer it to an excel file.
But for now I would like to know how to access this information in a mail body.
This is an example of an standard mail:
Subject: Test1

Hi,
You got a new answer from user Alex.

Code: alex123fj
Number1: 0611111111
Number2: 1020
Number3: 3032

This my code (I filtered mails so that I can access only mails that I got within 1 day):
import win32com.client
from datetime import datetime, timedelta

outlook = win32com.client.Dispatch('outlook.application')
mapi = outlook.GetNamespace("MAPI")

inbox = mapi.GetDefaultFolder(6)
messages = inbox.Items

received_dt = datetime.now() - timedelta(days=1)
received_dt = received_dt.strftime('%m/%d/%Y %H:%M %p')
messages = messages.Restrict("[ReceivedTime] >= '" + received_dt + "'")
messages = messages.Restrict("[SenderEmailAddress] = 'answers@gmail.com'")
messages = messages.Restrict("[Subject] = 'Test1'")

message = messages.GetLast()
body_content = message.body

A: Use regex example
https://regex101.com/r/b2t5iw/1

Code example with selected email
import re
import win32com.client

def get_body(Item):
    try:
        print(Item.Subject)
        body = Item.body
        matches = re.finditer(r"Code:\s(.*)$", body, re.MULTILINE)
        for match in matches:
            print("Code: ", match.group(1))
    except Exception as e:
        print(e)

if __name__ == '__main__':
    Outlook = win32com.client.Dispatch("Outlook.Application")
    Items = Outlook.ActiveExplorer().Selection
    Item = Items(1)
    get_body(Item)

should print

Code:  alex123fj


text:
Q: I can't make a redirection in wordpress I try to make a redirection in wordpress to change the page when the website is viewed by a mobile device. (I don't want wp-touch). The target page is external to wordpress.
I added this code in the header.php wordpress file:
//test if it is a mobile device
...

if ($mobile_browser > 0) {

    wp_redirect('Location: http://url-to-my-external-page' );
    exit;
}

I also tried in the index.php file but it doesn't work either.
What can I do?
Thanks

A: You're mixing PHP's header() function and WordPress' wp_redirect() function.
It's either:
header('Location: http://url-to-my-external-page');

or
wp_redirect('http://url-to-my-external-page');

A: Should be:
wp_redirect('url-to-my-external-page'); // without "Location:"


text:
Q: react-native-testing-library: how to test useEffect with act I am using react-native-testing-library to test my react-native component.
I have a component (for the purpose of this post, it has been over simplified):
export const ComponentUnderTest = () => {

 useEffect(() => {
   __make_api_call_here_then_update_state__
 }, [])

 return (
   <View>
     __content__goes__here
   </View>
 )
}

Here is my (simplified) component.spec.tsx:
import { render, act } from 'react-native-testing-library';
import { ComponentUnderTest } from './componentundertest.tsx';

test('it updates content on successful call', () => {
   let root;
   act(() => {
      root = render(<ComponentUnderTest />); // this fails with below error message
   });
   expect(...);
})

Now when I run this code, I get this error:
Can't access .root on unmounted test renderer

I don't even now what this error message means. I followed the docs from the react-native-testing-library on how to test with act and useEffect.
Any help would be greatly appreciated. Thanks

A: You can do it using: @testing-library/react-native
Example:
import { cleanup, fireEvent, render, debug, act} from '@testing-library/react-native'

afterEach(() => cleanup());

test('given correct credentials, gets response token.', async () => {
    const { debug, getByPlaceholderText, getByRole } = await render(<Component/>);

    await act( async () => {
            const emailInput = getByPlaceholderText('Email');;
            const passwordInput = getByPlaceholderText('Password');
            const submitBtn = getByRole('button', {name: '/submitBtn/i'});

            fireEvent.changeText(emailInput, 'email');
            fireEvent.changeText(passwordInput, 'password');
            fireEvent.press(submitBtn);
    });
});

Should work with useEffect also but I haven't tested it out myself. Works fine with useState.

A: root = render(<ComponentUnderTest />);

should be
 root = create(<ComponentUnderTest />);

----Full Code snippet. It works for me after above change
import React, { useState, useEffect } from 'react'
import { Text, View } from 'react-native'
import { render, act } from 'react-native-testing-library'
import { create } from 'react-test-renderer'

export const ComponentUnderTest = () => {
  useEffect(() => {}, [])

  return (
    <View>
      <Text>Hello</Text>
    </View>
  )
}

test('it updates content on successful call', () => {
  let root
  act(() => {
    root = create(<ComponentUnderTest />)
  })
})

A: I found a workaround:
import { render, waitFor } from 'react-native-testing-library';
import { ComponentUnderTest } from './componentundertest.tsx';

test('it updates content on successful call', async () => {
   const root = await waitFor(() =>
       render(<ComponentUnderTest />);
   );
   expect(...);
})

A: The following steps solved my case:

*

*Upgrading React and react-test-renderer versions to 16.9 or above which support async functions inside act (both packages need to be the same version as far as i know)

*Replacing react-native-testing-library's render with react-test-renderer's create as @helloworld suggested (Thank you kind sir, it helped me out)

*Making the test function async, preceding the act with await and passing an async function to it
The final result looked something like this:
test('it updates content on successful call', async () => {
  let root
  await act(async () => {
    root = create(<ComponentUnderTest />)
  })
})

A: The approach I'm using for testing asynchronous components with useEffect that triggers a rerender with setState is to set the test case up as normal, but use waitFor or findBy to block assertions until the component rerenders with the fetched data.
Here's a simple, runnable example:
import React, {useEffect, useState} from "react";
import {FlatList, Text} from "react-native";
import {render} from "@testing-library/react-native";

const Posts = () => {
  const [posts, setPosts] = useState(null);

  useEffect(() => {
    const url = "https://jsonplaceholder.typicode.com/posts";
    fetch(url).then(res => res.json()).then(setPosts);
  }, []);

  return !posts ? <Text>loading</Text> : <FlatList
    testID="posts"
    data={posts}
    renderItem={({item: {id, title}, index}) =>
      <Text testID="post" key={id}>{title}</Text>
    }
  />;
};

describe("Posts", () => {
  beforeEach(() => {
    global.fetch = jest.fn(url => Promise.resolve({
      ok: true,
      status: 200,
      json: () => Promise.resolve([
        {id: 1, title: "foo title"},
        {id: 2, title: "bar title"},
      ])
    }));
  });

  it("should fetch posts", async () => {
    const {findAllByTestId} = render(<Posts />);
    const posts = await findAllByTestId("post", {timeout: 500});
    expect(posts).toHaveLength(2);
    expect(posts[0]).toHaveTextContent("foo title");
    expect(posts[1]).toHaveTextContent("bar title");
    expect(fetch).toHaveBeenCalledTimes(1);
  });
});

This doesn't give me any act warnings, but I've had my share of those. This open GitHub issue appears to be the canonical resource.
Packages used:
{
  "dependencies": {
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-native": "^0.64.0",
    "react-native-web": "^0.15.6"
  },
  "devDependencies": {
    "@babel/core": "^7.13.15",
    "@testing-library/jest-native": "^4.0.1",
    "@testing-library/react-native": "^7.2.0",
    "babel-jest": "^26.6.3",
    "jest": "^26.6.3",
    "metro-react-native-babel-preset": "^0.65.2",
    "react-test-renderer": "^17.0.2"
  }
}

And in the Jest config:
setupFilesAfterEnv: ["@testing-library/jest-native/extend-expect"],

for the .toHaveTextContent matcher. Or you can use an import:
import "@testing-library/jest-native/extend-expect";

A: try it this way
it("should render <Component/>", async () => {
  await act(() => {
    render(<Activate />);
  });
});

A: You can use useEffects in your RNTL tests quite easily:
import { render, act } from '@testing-library/react-native';
import { ComponentUnderTest } from './componentundertest.tsx';

test('it updates content on successful call', () => {
   render(<ComponentUnderTest />)
   expect(await screen.findByText('Results)).toBeTruthy(); // A
})

There is no need to use act directly, RNTL uses it for you under the hook.
The exact predicate to be used on line A depends on the component changes you do in your useEffect callback. Here I just assume that when fetching succeeds there is some Text component displaying "Results" text.
Important thing to note is that your fetching is probably async so you need to use findBy* queries which will wait for async action to happen (default timeout it ~5000 ms, it can be tweaked).
Another thing to note, it's a good practice to mock network calls so your tests do not call true API. There are various reason for that, test execution speed, test stability, not always being able to achieve desired API response for testing purposes, etc. Recommend tool would be MSW library.

A: You need to use waitFor to wait for asynchronous requests to complete.
Here's an updated code snippet with an explanation:
import { render, waitFor } from 'react-native-testing-library';
import { ComponentUnderTest } from './componentundertest.tsx';

test('it updates content on successful call', async () => {

  // Mocking a successful API response
  yourMockApi.get.mockResolvedValue({});

  // Rendering the component under test
  render(<ComponentUnderTest />);

  // Wait for the API call to be made
  await waitFor(() => expect(yourMockApi.get).toBeCalled());
});

Explanation:

*

*The yourMockApi.get method is being mocked to return a successful
response using mockResolvedValue.

*The waitFor function is being used to wait until the mocked API call is made before continuing with the
test.

*The await keyword is used to wait for the waitFor function to
complete before continuing with the test.


text:
Q: Why is compiling with CGO_ENABLED=0 slower? When writing programs which utilize network, you can see quite noticeable slowdown of compilation with CGO_ENABLED=0.
For example, the simplest HTTP server:
package main

import (
    "flag"
    "fmt"
    "log"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hi! glad you requested %s.\n", r.URL.Path[1:])
}

func main() {
    port := flag.Int("port", 9000, "")
    flag.Parse()

    http.HandleFunc("/", handler)
    err := http.ListenAndServe(fmt.Sprintf(":%d", *port), nil)
    if err != nil {
        log.Fatal(err)
    }
}

the timings are:
% time go build
go build  0.46s user 0.06s system 131% cpu 0.396 total
% time CGO_ENABLED=0 go build
CGO_ENABLED=0 go build  3.93s user 0.15s system 143% cpu 2.849 total

So far I'm not using bindings to C so CGo handling or not seems irrelevant, what I'd like to do is to compile 100% static binary, but not if there's such slowdown.
What is the cause of such behavior?

A: This is the time spent re-building dependencies.
Go build by default does not save rebuilt dependencies. See the -i flag:

The -i flag installs the packages that are dependencies of the target.

Let's try your program with -i instead:
$ time go build -i .
real    0m0.337s
user    0m0.343s
sys 0m0.121s

$ time CGO_ENABLED=0 go build -i .
real    0m2.135s
user    0m3.098s
sys 0m0.196s

$ time CGO_ENABLED=0 go build .
real    0m0.329s
user    0m0.367s
sys 0m0.085s

$ time go build .
real    0m2.588s
user    0m3.393s
sys 0m0.300s

The first time you switch cgo mode, it needs to rebuild dependencies. If you specify -i, it will save them and the second build call will be much faster.

A: The problem is that the standard library packages are built without flags. CGO_ENABLED changes build flags and therefore it can't use the pre-built packages so most of the standard library needs to be rebuilt.
As the other answer mentioned, go build -i will install the packages built with the new flags, but that won't really solve much because if you install packages built with CGO_ENABLED=0, it will speed up all future builds with CGO_ENABLED=0, but it will slow down all the builds without it.
Unfortunately the way pre-built packages are installed by default today is pretty inefficient because everything goes into the same directory under the same names regardless of how it's built. If you want to be able to have fast builds of go programs with different flags, besides doing go build -i you also need to use the the -installsuffix and/or the -pkgdir flags. In the system I work in, we have a handful of different compilation modes, each mode has different flags (because of a lot of old C code we interface with) and each mode also has its own -pkgdir.


text:
Q: Show R documentation of a function in Shiny app I'm building a shiny app and I need one of the tabpanels to show the R Documentation of one of the functions of the package RecordLinkage, so the user can choose his argument options.
I have tried
library(shiny)
library(RecordLinkage)

ui <- fluidPage(

tabPanel("Literature of functions",

                  selectInput(
                    "literatureChoice",
                    "Choose a function : ",
                    choices = c("compare.dedup",
                                "compare.linkage")
                  ),

                  textOutput("literatureOutput")
         ),
)

server <- function(input, output) {
  output$literatureOutput <- renderText({
    ?compare.linkage
  })
}

But it doesn't show any documentation. I'm aware that ?compare.linkage shows in help panel in RStudio instead of the console.

A: R help documentations are stored in Rd objects. We need a way to fetch this object and render them in Shiny.
We fetch the Rd object with the help of Rd_fun() found in the gbRd package.
We then parse the file into html with Rd2HTML. The file is saved in the temp directory and read back into R.
The example is for the reactive() function found in the shiny package, replace it with whichever function required.
library(shiny)
library(gbRd)
library(tools)

ui <- fluidPage(

  tabPanel("Literature of functions",

           selectInput(
             "literatureChoice",
             "Choose a function : ",
             choices = c("compare.dedup",
                         "compare.linkage")
           ),

           htmlOutput("literatureOutput")
  )
)

server <- function(input, output) {
  output$literatureOutput <- renderText({
    temp = Rd2HTML(Rd_fun("reactive"),out = tempfile("docs"))
    content = read_file(temp)
    file.remove(temp)
    content
  })
}

shinyApp(ui,server)


text:
Q: How to determine 1000000th primitive number in less than 10 minutes in java? I need code to determine the 1000000-th primitive number in less than 10 minutes. I have written the class below, but it is not as fast as I need it to be. How to optimize this class to improve it's speed of calculation? You can use this class by calling the get_thPrimitive(int number). That will return a long.
public class PrimitiveF
{
    // this is our class named PrimitiveF
    private static boolean isPrimitive(long n)
    {
        //isPrimitive method is a private static method that is used in get_thPrimitive method
        //this method tells us if the number is primitive or not
        long p=(long)Math.sqrt(n);//here we get square of the input number

        int i=2;
        while(i<=p)//now we check the nember is primitive or not if it is primitive we'll return true
        {
            int k=0;
            for(int j=2;j<=i;j++)
                if(i%j==0)
                    k++;
            if(k==1)
            {
                if(n%i == 0)
                    return false;
            }
            i++;
        }

        return true;
    }

    public static long get_thPrimitive(int n)//get_thPrimitive method is a public static //method
    {
        //this method would give us the Xth primitive number
        int count=0,i=2;
        while(count < n)
        {
            if(isPrimitive(i))
                count++;
            i++;
        }

        return --i;
    }
}

A: You return false from that isPrimitive() method if and only if n has no prime divisiors.  To do that, you generate all primes up to sqrt(n)...but you are using many inner prime tests just to perform just one larger one, and you are using a slow method for those inner prime tests.
If the code is correct, but just too slow, then you can get a huge speedup by just:

*

*If n is even then return true if n is 2 or false for any other even number.

*In your loop, test only odd divisors starting at 3 and less than or equal to sqrt(n)+1. Do not worry if these are prime divisors or not.  It doesn't matter, and testing the divisors for primeness only slows you down.

If n is odd and has no odd divisors detected above, then it is prime.
That will drastically speed up your code.  If that still isn't fast enough, you can investigate using a Sieve algorithm.  The basic method is due to Eratosthenes in ancient times and is described at Wikipedia

A: If by primitive you mean prime (I have seen the terms used interchangeably), you're using one of the slowest algorithms. Search "sieve", perhaps "quadatric sieve" for a much faster solution.
Edit:
Oh, for the sieve, you'll need an array of size 16,000,000 (the millionth prime is a a bit shy of 15.5M).


text:
Q: How to skip certain row in listview's getView My listview get data from webservice and the returned data sometimes have some id (but different data).
For those data that have same id, i only want to display them in listview once.
What i tried in getView :
    if(position > 0)
        prevId = getItem(position-1).getId();

    if(getItem(position).getId() == prevId)
        //skip current row

The problem is, how to skip the current row? (because the id is same like the previous one)

A: The best way is to filter the data before entering it to the ListView
Please add the data structure and classes the you use to get detailed help
I think you need to do something like that (T stand for a type with getId() function):
   List<T> removeDuplicateFromList(List<T> data){
       HashMap<String,T> filterdData = new HashMap<String,T>();
       for (T t: data){
            if (!filterdData.containKey(t.getId()){
                  filterdData.put(t.getId(),t);
            }else{
                  //Update the data at the map if needed
            }
       }
       return filterdData.values();
   }

A: One solution might be that adding previous rows to an ArrayList , so on generating new row on getView() you can check that if the content of current row has an id which is inside of your arrayList then do nothing!


text:
Q: Hyphen in verbose regex comment causes error What's wrong with the following code - I pinpointed it to the hyphen in the comment, but why should that cause an error?
import re

valid = re.compile(r'''[^
\uFFFE\uFFFF   # non-characters
]''', re.VERBOSE)

Traceback (most recent call last):
  File "valid.py", line 5, in <module>
    ]''', re.VERBOSE)
  File "/usr/local/lib/python3.3/re.py", line 214, in compile
    return _compile(pattern, flags)
  File "/usr/local/lib/python3.3/re.py", line 281, in _compile
    p = sre_compile.compile(pattern, flags)
  File "/usr/local/lib/python3.3/sre_compile.py", line 494, in compile
    p = sre_parse.parse(p, flags)
  File "/usr/local/lib/python3.3/sre_parse.py", line 748, in parse
    p = _parse_sub(source, pattern, 0)
  File "/usr/local/lib/python3.3/sre_parse.py", line 360, in _parse_sub
    itemsappend(_parse(source, state))
  File "/usr/local/lib/python3.3/sre_parse.py", line 506, in _parse
    raise error("bad character range")
sre_constants.error: bad character range

This next segment without the hyphen is error free:
import re

valid = re.compile(r'''[^
\uFFFE\uFFFF   # non characters !! no errors
]''', re.VERBOSE)

Edit:
Adding to the answer of @nhahtdh, string concatenation seems another reasonable way to comment character classes in a verbose style:
valid = re.compile( r'[^'
r'\u0000-\u0008'    # C0 block first segment
r'\u000Bu\u000C'    # allow TAB U+0009, LF U+000A, and CR U+000D
r'\u000E-\u001F'    # rest of C0
r'\u007F'           # disallow DEL U+007F
r'\u0080-\u009F'    # All C1 block
r']'                # don't forget this!
r'''
| [0-9]    # normal verbose style
| [a-z]    # another term +++
''', re.VERBOSE)

A: According to the documentation (emphasis mine):

re.X
re.VERBOSE
This flag allows you to write regular expressions that look nicer. Whitespace within the pattern is ignored, except when in a character class or preceded by an unescaped backslash, and, when a line contains a '#' neither in a character class or preceded by an unescaped backslash, all characters from the leftmost such '#' through the end of the line are ignored.

Basically, you cannot have comment inside a character class, and whitespace inside character class is considered significant.
Since # is inside character class, it does not function as comment, and everything inside the character class is parsed as part of the character class without exception (even the new line character is parsed as part of the character class). The error is thrown due to n-c being invalid character range.
Valid way to write the expression would be:
valid = re.compile(r'[^\uFFFE\uFFFF]   # non-characters', re.VERBOSE)

Here is one suggestion on how to comment when you want to explain a lengthy character class:
r'''
# LOTS is for foo
# _ is a special fiz
# OF-LITERAL is for bar
[^LOTS_OF-LITERAL]
'''

A: Comments don't always play nice in regular expressions, and it looks like your regex engine is parsing the hyphen as part of the regular expression. You can't rely on comments not getting parsed here. This is a good thing to find out before implementing this code.


text:
Q: What the difference between Eclipse 3.7, 3.8 and 4.2? Eclipse Indigo is 3.7, and Eclipse Juno is 4.2, but 3.8M1 has just been released. What's 3.8 and how is this different from 3.7? I'm eagerly awaiting Java 7 support and am confused whether I should use 3.8M1 or wait for 3.7.1

A: 3.8M1 comes with Java 7 support. The JDT core build notes confirm that the work done for Java 7 support has been merged.

A: The Juno simultaneous release included both the 4.2 and the 3.8 versions of the Eclipse Application Platform (confusing, but true).
The 4.2 Eclipse Application Platform (also known as the e4, E4AP, or Eclipse 4.2 SDK) add changes to the workbench including "modeled UI, dependency injection and service-based programming model, CSS-based styling". Importantly, it also includes a 3.X compatibility layer. See the FAQ for more info.
Because of the compatibility layer, all of the Juno packages are supposed to run on either. The Juno packaged installs, however, are bundled with just the 4.2 Eclipse Application Platform.
That said, you can download the 3.8 Eclipse Platform and then install the Juno packages you want. See Eclipse 3.8: where is the download site? and How do I install an Eclipse EPP (for example EPP Modeling Feature on 3.8)?.
It's probably worth noting that 4.2 has numerous performance complaints (see What is the main reason for upgrading to Eclipse Juno? and Very slow Eclipse 4.2, how to make it more responsive?). This is probably related to the fact that the Eclipse Foundation ran out of funds to do the same performance testing on Juno that they have done in the past (see http://www.zdnet.com/google-sets-perfect-example-with-20000-donation-to-eclipse-7000003968/).

A:
...the feature and API set for the next feature release of the Eclipse
  SDK after 3.7, designated release 4.2 and code-named Juno. This
  release is occurring simultaneously with the 3.8 platform release. The
  4.2 release is a mature platform release containing significant new
  feature work, while the 3.8 release focuses on stability and bug
  fixes.

From:  http://www.eclipse.org/projects/project-plan.php?projectid=eclipse
Also, Java 7 support began with 3.7.1:
https://bugs.eclipse.org/bugs/show_bug.cgi?id=288548

A: There is very important difference: the debug buttons are available on the main toolbar so that you can continue the execution with editor maximized. This is 4.2 feature, not available in 3.7

A: All plugins for 3.8 fit 4.2 and 4.3 e.g. R statet plugin for 3.8 can be installed together with ADT (Android) and Pydev after many years of incompatibility between 3.7 and 4.1 (and earlier version pairs). 3.8 is emulated by 4.2 or sth like that.


text:
Q: ExpandableListView: inflate childview into parent groupview I have an ExpandableListView with a custom CursorTreeAdapter.
Group row layout has a frame (shape drawable) as background. I would like that child rows appear inside that frame and not below it.
How could I inflate child views inside parent groupview?


text:
Q: Notifications once product quantity reaches 0 I'm trying to send a notification when the product becomes out of stock.
This is the code I have on my Observer:
public function detectProductChanges($observer)
{
    $product = $observer->getEvent()->getProduct();

    if ($product->hasDataChanges()) {

        try {
            $oldStock = $product->getStockItem()->getOrigData('qty');
            $newStock = $product->getStockItem()->getData('qty');

            if ($newStock != '0' || $oldStock == $newStock) {
                return $this;
            }

            // send email...

        } catch (Exception $e) {
            Mage::log($e->getTraceAsString(), null, 'my_cute.log');
        }
    }

    return $this;
}

On the config.xml file I got the following:
<!-- ... -->
  <global>
    <events>
      <catalog_product_save_after>
        <observers>
          <reports_detect_product_changes>
            <type>singleton</type>
            <class>reports/observer</class>
            <method>detectProductChanges</method>
          </reports_detect_product_changes>
        </observers>
      </catalog_product_save_after>
    </events>
  </global>
<!-- ... -->

The thing is, if I edit a product on the admin side, everything's fine, but if I proceed to checkout a product, this event is not called, can you help please?

A: You also need to observe the event checkout_submit_all_after. That one is dispatched when an order is placed. You should get as parameter the order placed and you can access the products ordered and check their qty changes.


text:
Q: type of textarea in doctrine symfony1 i am wondering how to add types of textarea in symfony1 schema file,because i have tried all posibble ways but all become a textbox fields in forms
for exmaple
 file_desc: clob(65532)

Or
   file_desc: text

and result is
'dddd'  => new sfWidgetFormInputText(),

i want it should be like
 'dddd'               => new sfWidgetFormTextarea(),

thank you

A: With symfony 1.4/doctrine, you only need to use the type clob

file_desc: { type: clob }

http://docs.doctrine-project.org/projects/doctrine1/en/latest/en/manual/defining-models.html#clob

A: You should just define your column as string without specifying the length.
Like this:
file_desc: { type: string }


text:
Q: A good editor for APEX/VisualForce? I'm doing some APEX coding, which includes Triggers, and some Visualforce pages. I have found the editor that Salesforce provide is no good, and most of the time the auto complete functionality does not work.
Is there a good editor I can use so I get some autocomplete functionality?
If so, could it be tied to my Sandbox so when I save the code, it gets saved also in SFDC?

A: I highly recommend VS Code. Lot of useful extensions available here - https://developer.salesforce.com/tools/vscode/
Including one that you're looking for
https://developer.salesforce.com/tools/vscode/en/user-guide/deploy-on-save/

A: My recommendation is IntelliJ IDEA with the fantastic Illuminated Cloud 2 plugin. Unlike VSCode, this does cost money so it's only an option if you're going to continue developing for Salesforce.
Note that it works with all types of org and isn't restricted to using SFDX for your development (though I would recommend you did) since it also supports classic mdapi/tooling API development.

A: I haven't found better than JetBrains' Webstorm + a paid plugin called Illuminated Cloud (IntelliJ IDEA works with the plugin, too). I've used it for metadata and SFDX package development, and both are great.
Prior to that, I preferred Sublime with Maven's Mate. When that died, my team looked at several options, and settled on Webstorm because the performance of everything else was so poor.

A: I'd recommend you go with Visual Studio Code.  You can follow this Salesforce Trailhead to get everything setup quickly.
Set Up Visual Studio Code


text:
Q: How to normalize the schema to BCNF I am having some issues with normalization. I have a schema REPAYMENT which looks like this:
Now, from what I've gathered the functional dependencies that hold in the schema is
{borrower_id} --> {name, address, request_date, loan_amount}
{request_date} --> {repayment_date, loan_amount}
{loan_amount] --> {repayment_amount}
(correct me if I'm wrong?)
I'm supposed to normalise the schema to BCNF, but I'm a bit confused. Is the candidate key request_date and borrower_id?
It can be used to register information on the re- payments on micro loans. A borrower, his name and address, are identified with an unique borrower_id. Borrowers can have multiple loans at the same time, but each of those loans ( specified by loan_amount, repayment_date and repayment_amount) have a different re- quest date. Thus a loan can be identified with the borrower ID and the request date of the loan. The borrower can repay multiple (different) loans on the same date, but each loan can only be repaid once (on one date with one amount). There is a system which for each request date and amount of a loan determines the repayment date and amount to be repaid. The loan amount requested and the repaid amount are not the same since there is an interest rate that applies.

A: From the definition of candidate key:

In the relational model of databases, a candidate key of a relation is
  a minimal superkey for that relation; that is, a set of attributes
  such that:

*

*The relation does not have two distinct tuples (i.e. rows or records in common database language) with the same values for these
  attributes (which means that the set of attributes is a superkey)

*There is no proper subset of these attributes for which (1) holds (which means that the set is minimal).

Now your question :

Is the candidate key request_date and borrower_id?

It is a superkey, but not minimal one. Here's how we compute the candidate key.
Which attribute occurs only on the left side, considering all the F . D's ?
ITS  borrower_id.This means that it must be a part of every key of this given schema. Now let us compute its closure.
Because of {borrower_id} --> {name, address, request_date, loan_amount}:
closure(borrower_id) = borrower_id, name, address, request_date, loan_amount.
Because of {request_date} --> {repayment_date, loan_amount} and closure(borrower_id) has request_date, this means
closure(borrower_id) = borrower_id, name, address, request_date, loan_amount, repayment_date
And finally because of {loan_amount] --> {repayment_amount} and closure(borrower_id) has loan_amount, this means
closure(borrower_id) = borrower_id, name, address, request_date, loan_amount, repayment_date, repayment_amount
Because closure of borrower_id contains all the attributes, borrower_id is a key and since it is minimal, it is indeed the candidate key and the only one.
Now let us decompose the schema into BCNF. The algorithm is:

Given a schema R.

*

*Compute keys for R.

*Repeat until all relations are in BCNF.

*

*Pick any R' having a F.D A --> B that violates BCNF.

*Decompose R' into R1(A,B) and R2(A,Rest of attributes).

*Compute  F.D's for R1 and R2.

*Compute keys for R1 and R2.

Since {request_date} --> {repayment_date, loan_amount} and request_date is not a key, it violates BCNF so we split schema into two relations:

*

*R1(request_date,repayment_date,loan_amount)

*R2(borrower_id,name,address,request_date,repayment_amount)
Clearly R1 is in BCNF. But R2 is NOT in BCNF , because we missed the following F.D. which is:
address --> name

and we know address is not the key, so we split the R2 further as:

*

*R3(borrower_id,address,request_date,repayment_amount)

*R4(address,name)
Now, clearly both R3 and R4 are in BCNF. Had we not split the R2 further, we end up storing the same combination of address and name for every loan the person takes, which is redundancy.


text:
Q: checkout/session setQuote I am working with a module that has a lot of hard-coded calls to
Mage::getSingleton('checkout/session')->getQuote()
I am trying to call it from Adminhtml and in stead of rewriting a huge chunk of the module, I thought I would set the checkout session quote to the quote stored in my object (which is valid). However when I type the code:
Mage::getSingleton('checkout/session')
    ->setQuote($this->getQuote())
    ->save();

I get the following error:
Fatal error: Uncaught exception 'Exception' with message 'Serialization of 'Mage_Core_Model_Config_Element' is not allowed'

Is there a quick way to override the checkout/session's quote?

A: Normally if you want to load a quote from the admin you would use
/**
 * Retrieve quote object
 *
 * @return Mage_Sales_Model_Quote
 */
protected function _getQuote()
{
    return $this->_getSession()->getQuote();
}

/**
 * Retrieve session object
 *
 * @return Mage_Adminhtml_Model_Session_Quote
 */
protected function _getSession()
{
    return Mage::getSingleton('adminhtml/session_quote');
}

So if you know the quote id then you could try loading the quote
$this->_getSession()->clear();
$this->_getQuote()->setQuoteId($id)->setStoreId($store_id)->setIsActive(true)->load($id);


text:
Q: Error writing a file with file.write in Python. UnicodeEncodeError I have never dealt with encoding and decoding strings, so I am quite the newbie on this front.  I am receiving a UnicodeEncodeError when I try to write the contents I read from another file to a temporary file using file.write in Python. I get the following error:
UnicodeEncodeError: 'ascii' codec can't encode character u'\u201c' in position 41333: ordinal not in range(128)

Here is what I am doing in my code.  I am reading an XML file and getting the text from the "mydata" tag.  I then iterate through mydata to look for CDATA
    parser = etree.XMLParser(strip_cdata=False)
    root = etree.parse(myfile.xml, parser)
    data = root.findall('./mydata')
    # iterate through list to find text (lua code) contained in elements containing CDATA
    for item in myData:
        myCode = item.text

    # Write myCode to a temporary file.
    tempDirectory = tempfile.mkdtemp(suffix="", prefix="TEST_THIS_")
    file = open(tempDirectory + os.path.sep + "myCode.lua", "w")

    file.write(myCode + "\n")
    file.close()

It fails with the UnicodeEncodeError when I hit the following line:
file.write(myCode + "\n")

How should I properly encode and decode this?

A: Python2.7's open function does not transparently handle unicode characters like python3 does.  There is extensive documentation on this, but if you want to write unicode strings directly without decoding them, you can try this
>>> import codecs
>>> f = codecs.open(filename, 'w', encoding='utf8')
>>> f.write(u'\u201c')

For comparison, this is how the error happen
>>> f = open(filename, 'w')
>>> f.write(u'\u201c')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\u201c' in position 0: ordinal not in range(128)


text:
Q: How to configure JMX to bind to localhost only? I run Tomcat8 using JDK8 on Centos6.
I enable JMX using the following options:
CATALINA_OPTS="${CATALINA_OPTS} -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=9123 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.local.only=true"

Unfortunately, when I check what ports are opened I discover that these ports listen to all IP:
netstat -plunt | grep java
Proto Recv-Q Send-Q Local Address               Foreign Address             State       PID/Program name
tcp        0      0 :::60555                            :::*                LISTEN      22752/java
tcp        0      0 ::ffff:127.0.0.1:8080               :::*                LISTEN      22752/java
tcp        0      0 :::9123                             :::*                LISTEN      22752/java
tcp        0      0 :::40867                            :::*                LISTEN      22752/java

I suppose that if I configure -Dcom.sun.management.jmxremote.local.only=true all ports should be bind to localhost only (::ffff:127.0.0.1 will appear before all ports).
How to configure JMX to bind to localhost only?
Added
I do not create JMX I use Tomcat JMX: https://tomcat.apache.org/tomcat-8.0-doc/monitoring.html.

A: As far as I understand this answer and read Oracle's docs about it, there seems to be no way to configure it without coding. This says in the chapter "Connector server attributes":

When using the default JRMP transport, RMI socket factories can be
  specified using the attributes jmx.remote.rmi.client.socket.factory
  and jmx.remote.rmi.server.socket.factory in the environment given to
  the RMIConnectorServer constructor. The values of these attributes
  must be of type RMIClientSocketFactory and RMIServerSocketFactory,
  respectively. These factories are used when creating the RMI objects
  associated with the connector.

The only option I see is to implement a custom factory like here and pass the classname to the property along with the JAR/class in classpath.
Correct me if I am wrong.

A: What you ask for is unnecessary.
com.sun.management.jmxremote.local.only=true  (which by the way is already the default) means it will only accept connections from localhost. It doesn't mean it will only bind to the loopback interface as you assume. Not accepting connections from something not on the local host is just another way of doing it. From sun.management.jmxremote.LocalRMIServerSocketFactory you can see it is being done like this:
// Walk through the network interfaces to see
// if any of them matches the client's address.
// If true, then the client's address is local.
while (nis.hasMoreElements()) {
    NetworkInterface ni = nis.nextElement();
    Enumeration<InetAddress> addrs = ni.getInetAddresses();
    while (addrs.hasMoreElements()) {
        InetAddress localAddr = addrs.nextElement();
        if (localAddr.equals(remoteAddr)) {
            return socket;
        }
    }
}

Why it was done like this rather than binding to loopback, I don't know. But I believe it is just as secure. (or maybe not?)
But if you really want to, then since Java 8u102 and Java 7u131 system property com.sun.management.jmxremote.host binds the underlying RMI registry to the selected network interface. The value can be any string which is accepted by InetAddress.getByName(String).
Example:
-Dcom.sun.management.jmxremote.host=localhost
see: JDK-6425769 for more information.
Links: Java 8u102 Release Notes
What the docs doesn't mention anywhere is that even when setting com.sun.management.jmxremote.host you'll still see one JMX port which is bound to all network interfaces. This is because if com.sun.management.jmxremote.local.only=true then an instance of sun.management.jmxremote.LocalRMIServerSocketFactory will be started and that one doesn't allow customization, i.e. it doesn't respect com.sun.management.jmxremote.host property. If that is a bug, an oversight in the JDK-6425769 implementation or intentional, I do not know.


text: Q: Как получить доступ к библиотеке написанной на JS в приложении, написанном на Kotlin? Уже достаточно много времени потерял на поиск информации в интернете, но так ничего дельного и не нашёл. Заранее благодарю за ответ


text:
Q: Is (int&&)5 an integral constant expression? g++ accepts the code:
char b[static_cast<int&&>(5)];

N3936 [expr.const]/3 defines the term as:

An integral constant expression is an expression of integral or unscoped enumeration type, implicitly converted to a prvalue, where the converted expression is a core constant expression. [Note: Such expressions
  may be used as array bounds [...]

I'm unsure because the expression looks like it has type int&&  but the definition of integral type in 3.9 doesn't make any mention of reference types.
In case it was unclear, my question is: Is static_cast<int&&>(5) an integral constant expression?

Background: The question is motivated by the following example:
char *c = (1 - 1);
char *d = static_cast<int&&>(0);

All recent versions of g++ with -std=c++11 accept the c line but reject the d line.  The C++11 standard said that a null pointer constant is an integral constant expression with value 0 . (This was changed for C++14).
clang (3.4.1 and later) rejects the c line in -std=c++11 mode.
So it appears there is a bug in g++, but I'd like to confirm whether the bug is in the b or the d definition.

A: As far as I can tell static_cast<int&&>(5) is indeed a constant expression the result of this is an xvalue from the draft C++11 standard section 5.2.9 [expr.static.cast]:

[...]if T is an rvalue
  reference to object type, the result is an xvalue[...]

and if we then go to section 5.19 [expr.const] we have:

A conditional-expression is a core constant expression unless[...]

and we have the following bullet:

*

*an lvalue-to-rvalue conversion (4.1) unless it is applied to

with the following exception:

*

*a glvalue of literal type that refers to a non-volatile temporary object whose lifetime has not
  ended, initialized with a constant expression;

You also noted:

clang (3.4.1 and later) incorrectly rejects the c line in -std=c++11 mode.

but as T.C. noted since this change was applied via DR 903 clangs behavior is valid.


text:
Q: Copy/move semantics on FUSE I have a hash-value database with tags and I want to implement a FUSE interface for it. Because values are indexed by their hashes they must be read-only.
Native interface for this database is very simple:

*

*You can download, upload or tag a file.

*You can get the set of all defined tags.

*You can search for files tagged in accordance to a boolean combination of tags.

FUSE interface semantics are simple:

*

*Database is viewed as a big synthetic directory hierarchy where values are files named by its hash and tags are directories.

*cd-ing inside a directory is semantically equivalent to search for a given tag (naming conventions on paths can be used to implement boolean operations).

*read-ing a file is semantically equivalent to download (part of) a value (FUSE allows an stateless read so open and close can be no-ops).

*Copying/moving an inexistent file into a given path is equivalent to upload and tag it. Copying/moving an existent file into a given path is equivalent to add new tags.

*Any other operation throws an error.

This FUSE interface is quite usable and allows you to easily embed a tag file system inside a hierarchical one without the need of external tools like TagSpaces or Evernote.
My problem arises identifying a file copy or move from any other forbidden operation with FUSE interface: there are endless possible combination of operations with equivalent semantics.
What is the most reliable way to identify a file copy or move with FUSE interface?

A: Hooking rename of a file should be straightforward by implementing rename() fuse call. In this call, you will get path of both old and new location, so that you can check if the file comes from outside or not. That said, this would work only if user space tool renames a file by invoking rename(2) kernel call.
On the other hand, hooking file copy operation would be harder: it can't be done directly as there is no such fuse call - copying happens in user space completely and so it's not directly detectable in kernel space.
You could try to do some heuristics and process incoming fuse operations to detect rename of already stored file (eg. by hashing content of new file and comparing that with already existing files), but I'm not sure how much it makes sense in your case or if it would be actually practical.


text:
Q: VBA modify url link so it pulls data from today I am new to VBA and trying to create a module where data will be pulled on a daily bases and would like url link in the module to update automatically to today's date. How should I change current url? I assume I need to change only this part: 2021%2F11%2F23 . Appreciate any feedback
website = "https://fclm-portal.amazon.com/reports/processPathRollup?reportFormat=HTML&warehouseId=&maxIntradayDays=1&spanType=Intraday&startDateIntraday=2021%2F11%2F23&startHourIntraday=7&startMinuteIntraday=30&endDateIntraday=2021%2F11%2F23&endHourIntraday=18&endMinuteIntraday=0&_adjustPlanHours=on&_hideEmptyLineItems=on&employmentType=AllEmployees"

EDIT: now getting "Object variable or with block variable not set" on line ObVolume = ...
Dim response As String

Set request = CreateObject("MSXML2.XMLHTTP")
request.Open "GET", website, False
request.setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT" request.send

response = StrConv(request.responseBody, vbUnicode)
html.body.innerHTML = response
ObVolume = html.getElementsByClassName("actualVolume numeric").Item(172).innerText

A: Application.EncodeURL(Format(date,"yyyy/mm/dd")) will give you the part you need.
So:
website = "https://fclm-portal.amazon.com/reports/processPathRollup?" & _
     "reportFormat=HTML&warehouseId=&maxIntradayDays=1&spanType=Intraday&" & _
     "startDateIntraday=2021%2F11%2F23&startHourIntraday=7&startMinuteIntraday=30&" & _
     "endDateIntraday=<dt>&endHourIntraday=18&endMinuteIntraday=0&_adjustPlanHours=on&" & _
     "_hideEmptyLineItems=on&employmentType=AllEmployees"

website = Replace(website, "<dt>", Application.EncodeURL(Format(date,"yyyy/mm/dd")))


text:
Q: Changing the values of ng-repeat based on the ng-change function I am having the textfeilds where i will enter the date rage , so based on the date range the data will be fetched from the database . Now I am having the ng-repeat in view to show the data , So i need to change the data based on the values selected in the date rage . I have tried applying filters but it is not working because it has to hit the database when the values changed. can anyone suggest me solution?
<input ng-model="From_Date" ng-change="setCustomSelect()" type="text" class="form-control" placeholder="Select from  Date" datepicker readonly></input>
<input ng-model="To_Date" ng-change="setCustomSelect()" type="text" class="form-control "placeholder="Select to  Date" datepicker readonly></input>

              {{user.name}}

             {{user.email}}

A: As you stated your getting your data from a database, you should aim to pass the dates to your backend service, query your users by date and then return them.
You can use the ngChange directive on your inputs to call a function defined in your controller, which will in turn get data from your service and update your view with that data.
In your service you can make your request via Angular's $http service, passing the dates as params.
This is the sort of structure you can use:

// app.js
(function() {

  'use strict';

  angular.module('app', []);

})();

// main.controller.js
(function() {

  'use strict';

  angular.module('app').controller('MainController', MainController);

  MainController.$inject = ['UserService'];

  function MainController(UserService) {

    // make reference to this for controller as syntax
    var vm = this;

    // define our default dates
    vm.startDate = new Date();
    vm.endDate = new Date();

    // call our activate function
    activate();

    /*
     * @name activate
     * @type function
     *
     * @description
     * Initialises everything we need on startup
     *
     * @return nothing.
     */
    function activate() {

      // get our first set of users
      // Note: in my opinion you should make use of resolving
      // the data into the controller so you already have it
      getUsers(vm.startDate, vm.endDate);

    }

    /*
     * @name getUsers
     * @type function
     *
     * @description
     * Checks we have a valid start and end date
     * If we have valid dates, calls _getUsers
     *
     * @param {date} startDate The date to filter from
     * @param {date} endDate The date to filter to
     * @return nothing.
     */
    function getUsers(startDate, endDate) {

      if (!startDate || !endDate) {
        return;
      }

      _getUsers(startDate, endDate);

    }

    /*
     * @name _getUsers
     * @type function
     *
     * @description
     * Gets users from our API via our UserService
     *
     * @param {date} startDate The date to filter from
     * @param {date} endDate The date to filter to
     * @return nothing.
     */
    function _getUsers(startDate, endDate) {

      UserService.getUsers(startDate, endDate).then(function(users) {

        // update users
        vm.users = users;

      }, function(error) {

        // handle error

      });

    }

  }

})();

// user.service.js
(function() {

  'use strict';

  angular.module('app').factory('UserService', UserService);

  UserService.$inject = ['$log', '$q', '$http'];

  function UserService($log, $q, $http) {

    var service = {
      getUsers: getUsers
    };

    return service;

    /*
     * @name getUsers
     * @type function
     *
     * @description
     * Gets users from our API
     *
     * @param {date} startDate The date to filter from
     * @param {date} endDate The date to filter to
     * @return {promise} The result of the $http request
     */
    function getUsers(startDate, endDate) {

      // convert your date to whatever you need
      var startDateTime = startDate.getTime();
      var endDateTime = endDate.getTime();

      $log.debug("Getting users...");

      return $q(function(resolve, reject) {

        $http.get('http://example.com/api/users?startDate=' + startDateTime + '&endDate=' + endDateTime)
          .then(function(response) {

            $log.debug("Successful response getting users...", response);

            return resolve(response.data);

          }, function(error) {

            $log.debug("Failed to get users...", error);

            return reject(error);

          });

      });

    }

  }

})();

  <form name="dateForm">

    <input type="date" name="startDate" ng-model="MainCtrl.startDate" ng-change="MainCtrl.getUsers(MainCtrl.startDate, MainCtrl.endDate)">

    <input type="date" name="endDate" ng-model="MainCtrl.endDate" ng-change="MainCtrl.getUsers(MainCtrl.startDate, MainCtrl.endDate)">

  </form>

          {{user.name}}

          {{user.email}}


text:
Q: Conflicting class name in CSS I am using materializeCSS to build a website and it already has a class called carousel. However, I wish to use carousel from Flickity and I wanted to know what would happen if I include both files in an html.
This question is somewhat similar to this one but the answers do not satisfy my query.

A: I checked the flickity carousel on github ( https://github.com/metafizzy/flickity/blob/master/dist/flickity.css ) and it appears to me that everything in the css starts with .flickity- so it shouldn't be a problem.
You're probably talking about this part found on their site:
$('.main-carousel').flickity({
  // options
  cellAlign: 'left',
  contain: true
});

That .main-carousel could be anything you want, as long as it matches with the class you use in your markup:

...

...

...


text:
Q: How to load facebook JS SDk in the jQuery block? According to Facebook: "The best place to put this code is right after the opening  tag"
Example:

But I would like like to add this in the jquery block $(document).ready(function() { }
How can that be done?

A: Include jQuery, and then...
$(document).ready(function(){
    callFB();
    loginClick(); // Call function
});

function callFB(){
    window.fbAsyncInit = function() {
      FB.init({
        appId      : 'YOUR_APP_ID', // App ID
        channelURL : '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel File
        status     : true, // check login status
        cookie     : true, // enable cookies to allow the server to access the session
        oauth      : true, // enable OAuth 2.0
        xfbml      : true  // parse XFBML
      });

    // Additional initialization code here
  };

  // Load the SDK Asynchronously
  (function(d){
     var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
     js = d.createElement('script'); js.id = id; js.async = true;
     js.src = "//connect.facebook.net/en_US/all.js";
     d.getElementsByTagName('head')[0].appendChild(js);
   }(document));

}

function loginClick(){
   // your click handling code in here
}

A: This is more what you're looking for I think...
https://developers.facebook.com/docs/javascript/howto/jquery/

A: You can try this jQuery plugin i made too.. :]
jQuery.fbInit = function(app_id) {
    window.fbAsyncInit = function() {
        FB.init({
            appId      : app_id, // App ID
            status     : true, // check login status
            cookie     : true, // enable cookies to allow the server to access the session
            xfbml      : true  // parse XFBML
        });
    };

    // Load the SDK Asynchronously
    (function(d){
        var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
        js = d.createElement('script'); js.id = id; js.async = true;
        js.src = "//connect.facebook.net/en_US/all.js";
        d.getElementsByTagName('head')[0].appendChild(js);
    }(document));

    $('
').attr('id','fb-root').appendTo('body');
};

$(document).ready(function(){
    $.fbInit('12345678901234');
});


text:
Q: Is the trait Owner useful in unit tests? In 2012, Visual Studio has introduced the concept of trait, as described in this article.
One of the attributes is the Owner trait that specifies the person responsible for a test method.
I would like to know if it is recommended to use this trait or not. My primary intuition will be to ignore this feature because of the collective code ownership principle.
So my question is : what are the reasons we should use (or not) the Owner trait in Visual Studio unit testing framework ?

A: Your question can be broadened and applied to all forms of program source code.
On a large team it can be useful to have a reference naming a first point of contact, however such information is liable to become out of date. The source control commit history provides a more dynamic view of code familiarity/ownership but non technical QA people might not be familiar with these tools.
There is no right or wrong, it is a local cultural team decision.


text:
Q: Change text colour in custom Toolbar By default, my Action Bar has white text.
I have a View that uses a custom Toolbar, but the text shows up black instead.
I can't see what the issue is. I'm guessing it's do to with inheritance?
Snippet from activity_stories.xml:
<android.support.design.widget.AppBarLayout
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:theme="@style/AppTheme.NoActionBar">

   <android.support.v7.widget.Toolbar
       android:id="@+id/toolbar"
       android:layout_width="match_parent"
       android:layout_height="?attr/actionBarSize"
       android:background="?attr/colorPrimary"
       app:layout_scrollFlags="scroll|enterAlways" />

   <android.support.design.widget.TabLayout
       android:id="@+id/tabs"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       app:tabMode="fixed"
       app:tabGravity="fill"/>

</android.support.design.widget.AppBarLayout>

My styles.xml:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:textColor">@android:color/black</item>
    </style>

    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>

    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

</resources>

My AndroidManifest.xml:
<application
   android:allowBackup="true"
   android:icon="@mipmap/ic_launcher"
   android:label="@string/app_name"
   android:roundIcon="@mipmap/ic_launcher_round"
   android:supportsRtl="true"
   android:theme="@style/AppTheme">

   <activity android:name=".MainActivity">
       <intent-filter>
           <action android:name="android.intent.action.MAIN" />
           <category android:name="android.intent.category.LAUNCHER" />
       </intent-filter>
   </activity>
   <activity android:name=".StoriesActivity" android:theme="@style/AppTheme.NoActionBar" />
   <activity android:name=".StoryBodyActivity"></activity>

</application>

A: My solution was to change <activity android:name=".MainActivity" /> to <activity android:name=".MainActivity" android:theme="@style/AppTheme.NoActionBar" />

A: 1.set android:textColorPrimary and android:textColorPrimaryInverse in styles
2.set in Toolbar
Try this .
 <android.support.v7.widget.Toolbar
    app:theme="@style/yourToolbar" />

 <style name="yourToolbar" parent="Theme.AppCompat.NoActionBar">
     <!-- android:textColorPrimary is the  color of the title text
      in the Toolbar, in the Theme.AppCompat theme:  -->
     <item name="android:textColorPrimary">@color/my_color</item>

     <!-- android:textColorPrimaryInverse is the  color of the title
      text in the Toolbar, in the Theme.AppCompat.Light theme:  -->
     <item name="android:textColorPrimaryInverse">@color/my_color</item>
</style>


text:
Q: Does JavaScript have a Map literal notation? As of ES6, JavaScript has a proper Map object. I don't see a way to use a literal notation though, as you could with an Array or an Object. Am I missing it, or does it not exist?
Array: var arr = ["Foo", "Bar"];
Object: var obj = { foo: "Foo", bar: "Bar" };
Map: ???

A: No, ES6 does not have a literal notation for Maps or Sets.
You will have to use their constructors, passing an iterable (typically an array literal):
var map = new Map([["foo", "Foo"], ["bar", "Bar"], …]);

var set = new Set(["Foo", "Bar", …]);

There are some proposals to add new literal syntax to the language, but none made it into ES6 (and I'm personally not confident they will make it into any future version).

A: There is a way to do it, like we do with literals
const fruits = new Map(Object.entries({apples: 1, bananas: 2}))

A: It's like a HashMap -- there is no literal version. You have to define it like you would a constructor.
You can read this topic which discusses map literals though, and why they should be added. It's basically others potential proposals on Map literals. I personally can't forsee a literal syntax in ES7, since Maps are very easy to use as is -- but in future proposals there could be syntactic sugar applied.
An example of potential literal notation was discussed using an octothorp (a hash) to look something like:
const myMap = Map#{expression("derp"): value("herp")};

A: It's 2023 and map literal syntax is still not included in ECMAScript standard, though this NPM package called map-literal does exactly what you want.
Object.entries() can make a Map object for you, but it cannot deal with nested structures. Therefore you will need to use a package for that.


text:
Q: Woocommerce product rewrite rules not working I am trying to change the default structure of the woocommerce product url to include the author username.
The default url for woocommerce products in my installation is as so:
https://<site_url>/product/<product-name>

I want to change it to something like this:
https://<site_url>/product/<author-username>/<product-name>

This is the code that I have so far:
function so_pre_get_posts( $query ) {
    // check if the user is requesting an admin page
    // or current query is not the main query
    if ( is_admin() || ! $query->is_main_query() ){
        return;
    }
  //since the author is not included in woocommerce query vars add author username to query_vars
  $post_type = get_query_var( 'post_type' );
  if($post_type === 'product'){
    $post_name = get_query_var( 'name');
    if ( $post = get_page_by_path($post_name,OBJECT,'product') ){
      $id = $post->ID;
      $author_id = get_post_field( 'post_author', $id );
      $author = get_userdata($author_id);
      $author_username = $author->user_login;
      $query->set( 'seller',$author_username);
    }else{
      return;
    }
  }
}

//add rewrite rules
function so_rewrite_tag_rule() {
  add_rewrite_tag( '%seller%', '([^&]+)' );
    add_rewrite_rule('^product/([^/]+)/([^/]+)/?$', 'index.php?seller=$matches[1]&name=$matches[2]','top');
  flush_rewrite_rules();
}
add_action( 'pre_get_posts', 'so_pre_get_posts', 1 );
add_action('init', 'so_rewrite_tag_rule', 10, 0);

However when I visit the product page for any product it still resolves to the default woocommerce
permalink structure. I made sure to flush the permalinks in my code so I have no idea what the issue is.

A: No need to add additional rewrite rule for that, WooCommerce already provide a way to mess with product permalink. Visit Wp Admin > General > Permalink page, and use /product/%author%/ as Product permalinks value. This will organize the product url as you need.
However, WooCommerce won't replace %author% tag with product's author as like we see with post permalink, so you have to replace the tag using post_type_link filter.
// replace %author%

add_filter( 'post_type_link', 'wpse_post_type_link', 20, 2 );

function wpse_post_type_link( $permalink, $post ) {
    if ( 'product' === $post->post_type && false !== strpos( $permalink, '%author%' ) ) {
        $author = get_the_author_meta( 'user_nicename', $post->post_author );
        $permalink = str_replace( '%author%', $author, $permalink );
    }

    return $permalink;
}


text:
Q: C# project referring to VB.NET project: Could not find assembly 'Microsoft.VisualBasic, Version 10.0.0.0' I have a C# WPF project that refers to a VB.NET WPF project. Certain windows in the C# project use UserControls defined in the VB.NET project. Recently I have been unable to build the C# project because of these UserControls. The build output shows the following for each window that uses the VB.NET UserControl:
error MC1000: Unknown build error, 'Could not find assembly 'Microsoft.VisualBasic, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. Either explicitly load this assembly using a method such as LoadFromAssemblyPath() or use a MetadataAssemblyResolver that returns a valid assembly. Line 37 Position 134.'
The build error is resolved if I add a Microsoft.VisualBasic reference to the C# project's dependencies. However, this wasn't required until recently. I first noticed it with Visual Studio Preview 16.4 then changed back to Enterprise with 16.3. I'm currently using VS Enterprise 16.3.9 and now have the same issue there (even though it worked for this version before).
My question is, is it really necessary to add a Microsoft.VisualBasic reference to my C# project or is this something else?

A: If your referenced code relies on the Microsoft.VisualBasic assembly, the runtime needs to be able to find it when running your application.
Either add it as a direct reference from your application, or make sure that you set the Copy Local property of the reference to true in the VB.NET project.


text:
Q: Subset data in R I have several time series and want to regress the dependent variable on the explanatory variables. My question is: Because of structural breaks in my series I do not want to include all the observations in my regression. How can I select the a range of observations for my regression using R?

*

*5

*6

*8

*20

*25

*28

For example: Suppose this is my data set. Now for my first regression I just want to use the obeservations 1 to 3 and for the second regression I want to use the observations 4 to 6. How can this be done without opening my dataset in excel and then rearrange my data?

A: If ddf is your data.frame in R, ddf[1:3,] will be first 3 rows and ddf[4:6,] will be the next 3 rows.
> ddf
        vnum1 vint1
1   3.0234578     8
2   0.3066877     1
3   0.5863406    10
4   0.7042274     9
5  -0.3851640     8
6   1.1231421     3
7   1.8489773     5
8  -0.3630053     8
9   1.1821609     4
10 -0.5690902     9
>
>
> ddf[1:3,]
      vnum1 vint1
1 3.0234578     8
2 0.3066877     1
3 0.5863406    10
>
> ddf[5:8,]
       vnum1 vint1
5 -0.3851640     8
6  1.1231421     3
7  1.8489773     5
8 -0.3630053     8

So you can run your regression as:
lm(vnum1~vint1, data=ddf[1:3,])


text:
Q: How to convert .raw file video format to avi or mp4? I want to convert the raw format to any other format. Is there any software for it? I download more than 10 software. But it doesn't support .raw file type to convert

A: RAW files do not have a standard format and may require proprietary software so it's difficult to answer your question accurately without knowing what created the file.
The Wikipedia page on Raw Image Format does suggest some software that may read RAW files such as dcraw and darktable.


text:
Q: Razor with Url.Content helper is ending quotes at space in URL I'm using ASP.NET Core 2 with Razor to try and pass an image URL into the View via a ViewModel. Unfortunately, the image URL has spaces in it, which I don't have control over at the moment.
I have a file name like this (note the space):
https://example.com/images/file name.jpg

I'm using Razor to try and show the image like this:

The output HTML looks like this:

Obviously this will not do! I should mention, we know this all works when we use an image that has no spaces in the file name. Here are some ways I've tried to correct the issue:
Using Url.Content helper in Razor (this did not make a difference):

Using System.Web.HttpUtility.UrlEncode when populating the ViewModel (this results in a "double-encoding" error):
myViewModel.ImageUrl = HttpUtility.UrlEncode(someUrl);

My goal is to get the URL encoded properly (no "double-encoding" and no truncating at the space in the input string). How can I achieve this goal?

A: The problem is that Razor will attempt to create valid HTML, so when it sees a space it automatically closes the quotation marks, so:
@{string img = "a a.jpg";}

Gets rendered as
 // of course invalid

So, you need to be sure you include your quotation marks, then Razor will use them:

Which gets rendered as

A: You can try

but I agree that using invalid URLs (with spaces) doesn't seem very useful in the long run.


text:
Q: Cannot access Jenkins Master URL on slave machine I'm trying to configure the Jenkins Master/Slave on our AWS windows server. I looked at other posts and researched online and followed the steps. I installed Jenkins on the server, and changed the jenkins url to the ip address of the server by command ipconfig: http://x.x.x.x:8080/. On the Jenkins xml file, I added the line to the argument: --httpListenAddress=0.0.0.0.
I followed the online tutorial step by step guide to set up master and agent. On the agent computer, when i try to access the url, it shows This site can't be reached. I added the port 8080 to the firewall. I also tried to ping from the agent to the master and it failed, said lost 4 100%. I am not sure how can I access jenkins master url outside of the server. Any help is appreciated.

A: The root cause is hidden in the comments, so for clarity posting it as an answer - looks like the problem was that the agent is running on a users laptop and it's trying to connect on a private IP of the jenkins server running in AWS. Things should hopefully work after connecting the agent on a public IP of the master instead.


text:
Q: Difference between eval and alias commands what are the differences between eval and alias commands?
Examples:
x='ls -d -l $HOME'
$x
eval $x

alias y='ls -l -d $HOME'
y

A: Mostly semantics. While combining your command strings into variables is useful for scripting purposes, it isn't good for aliasing. One visible reason is completion - while various completion scripts, like bash_completion might be able to deal with aliases (which sadly never happened to be my case), making them assume that variables are extendable to commands could make it somehow messy.
Second reason is alias allows you to make command shortcuts without using any magic command nor character like $ to run them. This way the substitution is transparent and it allows to override default settings for some programs. One good example is ls, which is often aliased as ls --color=auto by default. Users don't have to know that to see colored output. Some distributions alias rm and related commands as rm -i, so they work in interactive mode and can prevent accidental removals.
Variables on the other hand may be useful for some uses that don't require mimicking binaries. A wide and good example is EDITOR environmental variable. It makes it possible not only to run your favorite editor using $EDITOR, but also makes other programs (which may not have access to shell) able to run it, taking it's value from their execution environment.
There might be some other things I'm not aware of, but the outcome is the same: those commands are to be used as they're intended.

A: Aliases are not to be used in scripts (disabled by default in non-interactive shells. You can even combine several aliases (like several strings for eval). But aliases don't give you the nice level of indirection which you get from the command line getting parsed twice:
text1=foo; text2=bar; text3=fubar
for((i=1;i<4;i++)); do
  eval echo \$text${i}
done

I admit this could be done without eval (varname=text${i}; echo ${!varname}). But when constructing commands I would always use eval.
shell-expand-line (M-C-e) works with neither without errors. :-)


text:
Q: How do I find how many different elements does a list have? in lisp How do I find, in Lisp, how many different elements does a list have?

A: (length (remove-duplicates <your list>))

The shortest way of doing it, but it is also possible to do it in a single pass, like so:
(defun count-distinct (list)
  (let ((table (make-hash-table)))
    (dolist (i list (hash-table-count table))
      (setf (gethash i table) t))))


text:
Q: Attribute error in a simple xmlrpc python script I have a simple xmlrpc server setup to start a SMTP server, the code is here:
from SimpleXMLRPCServer import SimpleXMLRPCServer
import smtplib

# Create server
server = SimpleXMLRPCServer(("localhost", 1025), allow_none = True)

# add the introspection functions (system.listMethods, system.methodHelp
# and system.methodSignature)
server.register_introspection_functions()

def send(host, port):
    server = smtplib.SMTP((host, port), None)

# register this method
server.register_function(send, 'send')

# start server
server.serve_forever()

I start this server and on the client side I perform the following steps:
import xmlrpclib
s = xmlrpclib.ServerProxy('http://localhost:1025')
s.send('0.0.0.0',25)

which result in the following error I do not understand:
xmlrpclib.Fault: <Fault 1: "<type 'exceptions.AttributeError'>:'tuple' object has no attribute 'find'">

What tuple object is meant here? Why does the code require an attribute find? Any ideas that help me to get this code working, i.e. that I am able to make a xmlrpc request to initialize (and later use) a smtp server inside the xmlrpc server?
Thanks
  Alex

A: In the smtplib documentation it's stated the the signature of the SMTP class accepts two distinct parameters for host and port.
Thus you should define your send function in this way:
def send(host, port):
    server = smtplib.SMTP(host, port)

Probably the SMTP constructor expects a string as host, and uses the find method.
But if you pass in the tuple (host, port) then that AttributeError is generated.


text:
Q: i want all nodes of level which i node i am passing in start with clause Suppose following is hierarchy:

I am passing 5, so i am excepting 5,4,2,1 so how can I do it.
Thanks in advance.

A: If you want all ancestors and siblings of 5 then use parent id in start with clause:
/* sample data
with t(id, pid) as (
    select 1, null from dual union all
    select 2,    1 from dual union all
    select 3,    1 from dual union all
    select 4,    2 from dual union all
    select 5,    2 from dual union all
    select 6,    3 from dual ) */
select distinct id
  from t connect by prior pid = id
  start with pid = (select pid from t where id = 5)


text:
Q: What do you call a fake abbreviation? What do you call a fake abbreviation? Like saying that CNN stands for Crap News Network instead of Cable News Network. What do you call it?

A: An acronym is an initialism that forms a pronounceable word, like SCUBA or RADAR or NASA. If someone develops an initialism for the express purpose of spelling a particular word, for example the USA PATRIOT Act,1 that is called a backronym (backwards acronym).
"CNN" is only an abbreviation, not an acronym, because "CNN" is not a pronounceable word. But you might be able to stretch the definition and say that "Crap News Network" is a backronym for CNN.

1Uniting and Strengthening America by Providing Appropriate Tools Required to Intercept and Obstruct Terrorism Act


text:
Q: Exceptions not being thrown in .net I turned my pc on this morning, and when I started testing some apps, I noticed that no exceptions are thrown (no dialog or anything).
The code just stops executing and nothing happens!
Example:
private void Form1_Load(object sender, EventArgs e)
{
    throw new Exception("error");
    //anything below will not execute
}

visual studio doesn't show any error dialog, I also tried to run the .exe directly and nothing happens as well...
I tested it with .net 2.0, 3.5 and 4.0! All the same...
any idea whats wrong?

A: Visual Studio: CTRL+ALT+E -> Enable "Thrown" under Common Language Runtime Exceptions.

A: I know of two possible reasons:

*

*You assigned an unhandled exception handler to your AppDomain that does nothing

*The code throwing the exception runs on a different thread

What does the Windows Application event log say?


text:
Q: PKCS1 encryption in Flutter won't work without reflection I'm writing some code to encrypt data from a flutter client and send it to our servers. We are using PKCS1 padded RSA but i get the error below when attempting to encrypt the data.
I/flutter (12394): Bad state: Reflectable has not been initialized.
I/flutter (12394): Please make sure that the first action taken by your program
I/flutter (12394): in `main` is to call `initializeReflectable()`.

The code responsible for this is as follows.
static String encrypt(String text, RSAPublicKey pubKey) {
    var cipher = PKCS1Encoding(RSAEngine());
    cipher.init(true, PublicKeyParameter<RSAPublicKey>(pubKey));
    Uint8List output1 = cipher.process(utf8.encode(text));
    return base64Encode(output1);
}

I've managed to get a non padded sample running fine but the PKCS1 padded encryption requires a random generator that is initialized through reflection and flutter is saying no.
Any help would be appreciated.

A: The reflection based Random constructor has been replaced with FortunaRandom and seeded.
_random = new FortunaRandom();
_random.seed(KeyParameter(_seed()));

The PR has been approved and is in master now so no one should have this issue ever again!


text:
Q: Prove that the limit of $\lim\limits_{x \to 4}{\frac{\sqrt{x}-2}{x-4}} = \frac{1}{4}$ I was asked to prove, using the definition of limit, that
$$\lim\limits_{x \to 4}{\frac{\sqrt{x}-2}{x-4}} = \frac{1}{4}$$
I tried doing it but I am not completely sure my prove is correct. I am publishing it here so that more knowledgeable people can check it for me, maybe pointing any pitfalls.
I need to prove that for any $\epsilon > 0$ there is a $\delta > 0$ such that if $0 < \left|x - 4\right| < \delta$ then $\left|\frac{\sqrt{x}-2}{x-4} - \frac{1}{4}\right| < \epsilon$
First part: Tying to find a suitable $\delta$, given an $\epsilon$
$$\left|\frac{\sqrt{x}-2}{x-4} - \frac{1}{4}\right| < \epsilon$$
$$\left|\frac{4(\sqrt{x}-2) - (x-4)}{4(x-4)}\right| < \epsilon$$
$$\left|\frac{4\sqrt{x} - 8 - x + 4}{4(x-4)}\right| < \epsilon$$
$$\left|\frac{4\sqrt{x} - x - 4}{4(x-4)}\right| < \epsilon$$
$$\left|\frac{-x + 4\sqrt{x} - 4}{4(x-4)}\right| < \epsilon$$
$$\left|\frac{-(x - 2\cdot\sqrt{x}\cdot 2 + 4)}{4(x-4)}\right| < \epsilon$$
$$\left|\frac{-(\sqrt{x} - 2)^2}{4(\sqrt{x}+2)(\sqrt{x}-2)}\right| < \epsilon$$
$$\left|\frac{-(\sqrt{x} - 2)}{4(\sqrt{x}+2)}\right| < \epsilon$$
$$\left|-\frac{1}{4}\right| \left|\frac{\sqrt{x} - 2}{\sqrt{x}+2}\right| < \epsilon$$
$$\frac{1}{4} \left|\frac{\sqrt{x} - 2}{\sqrt{x}+2}\right| < \epsilon$$
$$\left|\frac{\sqrt{x} - 2}{\sqrt{x}+2}\right| < 4\epsilon$$
$$-4\epsilon < \frac{\sqrt{x} - 2}{\sqrt{x}+2} < 4\epsilon$$
First inequation:
$$-4\epsilon < \frac{\sqrt{x} - 2}{\sqrt{x}+2}$$
Multiplying by $\sqrt{x} + 2$ (which is positive):
$$-4\epsilon (\sqrt{x}+2) < \sqrt{x} - 2$$
$$-4\epsilon \sqrt{x} -8\epsilon < \sqrt{x} - 2$$
$$ - 8\epsilon + 2 < \sqrt{x} + 4\epsilon \sqrt{x}$$
$$ 2(1 - 4\epsilon) < (1 + 4\epsilon) \sqrt{x}$$
$$ \frac{2(1 - 4\epsilon)}{1+4\epsilon} < \sqrt{x}$$
$$ \left[\frac{2(1 - 4\epsilon)}{1+4\epsilon}\right]^2 < (\sqrt{x})^2$$
$$ \frac{4(1 - 4\epsilon)^2}{(1+4\epsilon)^2} < x$$
$$ \frac{4(1 - 4\epsilon)^2}{(1+4\epsilon)^2} - 4 < x - 4$$
$$ 4\left[\frac{(1 - 4\epsilon)^2}{(1+4\epsilon)^2} - 1\right] < x - 4$$
$$ 4\left[\frac{(1 - 4\epsilon)^2 - (1 + 4\epsilon)^2}{(1+4\epsilon)^2}\right] < x - 4$$
$$ 4\left[\frac{1 - 8\epsilon + 16\epsilon^2 - 1 - 8\epsilon - 16\epsilon^2}{(1+4\epsilon)^2}\right] < x - 4$$
$$ 4\left[\frac{-16\epsilon}{(1+4\epsilon)^2}\right] < x - 4$$
$$ \frac{-72\epsilon}{(1+4\epsilon)^2} < x - 4$$
Second inequation:
$$\frac{\sqrt{x} - 2}{\sqrt{x}+2} < 4\epsilon$$
Multiplying by $\sqrt{x} + 2$ (which is positive):
$$\sqrt{x} - 2 < 4\epsilon (\sqrt{x}+2)$$
$$\sqrt{x} - 2 < 4\epsilon \sqrt{x} + 8\epsilon$$
$$\sqrt{x} - 4\epsilon \sqrt{x} < 8\epsilon + 2$$
$$ (1 - 4\epsilon) \sqrt{x} < 2(1 + 4\epsilon)$$
$$\sqrt{x} <  \frac{2(1 + 4\epsilon)}{1-4\epsilon}$$
$$(\sqrt{x})^2 <  \left[\frac{2(1 + 4\epsilon)}{1-4\epsilon}\right]^2$$
$$x <  \frac{4(1 + 4\epsilon)^2}{(1-4\epsilon)^2}$$
$$x - 4 < \frac{4(1 + 4\epsilon)^2}{(1-4\epsilon)^2} - 4$$
$$x - 4 < 4\left[\frac{(1 + 4\epsilon)^2}{(1-4\epsilon)^2} - 1\right]$$
$$x - 4 < 4\left[\frac{(1 + 4\epsilon)^2 - (1 - 4\epsilon)^2}{(1-4\epsilon)^2}\right]$$
$$x - 4 < 4\left[\frac{1 + 8\epsilon + 16\epsilon^2 - 1 + 8\epsilon - 16\epsilon^2}{(1-4\epsilon)^2}\right]$$
$$x - 4 < 4\left[\frac{16\epsilon}{(1-4\epsilon)^2}\right]$$
$$x - 4 < \frac{72\epsilon}{(1-4\epsilon)^2}$$
Therefore:
$$- \frac{72\epsilon}{(1+4\epsilon)^2} < x - 4 < \frac{72\epsilon}{(1-4\epsilon)^2}$$
Taking the minimum of $\frac{72\epsilon}{(1+4\epsilon)^2}$ and $\frac{72\epsilon}{(1-4\epsilon)^2}$ as the value for $\delta$:
$$ \delta = \min\left[\frac{72\epsilon}{(1+4\epsilon)^2} , \frac{72\epsilon}{(1-4\epsilon)^2}\right]$$
$$ \delta = \frac{72\epsilon}{(1+4\epsilon)^2}$$
Second part: Prove
Prove that
$$ 0 < \left|x-4\right| < \frac{72\epsilon}{(1+4\epsilon)^2} \implies \left|\frac{\sqrt{x}-2}{x-4} - \frac{1}{4}\right| < \epsilon$$
Is it correct so far? How to proceed from here?

A: Correct. Now,
$$0 < \left|x-4\right| < \frac{72\epsilon}{(1+4\epsilon)^2} \implies  \frac{-72\epsilon}{(1+4\epsilon)^2} < x-4 < \frac{72\epsilon}{(1+4\epsilon)^2}$$
But: $$\frac{72\epsilon}{(1+4\epsilon)^2} < \frac{72\epsilon}{(1-4\epsilon)^2}$$
Hence:
$$\frac{-72\epsilon}{(1+4\epsilon)^2} < x-4 < \frac{72\epsilon}{(1-4\epsilon)^2}$$
I am sure you can proceed from here.

A: $$\frac{\sqrt x -2}{x-4}=\frac{\sqrt x -2}{(\sqrt x -2)(\sqrt x +2)}$$
so
$$\lim_{x\to 4}\frac{\sqrt x -2}{x-4}=\lim_{x\to 4} \frac{1}{\sqrt x +2}=\frac 14$$


text:
Q: Use Environ("LOCALAPPDATA") with a Public Const. (or an alternative solution) I have been using the following VBA code
Public Const COSTER_FOLDER = "C:\Coster"

But this will no longer work when they shift the folder location.
The new Coster folder is Environ("LOCALAPPDATA") & "\Coster"
Is there a simple way to do this using a Constant or is there a better way?
Regards Peter

A: Here's another option. Remove the old definition, and use this.
Public Function COSTER_FOLDER() As String
    COSTER_FOLDER = Environ("LOCALAPPDATA") & "\Coster"
End Function

Then you can use it the same way:
Debug.Print COSTER_FOLDER & "\test.txt"


text:
Q: Designing DAL in .NET to be "data-source independent" and not just "database independent"? How to design such flexible DAL (specifically in .NET) ?
What interfaces .NET provides and what should be done on my own ?
Its a greenfield project starting with SQL Server as data source but in future, parts of it will move to different NoSQL type of datastores.
Also, we may need to experiment with lot of different datastores (like some data may have to go with Cassandra, some with RDBMS, some to other DHT etc.)
Therefore easily switchable access layer will be needed. All i know right now is the 'data' and 'operations needed on that data'.

A: Simply: you do not. Ths is not so much about technology, but about totally different behavioral characteristics between different stores.
For example, SQL really shines in queries, and any decent DAL will expose those in a dynamic fashion (i..e no "GetCustomerById" function).
Replacing this with a XML File will be horrific and put a lot of stress on the DAL side - you need to reimplement a very powerfull search semantics without the proper disc structures to speed it up.
Most NoSQL data stores seriously ysuck once you get used to the proper relational theorem. They are not compareable in behavior and functionality, and as such a DAL can not abstract this away in a nontrivial project.

A: Ok, it's a bit of a fluffy question, but you might get some ideas if you look at something like NHibernate. I'm not suggesting you adopt it (or don't adopt it) but you'll see how a mature framework like that separates repository specifics from the code.
Also, take a look at how the framework defines connections, commands, etc for SQL Server. There's a SqlConnection which implements IDbConnection. If your code then operates on IDbConnection you are free to switch to say an oracle connection (well in theory).


text:
Q: How to get a CNG key handle to a public certificate previously imported to windows Cert: store (in Delphi)? I need to use CNG to verify a message signature (RSA). The only problem is how to get the CNG key handle (NCRYPT_KEY_HANDLE or BCRYPT_KEY_HANDLE) if I have the public certificate stored in windows certs (Cert:\CurrentUser\My).
I am using a
NCryptOpenStorageProvider({out}hProv, MS_KEY_STORAGE_PROVIDER, 0)

and I tried to get the public key handle using
NCryptOpenKey(hProv, {out}hKey, PWideChar('my.test.com'), AT_KEYEXCHANGE, 0)

but it seems that NCryptOpenKey() can only open the certificates that also have private keys.
I was also looking at BCryptImportKeyPair() but this requires to have the public key in BCRYPT_RSAKEY_BLOB structure which I don't know how to achieve.
The last function I was looking at was NCryptImportKey() but this again only works with private keys.
Anyone knows how to get the public key handle using CNG?
I have the public key in a file (cer/pem) and I imported it to windows Cert: store but if you know how to load it directly from a file to CNG key handle I would be happy as well.

A: NCrypt* functions works with persisted key pairs which stored at Key Storage Provider. If you import certificate in certificate store and this certificate does not contain private key then public key will not save in KSP.
You can use function CryptImportPublicKeyInfoEx2 to acquire BCRYPT_KEY_HANDLE.
Sample code in C:
HCERTSTORE hStore = nullptr;
    PCCERT_CONTEXT pCert = nullptr;
    BCRYPT_KEY_HANDLE hKey = nullptr;

    /* Open MY certificate store */
    hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, NULL, CERT_SYSTEM_STORE_CURRENT_USER, L"MY");
    if (!hStore) {
        goto Exit;
    }

    /* Find your certificate in store. For example search by subject name */
    pCert = CertFindCertificateInStore(hStore, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0, CERT_FIND_SUBJECT_STR, L"subject name", nullptr);
    if (!pCert) {
        goto Exit;
    }

    /* Or if you want to load certificate from file (assuming you read file to cert_data):

        pCert = CertCreateCertificateContext(X509_ASN_ENCODING, cert_data, cert_size);

    */

    /* Now you can create BCRYPTKEY_HANDLE from your public key */
    if (!CryptImportPublicKeyInfoEx2(X509_ASN_ENCODING, &pCert->pCertInfo->SubjectPublicKeyInfo, 0, nullptr, &hKey)) {
        goto Exit;
    }

    /* Now you can verify signature with BCryptVerifySignature(hKey...) */

Exit:
    /* Don't forget to free handle after use */
    if (hKey) {
        BCryptDestroyKey(hKey);
    }
    if (pCert) {
        CertFreeCertificateContext(pCert);
    }
    if (hStore) {
        CertCloseStore(hStore, 0);
    }
    return 0;


text:
Q: Show that this process is identically Bernoulli distributed, indepednent and stationary Let $$\operatorname{frac}(x):=x-\lfloor x\rfloor\;\;\;\text{for }x\ge0$$ and $$\theta(x):=\operatorname{frac}(2x)\;\;\;\text{for }x\in[0,1)$$ denote the Bernoulli shift. Now define $$X(x):=\lfloor 2x\rfloor=\left.\begin{cases}0&\displaystyle\text{, if }x\in\left[0,\frac12\right)\\1&\displaystyle\text{, if }x\in\left[\frac12,1\right)\end{cases}\right\}\;\;\;\text{for }x\in[0,1)$$ and $$X_n:=X\circ\theta^{n-1}\;\;\;\text{for }n\in\mathbb N.$$

How can we show that $(X_n)_{n\in\mathbb N}$, considered as a process on the probability space $([0,1),\mathcal (B[0,1)),\operatorname P)$, where $\operatorname P$ is the Lebesgue measure on $\mathcal B([0,1))$, is an independent stationary process and each $X_n$ is Bernoulli distributed with parameter $1/2$?

I guess this is really simple, but I even fail to show the claim about the distributions. Clearly, $$\operatorname P\left[X_1=0\right]=\operatorname P\left[\left[0,\frac12\right)\right]=\frac12\tag1.$$ So, at least $X_1$ has the claimed distribution.
But how can we easily prove the other claims? What's the "trick"?
EDIT: The stationarity is clearly trivial, if we can show the independence and distribution claim ...

A: Hint: $\ X_n(x)\ $ is the $\ n^\text{th}\ $ bit in the binary expansion of $\ x\ $ (i.e. the coefficient of $\ \frac{1}{2^n}\ $ in that expansion). What interval must $\ x\ $ belong to if $\ X_i=a_i\ $ for $\ i=0,1,\dots,n-1\ $, and $\ a_i\ $ is some arbitrary sequence of zeroes and ones?
Response to query in comments:
$$\ P\left[X_1=a_1, X_2=a_2, \dots, X_n=a_n\right]=\text{Lebesgue measure of }\left[\sum_{i=1}^n\frac{a_i}{2^i}, \sum_{i=1}^n\frac{a_i}{2^i}+\frac{1}{2^n}\right)=\ ?\ $$


text:
Q: AddJwtBearer + AddAzureADBearer Not working together I am writing a authentication piece (.Net Core 2.1) where it can make use of either a JWT from a service provider or a token from AzureAD. I have written the following test to understand what is required , but it seems as if the first authentication provider is always hit when I test with Postman and send through a bearer token.
I have put a break point on both bearer providers events, if i call the values controller with the bearer token it hits the "first"  one even though i have specified to use the AuthenticationScheme of "second"
Startup.cs
services.AddAuthentication("first")
    .AddJwtBearer("first", options =>
    {
        options.Authority = "https://123";
        options.TokenValidationParameters =
        new Microsoft.IdentityModel.Tokens.TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidAudiences = new[] { "123" }
        };
        options.Events = new JwtBearerEvents
        {
            OnTokenValidated = context =>
            {
                var accesToken = context.SecurityToken;
                return Task.CompletedTask;
            },
            OnAuthenticationFailed = context =>
            {
                var accessToken = context.Principal;
                return Task.CompletedTask;
            },
        };
        })
    .AddAzureADBearer("second",
        AzureADDefaults.JwtBearerAuthenticationScheme,
        options => Configuration.Bind("AzureAd", options));

    // Added
    services.Configure<JwtBearerOptions>(AzureADDefaults.JwtBearerAuthenticationScheme,
        options =>
        {
        //Configuration.Bind("AzureAd", options);
        //options.Authority += "/v2.0";
            options.TokenValidationParameters.ValidAudiences = new[] { options.Audience, $"api://{options.Audience}" };

            options.TokenValidationParameters.ValidateIssuer = true;
            options.IncludeErrorDetails = true;
            options.TokenValidationParameters.ValidateLifetime = false;

            options.Events = new JwtBearerEvents
            {
                OnTokenValidated = context =>
                {
                    var accesToken = context.SecurityToken;
                    return Task.CompletedTask;
                },
                OnAuthenticationFailed = context =>
                {
                    var accessToken = context.Principal;
                    return Task.CompletedTask;
                }
            };
        });

ValuesController.cs
[Route("api/[controller]")]
[ApiController]
[Authorize(AuthenticationSchemes = "second")]
public class ValuesController : ControllerBase
{
    // GET api/values
    [HttpGet]
    public ActionResult<IEnumerable<string>> Get()
    {
        return new string[] { "value1", "value2" };
    }
}

any help will be appreciated.

A: Try using policies to enable AuthenticationSchemes
We use something like this (didn't try running the code)
services
.AddPolicyScheme("first", "First policy selector", options =>
{
    options.ForwardDefaultSelector = context =>
    {
        return "first"
    };
})
.AddPolicyScheme("second", "Second policy selector", options =>
{
    options.ForwardDefaultSelector = context =>
    {
        return "second"
    };
})
.AddAuthentication("first")
    .AddJwtBearer("first", options =>
    {
        options.Authority = "https://123";
        options.TokenValidationParameters =
        new Microsoft.IdentityModel.Tokens.TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidAudiences = new[] { "123" }
        };
        options.Events = new JwtBearerEvents
        {
            OnTokenValidated = context =>
            {
                var accesToken = context.SecurityToken;
                return Task.CompletedTask;
            },
            OnAuthenticationFailed = context =>
            {
                var accessToken = context.Principal;
                return Task.CompletedTask;
            },
        };
        })
    .AddAzureADBearer("second",
        AzureADDefaults.JwtBearerAuthenticationScheme,
        options => Configuration.Bind("AzureAd", options));

    // Added
    services.Configure<JwtBearerOptions>(AzureADDefaults.JwtBearerAuthenticationScheme,
        options =>
        {
        //Configuration.Bind("AzureAd", options);
        //options.Authority += "/v2.0";
            options.TokenValidationParameters.ValidAudiences = new[] { options.Audience, $"api://{options.Audience}" };

            options.TokenValidationParameters.ValidateIssuer = true;
            options.IncludeErrorDetails = true;
            options.TokenValidationParameters.ValidateLifetime = false;

            options.Events = new JwtBearerEvents
            {
                OnTokenValidated = context =>
                {
                    var accesToken = context.SecurityToken;
                    return Task.CompletedTask;
                },
                OnAuthenticationFailed = context =>
                {
                    var accessToken = context.Principal;
                    return Task.CompletedTask;
                }
            };
        });