text:
Q: How can I simulate/create a unit ramp signal by netlist or in schematic in TopSpice? I have some circuits in schematic form. I want to see the circuits' response to a unit ramp signal but I can't out find how to implement this signal in the schematic.
I would like to know how could create this signal in netlist form for a circuit as simple as a resistor in parallel with the unit ramp source.
I´m a little stuck in how to create circuits by netlist in TopSpice and I would like to learn this topic.

A: I would use a PWL (piece-wise linear) source. You specify a list of time/voltage pairs and the source voltage or current changes linearly between the points.
You can't do a true step. Time must increase monotonically; a voltage can't have two different values at the same time.


text:
Q: Integrating OneSignal with Angular 5 I am trying to integrate OneSignal with my Angular 5 app. I have placed manifest.json, OneSignalSDKWorker.js and OneSignalSDKUpdaterWorker.js inside src folder and made entry under assets in .angular-cli.json so that these files become accessible, but I am still facing this issue of service worker installation failure.
Error is GET http://localhost:4200/OneSignalSDKWorker.js?appId=xxx-xxx--xxx 404
In app.component.ts I have placed the initialization code but still I am getting error:
[Service Worker Installation] Installing service worker failed TypeError: Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script.
ngOnInit(){

    var OneSignal = window['OneSignal'] || [];
    console.log("Init OneSignal");
    OneSignal.push(["init", {
        appId: "xxx-xxx-xxx-xxx-xxx",
        autoRegister: false,
        allowLocalhostAsSecureOrigin: true,
        notifyButton: {
            enable: true
        }
    }]);
    console.log('OneSignal Initialized');
    OneSignal.push(function () {
        console.log('Register For Push');
        OneSignal.push(["registerForPushNotifications"]);
    });
    OneSignal.push(function () {
        OneSignal.on('subscriptionChange', function (isSubscribed) {
        console.log("The user's subscription state is now:", isSubscribed);
            OneSignal.getUserId().then(function (userId) {
                console.log("User ID is", userId);
            });
        });
    });
}

A: I don't think that it will work on localhost, you will need to publish it to a separate hosting (you can use Firebase, it's free).
The simplest solution would be to just put the script provided by One Signal into your index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
    <meta
      content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"
      name="viewport"
    />

    ...
    ...

    <link rel="manifest" href="/manifest.json" />
    <script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async=""></script>
    <script>
      var OneSignal = window.OneSignal || [];
      OneSignal.push(function() {
        OneSignal.init({
          appId: 'xxx-xxxx-xxxxx',
        });
      });
    </script>

    ...

Add the following into angular.json

    ...
    "architect": {
        "build": {
          "builder": "ngx-build-plus:build",
          "options": {
            "outputPath": "dist/browser",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/favicon.png",
              "src/manifest.json", <-- this
              "src/OneSignalSDKUpdaterWorker.js", <-- this
              "src/OneSignalSDKWorker.js", <-- and finally this one
              "src/assets"
            ],
            "styles": [
              "src/styles.scss"
            ],
            "stylePreprocessorOptions": {
              "includePaths": ["src/assets/sass"]
            },
            "scripts": []
          },
          ...

And place the manifest and the 2 *.js file into /src/*
That's it.
I got it to work on mine using this method. Hope that helps

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why the law of total expectations can be written as $E[X^T \epsilon]=E[X^TE[\epsilon | X ]]$ From Wikipedia the law of total expectations provides that:
Eq. 1:
$$ E[E[\epsilon|X]] = E[\epsilon] $$
I have asked a question here, and the answer provided the law of total expectation as:
Eq 2:
$$ E[X^T \epsilon]=E[X^TE[\epsilon | X ]] $$
Provided that $X$ is a stochastic variable, and thus cannot be taken out from the expectation operator, how can I go from eq. (1) to eq. (2)?

A: There's a few things to clear up here. First off, it's probably helpful to rewrite the law of total expectations without using your variables, since you may give them linear regression interpretations. Given any rvs $W,V$, the law of total expectations says that
$$E[W] = E[E[W|V]].$$
So what you "feed" as $W$ and $V$ in the above will obviously change the interpretation. Eq 1 takes $W = \epsilon$ and $V = X$, whereas Eq 2 takes $W = X^T\epsilon$ and $V =X$ and uses the property of conditional expectations that $E[VW|V] = VE[W|V]$ to the get the RHS of Eq 2. If $X,\epsilon$ were just any random variables, theres no reason to expect them to be equal.
As it turns out, you asked the linked question in the context of a linear regression, where you assume $E[\epsilon|X]=0$. In this case, then they are indeed equal, because
$$E[\epsilon] = E[E[\epsilon|X]] = E[0]=0$$
and
$$E[X^T\epsilon] = E[E[X^T\epsilon|X] = E[X^TE[\epsilon|X]] = E[X^T0] = 0.$$
So in this case, you can add whatever rv $W$ into $E[WE[\epsilon|X]]$ and you will get that it is $0$ because $E[\epsilon|X] = 0$! But this shouldn't amaze you, because you just assumed that it was $0$, and it wasn't anything you derived.


text:
Q: pyansys mapdl reader visualization I am working on Pyansys mapdl reader to visualise the values on the FE model. I have calculated few scalar values of no.of cycles to failure at each element and wrapped around the mesh to visualise it but the issue here is that the maximum values of scalar are in a range of blue colour in scalar_bar_args. I am attaching you the picture of the result. My question is do we have an option to visulaise only critical area or any method to scale the scalar_bar_args so that all the values are visible clearly. I will also attach the code in the attachments. Please let me know is there is any solution. It would be appreciated for the early reply
solver,filename_FEM = "ansys", "C:/Users/Desktop/SpecimenModel_ANSYS/BZ12_CADMOULDKOS_W0_PA66GF30_files/dp0/SYS-8/MECH/ds.dat"
if solver.lower() =="ansys": #Read RECIEVING MESH File via pyanys

# Read FEM archive file
    archive_FEM = pymapdl_reader.Archive(filename_FEM, parse_vtk=True,force_linear=True)
    print ("archive_FEM.enum Ansys element numbers", archive_FEM.enum)
mesh_FEM = archive_FEM.grid
#Ansys-Informationen sind im Grid in cell_data gespeichert! mesh_FEM.cell_data
print ("mesh_FEM.cell_data", mesh_FEM.cell_data)
points = mesh_FEM.points
mesh_FEM.cell_data["my_data"] = np.arange(mesh_FEM.n_cells)
print(mesh_FEM.cell_data)
scalars = cycles

sbar_kwargs = {"color": "black", "title": "life cycles"}
mesh_FEM.plot(scalars= scalars,show_scalar_bar=True, show_edges= True,
scalar_bar_args=sbar_kwargs)
[![Pyansys mapdl reader view][1]][1]
  [1]: https://i.stack.imgur.com/3bbj6.png


text:
Q: Deploy war inside project folder I have a project called myapp (webapps/myapp)
Now I want to deploy a sample.war inside myapp.
What I need to do?
If I have to write a context.xml inside META-INF. What will be the content of context.xml?
Do I need server.xml? If yes, What will be the content of context.xml?


text:
Q: conditionally render different header I am new to react js and try to create basic login UI, after user login the header of the UI change automatically. For testing purpose, I just want to remove the login option from the header, later, I may add more options such as logout and others.
Here is my code
import { useState,useEffect } from 'react';
import Container from 'react-bootstrap/Container';
import Nav from 'react-bootstrap/Nav';
import Navbar from 'react-bootstrap/Navbar';

const Header = () => {
  const [localtoken, setLocaltoken] = useState(null);
  useEffect(() => {
    const jwt_token= localStorage.getItem('jwt_token');
    if (jwt_token) {
      setLocaltoken(jwt_token);
    }},[]);
  console.log(localtoken)
  if (!localtoken){
    console.log(localtoken)
    return (
      <Navbar bg="primary" variant="dark">
      <Container>
        <Navbar.Brand href="home">Navbar</Navbar.Brand>
        <Nav>
          <Nav.Link href="home">Home</Nav.Link>
          <Nav.Link href="login">Login</Nav.Link>
          <Nav.Link href="register">Register</Nav.Link>
        </Nav>
      </Container>
    </Navbar>)}
  else {
    return (
      <Navbar bg="primary" variant="dark">
      <Container>
        <Navbar.Brand href="home">Navbar</Navbar.Brand>
        <Nav>
          <Nav.Link href="home">Home</Nav.Link>
          <Nav.Link href="register">Register</Nav.Link>
        </Nav>
      </Container>
    </Navbar>)
  }
}

export default Header

The problem for me is after I login, the header still show "Home Login Register", I have to click either "Home" or "Login" again to make the header change to the required status.

A: According to your code, on mount, the Header decides whether he should be in logged in mode or not based on some data in the localStorage.
But if it starts in unlogged mode, how would the Header know when the user logs in? With the current code, the Header is totally unaware of the login state since there is only a localStorage check at mount time (and the Header is likely to be mounted only once when the page loads).
Here are a few possibilities to fix this:
// After you login and update the localStorage, force a page reload (kinda awful)
location.reload();

// Regularly check your localStorage (pretty bad) in your Header Component
  useEffect(() => {
    const interval = setInterval(() => {
      const jwt_token= localStorage.getItem('jwt_token');
      if (jwt_token) {
        setLocaltoken(jwt_token);
        clearInterval(interval);
      }
   }, 100);
   return () => clearInterval(interval);
 },[]);

// Add a isLoggedIn props to the Header and update that prop after the login call
const App = () => {
  const {isLoggedIn, setIsLoggedIn} = useState(!!localStorage.get('token'));
  const loginFn = async (credentials: any) => { const resp = await fetchToken(credentials); if (resp is successful) setIsLoggedIn(true)}
  return <><Header isLoggedIn={isLoggedIn}/><LoginPage login={loginFn}></>
}

const Header = (props) => {
    return
      <Navbar bg="primary" variant="dark">
      <Container>
        <Navbar.Brand href="home">Navbar</Navbar.Brand>
        <Nav>
          <Nav.Link href="home">Home</Nav.Link>
          {!props.isLoggedIn && <Nav.Link href="login">Login</Nav.Link>}
          <Nav.Link href="register">Register</Nav.Link>
        </Nav>
      </Container>
    </Navbar>

Or another option (the best one?) might be to use a proper state manager such as redux. Connect your Header component to the store and rerender is when isLoggedIn changes. When your login process successfully gets a token, update the store with isLoggedIn = true.


text:
Q: How do I access a local variable in my decorated function from my decorator I just started playing with decorators in Python. I am currently having trouble figuring out the best possible way to handle this use cases. Since a decorated function cannot access local variables from the decorator.
schema = {
    'lang': {'type': 'string', 'required':True}
}

def validate(schema):
    def my_decorator(func):
        def wrapper(*args, **kwargs):
            # Read from request body args[1]
            # Validate the json is in fact correct
            valid_json = json.loads(body.decode('utf-8'))
            # Compare valid_json to the schema using "Cerberus"
            return args, kwargs
        return wrapper
    return my_decorator

@validate(schema)
def main_function(self, req, resp):
    # call database with valid_json

My question is: How do I access valid_json from my decorated function to be able to insert into my database afterwards. What is the best practice for this situation?
Edit: I am running pypy 2.4

A: IIUC what you asked, the following could do so. I can't say that I'm crazy about this solution (or about what you're asking, for that matter) - it's too much "magic" for my taste.
For simplicity, let's assume that schemas and everything are integers, and validating something by a schema simply means adding the schema integer to it (this is just for illustration). So we have:
def validate_schema(schema, arg):
    return arg + schema

Now we can write the following decorator:
def validate(schema, arg_pos):
    """
    Decorates a function so that the arg_pos argument will
       be modified to be validated by schema.
    """
    def decorator(method):
        @functools.wraps(method)
        def f(*args, **kwargs):
            # Manipulate args to modify the validated argument:
            args = args[: arg_pos] + (validate_schema(schema, args[arg_pos]), ) + args[arg_pos + 1: ]

            # Call the method with the modified arguments
            return method(*args, **kwargs)
        return f
    return decorator

Now we can use it as so:
# Validate arg #0 with schema 12
@validate(12, 0)
def bar(inp_):
    print inp_

>>> bar(1)
13

Of course, you can elaborate this further, to take pairs of schema+arguments, handle keyword arguments, and so forth. That is the principle of this answer, though. I think it's somewhat amusing, but I wouldn't use it.

A: You can't do this directly. The scope of the function being decorated is set before it's wrapped by the decorator, and it has no connection to the scopes established by the decorator added wrapper.
The best you can do is have the function accept additional arguments which the decorator passes, e.g.:
@validate(schema)
def main_function(self, req, resp, valid_json=None):
    # call database with valid_json

with the decorator explicitly adding valid_json=valid_json when it calls the wrapped function, e.g. return func(*args, **kwargs, valid_json=valid_json).

A: I've also been playing with decorators lately and I am under the impression that there's not really a good way to do this. You can't access the local scope of the function from outside the function.
A potential solution, albeit not exactly what you want, using partial function application and function member data might be:
from functools import wraps

schema = { 'lang': {'type': 'string', 'required':True} }

def compare(schema, json):
    return schema == json

def validate(schema):
    def outer(function):
        @wraps(function)
        def inner(*args, **kwargs):
            return function(*args, **kwargs)
        inner.validate = lambda json: compare(schema, json)
        return inner
    return outer

@validate(schema)
def main_function():
    print main_function.validate({ 'lang': {'type': 'string', 'required':True} })
    print main_function.validate({})

main_function()
# Output:
#     True
#     False

The compare function can obviously be customized to do something useful, but you still need to validate the json from within main_function. I don't know if there is a way around this without making a inner function within main_function.
It is also possible to "inject" a variable into a function's global scope and use a decorator to do the necessary book-keeping:
from functools import wraps

schema = {
    'lang': {'type': 'string', 'required':True}
}

def validate(schema):
    def my_decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            _backup, _check = None, False

            if 'valid_json' in func.func_globals:
                _backup, _check = func.func_globals['valid_json'], True

            valid_json = {'hi': 'mom'} # or whatever

            func.func_globals['valid_json'] = valid_json
            output = func(*args, **kwargs)

            if _check:
                func.func_globals['valid_json'] = _backup
            else:
                del func.func_globals['valid_json']

            return output
        return wrapper
    return my_decorator

@validate(schema)
def main_function():
    print valid_json

main_function()
# Output:
#     {'hi': 'mom'}


text:
Q: What is the correct way to assign Parent's static field values to Child's non-static field values? I'm new to programming so please excuse me if my question sounds stupid. However, following is what I want to do. (Currently I'm learning about Java's Comparable and Cloneable Interfaces)
I was testing how Cloneable and Comparable Interface works in java and created these two classes for that purpose:
Class 1 --> Abstract Class --> GeometricShapes
Class 2 --> Non-Abstract   --> Circle
I was trying to create different objects of the Circle class with unique IDs.
Following is my code for both the classes. While, I'm able to achieve what I wanted to but vsCode is giving a warning "The static field GeometricShapes.id should be accessed in a static way". So I know this is not the best way to do what I'm trying to do.
Is there a better way to achieve this?
Codes:
public abstract class GeometricShapes {
protected static int id = 0;
protected String colour;
protected boolean filled;
protected java.util.Date creationDate;

protected GeometricShapes(String colour, boolean filled) {
    id++;
    creationDate = new java.util.Date();
    this.colour = colour;
    this.filled = filled;
}

protected abstract double getArea();

protected abstract double getPerimeter();

}
public class Circle extends GeometricShapes implements Comparable<Circle>, Cloneable {

private double radius;
private int circleID = super.id; //This is where the problem is

public double getRadius() {
    return this.radius;
}

public Circle(String colour, boolean filled, double radius) {
    super(colour, filled);
    this.radius = radius;
}

@Override
public int compareTo(Circle arg0) {
    if (this.radius > arg0.radius)
        return 1;
    else if (this.radius < arg0.radius)
        return -1;
    else
        return 0;
}

@Override
public Object clone() throws CloneNotSupportedException {
    return super.clone();
}

@Override
public double getArea() {
    return ((this.radius * this.radius) * Math.PI);
}

@Override
public double getPerimeter() {
    return (2 * Math.PI) * this.radius;
}

@Override
public String toString() {
    return ("Circle id: \t" + this.circleID + "\nCreated on: \t" + this.creationDate + "\nRadius: \t" + this.radius
            + "\nArea: \t\t" + this.getArea() + "\nPerimtr: \t" + this.getPerimeter());
}

public java.util.Date getCreationDate() {
    return this.creationDate;
}

public int getID() {
    return this.circleID;
}

}

A: Define two fields related to Id number generation. Define one static field which indicates the next Id to use when a new object is created. This value increases which each new instance. Define another non-static field for the actual Id of that specific instance.
public abstract class GeometricShapes {
    /**
     * Field for the next Id to use.
     */
    private static int nextIdToUse = 1;

    /**
     * The Id of this geometric shape.
     */
    private final int id;

    protected GeometricShapes(String colour, boolean filled) {
        this.id = nextIdToUse++;
        // [...]
    }

    /**
     * Returns the Id of this geometric shape.
     *
     * @return The Id.
     */
    public int getId() {
        return this.id;
    }
}


text:
Q: Dspace Enron Search Facility I have been  working on a project on Dspace
I have been using Enron Mail Corpus (downloaded from CMU source).
My problem is :

*

*I want to take entire collection of 600k emails and then generate a repository which enables search on them

Manually Feeding metadata of Each Mail is not a viable option as they are in millions!
Can the import facility in Dspace Be of any help? or is there a file to be edited?
I need something feasible and fast: What should I do to feed the system with so many mails?

*

*Second question: Can the attached file within any collection be indexed? I mean can I search for the content of the file search facility?

A: If you want to edit or import a large amount of data, you can use batch metadata editing. Its perfect for import metadata values, but files must be added manually later.
More information at https://wiki.duraspace.org/display/DSDOC3x/Batch+Metadata+Editing#BatchMetadataEditing-TheCSVFiles
About the second question, there is a process that index supported files called "Filter-media". It support Adobe PDF, HTML, Text, Microsoft Word and Microsoft Powerpoint. And you can write a java class to index other formats to your needs.
Its executed doing /bin/dspace filter-media, and should be added as a cron.


text:
Q: Uploading and downloading small files to a cloud drive in-game? (Unity3D) I need any player's client to be able to upload and download files (they are text files that have replay data. I'm making a racing game and want players to be able to send and download replays.) while in-game. I'm trying to use Dropbox but I'm having problems. I'm open to other file hosting services but I don't really know how to send and get data from them. I keep making little changes here and there and they all give me different errors. Is there anything I'm doing blatantly wrong here? I'm expecting the main problem to be in the dropbox URL I'm using. Here's what my code looks like:
    private void DownloadReplay()
{
    string l_playerID = PlayFabManager.load_PlayfabId;
    string l_levelID = PlayFabManager.load_levelID;

    using (WebClient wc = new WebClient())
    {
        string path = Path.Combine(Application.persistentDataPath, $"{l_playerID}{l_levelID}.replay");
        string url = ("https://www.dropbox.com/s/f786vep0z9yd11s/"+ $"{l_playerID}{l_levelID}");
        wc.Credentials = new NetworkCredential("xx", "xx");
        wc.DownloadFile((new System.Uri(url)), path);
    }
}

private void UploadReplay()
{
    string s_playerID = PlayFabManager.load_PlayfabId;
    string s_levelID = PlayFabManager.load_levelID;

    using (WebClient client = new WebClient())
    {
        string path = Path.Combine(Application.persistentDataPath, $"{s_playerID}{s_levelID}.replay");
        string url = Path.Combine("https://www.dropbox.com/s/f786vep0z9yd11s/" + $"{s_playerID}{s_levelID}");
        client.Credentials = new NetworkCredential("xx", "xx");
        client.UploadFile(url, path);
    }
}

Right now this one gives me an error 404, even though the file matching the string is in my dropbox.


text:
Q: Confusion concerning the Euclidean Norm and unitary invariance on $\mathbb C^n$ For a unitarily invariant norm on $\mathbb C^n$, how do I show that $||x||=||x||_2||e_1||$? I can show that $||e_1||=1$ for the Euclidean norm by definition, and is therefore unitarily invariant, does that suffice as proof?
I've been told that the only unitarily invariant norm on $\mathbb C^n$ satisfying the above equality (that $||e_1||=1$) is the Euclidean norm, would someone help me understand why that is?
Note that $e_1$ is the elementary $n\times1$ col vector, $[1,0,0,...0]^T$


text:
Q: Extension Quokka for vscode 1.67.2 don't start on macOS 12.4 when i start quokka on a js file i have this error message on the output window:
try{this._fileExistsSync(a)&&(l=JSON.parse(this._readFileSync(a)))}catch(o){}l.projects||(l.projects={});var c=s(this._localRoot);e.projectRoot=this.localRoot;var u=l.projects[c]||{};delete l.projects[c],l.projects[c]=u;var h=e.fileId||s(e.path),d=!u[h];for(delete u[h],u[h]=e,d&&(l.total=(l.total||0)+1);l.total>t;)for(var p in l.projects){var f=l.projects[p];if(!.isEmpty(f)){for(var g in f){var v=f[g];if(delete f[g],l.total--,v.scratchFile&&!v.content)try{this._unlinkFileSync(n(v.fileId))}catch(o){}break}break}delete l[p]}try{this._writeFileSync(a,JSON.stringify(l))}catch(o){}}}),module.exports=Project},{"./babelCompiler":8,"./chromeProfileViewer":11,"./config":14,"./extension/shared/utils":39,"./instrumentor":42,"./processor":59,"./testTask":63,"./tracking":65,"./typeScriptPostprocessor":67,"./typeScriptUtils":68,"./utils":70,child_process:void 0,"lru-cache":void 0,os:void 0,path:void 0,semver:void 0,typescript:void 0,url:void 0,util:void 0}],61:[function(e,t,i){var r=this&&this.__assign||function(){return r=Object.assign||function(e){for(var t,i=1,r=arguments.length;i<r;i++){t=arguments[i];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e},r.apply(this,arguments)},n=this&&this.__awaiter||function(e,t,i,r){function n(e){return e instanceof i?e:new i(function(t){t(e)})}return new(i||(i=Promise))(function(i,s){function o(e){try{l(r.next(e))}catch(t){s(t)}}function a(e){try{l(r"throw")}catch(t){s(t)}}function l(e){e.done?i(e.value):n(e.value).then(o,a)}l((r=r.apply(e,t||[])).next())})},s=this&&this.__generator||function(e,t){function i(e){return function(t){return r([e,t])}}function r(i){if(n)throw new TypeError("Generator is already executing.");for(;l;)try{if(n=1,s&&(o=2&i[0]?s["return"]:i[0]?s["throw"]||((o=s["return"])&&o.call(s),0):s.next)&&!(o=o.call(s,i[1])).done)return o;switch(s=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return l.label++,{value:i[1],done:!1};case 5:l.label++,s=i[1],i=[0];continue;case 7:i=l.ops.pop(),l.trys.pop();continue;default:if(o=l.trys,!(o=o.length>0&&o[o.length-1])&&(6===i[0]||2===i[0])){l=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){l.label=i[1];break}if(6===i[0]&&l.label<o[1]){l.label=o[1],o=i;break}if(o&&l.label<o[2]){l.label=o[2],l.ops.push(i);break}o[2]&&l.ops.pop(),l.trys.pop();continue}i=t.call(e,l)}catch(r){i=[6,r],s=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}var n,s,o,a,l={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return a={next:i(0),"throw":i(1),"return":i(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a},o=this&&this.__read||function(e,t){var i="function"==typeof Symbol&&e[Symbol.iterator];if(!i)return e;var r,n,s=i.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(r=s.next()).done;)o.push(r.value)}catch(a){n={error:a}}finally{try{r&&!r.done&&(i=s["return"])&&i.call(s)}finally{if(n)throw n.error}}return o},a=e("os"),l=e("path"),c=e("http"),u=e("./utils"),h=logger.create("workers").debug,d=e("ws").Server,p=/^win/.test(process.platform),f="&wallabyFileId=",g="Wallaby.js cache is corrupted, please restart wallaby.js",v="Jest cache is corrupted, please clear jest cache (npx jest --clearCache) and then restart wallaby.js",y=/.jasmine.js:(\d|\s)throw error;[^^]^\s/s,m=function(e,t){var i=this;i._project=e,i._opts=e.settings(),i._extension=t,i._mapConsoleMessagesStackTrace=i.project.settings().mapConsoleMessagesStackTrace,process.env.quokka&&(i.reportConsoleOutput=function(t){var i=.extend({},t);e.resolveLogEntryRange(i),e._emitInternal({type:"consoleOutput",data:i})},i.reportIntermediateResult=function(e){}),i._sessions={},i._executedTestNumber=0,i._testRunId=0,i._workers={},i._testFilesByWorker={},i._workerPingTimeoutOverride={},i._connectingWorkers={},i._workerPendingCleanup={},i._calculateNumberOfParallelWorkers(),i._hasGlobalSetupOrTeardown=this._project.hasGlobalSetupOrTeardown();for(var r=Math.max(i._maxWorkers,i._minWorkers)+(i._hasGlobalSetupOrTeardown?1:0),n=0;n<r;n++)i.getWorker(n);i._globalWorkerId=r,i._normalizedWallabyServerPath=this._project.normalizePath(l.dirname(process.mainModule.filename)),i._normalizedLocalRoot=this._project.normalizePath(this._project._localRoot),i._zeroConfigJest=this._project.isZeroConfigJest(),i._nodeJasmine=this._project.isNodeJasmine(),i._unresponsiveStandardTimeout=Math.max(500,i._opts.unresponsiveStandardTimeout||(i._zeroConfigJest?2e3:200)),i._unresponsiveInitialTimeout=Math.max(i._unresponsiveStandardTimeout,i._opts.unresponsiveInitialTimeout||(i._zeroConfigJest?7e3:200)),i._longExecutingWarningTimeout=Math.max(500,i._opts.longExecutingWarningTimeout||5e3),i._longExecutingPingTimeout=Math.max(200,i._opts.longExecutingPingTimeout||200),i._globalSetupTeardownTimeout=Math.max(10,i._opts.globalSetupTeardownTimeout||5e3)};m.prototype={"worker:transformedFile":function(e){this._project.testRunnerTransformedFile(e)},"worker:profile":function(e){this._resolveProfileRunPromise&&(this._resolveProfileRunPromise(e),delete this._resolveProfileRunPromise)},start:function(e){var t=this,i=t._httpServer=e?c.createServer(e):c.createServer();return i.listen(0),Q.promise(function(e,r){i.on("listening",function(){try{t._receiverPort=i.address().port,h("Web server is listening at "+t._receiverPort),t._wss=new d({server:i,verifyClient:function(e){return _.verifyLocalOrigin(e.origin)}}),t._wss.on("connection",function(e){e.on("message",function(i){var r;try{r=JSON.parse(i)}catch(n){return void console.error("Failed to deserialize message from worker: "+i+", "+(n&&n.message))}if(t["worker:"+r.type])return t"worker:"+r.type;if(r.worker){var s=t._workers[r.worker];if(!s)return;if(s.onConnected)s.onConnected(e);else if(process.env.quokka&&s.instance){if(s.instance.channel)try{s.instance.channel.close(),s.instance.channel.removeAllListeners()}catch(n){}s.instance.channel=e}try{e.send(JSON.stringify({type:"in:connected"}))}catch(n){console.error('Failed to send the "connected" message to worker. '+n.message)}}else if(r.session){var o=t._sessions[r.session],a=!o||(o._disposing||t.cancelled(o._testRunId))&&!o._globalSetup;if("console"===r.type&&r.data){if("debugLog"===r.data.type)return void h(r.data.text);(r.data.spec||process.env.quokka)&&!a||"autoLog"===r.data.type||console.log("console."+r.data.type+": "+r.data.text)}if(a)return;try{or.type}catch(n){console.error("Failed to process message "+r.type+" from worker, "+(n&&n.message)),o.reject(n)}}})}),e()}catch(n){r(n)}})})},wallabyFileIdPrefix:function(){return f},traceContext:function(){return this._traceContext},receiverPort:function(){return this._receiverPort},setFileRoot:function(e){this._fileRoot=this._project.normalizePath(e)},run:function(e){return n(this,void 0,void 0,function(){var t,i,n,o,a,l,c,u,d,p,f,g,v,y,m,b,k,T,S,C;return s(this,function(s){switch(s.label){case 0:if(t=this,t._cancelled=!1,t._testRunId++,t._executedTestNumber=0,t._runPriority=e.priority,t._traceContext=e.traceContext,t._profileRun=e.profileRun,i=0,t._profileRun?(t._profileRunPromise=Q.promise(function(e){t._resolveProfileRunPromise=e}),e.testFilesToLoad&&1===e.testFilesToLoad.length&&(i=t._findWorkerThatExecutedTestFile(e.testFilesToLoad[0])||0)):(delete this._resolveProfileRunPromise,delete this.profileRunPromise),e.recycleBeforeRun&&.each(t._workers,function(e,i){t.recycleWorker(i)}),h("Starting test run, priority: "+t._runPriority),t._startTime=(new Date).getTime(),n=e.fullRun&&t._maxWorkers>1&&e.testFilesToLoad.length>1?t._maxWorkers:t._minWorkers>1&&e.testFilesToLoad.length>1&&!(e.fullRun&&t._maxWorkers<t._minWorkers)?t._minWorkers:1,o=void 0,!t._hasGlobalSetupOrTeardown||!e.testFilesToLoad.length)return[3,4];a=setTimeout(function(){console.log("Some long running code has been detected: Global Setup")},t._longExecutingWarningTimeout),s.label=1;case 1:return s.trys.push([1,3,,4]),[4,t.runGlobalSetup(e)];case 2:return o=s.sent(),clearTimeout(a),[3,4];case 3:if(l=s.sent(),clearTimeout(a),l.error)throw l.error;return[2,l.result];case 4:1===n&&.each(e.testFilesToLoad,function(e){


text:
Q: R grepl variable comparison Just need some help with grepl, it's doing my head in!
I have two variables:
str1<-"AAV.L"
str2<-"AAV2.L"

And what I want to do is check if str2 is an extension of str1 (which it is in this case). Basically here str2 has an extra "2" in it's name..
Ideally the solution is something like:
grepl(str1,paste0(str2,...))

But I have no idea to account for the . in str1. The lengths of variables aren't the same either so I can't just check if the first 3 characters of str1 are present in str2.
Anyone have any ideas?
Thanks!
EDIT - Clarification..
Basically by "extension of" I mean if one variable contains exactly the same letters, and more, in the same order. So the above example, AAV.L and AAV2.L would match because it contains AAV..L. It doesn't have to be like this however, it should match REWR with REWRLE as well meaning REWR...
So c("AAV.LE", "BAAV.L","AABV.L","AAV..L","ABCAV.L"), none would match. If I were to put a rule for the match into plain English it would be:
Does str2 start with str1 OR does str2 start with any subset of str1 and end with the other subset?
I've taken a look into agrep but it matches too inaccurately. For example AAV.L and AAV2.L match which is good, but then ADD and APUAD do as well, which is incorrect! I know I can specify max.distance but some strings could be ADD and ADDDDDDDDD which would make settings this value implausible..
Let me know if this helps.

A: You could drop the dot extension before placing in grepl.
str1 <- sub("\\.[[:alnum:]]+$", "", str1);
## AAV

str2 <- sub("\\.[[:alnum:]]+$", "", str2);
## AAV2

Note: This is a method for removing file extensions. It won't remove any other occurances of the dot character. It works by replacing an occurance of a period followed by nothing but alphanumeric characters, and searches from the end of the string. It replaces it with an empty ("") string.
str3 <- "A.A.V.L"
str3 <- sub("\\.[[:alnum:]]+$", "", str3);
## A.A.V

Then, using grepl
grepl(str1, str2)
## TRUE


text:
Q: Sending email via Amazon SES SMTP error I'm trying to send email via Amazon SES new SMTP service using .NET's built-in SmtpClient
Code:
    var emailClient = new SmtpClient("email-smtp.us-east-1.amazonaws.com", 465);
                    emailClient.EnableSsl = true;
....
emailClient.Send(message);

I get an exception:

Unable to read data from the transport connection:
  net_io_connectionclosed

Google says this error means that I can't reach SMTP server.
They require TLS which I beleive achieved by "EnableSsl" property.
Anybody know how I need to tweak my code to make it work?
EDIT:
I guess I will close this question. No, it's not possible to do what I want with SmtpClient
https://forums.aws.amazon.com/thread.jspa?messageID=302112&#302112

A: According to Amazon - it is not supported as we used to.
https://forums.aws.amazon.com/thread.jspa?messageID=302112&#302112

The .NET email TLS libraries only support STARTTLS which SES does not
  support today. We support what is called "TLS Wrapper" or SMTPS
  authentication.   I can understand how this would be frustrating, but
  you can use OpenSSL as a workaround and tunnel through that software
  running on your computer to use .NET to program against our SMTP
  endpoint.

A: I can confirm that it works with STARTTLS and port 587.
Hope that helps

A: As masterfu mentions in his blog post, Amazon SES started supporting STARTTLS in March of 2012.
Below is the code that I used to get SMTP working with Amazon.
  string username = ConfigurationManager.AppSettings["AWSSMTPUser"];
  string password = ConfigurationManager.AppSettings["AWSSMTPPass"];

  SmtpClient smtp = new SmtpClient();
  smtp.Host = "email-smtp.us-east-1.amazonaws.com";
  smtp.Port = 587;
  smtp.UseDefaultCredentials = false;
  smtp.Credentials = new NetworkCredential(username, password);
  smtp.EnableSsl = true;

  smtp.Send(mail);

A: Now SES supports STARTTTLS:

Outgoing server (SMTP)—25, 587, or 2587 (to connect using STARTTLS),
  or 465 or 2465 (to connect using TLS Wrapper).

Pruf link: http://s3.amazonaws.com/awsdocs/ses/latest/ses-dg.pdf

A: It is possible to do this by specifying port 587.
<system.net>
   <mailSettings>
     <smtp deliveryMethod="Network">
       <network enableSsl="true" port="587" host="email-smtp.us-east-1.amazonaws.com" password="[password]" userName="[username]"/>
     </smtp>
   </mailSettings>
</system.net>

With that as the configuration, you can use the SmtpClient as you normally would
var client = new SmtpClient();
var message = new MailMessage(fromemail, recipient, subject, body);
client.Send(message);

A: For Anyone who wants to send with normal .Net SMTPClient. It is possible as you just need a wrapper.
Here's a link with all the info:
http://docs.amazonwebservices.com/ses/latest/DeveloperGuide/SMTP.Client.html
Install the tunneling software and configure as the describe in the link then its as simple as :
System.Net.Mail.SmtpClient sc = new SmtpClient();
sc.Host = host;
sc.Port = port;
sc.Credentials = new NetworkCredential(username, password);
sc.Send(mm);

A: Have you set defaultCredentials="false" in web.config?

A: Try using port no. 2587, other port 25, 425, 587 dint work for my case.


text:
Q: How to properly play a WAV file by constructing an AudioBuffer in JavaScript? I am struggling to play this WAV file, which plays in VLC (according to which it is a Mono, IMA WAV APDCM Audio (ms) file sampled at 24000Hz with 16 bits per sample).
I suspect that there is something wrong with the WAV file itself, since when I try to play it by embedding it directly via <audio>, the play button is inactive…when I try to play it programmatically using new Audio(), I get the error Failed to load because no supported source was found.
Here is the simplest example of what I've tried which produces some sound…other attempts I've tried which attempt to use AudioContext.decodeAudioData all choke on loading the audio, throwing Unable to decode audio data.
This example produces some, somewhat recognizable sound, but I'm clearly doing something wrong because it is so scratchy— My understanding is that AudioBuffer requires a Float32Array whose values fall between [-1,1], which these don't.  But I don't know how to normalize them, since many of the values are on the order of 10e32.
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <style>

    </style>
</head>

<body>
    <script>
    var context = new AudioContext();

    function loadSound(url) {
        var request = new XMLHttpRequest();
        request.open("GET", url, true);
        request.responseType = "arraybuffer";

        request.onload = function() {
            data = new Uint8Array(request.response);

            var buffer = context.createBuffer(1, data.length, 24000);

            var channelData = buffer.getChannelData(0);
            for (var i = 0; i < data.length; i++) {
                channelData[i] = data[i];
            }

            var source = context.createBufferSource();
            source.buffer = buffer;
            source.connect(context.destination);
            source.start(0);
        }

        request.send();
    }

    loadSound('./test.wav');
    </script>
</body>

</html>

Any help would be appreciated; thank you!

A: In this phosphorous issue I found a suitable answer in the readADPCM and encodeAudio16bit function reading a UInt8Array and encoding 16 bit audio.


text:
Q: Workstations are disconnected from server after 10 hours We recently had some electrical work done and the domain server went off unintentionally rather than being switched off. Since then, the workstations can only connect to the server for 10 hours before having to log out of Windows and back in again, they just suddenly lose their connection to the server.
Has something got corrupted, or is there something which expires after 10 hours (like a security token or something), if so what can I look for to fix this?

A: Just in case anyone stumbles across this in the future, I did eventually remedy it.
The server had two network cards, one on 192.168.0.1 and one on 192.168.0.2 however the 0.2 card didn't have a network cable plugged into it, however due to some kind of bridging it was resolving back to the server correctly.
I disabled the 0.2 network card and changed the DNS server to work off 0.1 instead of 0.2, that seemed to fix the problem.


text:
Q: Having issue in updating xcode vesion 9.0.1 Is it necessary to update OS X El Capitan for updating xcode version 9.0.1 ?
can anyone know this thing ?

A: Here https://developer.apple.com/library/content/releasenotes/DeveloperTools/RN-Xcode/Chapters/Introduction.html you can see the requirements for Xcode 9.0.1:

Xcode 9 requires a Mac running macOS 10.12.6 or later.

So, yes, you have to update at least to macOS Sierra unfortunately. OS X El Capitan is version 10.11.


text:
Q: How to execute a jar file within a jar file I have a project who's structure cannot be changed. What i have to do is that
I have a main jar file that have directores
/classes
/lib
/main
/manifest

I have to call a Test1 class when i execute the main jar file. so in the manifest file i gave the path of the Main-Class : path.to.file.
I have another jar file inside the main folder that contains the actual application. What can i do to execute the jar in main folder and execute its Test2 class mentioned in the Manifest file.
Please give me a solution or any direction to work on. Any help appreciated.

A: You can not do this in the current ClassLoader, you need a new one.
If your jar named foobar.jar and you have a main-method in the class test.abc.Main this may work:
    URL[] urls={new URL("classloader:/main/foobar.jar")};
    ClassLoader parentClassLoader = this.getClass().getClassLoader();
    URLClassLoader childClassLoader=new URLClassLoader(urls,parentClassLoader);
    Class clazz = childClassLoader.loadClass("test.abc.Main");
    String[] arguments = new String[]{};
    clazz.getMethod("main", arguments.getClass()).invoke(null,arguments);

A: *

*You could use JarClassLoader http://www.jdotsoft.com/JarClassLoader.php if you're okay with using GPLv3'd code to make a launcher class.

*Extract the jars inside of the main jar to a temporary location, execute and delete upon exit

*Simply change the file structure, since you haven't listed any reasons for "not doing that", I don't see why not. :D


text:
Q: MongoDB authentication failed? I'm currently trying to set up a secure MongoDB database for my various applications, but whenever I try to login with a username and password, but the shell always replies with Error: Authentication failed. and keeps me from accessing my database.
Errors from mongod --auth:
2016-02-12T17:11:57.039-0600 I ACCESS   [conn1] SCRAM-SHA-1 authentication failed for app-client on application-userdata from client 127.0.0.1 ; UserNotFound Could not find user app-client@application-userdata
Can someone give me some help as to trying to make this work? I've already tried dropping and re-adding the user, but that does nothing. In case it matters, the user only has the readWrite role enabled.
(Ubuntu 15.10, x86_64)

A: Look at that, I figured it out. Turns out I had to change mongod.conf to enable authentication.
For those who are coming here in the future, add the following to /etc/mongod.conf:
security:
  authorization: enabled


text:
Q: async function in Python not working as expected I have the following code snippet:
import asyncio

def main():
    asyncio.run(work())
    print("BEFORE")

async def work():
    await asyncio.sleep(1)
    print("AFTER")

main()

I would like "BEFORE" to be printed first, followed by "AFTER" however this prints "AFTER" first instead - have I misunderstood how async functions work? I thought that running asyncio.run(...) would allow my code to skip to print("BEFORE") while still running work() in the background.
Ideal output is:
BEFORE
AFTER

Right now it's
AFTER
BEFORE

A: run seems to be blocking, so you might want to just use gather here:
import asyncio

async def main():
    await asyncio.gather(work(), setup())
    print('After gather')

async def work():
    await asyncio.sleep(2)
    print("AFTER")

async def setup():
    print("BEFORE")

asyncio.run(main())

This correctly prints
BEFORE
AFTER
After gather

The entire gather statement itself is blocking as well, but all of the functions specified in the gather statement can run asynchronously.

A: According to the documentation:

The asyncio.run() function to run the top-level entry point "main()" function (see the above example.)

The asyncio.run should be the entry point, not used for starting a background job. So it does not skip to print("BEFORE").


text:
Q: CSS Only Shows Up When I Manually Drag My Stylesheet Into Inspect Element In Browser I'm currently working on a small graphic design portfolio. My css will only apply to my html if I manually drag it into inspect element in a web browser. I cant seem to figure out this issue. Would really appreciate some feedback
I've made sure my stylesheet is in the same folder as my index. I'm not 100% sure if I linked them correctly though in my html.
 <!DOCTYPE html>
    <meta charset="utf-8"/>
    <html>
    <head>
    <title>My Website</title>
    <link rel="stylesheet" href="style.css" type=text/css">
    <link rel="stylesheet" href="normalize.css" type=text/css">
    </head>

   @import url('https://fonts.googleapis.com/css?family=Nunito:300,400,700');

body {
    font-family: 'Nunito', sans-serif;
    background: #EFF1F7;
}

.content {
   grid-area: content;
  background: url(images/background-shapes.png);
  }
.sidebar {
  grid-area: sidebar;
  background: linear-gradient(#fa5c98, #795ef8);
  rgba(249,107,142,1),
  rgba(218,103,230,1),
  rgba(130,125,253,1);
  justify-content: center;
 }

I'm trying to apply a linear gradient (Sorry about my css I couldnt figure out how to properly format it like my html)

A: It looks like your missing a quote in text/css at the beginning try this code
<link rel="stylesheet" href="style.css" type="text/css">
<link rel="stylesheet" href="normalize.css" type="text/css">


text:
Q: React Web// iOS like select dropdown on mobile I have a web project built with React. I am trying to open an iOS like select dropdown when user clicks the 'category image button' like the images below.
What I expect
When I click the 'category image button', iOS like dropdown options should appear.
My code logic

*

*select default style is 'display: none'.

*when 'category image button' is clicked, it will change 'showWishSelect' state to true & trigger the select click action using select ref.

*once 'showWishSelect' state is set to true, the style of select will be set to 'display: initial'.

*then the select options appear. [ image 3 ]

Issue
When I click the 'category image button', [ image 1 ]
It will display the select input box which I don't want it to be shown in the first place. [ image 2 ]
then I have to click the select input box again to open the dropdown select options. [ image 3 ]
The 'selectRef.click()' doesn't seem to be triggered.
Code
state = {
    showWishSelect: false,
  };

onShowWishSelect = () => {
    this.setState({ ...this.state, showWishSelect: true });
    this.selectRef.click();
  };

return (
  <div className="mobile_filter_icon profile_filter_icon" onClick={this.onShowWishSelect}>
    <select
     size="4"
     style={{ display: this.state.showWishSelect ? 'initial' : 'none' }}
     ref={(select) => { this.selectRef = select; }}
     onChange={(e) => this.onCategory(e.target.value)}
     value={categoryId || 'current-wish'}
    >
     {allWishCategories.length
       ? allWishCategories.map((data, index) => (
         <option key={index} value={data.categoryId}>
           {data.name}
         </option>
       )): null}
     </select>
  </div>
)

/* CSS */
.mobile_filter_icon{ background:url("/.../web/2019/search/btn_filter_right_n.png") no-repeat; width:28px; height:27px; background-size: 28px 27px; }
.mobile_filter_icon.profile_filter_icon { position: absolute; right: 0px; border-radius: 1px; }

What I have tried..

*

*delay selectRef.click() event

onShowWishSelect = () => {
    this.setState({ ...this.state, showWishSelect: true });
    setTimeout(() => this.selectRef.click(), 1000);
  };

*disable the default select style and add 'category image' to select tag.

<select
  size="4"
  className="mobile_filter_icon profile_filter_icon"
  onChange={(e) => this.onCategory(e.target.value)}
  value={categoryId || 'current-wish'}
>
  {allWishCategories.length
    ? allWishCategories.map((data, index) => (
      <option key={index} value={data.categoryId}>
         {data.name}
      </option>
    ))
   : null}
</select>

/* CSS */
.mobile_filter_icon.profile_filter_icon { position: absolute; right: 0px; border-radius: 1px; -webkit-appearance: none; -moz-appearance: none; appearance: none; }

image 1. category button image

image 2. [ bug ] select input box is displayed

image 3. category dropdown options

Thanks for your help in advance !! :)

A: <select value={categoryId} className="mobile_filter_icon profile_filter_icon" onChange={e => this.onCategory(e.target.value)}>
    {allWishCategories.map((data, index) => (
       <option key={index} value={data.categoryId}>
          {data.name}
       </option>
    ))}
</select>

/* css */
.mobile_filter_icon{ background:url("//ccimage.hellomarket.com/web/2019/search/btn_filter_right_n.png") no-repeat;width:28px;height:27px; background-size: 28px 27px; }
.mobile_filter_icon.profile_filter_icon { position: absolute; right: 0px; border-radius: 1px; color: transparent;}
.mobile_filter_icon.profile_filter_icon > select { -webkit-appearance: none; -moz-appearance: none; appearance: none; position: absolute; top: -9999px; }


text:
Q: Junk Characters being added to string when reading HTTP request parameters I have an html form :

 Select beer characteristics

  Color:
  <select name="color" size="1">
    <option value="light"> light </option>
    <option value="amber"> amber </option>
    <option value="brown"> brown </option>
    <option value="dark"> dark </option>
  </select>

<input type = "submit" value="submit">

*

*for the input parameter name = "color", there are four options: light, amber, brown, dark

*based on which value is chosen, a result page is shown

*however, when I select an option, there are some junk characters being added in front and at the end of the string for the option value

*on debugging, this is the value read (on selecting "amber") when I read using request.getParameter("color") look like:
â€amberâ€

*this is causing a problem in the back end where i want to do a string match with the input parameter

Any suggestions?

A: You're using the wrong kind of quote characters in your HTML code.
What you probably have is something like this:
<option value="light">

Unless you use the correct double quotes (") or single quote (') to enclose an attribute, the browser will interpret the value as "light" and not light, and that's what it sends to the server.
(Note that this wouldn't be valid in XHTML, where only quoted attributes are allowed, but in plain HTML specifying attributes in a <foo bar=value> format works.)
The strange output can be explained by the fact that your browser and your server use different encodings: one uses ISO-8859-1 and the other UTF-8. The UTF-8 sequence for the left double quotation mark character is 0xe2 0x80 0x9c, which when read with ISO-8859-1, gives exactly the two characters you mention. (The third one falls in an unused block and is dropped silently.)
This is a separate problem that needs to be remedied too, see the other answers for tips to deal with it.

A: This is result of wrong encoding in browser, which is most probably not set on response. You can try to use:
response.setContentType("text/html; charset=UTF-8");

A: I am quite sure that this is related to character encoding or URL encoding mismatches.
First of all, make sure to specify a charset
<form action="..." method="..." accept-charset="UTF-8">
    <select ...> ... </select>
</form>

If the client sends all your stuff correctly with a good encoding (UTF-8), you have to configure your server side to read the data as well.
I don't know what you're using, but one method is:
URLDecoder.decode(formParams, "UTF-8");

To be sure, you can add an encoding to your HTML file as well:

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    ...

Edit: make sure to send and receive all the stuff correctly as well.
Sending HTML file from Server:
1) Make sure to set this:
Content-Type: text/html; charset=UTF-8
If you're sending a file, make sure to save your file using the UTF-8 encoding.
If your HTML is a generated String, use:
PrintWriter writer = new PrintWriter(new OutputStreamWriter(httpOutputStream, "UTF-8"));
writer.print(string);
...

The URL from the request is received in US-ASCII encoding:
String urlEncodedString = new String(receivedBytes, "UTF-8");
String decoded = URLDecoder.decode(urlEncodedString, "UTF-8");

A: I faced the same problem while converting xhtml to PDF using wkhtmltopdf
tool.
Adding <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> in my HTML template resolved the issue.


text:
Q: Given an array of integers and target, return true if any two elements sum to target As the title states, I'm looking to find two elements whose sum is equal to the target integer. I've already worked out the solution below, but this works only for unique integers. I'm having an issue when it comes to duplicate values. Of course, I can use multiple loops that keep track of two separate indices and, in this way, make sure those two indices are the same. However, I wanted to see if there was a way to solve this with one iteration.
two_sum([1,2,3,4,5,6], 8) = true
two_sum([4,4], 8) = false

def two_sum(array, target)
  idx = 0
  while idx < array.length
    complement = target - array[idx]
    if array.include?(complement) && complement != array[idx]
      return true
    end
    idx+=1
  end
  return false
end

A: require 'set'

def two_sum(arr, tot)
  st = Set.new
  arr.each { |n| st.include?(tot-n) ? (return true) : st << n }
  false
end

two_sum [1,2,3,4,5,6], 8    #=> true
two_sum [4,4], 8            #=> true
two_sum [1,2,3,4,5,6], 3421 #=> false

If you'd prefer to return the two values that sum to tot (when true), replace true with [n, tot-n] (or just return n, the other being tot - n).
I used a set rather than an array for faster lookups.

A: def two_sum(array, target)
  array.combination(2).each { |pair| return true if pair.inject(:+) == target }
  return false;
end


text:
Q: Error while building an angular project for Tuple type '[]' of length '0' has no element at index '0' Following is the error when I am executing the following prod command
ng build --prod
ERROR in src/app/inventory/inv-parts-main-table/dialog-component/dialog-component.component.html(5,16): Tuple type '[]' of length '0' has no element at index '0'.
src/app/inventory/inv-parts-main-table/dialog-component/dialog-component.component.html(5,62): Tuple type '[]' of length '0' has no element at index '0'.
src/app/inventory/inv-parts-main-table/dialog-component/dialog-component.component.html(5,62): Tuple type '[]' of length '0' has no element at index '0'.
src/app/inventory/inv-parts-main-table/dialog-component/dialog-component.component.html(9,16): Tuple type '[]' of length '0' has no element at index '1'.
src/app/inventory/inv-parts-main-table/dialog-component/dialog-component.component.html(9,62): Tuple type '[]' of length '0' has no element at index '1'.
src/app/inventory/inv-parts-main-table/dialog-component/dialog-component.component.html(9,62): Tuple type '[]' of length '0' has no element at index '1'.
src/app/inventory/inv-parts-main-table/dialog-component/dialog-component.component.html(13,16): Tuple type '[]' of length '0' has no element at index '2'.
src/app/inventory/inv-parts-main-table/dialog-component/dialog-component.component.html(13,62): Tuple type '[]' of length '0' has no element at index '2'.
src/app/inventory/inv-parts-main-table/dialog-component/dialog-component.component.html(13,62): Tuple type '[]' of length '0' has no element at index '2'.
Source code related to the above error looks like this

      {{data.quote[0] | currency}}

      {{data.lastUpdatedDate[0] | date :'mediumDate'}} | {{data.supplierName[0]}}

      {{data.quote[1] | currency}}

      {{data.lastUpdatedDate[1] | date :'mediumDate'}} | {{data.supplierName[1]}}

      {{data.quote[2] | currency}}

      {{data.lastUpdatedDate[2] | date :'mediumDate'}} | {{data.supplierName[2]}}

The Ts file looks like below
export interface DialogData {
  quote: [];
  lastUpdatedDate : [];
  supplierName: [];
}

A: Following ts change helped me to fix this issue
Tuple type '[]' of length '0' has no element at index '1'.
export interface DialogData {
  quote: string[];
  lastUpdatedDate : string[];
  supplierName: string[];
}


text:
Q: Other Ways of Singleton in Java Just i was thinking about the other ways of writing singleton class. So is this class considered as a singleton class?
      public class MyClass{
            static Myclass myclass;

            static { myclass = new MyClass();}

            private MyClass(){}

            public static MyClass getInstance()
            {
                return myclass;
            }
       }

as the static block run only once.

A: There are 3 ways to create a singleton in java.

*

*eager initialization singleton
public class Test {
    private static final Test TEST = new Test();

    private Test() {
    }

    public static Test getTest() {
        return TEST;
    }
}

*lazy initialization singleton (thread safe)
public class Test {
    private static volatile Test test;
    private Test(){}
    public static Test getTest() {
        if(test == null) {
            synchronized(Test.class) {
                if(test == null){test = new Test();}
            }
        }
        return test;
    }
}

*Bill Pugh Singleton with Holder Pattern (Preferably the best one)
public class Test {
    private Test(){}

    private static class TestHolder {
        private static final Test TEST = new Test();
    }

    public static Test getInstance() {
        return TestHolder.TEST;
    }
}

A: No, it is not. You didn't declare myClass private static final, nor the getInstance() is static. The code also doesn't really compile.
Here's the Singleton idiom:
public class MyClass {
    private static final MyClass myClass = new MyClass();

    private MyClass() {}

    public static MyClass getInstance() {
        return myClass;
    }
}

It should be private, so that nobody else can access it directly. It should be static so that there's only one of it. It should be final so that it cannot be reassigned. You also need to instantiate it directly during declaration so that you don't need to worry (that much) about threading.
If the loading is expensive and you thus rather prefer lazy loading of the Singleton, then consider the Singleton holder idiom which does initialization on demand instead of during classloading:
public class MyClass {
    private MyClass() {}

    private static class LazyHolder {
        private static final MyClass myClass = new MyClass();
    }

    public static MyClass getInstance() {
        return LazyHolder.myClass;
    }
}

You should however put big question marks whether you need a Singleton or not. Often it's not needed. Just a static variable, an enum, a factory class and/or dependency injection is often the better choice.

A: Using your example and using the GoF's way of implementing it:
public class MyClass{
    private static Myclass instance;

    private MyClass(){
        //Private instantiation
    }

    public static synchronized MyClass getInstance()  //If you want your method thread safe...
    {
        if (instance == null) {
            instance = new MyClass();
        }

        return instance;
    }
}

Hope this helps:

A: Here is how I do it. It is faster, because it only requires a synchronized block when the instance is created.
public class MyClass
{
    private static MyClass INSTANCE=null;

    private MyClass()
    {
    }

    public static MyClass getInstance()
    {
        if(INSTANCE==null)
        {
            synchronized(MyClass.class)
            {
                if(INSATCNE==null) INSTANCE=new MyClass();
            }
        }
        return INSTANCE;
    }
}

A: Here's one more way to do it :
public enum Singleton{
  INSTANCE("xyz", 123);

  // Attributes
  private String str;
  private int i;

  // Constructor
  Singleton(String str, int i){
    this.str = str;
    this.i = i;
  }
}

According to Josh Bloch's Effective Java, this is the best way to implement Singleton in Java. Unlike implementations that involve a private static instance field, which can be multiply instantiated through the abuse of reflection and/or serialization, the enum is guaranteed to be a singleton.
The main limitation with enum singletons is that they are always instantiated at class loading time and can't be lazily instantiated. So if, for example, you want to instantiate a singleton using run-time arguments, you'll have to use a different implementation (preferably using double-checked locking).

A: Your class (original code, before editing):
public class MyClass {
    Myclass myclass;

    static { myclass = new MyClass();}

    private MyClass(){}

    public MyClass getInstance()
    {
        return myclass;
    }
}

is not a real singleton:

*

*the field myclass is not private, can be read and changed from outside (assuming you got an instace to do it on

*the field myclass is not static, can not be accessed in the static constructor (compilation error)

*the getInstance() method is not static, so you need an instance to call it

The actual code:
public class MyClass {
    static Myclass myclass;

    static { myclass = new MyClass();}

    private MyClass(){}

    public static MyClass getInstance()
    {
        return myclass;
    }
}

still has myclass not being private (nor final)... declaring it final would help to prevent it being unintentionally changed from inside the class.
private static final Myclass myclass;

A: public class singletonPattern {
    private static singletonPattern obj;

    public static singletonPattern getObject() {
        return obj = (obj == null) ? new singletonPattern() : obj;
    }

    public static void main(String args[]) {
        singletonPattern sng = singletonPattern.getObject();
    }
}

A: Might be a little late to the game on this, but a basic implementation would look something like this:
public class MySingleton {

     private static MySingleton INSTANCE;

     public static MySingleton getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new MySingleton();
        }

        return INSTANCE;
    }
    ...
}

Here we have the MySingleton class which has a private static member called INSTANCE, and a public static method called getInstance(). The first time getInstance() is called, the INSTANCE member is null. The flow will then fall into the creation condition and create a new instance of the MySingleton class. Subsequent calls to getInstance() will find that the INSTANCE variable is already set, and therefore not create another MySingleton instance. This ensures there is only one instance of MySingleton which is shared among all callers of getInstance().
But this implementation has a problem. Multi-threaded applications will have a race condition on the creation of the single instance. If multiple threads of execution hit the getInstance() method at (or around) the same time, they will each see the INSTANCE member as null. This will result in each thread creating a new MySingleton instance and subsequently setting the INSTANCE member.

private static MySingleton INSTANCE;

public static synchronized MySingleton getInstance() {
    if (INSTANCE == null) {
        INSTANCE = new MySingleton();
    }

    return INSTANCE;
}

Here we've used the synchronized keyword in the method signature to synchronize the getInstance() method. This will certainly fix our race condition. Threads will now block and enter the method one at a time. But it also creates a performance problem. Not only does this implementation synchronize the creation of the single instance, it synchronizes all calls to getInstance(), including reads. Reads do not need to be synchronized as they simply return the value of INSTANCE. Since reads will make up the bulk of our calls (remember, instantiation only happens on the first call), we will incur an unnecessary performance hit by synchronizing the entire method.

private static MySingleton INSTANCE;

public static MySingleton getInstance() {
    if (INSTANCE == null) {
        synchronize(MySingleton.class) {
            INSTANCE = new MySingleton();
        }
    }

    return INSTANCE;
}

Here we've moved synchronization from the method signature, to a synchronized block that wraps the creation of the MySingleton instance. But does this solve our problem? Well, we are no longer blocking on reads, but we've also taken a step backward. Multiple threads will hit the getInstance() method at or around the same time and they will all see the INSTANCE member as null. They will then hit the synchronized block where one will obtain the lock and create the instance. When that thread exits the block, the other threads will contend for the lock, and one by one each thread will fall through the block and create a new instance of our class. So we are right back where we started.

private static MySingleton INSTANCE;

public static MySingleton getInstance() {
    if (INSTANCE == null) {
        synchronized(MySingleton.class) {
            if (INSTANCE == null) {
                INSTANCE = createInstance();
            }
        }
    }

    return INSTANCE;
}

Here we issue another check from INSIDE the block. If the INSTANCE member has already been set, we'll skip initialization. This is called double-checked locking.
This solves our problem of multiple instantiation. But once again, our solution has presented another challenge. Other threads might not "see" that the INSTANCE member has been updated. This is because of how Java optimizes memory operations. Threads copy the original values of variables from main memory into the CPU's cache. Changes to values are then written to, and read from, that cache. This is a feature of Java designed to optimize performance. But this creates a problem for our singleton implementation. A second thread — being processed by a different CPU or core, using a different cache — will not see the changes made by the first. This will cause the second thread to see the INSTANCE member as null forcing a new instance of our singleton to be created.

private static volatile MySingleton INSTANCE;

public static MySingleton getInstance() {
    if (INSTANCE == null) {
        synchronized(MySingleton.class) {
            if (INSTANCE == null) {
                INSTANCE = createInstance();
            }
        }
    }

    return INSTANCE;
}

We solve this by using the volatile keyword on the declaration of the INSTANCE member. This will tell the compiler to always read from, and write to, main memory, and not the CPU cache.
But this simple change comes at a cost. Because we are bypassing the CPU cache, we will take a performance hit each time we operate on the volatile INSTANCE member — which we do 4 times. We double-check existence (1 and 2), set the value (3), and then return the value (4). One could argue that this path is the fringe case as we only create the instance during the first call of the method. Perhaps a performance hit on creation is tolerable. But even our main use-case, reads, will operate on the volatile member twice. Once to check existence, and again to return its value.

private static volatile MySingleton INSTANCE;

public static MySingleton getInstance() {
    MySingleton result = INSTANCE;
    if (result == null) {
        synchronized(MySingleton.class) {
            result = INSTANCE;
            if (result == null) {
                INSTANCE = result = createInstance();
            }
        }
    }

    return result;
}

Since the performance hit is due to operating directly on the volatile member, let's set a local variable to the value of the volatile and operate on the local variable instead. This will decrease the number of times we operate on the volatile, thereby reclaiming some of our lost performance. Note that we have to set our local variable again when we enter the synchronized block. This ensures it is up to date with any changes that occured while we were waiting for the lock.
I wrote an article about this recently. Deconstructing The Singleton. You can find more info on these examples and an example of the "holder" pattern there. There is also a real-world example showcasing the double-checked volatile approach. Hope this helps.

A: Singloton class is the class where you get the same object every time.
When you want to restrict a class from creating more than one object the we need the Singleton Class.
For example :
public class Booking {
    static Booking b = new Booking();
    private Booking() { }
    static Booking createObject() { return b; }
}

To create object of this class we can use  :
Booking b1, b2, b3, b4;
b1 = Booking.createObject();
b2 = Booking.createObject();
Booking b1, b2, b3, b4;
b1 = Booking.createObject();
b2 = Booking.createObject();

b1 and b2 are referring to same object.

A: You should think about the following properties while creating a singleton class

*

*Reflection

*Multi threading

*Clone

*Serialization

if no Clone or Serialization interfaces in your class, i think the following class is best as singleton class.
public class JavaClass1 {
private static JavaClass1 instance = null;
private JavaClass1() {
    System.out.println("Creating -------");
    if (instance != null) { // For Reflection
        throw new RuntimeException("Cannot create, please use getInstance()");
    }
}

public static JavaClass1 getInstance() {
    if (instance == null) {
        createInstance();
    }
    return instance;
}
 private static synchronized void createInstance() { // for multithreading
    if (instance == null) {
        instance = new JavaClass1();
    }
}}


text:
Q: Copy doesn't work on DataGrid templated columns? When working with templated column in WPF datagrid, you cann't copy cell content anymore, does anyone knows how this can be solved?

A: You need to set the ClipboardContentBinding property to the desired property in the row item, see the following code:
<DataGrid>
        <DataGrid.Columns>
            <DataGridTemplateColumn ClipboardContentBinding="{Binding YouProperty}">

            </DataGridTemplateColumn>
        </DataGrid.Columns>
</DataGrid>


text:
Q: Android database creation issue In my android application i'm using a manually created sqlite database.It works fine.Now i want to create a another temporary sqlite database by the application not manually.For that i created another Database helper class.Following is the code.But that databse is not creating.I checked the DDMS file explorer to verify the database.But it shows only my manually created database.
package com.buddhi.app;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class TempDatabaseHelper extends SQLiteOpenHelper{

private static final int DATABASE_VERSION = 1;
private static final String USER_INPUT_TABLE = "user_input";
private static String DATABASE_NAME = "temp_db.sqlite";

private static final String USER_INPUT_TABLE_CREATE =
            "CREATE TABLE " + USER_INPUT_TABLE + " (" +
                    "_id" + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                    "input" + " TEXT);";

TempDatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(USER_INPUT_TABLE_CREATE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    Log.w("","Drop table...");
        db.execSQL("DROP TABLE IF EXISTS " + USER_INPUT_TABLE);
        onCreate(db);
}

}


text:
Q: Thinkorswim and Ubuntu 22.04.1 jammy Why is my thinkorswim graphic (GUI) not appearing?
I upgraded to 22.04.1 and doing so removed TD Ameritrade's Thinkorswim. I installed thinkorswim again successfully.  However, it only fully open once in both the live and paper trade.
When I click on the ThinkorSwim desktop icon, the login popup appears, I log in, thinkorswim updates happen, the background browser screen goes black for a second then the open program icon appears in my side tray, but no graphic.
It seems thinkorswim is running but the display isn't there.  This is because when I right click on the open program icon and choose to quit a new small window opens asking me to confirm the quit.
I can also see the phrase java-lang-Thread up on the top bar.  It goes away upon the close.screen shot
I had no problems before the upgrade.
Thank you.

The next day... I left the thinkorswim applicaiton open overnight and when I opened up my laptop this afternoon the GUI was there and working.
I have an older laptop and a slow internet connection, so maybe it just takes a while to open with the new Ubuntu release.
ubfan1 suggested looking at the show applications to see if thinkorswim is open with a different name.  I didn't find it.
Below is another screenshot of the processes running when thinkorswim is open.
I think the Ubuntu and/or thinkorswim developers will work this out eventually.
Thank you.Screen Shot of Processes

Here is the link for the Zulu OpenJDK download from TDAmeritrade
TD Zulu Link
I have to admit, I'm afraid to close thinkorswim

Later that day I closed thinkorswim, opened it again, and left to do something else.  I came back about 2 hours later and the GUI was operational.

A: Ubuntu 22.04 defaults to two desktops, and while a four finger swipe may work to change desktops, selecting desktops from the app list works for me. Click on the App library on the bottom of the launch bar.  The two desktops are right under the search bar, with windows of what's running on each -- click on a desktop to select it.I did the install without the zulu java, and up to the login, seems to work, but without an account, can't go any further.

A: I had the same problem. It is like the desktop application window has disappeared. What I did was select the window using Super+TAB and then used the keyboard shortcut to maximize the window ALT+F10. That displayed the application. Then clicking on the un-maximize button made it normal again.


text:
Q: How to obtain gmail messages received after a particular date using Google Apps Script? How to get gmail messages received after a particular date using Google Apps Script?
Here is my current code.
function getGmailEmails(){
  var label = GmailApp.getUserLabelByName("TestLabel");
  var threads = label.getThreads();

  for (var i = threads.length - 1; i >=0; i--){
    var messages = threads[i].getMessages();

    for (var j = 0; j <messages.length; j++){
      var message = messages[j];
      extractDetails(message);
    }
  }
}

I know we can set limits with getThread(0,50) for example but how can I do it so I can retrieve all my gmails from a specific period of time while also getting it within a certain label from my inbox?

A: Messages After a Date:
function getGmailEmailsAfter(date){
  const label = GmailApp.getUserLabelByName("TestLabel");
  const threads = label.getThreads();
  const dtv = new Date(date.getFullYear(),data.getMonth(),date.getDate()).valueOf();
  for (let i = threads.length - 1; i >=0; i--){
    let messages = threads[i].getMessages();
    for (let j = 0; j <messages.length; j++){
      let message = messages[j];
      let dt = new Date(message.getDate())
      if(new Date(dt.getFullYear(),dt.getMonth(),dt.getDate()).valueOf() > dtv) {
        extractDetails(message);
      }
    }
  }
}


text:
Q: PHP Includes and Load Time If I add PHP includes to a page. include('example.php') - It then has to load that file which would / could slow down load time correct? Right now I am making unnecessary redirects back to the a login page if the logins are wrong via javascript snippet that is inside my login.php page (which does all the login checking against the database). So in the address bar it shows "admin.php > login.php > admin.php" , but I don't ever want to show what file it is going to in order to test the logins, but I also do not want to include this inside admin.php because I'm afraid it might affect load time.

If you understand my question then suggestions would be helpful.

A: Do what you feel is best in terms of readability and maintainability at server-side. Then, if you have a performance problem, find where it comes from by measuring (and not guessing), and try to optimize.
You're optimizing prematurely, and this is the root of all evil. Compared to the time it takes to a HTTP request/response to execute, including some additional lines of PHP is very certainly negligible.

A: New HTTP requests (redirects) are always a bigger performance hit than includes, so there's no reason to use redirects (especially Javascript ones) if you're only concerned about the performance. So if I understand you I'd like to suggest that you just include the file.


text:
Q: How to use AsyncLocalStorage for an Observable? I'd like to use use AsyncLocalStorage in a NestJs Interceptor:
export interface CallHandler<T = any> {
    handle(): Observable<T>;
}
export interface NestInterceptor<T = any, R = any> {
    intercept(context: ExecutionContext, next: CallHandler<T>): Observable<R> | Promise<Observable<R>>;
}

The interceptor function gets a next CallHandler that returns an Observable.
I cannot use run in this case (the run callback will exit immediately before the callHandler.handle() observable has finished):
  intercept(context: ExecutionContext, callHandler: CallHandler): Observable<any> | Promise<Observable<any>> {
    const asyncLocalStorage = new AsyncLocalStorage();
    const myStore = {  some: 'data'};
    return asyncLocalStorage.run(myStore, () => callHandler.handle());
  }

See broken replit-example
The solution I came up with is this:
const localStorage = new AsyncLocalStorage();

export class MyInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, callHandler: CallHandler): Observable<any> | Promise<Observable<any>> {
    const resource = new AsyncResource('AsyncLocalStorage', { requireManualDestroy: true });
    const myStore = { some: 'data' };

    localStorage.enterWith(myStore);
    return callHandler.handle().pipe(
      finalize(() => resource.emitDestroy())
    );
  }
}

See working replit example
This seems to work fine, but I am not sure if this is really correct - and it looks messy and error-prone. So I wonder:

*

*Is this correct at all?

*Is there a better/cleaner way to handle this?

A: Below is the solution I came up with.  My understanding of the problem is that you need the run function to receive a callback function that will fully encapsulate the execution of the handler, however, the intercept function is expected to return an observable that has not yet been triggered.  This means that if you encapsulate the observable itself in the run callback function, it will not have been triggered yet.
My solution, below, is to return a new observable that, when triggered, will  be responsible for triggering (i.e. subscribing to) the call handler itself.  As a result, the promise we create in the run call can fully encapsulate the handle function and it's async callbacks.
Here is the general functionality in a stand-alone function so that you can see it all together:
intercept(context: ExecutionContext, next: CallHandler<any>): Observable<any> {
    return new Observable((subscribe) => {
        asyncStorage.run({}, () => new Promise(resolve => {
            next.handle().subscribe(
                result => {
                    subscribe.next(result);
                    subscribe.complete();
                    resolve();
                },
                error => {
                    subscribe.error(err);
                    resolve();
                }
            );
        }));
    });
}

Next, I took that concept and integrated it into my interceptor below.
export class RequestContextInterceptor implements NestInterceptor {
    constructor(
        private readonly requestContext: RequestContext,
        private readonly localStorage: AsyncLocalStorage<RequestContextData>
    ) {}

    intercept(context: ExecutionContext, next: CallHandler<any>): Observable<any> {
        const contextData = this.requestContext.buildContextData(context);
        return new Observable((subscribe) => {
            void this.localStorage.run(contextData, () => this.runHandler(next, subscribe));
        });
    }

    private runHandler(next: CallHandler<any>, subscribe: Subscriber<any>): Promise<void> {
        return new Promise<void>((resolve) => {
            next.handle().subscribe(
                (result) => {
                    subscribe.next(result);
                    subscribe.complete();
                    resolve();
                },
                (err) => {
                    subscribe.error(err);
                    resolve();
                }
            );
        });
    }
}

It's worth noting that the Promise that is created during the run call does not have a rejection path.  This is intentional.  The error is passed on to the observable that is wrapping the promise.  This means that the outer observable will still succeed or error depending upon what the inner observable does, however, the promise that wraps the inner observable will always resolve regardless.

A: Here is a solution for cls-hooks:
return new Observable(observer => {
  namespace.runAndReturn(async () => {
    namespace.set("some", "data")
    next.handle()
        .subscribe(
          res => observer.next(res),
          error => observer.error(error),
          () => observer.complete()
        )
  })
})

A: here is our current solution to the problem:

*

*we create an observable that will simply pass all emissions to the callHandler

*the important part is, that we subscribe inside the localStorage.run method

const localStorage = new AsyncLocalStorage();

export class MyInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, callHandler: CallHandler): Observable<any> | Promise<Observable<any>> {
    const myStore = { some: 'data' };

    return new Observable((subscriber) => {
      const subscription = localStorage.run(myStore, () => {
        /**
         * - run the handler function in the run callback, so that myStore is set
         * - subscribe to the handler and pass all emissions of the callHandler to our subscriber
         */
        return callHandler.handle().subscribe(subscriber);
      });
      /**
       * return an unsubscribe method
       */
      return () => subscription.unsubscribe();
    });
  }
}


text:
Q: Fourier sine series for $f(x) = x(1-x)$ on the interval $[0,1]$ So I'm trying to find the Fourier series for $f(x) = x(1 - x)$ on the interval $[0, 1]$ and so the coefficients are
$$
b_n = \int_{0}^{1} x(1-x)\sin(n\pi x)dx
$$
which is a pretty simple integration parts, from which I get
$$
b_n = \frac{4\left(1-\left(-1\right)^{n}\right)}{n^{3}\pi^{3}}
$$
Which would give me the association
$$
x(1-x) = \frac{4}{\pi^3}\sum_{n=1}^{\infty}\frac{\left(1-\left(-1\right)^{n}\right)}{n^{3}}\sin\left(n\pi x\right)
$$
But I know that the answer I'm supposed to get is
$$
x(1-x) = \frac{8}{\pi^3}\sum_{n=1}^{\infty}\frac{2}{\left(2n-1\right)^{3}}\sin\left(\left(2n-1\right)\pi x\right)
$$
Am I going wrong somewhere? I followed all the steps correctly and I am pretty sure I have the correct coefficients. Just a bit confused how to get the right answer

A: You are correct. Simply note that $1-(-1)^n$ is zero if $n$ is even and $2$ if $n$ is odd. An odd number can be written as $2m-1$ and finally $n$ can be substituted to $m$.


text:
Q: Getting the locale time that is not depending on client browser I want to get the locale time from ISO format that is not depending on local browser.
For example, I want to get the date at ko-KR though the browser opened in the other time zone(for example, in en-US).
The ISO string I have is 2020-10-22T00:00:00.000Z and if I use new Date to it like
new Date('2020-10-22T00:00:00.000Z');

it returns the date 2020-10-21 16:00:00 GMT-0800.
But I want to get date in Korea like 2020-10-22 09:00:00 GMT+0900.
The toLocaleString method returns string value. But I want the date object to certain locale.

A: "The toLocaleString method returns string value. But I want the date object to certain locale.
That's not possible. The timestamp is stored as UTC. It's only converted for the output. The date object won't change.

Creates a JavaScript Date instance that represents a single moment in time in a platform-independent format. Date objects contain a Number that represents milliseconds since 1 January 1970 UTC.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date

A: you can use moment-timezone to get the time as per the specific timezone.

let date= moment()

let dateAsPerTimeZone = moment.tz(date,'Asia/Seoul');

console.log(dateAsPerTimeZone.format());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data-2012-2022.min.js"></script>

A: So, I make a function to handle this problem. The point is the getTimezoneOffset. Following is my code and the return value and function process can be different depending on your needs.
const ko_offset = -540 * 60 * 1000; // it is the Asia/Seoul time zone offset in milliseconds

/**
 * Input : any locale date object
 * Output : translated input date object to Asia/Seoul timezone date object
*/
const toKoreaTime = date => {
  const d = typeof date === 'string' ? new Date(date) : date;
  let kd;
  if (d.getTimezoneOffset() === ko_offset) {
    kd = d;
  } else {
    kd = new Date(d.getTime() + (d.getTimezoneOffset() * 60 * 1000) - ko_offset);
  }
  const Y = kd.getFullYear(), M = kd.getMonth() + 1, D = kd.getDate(), h = kd.getHours(), m = kd.getMinutes(), s = kd.getSeconds();

  return { Y, M, D, h, m, s };
};

It can be used to get the certain timezone date time for any timezone date. For example, if I want to know the Korea date time in the US
const usDate = new Date(); // I'm use it in the US. (UTC -8)
const koDate = toKoreaTime(usDate); // return Korea date and time. (UTC +9)


text:
Q: Socket.io + React: Different classes -> use same socket? This is hopefully my best take at describing and simplifying my problem:
I have my main class for my react app called App  in App.js (I use [...] as Placeholder for other code):
import {myComponent} from "./components.js";

const { io } = require("socket.io-client");

class App extends Component {
    constructor(props) {
    super(props)
    this.state = {
        isLoaded
         [...]
         }
      }
    componentDidMount() {
        this.socket = io()
        [...]
        }
    render() {
       const {isLoaded, [...]} = this.state
       return (

BLUB

         <myComponent/>
         [...]
         )
       }
  }

myComponent is defined in components.js and imported into App.js. I have also implemeted socket.io following the instructions in their documentation. As you see on componentDidMount() I define this.socket for the communication to the server. My question is how can I tell myComponent to use this specific socket as well, eventough it is located in components.js?
class myComponent extends Component {
 ???
}

 export {myComponent}

Thanks for every piece of advice :)
PS: I moved myComponent out of App.js and the class App, to reduce the class size, it was getting out of control...


text:
Q: cocoa - quickly release all IBOUtlets I have a view with many retained IBOutlets, loaded from a XIB.
I have read that they have to be released when the controller's dealloc method is called.
May I use a cycle to do this(also to avoid releasing each outlet separately)?
something like
for(UIView *v in self.view.subviews){
[v release];
v=nil;
}

?
also, after that, should I release the view as well?

A: That would only make sense if you've actually retained every single subview, and even then it seems like asking for trouble -- if you ever wanted to change your .xib, you'd have to remember to update you code as well. And there may also be non-view objects in a nib that can be connected to outlets, like view controllers.
There are only so many views you can fit on an iPhone- or iPad-sized screen, so it's hard to imagine that you have more than a few dozen outlets. I think the prudent thing to do here is to simply release each one separately. This is what and iOS developer would expect to see, and it won't be any slower than using a loop. It'll be more code, yes, but the code will be easy to understand.

A: self.view is automatically released on UIViewController deallocation, and subviews also, if not retained by your code.
You should re-read the chapter on memory management in Apple Documentation... ;)

A: I wrote like a releaseVars function, which takes address of variables, release them and set to nil. This save some lines of code, but still you have to manually take care of them.


text:
Q: how can i recursively track empty folders and put an .keep file in it? In order to push empty folders into git,
i want to use a recursive windows command to track those empty folders and put a ".keep" file in them.
Thanks

A: Run this powershell script to populate all empty folders with .keep
(gci . -r | ? {$_.PSIsContainer -eq $True}) | ? {$_.GetFiles().Count -eq 0} | foreach-object { New-Item (Join-Path $($_.FullName) ".keep")}


text:
Q: Global sections appearing in Dolbeault complex with values in vector bundle Given a holomorphic vector bundle $E$ on a compact complex Kähler manifold $X$ (I am happy to assume $X$ projective), we can compute the sheaf cohomology $H^\ast(E)$ of $E$ using the Dolbeault complex with values in $E$ (see e.g. Huybrechts' book Complex Geometry, Section 2.6).
The Dolbeault complex consists of the (smooth) global sections $\Gamma(X, \mathcal{A}^{0,q}_X \otimes E)$ of the (smooth) bundle $\mathcal{A}^{0,q}_X \otimes E$. Is it known whether the (infinite-dimensional) vector space $\Gamma(X, \mathcal{A}^{0,q}_X \otimes E)$ is generated by tensor products $\omega \otimes v$ with $\omega$ respectively $v$ smooth sections of $\mathcal{A}^{0,q}_X$ respectively $E$? I believe this does not need to hold.
Note that the description of the question Global Definition of the Dolbeault Complex of a Vector Bundle seems to assume this is true, whereas the comment underneath says that the operator $\bar{\partial}_E$ only locally agrees with $\bar{\partial} \otimes id$ (which I interpret as a negative answer to my question).


text:
Q: Using SQL dB column as a lock for concurrent operations in Entity Framework We have a long running user operation that is handled by a pool of worker processes. Data input and output is from Azure SQL.
The master Azure SQL table structure columns are approximated to
[UserId, col1, col2, ... , col N, beingProcessed, lastTimeProcessed ]

beingProcessed is boolean and lastTimeProcessed is DateTime. The logic in every worker role is as shown below and with multiple workers processing (each with their own Entity Framework layer), in essence beingProcessed is being used a lock for MutEx purposes
Question: How can I deal with concurrency issues on the beingProcessed "lock" itself based on the above load? I think  read-modify-write operation on the beingProcessed needs to be atomic but I'm open to other strategies. Open to other code refinements too.
[Update]: I wonder if TransactionScope is what's needed here ... http://msdn.microsoft.com/en-US/library/system.transactions.transactionscope(v=vs.110).aspx
Code:
public void WorkerRoleMain()
{
    while(true)
    {
        try
        {
            dbContext db = new dbContext();

            // Read
            foreach (UserProfile user in db.UserProfile
                    .Where(u => DateTime.UtcNow.Subtract(u.lastTimeProcessed)
                            > TimeSpan.FromHours(24) &
                            u.beingProcessed == false))
            {
                user.beingProcessed = true; // Modify
                db.SaveChanges();           // Write
                // Do some long drawn processing here
                ...
                ...
                ...
                user.lastTimeProcessed = DateTime.UtcNow;
                user.beingProcessed = false;
                db.SaveChanges();
            }
        }
        catch(Exception ex)
        {
            LogException(ex);
            Sleep(TimeSpan.FromMinutes(5));
        }
    } // while ()
}

A: What we usually do is this:
At the beginning of a long operation we start a transaction:
BEGIN TRANSACTION

Then we select a row from the table we would like to update/delete using these hints:
SELECT * FROM Table WITH (ROWLOCK, NOWAIT) Where ID = 123;

Then we check that we have the row. If the row is locked by another process there will be an SQL Error. In this case we rollback the transaction and advise the user.
If the record is locked we process the record, and do the required updates, using the same transaction object we used to lock the record:
UPDATE Table SET Col1='value' WHERE ID = 123;

Then we COMMIT the transaction.
COMMIT;

This is just the Pseudo-code of the process. You will have to implement it in your program.
One small note regarding the above process. When you lock the record in SQL Server (or Azure), use the primary key in your WHERE Clause, otherwise the SQL Server will decide to use a Page lock, or Table lock


text:
Q: How can I verify that my graphics card is used correctly when playing games I recently installed steam on my laptop to play some games but the experience is not that good. I don't play a lot but with the computer I use I would have expected something better. I am getting really low frame rates even on low resolutions.
My computer is a Lenovo Y50-70:

*

*Processor: Intel® Core™ i7-4710HQ CPU @ 2.50GHz × 8

*Ram 16Gb

*Graphics card: GeForce GTX 860M

I want to confirm that my actual graphics card is used and not the intel integrated one. When I check system details it says "Intel® Haswell Mobile". Another question on this site has this answer for how to find the model of the computers graphics card. If I run that command the output is Intel Corporation 4th Gen Core Processor Integrated Graphics Controller
However the full output of that command also shows NVIDIA Corporation GM107M [GeForce GTX 860M] as "3D controller".
The low frame rates in the games makes me question whether my graphics card is actually used. What can I do to confirm it is? Or is gaming that bad on linux?
After problem solved:
I reinstalled the nvidia drivers (which I already had installed) and suddenly it worked. Games play much better now. When checking system details it now says "GeForce GTX 860M/PCIe/SSE2" for "Graphics" so if your proper graphics card is not listed here, chances are that is is not installed correctly.

A: Check the Additional Drivers app. If Nouveau is selected, Intel graphics are most likely being used for games and videos. You can switch to using NVIDIA by selecting one of the proprietary driver options and clicking Apply Changes.
There may be multiple versions to select. Ignore the -updates options, since those are experimental and not fully tested. Use them only if the other proprietary options don't work for you. If there are still a couple proprietary options, start with the newest version.
Once you install the proprietary drivers and reboot, you will be using NVIDIA, but full-time, meaning less battery life. You can open the NVIDIA X-Server Settings app, go to PRIME Profiles and switch to Intel, but that switches everything over, and requires you to relog.
As an alternative to the PRIME Profiles, there is an app called Bumblebee, which acts like the Windows NVIDIA Control Panel, allowing you to select which programs you want to run on which card. It should be available from the Software Center. Be aware, though, this program may not be very stable. I currently have it on my Ubuntu 15.10 installation and have no problems so far, but I haven't really tried it out. Other people have reported that it completely breaks the system or just doesn't work in the first place. It's a hit-or-miss situation. You're welcome to try it. Just don't get your hopes too high.


text:
Q: Firebase Deploy Function and website hosting Error i  deploying database, storage, firestore, functions, hosting
Running command: npm --prefix $RESOURCE_DIR run lint
npm ERR! path D:\public\$RESOURCE_DIR\package.json
npm ERR! code ENOENT
npm ERR! errno -4058
npm ERR! syscall open
npm ERR! enoent ENOENT: no such file or directory, open 'D:\public\$RESOURCE_DIR
\package.json'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\bonrix\AppData\Roaming\npm-cache\_logs\2018-01-31T07_42_27
_103Z-debug.log

Error: functions predeploy error: Command terminated with non-zero exit code4294
963238

D:\public>

====================================================
Check Attachment$RESOURCE_DIR folder have no file named package.json

A: as it show the log, you have no package.json inside your dir.
btw, you should run it from root of the project with installed firebase-tools globaly via npm.
Then just do all steps from there (firebase) guide.


text:
Q: Get identity claims from bearer token (Web API) I have two Web APIs with a shared machine.key. I would like to pass the bearer token generated by the first Web API to the second Web API as a parameter (i.e. token=xxxxxxxx) and extract the identity claims (i.e userId) from it.
Is this possible? I've looked all over but there doesn't seem to be much information on parsing a text bearer token to extract claims.
Thanks.

A: If you're using OWIN, you could implement your own OAuthBearerAuthenticationProvider, which takes the token from the query string and sets it to the context:
internal class MyAuthProvider : OAuthBearerAuthenticationProvider
{
    public override Task RequestToken(OAuthRequestTokenContext context)
        if (context.Token == null)
        {
            var value = context.Request.Query.Get("token");
            if (!string.IsNullOrEmpty(value))
            {
                context.Token = value;
            }
        }

        return Task.FromResult<object>(null);
    }
}

You could use it in your Startup.cs like this:
public void Configuration(IAppBuilder app)
{
    // All the other stuff here

    var audience = "";
    var secret = "...";

    app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
    {
        Provider = new MyAuthProvider(),
        AuthenticationMode = AuthenticationMode.Active,
        AllowedAudiences = new [] { audience },
        IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
        {
            new SymmetricKeyIssuerSecurityTokenProvider("MyApp", TextEncodings.Base64Url.Decode(key))
        }
    });

    // All the other stuff here
}

When you've implemented your auth like this, you can access the token information in your WebApi controller via the User.Identity property. To read custom claims, you can cast it to ClaimsIdentity.
var identity = User.Identity as ClaimsIdentity;
var myClaim = identity.Claims.FirstOrDefault(c => c.Type == "myClaimKey");