text:
Q: Docker creation with web service in complex architecture I need to create a docker containing some code and a small flask server to expose some part of the code. But I struggle to make it working to my complex file architures.
My files are organized as :
main_project
    --sub_part_1
        --repo_1
            --some_code.py
        --repo_2
            --app.py
            --Dockerfile
        --repo_3
        Pipfile.lock
    --sub_part_2
    --sub_part_3
    --docker-compose.yml

I have to create a Dockerfile and a docker-compose.yml to run the app.py (flask app) and expose it on a given port
What I have now is
Dockerfile
FROM python:3.8-slim-buster as base

ENV LANG C.UTF-8
ENV LC_ALL C.UTF-8
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONFAULTHANDLER 1
ENV PYTHONUNBUFFERED 1
ENV FLASK_APP subpart_1/repo_2/app.py
ENV FLASK_RUN_HOST 0.0.0.0

RUN pip install pipenv
RUN apt-get update && apt-get install -y --no-install-recommends build-essential libpq-dev gcc musl-dev
COPY ./subpart_1/Pipfile /subpart_1/Pipfile
COPY ./subpart_1/Pipfile.lock /subpart_1/Pipfile.lock

WORKDIR /subpart_1
RUN PIPENV_VENV_IN_PROJECT=1 pipenv install --deploy --ignore-pipfile --sequential
WORKDIR /
COPY ./subpart_1/repo_2 /subpart_1/repo_2/
COPY ./subpart_1/repo_1 /subpart_1/repo_1/

ENV PYTHONPATH /subpart_1/

WORKDIR /subpart_1

EXPOSE 5000
CMD ["flask", "run"]

and the docker-compose.yml
version: "3.9"
services:
  web:
    build: subpart_1/repo_2/
    ports:
      - "5000:5000"

But when I go in my main_project directory and run docker-compose up I have
failed to compute cache key: failed to walk /var/lib/docker/tmp/buildkit-mount585608421/subpart_1: lstat /var/lib/docker/tmp/buildkit-mount585608421/subpart_1: no such file or directory
ERROR: Service 'web' failed to build : Build failed

A: It seems to me that's a path issue.
When setting subpart_1/repo_2/ in your docker-compose build file, the build will be done in this repertory. Docker will see the following files:
-app.py
-Dockerfile

thus the copy ./subpart_1/Pipfile /subpart_1/Pipfile cannot work.
I think the easiest way is to put:
version: "3.9"
services:
  web:
    build:
      context: .
      dockerfile: sub_part_1/repo_2/Dockerfile
    ports:
      - "5000:5000"


text:
Q: Stored Procedures, MySQL and PHP The question is a fairly open one. I've been using Stored Procs with MS SQLServer for some time with classic ASP and ASP.net and love them, lots.
I have a small hobby project I'm working on and for various reasons have gone the LAMP route. Any hints/tricks/traps or good starting points to get into using stored procedures with MySQL and PHP5? My version of MySQL supports Stored Procedures.

A: @michal kralik - unfortunately there's a bug with the MySQL C API that PDO uses which means that running your code as above with some versions of MySQL results in the error:

"Syntax error or access violation: 1414 OUT or INOUT argument $parameter_number for routine $procedure_name is not a variable or NEW pseudo-variable".

You can see the bug report on bugs.mysql.com.   It's been fixed for version 5.5.3+ & 6.0.8+.
To workaround the issue, you would need to separate in & out parameters, and use user variables to store the result like this:
$stmt = $dbh->prepare("CALL sp_takes_string_returns_string(:in_string, @out_string)");
$stmt->bindParam(':in_string', 'hello');

// call the stored procedure
$stmt->execute();

// fetch the output
$outputArray = $this->dbh->query("select @out_string")->fetch(PDO::FETCH_ASSOC);

print "procedure returned " . $outputArray['@out_string'] . "\n";

A: Forget about mysqli, it's much harder to use than PDO and should have been already removed. It is true that it introduced huge improvements over mysql, but to achieve the same effect in mysqli sometimes requires enormous effort over PDO i.e. associative fetchAll.
Instead, take a look at PDO, specifically
prepared statements and stored procedures.
$stmt = $dbh->prepare("CALL sp_takes_string_returns_string(?)");
$value = 'hello';
$stmt->bindParam(1, $value, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 4000);

// call the stored procedure
$stmt->execute();

print "procedure returned $value\n";

A: You'll need to use MySQLI (MySQL Improved Extension) to call stored procedures. Here's how you would call an SP:
$mysqli = new MySQLI(user,pass,db);

$result = $mysqli->query("CALL sp_mysp()");

When using SPs you'll need close first resultset or you'll receive an error. Here's some more information :

http://blog.rvdavid.net/using-stored-procedures-mysqli-in-php-5/
  (broken link)

Alternatively, you can use Prepared Statements, which I find very straight-forward:
  $stmt = $mysqli->prepare("SELECT Phone FROM MyTable WHERE Name=?");

  $stmt->bind_param("s", $myName);

  $stmt->execute();

MySQLI Documentation: http://no.php.net/manual/en/book.mysqli.php

A: It isn't actually mandatory to use mysqli or PDO to call stored procedures in MySQL 5. You can call them just fine with the old mysql_ functions. The only thing you can't do is return multiple result sets.
I've found that returning multiple result sets is somewhat error prone anyway; it does work in some cases  but only if the application remembers to consume them all, otherwise the connection is left in a broken state.

A: I have been using ADODB, which is a great thing for abstracting actual commands to make it portable between different SQL Servers (ie mysql to mssql).  However, Stored procedures do not appear to be directly supported. What this means, is that I have run a SQL query as if it is a normal one, but to "call" the SP.
An example query:
$query = "Call HeatMatchInsert('$mMatch', '$mOpponent', '$mDate', $mPlayers, $mRound,  '$mMap', '$mServer', '$mPassword', '$mGame', $mSeason, $mMatchType)";

This isn't accounting for returned data,which is important. I'm guessing that this would be done by setting a @Var , that you can select yourself as the return @Variable .
To be Abstract though, although making a first php stored procedure based web app was very difficult to work around (mssql is very well documented, this is not), It's great after its done - changes are very easy to make due to the seperation.

redpajama_set_name: RedPajamaStackExchange


text:
Q: error while querying Solr : Failed to query Solr using '(**)': [Reason: undefined field django_ct] I am very new to solr and was trying to implement using examples in the official quick start guide.
here are the steps i took

*

*bin/solr start -e cloud -noprompt

*bin/post -c gettingstarted example/exampledocs/schema.xml

here is the error log
org.apache.solr.common.SolrException: undefined field django_ct
    at org.apache.solr.schema.IndexSchema.getDynamicFieldType(IndexSchema.java:1298)
    at org.apache.solr.schema.IndexSchema$SolrQueryAnalyzer.getWrappedAnalyzer(IndexSchema.java:444)
    at org.apache.lucene.analysis.DelegatingAnalyzerWrapper$DelegatingReuseStrategy.getReusableComponents(DelegatingAnalyzerWrapper.java:74)
    at org.apache.lucene.analysis.Analyzer.tokenStream(Analyzer.java:172)
    at org.apache.lucene.util.QueryBuilder.createFieldQuery(QueryBuilder.java:199)
    at org.apache.solr.parser.SolrQueryParserBase.newFieldQuery(SolrQueryParserBase.java:370)
    at org.apache.solr.parser.SolrQueryParserBase.getFieldQuery(SolrQueryParserBase.java:753)
    at org.apache.solr.parser.SolrQueryParserBase.handleBareTokenQuery(SolrQueryParserBase.java:537)
    at org.apache.solr.parser.QueryParser.Term(QueryParser.java:299)
    at org.apache.solr.parser.QueryParser.Clause(QueryParser.java:185)
    at org.apache.solr.parser.QueryParser.Query(QueryParser.java:107)
    at org.apache.solr.parser.QueryParser.Clause(QueryParser.java:189)
    at org.apache.solr.parser.QueryParser.Query(QueryParser.java:107)
    at org.apache.solr.parser.QueryParser.TopLevelQuery(QueryParser.java:96)
    at org.apache.solr.parser.SolrQueryParserBase.parse(SolrQueryParserBase.java:151)
    at org.apache.solr.search.LuceneQParser.parse(LuceneQParser.java:50)
    at org.apache.solr.search.QParser.getQuery(QParser.java:141)
    at org.apache.solr.handler.component.QueryComponent.prepare(QueryComponent.java:203)
    at org.apache.solr.handler.component.SearchHandler.handleRequestBody(SearchHandler.java:229)
    at org.apache.solr.handler.RequestHandlerBase.handleRequest(RequestHandlerBase.java:143)
    at org.apache.solr.core.SolrCore.execute(SolrCore.java:2064)
    at org.apache.solr.servlet.HttpSolrCall.execute(HttpSolrCall.java:654)
    at org.apache.solr.servlet.HttpSolrCall.call(HttpSolrCall.java:450)
    at org.apache.solr.servlet.SolrDispatchFilter.doFilter(SolrDispatchFilter.java:227)
    at org.apache.solr.servlet.SolrDispatchFilter.doFilter(SolrDispatchFilter.java:196)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:585)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:577)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:223)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1127)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1061)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
    at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:215)
    at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:110)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
    at org.eclipse.jetty.server.Server.handle(Server.java:497)
    at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:310)
    at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:257)
    at org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:540)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:635)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:555)
    at java.lang.Thread.run(Thread.java:745)

A: The problem was with where I kept my schema file. The quick star guide is really not particular about it and most tutorials dont cover 5.2.
The schema file has to be put inside the 'conf' folder.


text:
Q: Map Sets in Golang If I have a struct like:
type Foo struct {
  title string
  Tags map[string]string
}

How might approach maintaining a unique set of such structs? From what I understand, although struct equality is a thing - map equality isn't. This means I can't compare my above structs. Therefore I can't just implement the map as set pattern.
The two options that might work I can think of are: convert the Tags to a sorted [][]string or use reflect.Deepequal. Anyone have a better idea?

A: There are a few ways of implementing this. James Henstridge actually had a good idea, and I attempted to implement it. It performed pretty poorly just to use map in the first place, without my own hash algorithm.
The way I solved this problem is just keep an array of your structs and then remove any duplicates as you insert them.
package structset

type Foo struct {
  title string
  Tags  map[string]string
}

func (f Foo) Equals(f2 Foo) bool {
  if f.title != f2.title {
    return false
  }

  if len(f.Tags) != len(f2.Tags) {
    return false
  }

  for k, v := range f.Tags {
    if w, ok := f2.Tags[k]; !ok || v != w {
      return false
    }
  }

  return true
}

type FooSet []Foo

func (this FooSet) Add(value Foo) {
  if !this.Contains(value) {
    this = append(this, value)
  }
}

func (this FooSet) Length() int {
  return len(this)
}

func (this FooSet) Contains(f Foo) bool {
  for _, v := range this {
    if v.Equals(f) {
      return true
    }
  }
  return false
}

func NewSet() FooSet {
  return FooSet(make([]Foo, 0, 100))
}

I benchmarked this on my i7-3770K Windows machine and got:
BenchmarkSmallSetWithFewCollisions         50000             46615 ns/op
BenchmarkSmallSetWithMoreCollisions        50000             46575 ns/op
BenchmarkSmallSetWithManyCollisions        50000             46605 ns/op
BenchmarkMediumSetWithFewCollisions         1000           2335296 ns/op
BenchmarkMediumSetWithMoreCollisions        1000           2352298 ns/op
BenchmarkMediumSetWithManyCollisions        1000           2336796 ns/op
BenchmarkLargeSetWithFewCollisions            50          46805944 ns/op
BenchmarkLargeSetWithMoreCollisions           50          47376016 ns/op
BenchmarkLargeSetWithManyCollisions           50          46815946 ns/op

To eek out a very small amount of performance, you can insert all your data into the array first, and then remove all duplicates after.
The remove duplicates code is:
func (this FooSet) RemoveDuplicates() {
  length := len(this) - 1
  for i := 0; i < length; i++ {
    for j := i + 1; j <= length; j++ {
      if this[i].Equals(this[j]) {
        this[j] = this[length]
        this = this[0:length]
        length--
        j--
      }
    }
  }
}

The benchmarks for this is:
BenchmarkSmallSetWithFewCollisions         50000             45245 ns/op
BenchmarkSmallSetWithMoreCollisions        50000             45615 ns/op
BenchmarkSmallSetWithManyCollisions        50000             45555 ns/op
BenchmarkMediumSetWithFewCollisions         1000           2294791 ns/op
BenchmarkMediumSetWithMoreCollisions        1000           2309293 ns/op
BenchmarkMediumSetWithManyCollisions        1000           2286290 ns/op
BenchmarkLargeSetWithFewCollisions            50          46235870 ns/op
BenchmarkLargeSetWithMoreCollisions           50          46515906 ns/op
BenchmarkLargeSetWithManyCollisions           50          45865824 ns/op

Here is the benchmark of just assigning Foo to a map[string]Foo.
BenchmarkSmallSetWithFewCollisions         50000             65718 ns/op
BenchmarkSmallSetWithMoreCollisions        50000             64238 ns/op
BenchmarkSmallSetWithManyCollisions        50000             55016 ns/op
BenchmarkMediumSetWithFewCollisions          500           3429435 ns/op
BenchmarkMediumSetWithMoreCollisions         500           3117395 ns/op
BenchmarkMediumSetWithManyCollisions        1000           2826858 ns/op
BenchmarkLargeSetWithFewCollisions            20          82635495 ns/op
BenchmarkLargeSetWithMoreCollisions           20          85285830 ns/op
BenchmarkLargeSetWithManyCollisions           20          73659350 ns/op

It seems to me even if a map was hashable, it still wouldn't perform very well.

A: Depending on what you are doing, one option might be to store the structs as the values in the map rather than keys.  For this to work, you will need to create some way to generate a unique key from each struct value though.
Something like this might work:
// Doesn't have to be a string: just has to be suitable for use as a map key.
func (foo *Foo) key() string {
    return key_string
}

fooSet := make(map[string] *Foo)

// Store a Foo
fooSet[x.key()] = x

// Check if x is in the set:
if fooSet[x.key()] != nil {
    println("x is in the set")
}

How well this works will depend on how efficient you can derive a key for your struct.

A: Are you sure your example works?
I believe you have to pass a pointer to the Add() method for your code to work. Anyways, here is my implementation:
package math

// types

type IntPoint struct {
    X, Y int
}

// set implementation for small number of items
type IntPointSet struct {
    slice []IntPoint
}

// functions

func (p1 IntPoint) Equals(p2 IntPoint) bool {
    return (p1.X == p2.X) && (p1.Y == p2.Y)
}

func (set *IntPointSet) Add(p IntPoint) {
    if ! set.Contains(p) {
        set.slice = append(set.slice, p)
    }
}

func (set IntPointSet) Contains(p IntPoint) bool {
  for _, v := range set.slice {
    if v.Equals(p) {
      return true
    }
  }
  return false
}

func (set IntPointSet) NumElements() int {
    return len(set.slice)
}

func NewIntPointSet() IntPointSet {
  return IntPointSet{(make([]IntPoint, 0, 10))}
}


text:
Q: Filters for potentiometer potentially causing issues with ADC I am sampling potentiometers on an Arduino Zero using the SAMD21 microcontroller.
Listed on the SAMD21 datasheet the ADC input is 3.5 kiloohms of impedance.
On my setup I am using a low pass filter by simply using a RC filter. The issue is if I used a smaller resistor with a larger capacitor I seem to get resistor loading with the potentiometer. The voltage divider isn't directly proportional to the potentiometer's position due to the loading effect (shown in picture 1.)
Using a a higher resistor value with a lower capacitor value fixes the loading affect. The correct voltage divider comes out of the potentiomter.
I am just concerned that the high resistance of the filter affects the analogue signal going into the ADC. Shown in picture 2 is the current setup. The 3.5k resistor represents the input impedance of the ADC in of the Arduino. In the second picture it shows only approxiamtely 50 mV  going into the ADC.
Would this scenario happen in a real world application or would the ADC input receive the 1.615 volts with no issue with a setup like the one in picture 2?
Picture 1
Voltage from wiper arm of potentiomter not having 50/50 voltage divider.

Picture 2
Voltage from wiper arm of the potentiomter has 50/50 voltage divider split but not getting that same voltage at ADC in.

A: You have misread the datasheet. The ADC input does not have input impedance of 3500 ohms to ground. Your simulation has 3500 ohms to ground so a series resistor of 100k will form a resistor divider network and thus explains your simulation having low voltages at the ADC input.
You can fix the simulation by just removing the 3500 ohm resistor.


text:
Q: Python path - handling home AND relative directory I'm trying to get the absolute path from a user input so there's no ambiguity within my script. I need to be able to handle both paths ~/Documents/repos/project and ./project.
Libraries like os.path and pathlib are able to resolve both cases - for example, in pathlib, expanduser resolves ~ and resolve() figures out relative paths, but neither can do both at the same time.
To elaborate, expanduser will strip relative paths of any periods, and resolve() will incorrectly resolve paths containing ~. This means that combining the two will leave me with an incorrect path.
I could simply replace ~ with Path.home(), and then resolve the path, but I'm wondering if there's a "more correct", or simpler way to achieve this.

A: You can use os.path.abspath and os.path.expanduser together:
/var/tmp $ python
>>> from os.path import abspath, expanduser
>>> abspath(expanduser("./bar"))
'/var/tmp/bar'
>>> abspath(expanduser("~/foo"))
'/home/my.username/foo'

The pathlib method:
>>> PosixPath('./bar').expanduser().resolve()
PosixPath('/var/tmp/bar')
>>> PosixPath('~/foo').expanduser().resolve()
PosixPath('/home/my.username/foo')


text:
Q: Cloud Run warning log: Container called exit(3) Cloud Run issued 'warning' log Container called exit(3) with no other errors messages neither from the CloudRun instance nor from the script that was calling the instance.
Metrics show normal CPU and memory utilization. No such logs reported before and there are a few container instances are active simultaneously. I assume only one of those issued the warning.
Is it something I need to dig into or is it something that may happen from time to time?


text:
Q: is a direct sum of Hilbert spaces a Hilbert space.? I have read in proofwiki that a direct sum of Hilbert spaces is a Hilbert space. However, Wikipedia Page about direct sum says it is not necessarily true, that is, the direct sum of Hilbert spaces is not always a complete space. Which of them is right? In what Conditions the direct sum of Hilbert spaces is a Hilbert space?

A: The answer is not in general, in fact you need to add some conditions, please see this proof 1, I think it can be of help.


text:
Q: PrimeReact Select Item is empty after loading data from API My Functional component is as follows:
const Scratch = () => {

 const [isLoaded, setIsLoaded] = useState(false);
 const colorSelectItems=[];
 const [selectedColor, setSelectedColor] = useState("fffff");

 useEffect(() => {
    fetch(
           `http://localhost:8765/fetchData?userId=1`
         )
      .then((response) => response.json())
      .then((data) => {
       createDropDown(data));
       setIsLoaded(true);
      });
  }, []);

 const createDropDown= (data) => {
    data.map((color) => {
      colorSelectItems.push({
        label: color.colorName,
        value: color.hexValue,
      });
    });

 return (

         {!isLoaded&&
Loading..
}
         {isLoaded&& (
           <Dropdown
            value={selectedColor}
            optionLabel="label"
            options={colorSelectItems}
            onChange={(e) => setSelectedColor(e.target.value);}
           />
          )}

  );
};

export default Scratch;

The problem is, it is displaying Loading... until the API call is complete, and it is rendering DropDown after that. But even after the completion of API call, the DropDown is still empty!
What am I missing here?
PS: This DropDown works perfectly if I replace fetching data from API to fetching data from local json file

A: Try this .In case any problem plz reply
const Scratch = () => {

 const [isLoaded, setIsLoaded] = useState(false);
 const colorSelectItems=[];
 const [selectedColor, setSelectedColor] = useState("fffff");

 useEffect(() => {
    fetch(
           `http://localhost:8765/fetchData?userId=1`
         )
      .then((response) => response.json())
      .then((data) => {
       var temp=data?.map((item)=>({label: item?.colorName,
        value: item?.hexValue }));
       colorSelectItems=temp;
       setIsLoaded(true);
      });
  }, []);

 return (

         {!isLoaded&&
Loading..
}
         {isLoaded&& (
           <Dropdown
            value={selectedColor}
            optionLabel="label"
            options={colorSelectItems}
            onChange={(e) => setSelectedColor(e.target.value);}
           />
          )}

  );
};

export default Scratch;


text:
Q: Pass multiple params to a tailwind plugin I have written this plugin to create a style of a border gradient element:
    plugin(function ({matchUtilities, theme, }) {
      matchUtilities(
        {
          'border-gradient-primary': (background) => ({
            'border': '1px solid transparent',
            'background-image': `linear-gradient(to right, ${background}, ${background}),linear-gradient(94deg, rgba(149, 78, 245, 0.6) 0.69%, rgba(166, 118, 171, 0.6) 100%)`,
            'background-clip': 'padding-box, border-box',
            'background-origin': 'padding-box, border-box'
          }),
        },
        {
          values: Object.assign(
            theme('borderGradBg1', {}),
            {
              'bg-gray-scale-500': myTheme["gray-scale"]["500"],
              'bg-primary-scale-600': myTheme["primary-scale"]["600"],
              'bg-primary-scale-800': myTheme["primary-scale"]["800"],
            }
          )
        }
      )
    })

the background-image css attribute set the border to be a gradient and it accepts the background of the element as a value.
I want to extend this plugin so the background itself can also be a gradient, so I can do:
linear-gradient(to right, ${background1}, ${background2}),linear-gradient(94deg, rgba(149, 78, 245, 0.6) 0.69%, rgba(166, 118, 171, 0.6) 100%)


text:
Q: With react-native-router-flux, how can I have a tab bar click specify which tab to switch to? I have a tab bar, with a user profile tab. I want it to redirect to signup if a user is not logged in, but if they are logged in, to go to to the userProfile tab.
here's the code:
         <Tabs
           key="tabbar"
         >
           {/* Main Screen */}
           <Scene
             key="main"
             component={MainScreen}
             title="Main"
             tab
           />
           {/* User Profile */}
           <Scene
             key="profile"
             component={ProfileScreen}
             title="Profile"
             tab
             type="reset"
             tabBarOnPress={() => {
               if (this.props.userIsLoggedIn) {
                 // how to show the correct tab. tried this didn't
                 // work:
                 // return NavigationActions.tabbar({routes: 1});
               }
               return NavigationActions.loginSignup();
             }}
           />
         </Tabs>

I have it so that if user is NOT logged in, it indeed navigates to the correct screen to sign up, but I do not know how to make it show the tab if the user is logged in.
EDIT: * we have tried doing
onEnter={() => {
  if (!this.props.userIsLoggedIn) {
    NavigationActions.loginSignup();
  }
});

however we very briefly see the profile screen, would ideally go directly to signup, without showing any of the profile screen.

A: Great question, not much documentation for this function, here is the answer.
({ scene, jumpToIndex }) => { jumpToIndex(scene.index); }

A: Nikolai Answer is old.
You can follow below answer.
tabBarOnPress={(props) => {
  const routeName = props.navigation.state.key;
  props.navigation.navigate(routeName)
}}


text:
Q: Laptop turns off randomly Tonight I started having problems, meaning that my laptop started turning off instantly. I guess it is from overheating. It was happening when I tried playing some heavy game, but now it started doing it even before the OS has loaded. I opened it (thinking that it is the thermal paste). I was right - the last time (about 6 months ago) when I changed it, I apparently missed a little end of one corner on the plate of the GPU. Even the plate, that connects to the cooling way, started getting black-ish.
So I changed the thermal paste and it was fine. Though, I couldn't hear the fan working. Putting a napkin next to the exit of the fan proved it's working, so I thought "ooh, there is such good thermal conductivity that the fan doesn't even have to turn on higher speed..." Even when I turned on a game (which was strange).
5 min. later, while I was just browsing around, the laptop shut down again. Now I am writing from an open machine, looking at the fan rotating...
I don't know if it is gonna turn off again, but the laptop is quite hot from bellow and I have no idea why is that happening. And why doesn't the fan turn on higher rate? It seems to work on only 1 frequency (as if just to show that it's working)?! The CPU is not over-heating. The GPU makes the problem here...
UPDATE: After I changed the thermal paste and turned on the machine again, it went into Windows recovery mode. I was like "okey, sure...", but it froze and I was forced to restart. After this, the fan started failing. My guess is that not finishing the process of recovery mode broke the driver or some other part of the firmware, which is connected to the fan, or smth like that. Re-installing the drivers for the video card and updating the BIOS did not help...
P.S. the laptop is HP probook 4520s

A: First thing is to go to support.hp.com and get the latest drivers for your video card, bios and chipset.  If that still shuts off randomly after install, I would go to the manufacturers website (intel, NVidia etc..) and download the driver from there.  Make sure this isn't on your lap, you could be constricting air flow.
Lastly the daily operation.  You could turn off as many of the graphical effects in windows as possible (aero, desktop themes, etc..) till Hp or Microsoft, or the manufacturer of the component fixes the problem.  But if you are going to do that then please give them a call if it's under warranty.   They can't fix what they don't know about.


text:
Q: greene and krantz, function of one complex variable, Theorem 3.1.3 Why is it that
$$
f(z)=\frac{1}{2\pi i}\oint_{\partial D(0,1)}\frac{\overline\zeta}{\zeta-z}d\zeta=0,\forall z\in D(0,1) ?
$$

A: We may parametrize the circle as $t\mapsto e^{it}$, $0<t<2\pi$, then
$$f(z)=\frac{1}{2\pi i}\int_0^{2\pi}\frac{e^{-it}}{e^{it}-z}ie^{it}dt=\frac{1}{2\pi }\int_0^{2\pi}\frac{1}{e^{it}-z}dt =\frac{1}{2\pi }\int_0^{2\pi}\sum_{n\geq0} z^ne^{-(n+1)it}dt=0$$
since $|z|<1$ (which by the M-test ensures that the last sum converges uniformly, and we may switch the order of integration and summation).

A: Here is a different approach, circumventing the use of infinite series. We know that
$$\frac{\zeta^*}{\zeta-z} = \frac{\zeta\zeta^*}{\zeta(\zeta-z)} = \frac{1}{\zeta(\zeta-z)}$$
for $\zeta \in \partial D(0,1)$. If $z = 0$, we have $z^{-2}$ and when we integrate via A.D.'s parametrization, we immediately obtain 0. Otherwise, by partial fractions we have
$$\frac{1}{\zeta(\zeta-z)} = \frac{1}{z (\zeta -z)}-\frac{1}{\zeta  z}$$
And the integral becomes
$$\frac{1}{2\pi iz}\int_{\partial D}\frac{1}{\zeta -z}d\zeta - \frac{1}{2\pi iz}\int_{\partial D}\frac{1}{\zeta}d \zeta$$
Each of these integrals gives you $2\pi i$ and after subtracting, we have 0.


text:
Q: Ubuntu: Edit environment variables via command line How can you edit the environment variables via command line in ubuntu?

A: You can set environment variables from the command line, but the new values will apply only to that terminal session and any processes launched from it. Environment variables are handled differently in Unix than they are in Windows. When a Unix process is created, it inherits an environment from its parent process that includes environment variables.  Changes to a process's environment affect that process and its children, but not any other processes.
With that caveat, you can set an environment variable in a Bourne-like shell such as bash like this:
export MYVAR=myvalue

A: Edit /etc/environment. When you log out and log back in, the new values will be present.

A: If you want to modify/set environment variable(s) for your current shell session, which will last until you close/exit it, then
export MYVAR=value

If you want to modify/set environment variable(s) to be present every time you run your shell, then you should modify your shell's config file to include the above line.
To find out what shell you're running, type:
# echo $SHELL

Then edit the appropriate configuration file:

*

*For sh you would modify ~/.profile

*For bash you would modify ~/.bashrc

*For zsh you would modify ~/.zshrc or ~/.zshenv
Where the ~ character in each case represents the path to your home directory. If editing on the command line, you can just use it directly, e.g. to open the file in the vim editor:
# vim ~/.profile

If you're using a GUI-based editor you should just navigate to your home directory to find the appropriate config file.

A: To set TEST to XYZ, use this format:
TEST=XYZ; export TEST

A: I also found it useful to install nano and edit the text of the environment file which in my case was found in the /etc folder.
sudo apt-get install nano
sudo nano filename

A: Adding to the @drfrogsplat answer.
Once you have made the change in either ~./profile or ~./bashrc. It's necessary to use the following command to reflect the changes.
$ source ~./bashrc


text:
Q: Could someone please tell me why algebra of limit incorrectly used here For a sequence ($a_n$) $=$ $(n!)^{1/n}$, how can I show this tend to infinity?
My attempt was that write $(n!)^{1/n}$ = $(n\times...2\times1)^{1/n}$ = $n^{1/n} \times...\times 1^{1/n}$ and since each term has limit 1 then the limit of the sequence is 1 by AOL? Where did I go wrong?

A: Look at this argument that "proves" that $1=0$. Write
$$1=\frac1n+\frac1n+\cdots+\frac1n\qquad(n\text{ times})$$
Now since $1/n\to0$ as $n\to\infty$, it follows that
$$1=\lim_{n\to\infty}1=0+\cdots+0=0.$$
Your situation is analogous. Notice that the number of terms in the sum (or product in your case) depends on $n$.


text:
Q: How to separate string output? I have a query which output a a column name member_name
select
LEFT(member_name, charindex('/', member_name) - 1) + ' '
+ SUBSTRING(member_name, charindex('/', member_name) + 1, 1) as member_name

from member

It output the string with the last name and first letter of first name.
How can I output in the table with the first letter and last name in different columns?
For example to have it output something like this:
first | last name
-----------------
J     | DOE

B     | DOE-DOE

Z     | SMITH

I made a http://sqlfiddle.com/#!6/c7a74/7

A: select
   substring(member_name, charindex('/', member_name) + 1, 1) as first_initial,
   left(member_name, charindex('/', member_name) - 1) as last_name
from
   member

A: I don't have the reputation to reply to comments just yet, but as you asked in a comment in the answer, It can be done in cold fusion, but I'd think SQL is your better choice.
<cfoutput query="get_names">
  <cfset l_name = listfirst(member_name,"/")>
  <cfset f_initial = left(listlast(member_name,"/"),1)>

  <cfset f_initial = ucase(left(listlast(member_name,"/"),1))>

  First initial: #f_initial#, Last name: #l_name#

</cfoutput>

That would output, based on your fiddle:
First initial: J, Last Name: suarez
First initial: J, Last Name: suarez
First initial: S, Last Name: mejia
First initial: D, Last Name: orozco

It's a good exercise to help understand how cf works, and more importantly that there is an overlap between what your queries can do for you and what your code can but once again I recommend the sql solution.

A: Although I believe the best way to handle this situation is the SQL modification in my other answer, here's a way to do it in CF only, based on your fiddle's data layout.
<cfquery name="getMembers">
   select member_name from member
</cfquery>

First	Last Name

   <cfoutput>
      <cfloop query="getMembers">
         <cfset aMember = ListToArray(member_name, "/")>

#left(aMember[2],1)#	#aMember[1]#

      </cfloop>
   </cfoutput>


text:
Q: Joining same table multiple times is throwing error I have the following mysql code
SELECT * FROM `user_credentials`
  JOIN `friends` ON `friends`.`1stpal` = `user_credentials`.`cred_regiden`
  JOIN `friends` ON `friends`.`2ndpal` = `user_credentials`.`cred_regiden`
WHERE (`cred_fname` LIKE'".$search_text. "%') AND (`friends`.`1stpal` = '$current_user'
  OR `friends`.`2ndpal` = '$current_user')  LIMIT 0, 5;

I'm trying to join the table 'friends' two times and this throws error: Not unique table/alias: 'friends'. When I change the script to following,
SELECT * FROM `user_credentials`
  JOIN `friends` AS `f1` ON `friends`.`1stpal` = `user_credentials`.`cred_regiden`
  JOIN `friends` AS `f2` ON `friends`.`2ndpal` = `user_credentials`.`cred_regiden`
WHERE (`cred_fname` LIKE'".$search_text. "%') AND (`friends`.`1stpal` = '$current_user'
  OR `friends`.`2ndpal` = '$current_user')  LIMIT 0, 5;

It now says: Unknown column 'friends.1stpal'.
When I run the single join, it works perfectly. But that is not I want, I want results from both the table.

A: On the second example you still use table friends but you should use either f1 or f2 instead.

A: Since you named it the tables with alias f1 and f2, you should use them in the query:
... ON `f1`.`1stpal` ...

A: You need to use table aliases (abbreviations) when joining to the same table more than once.  They need to be used throughout the query to disambiguate the columns:
SELECT *
FROM `user_credentials` uc JOIN
     `friends` `f1`
     ON f1.`1stpal` = uc.`cred_regiden` JOIN
     `friends` `f2`
     ON f2.`2ndpal` = uc.`cred_regiden`
WHERE (uc.`cred_fname` LIKE'".$search_text. "%') AND
      '$current_user' in (f1.`2ndpal`, f2.`1stpal`)
LIMIT 0, 5;

Note:  I am guessing as to the second condition in the where clause.  It could be:
 '$current_user' in (f2.`2ndpal`, f1.1stpal`)

Some more comments:

*

*If you use table aliases, you might as well use them for all tables for readability.

*Don't use backticks around column names that don't need them.  They just clutter the query.

*Using limit without an order by could be dangerous.  The rows returned will match but could change from query to query.

*in is easier to write and understand than long sequences of or expressions (or even short sequences).


text:
Q: Adding new section in control panel of Liferay I want to add a new section in control panel of liferay and within that section I want to have my custom-portlet. I did it using ext. However I want to do it with hook . Is it possible ?

A: I don't think it would be that easy with a hook, because of the following reasons:

*

*You can't modify in a Hook - the class com.liferay.portal.util.PortletCategoryKeys which contains the keys for displaying the different sections. The different sections are hard-coded in this class in a String array ALL.

*You can't modify the logic of PortalImpl#isControlPanelPortlet() which uses the PortletCategoryKeys#ALL to determine if the request in question is for a control panel portlet.

*Then you also have another method which you can't modify with a Hook and is used extensively PortalImpl#getControlPanelCategory()
Doing it with a hook:
I have not tried this but I think if you need to do it with a hook you would have to change all those JSPs which make use of PortletCategoryKeys#ALL and the methods of PortalImpl as stated above, and provide your custom implementation for all these methods in the JSP.
I would really like to know how you implemented it with an EXT may be just the steps or the methods you have overridden. So that I can try to convert those in terms of a hook.
This is as far as my understanding goes. Hope this helps.

A: With the advent of Marketplace, ControlPanel has a new category named "Marketplace" and that section is introduced in a plugin. However, I never checked if 6.1 GA2 introduced a new section that this plugin just fills. Check the marketplace plugin if you can find a trace of this section implemented there.
On the other hand, nobody has yet named any section that definitely required a new section (though some have asked me how to solve the same problem). For this reason, you might want to re-think the requirement and choose one of the existing sections. If you don't, at least I'd be interested in the name and purpose of the new section - I might find a first one actually justifying this kind of implementation...


text:
Q: Why call the default destructor of an object before freeing the memory allocated to that object? I seen some code do the following:
ExampleObject< T > * eo = const_cast< ExampleObject< T > * >(this);
eo->~ExampleObject();
free( eo );

The ExampleObject in question has been allocated using placement new.
There is no user-defined destructor supplied, so it's the compiler supplied default destructor being used here, I think.
I don't understand why it is necessary to call the destructor here. If we had a user-defined destructor that de-allocated memory for some of it's class members I could understand the usage here, but in the case of a default destructor I don't know why we'd do this.
What does the default destructor of an object do, that would require us to call it before freeing the allocated memory for the object?

A:
What does the default destructor of an object do

It calls the destructors, if any, for the object's data members.

that would require us to call it before freeing the allocated memory for the object?

The ONLY time a destructor should ever be called explicitly is when the object has been constructed using placement-new inside a pre-existing memory block.  Using placement-new separates the tasks of object construction/destruction from memory allocation/deallocation, so you need to construct and destruct an object explicitly, but you don't have to allocate/deallocate its memory block, you can manage that however you want elsewhere.
If you do not use placement-new to construct the object, but rather allocate + construct the object using new instead, then you must destruct + deallocate the object using delete (and you should preferably use a smart pointer, std:unique_ptr or std::shared_ptr, to handle that for you).
If you do not construct the object using any form of new, then DO NOT try to destruct the object manually at all.  The object is in automatic storage and the compiler will manage it for you.

A: The C allocation functions know nothing about C++ objects.  Unlike new and delete that allocate the memory needed and call the constructor/destructor, all The C functions do is allocate/deallocate a suitably sized amount of memory that you can use.
So when you use the C functions, you have to call the allocation function to get the memory, call placement new on it to actually construct the object in the memory (this is required to actually have an object of that type).  Then, when you are done with it you need to destroy the object by manually calling the destructor (you need to do this so the objects lifetime properly ends) and then pass the pointer to free so the memory can be released.
This is why you should not be using *alloc and free in C++.  They require a lot of extra work and are not type safe.

A: A default destructor function is called automatically when the object goes out of scope:

*

*The function ends

*The program ends

*A block containing local variables ends

*A delete operator is called

Default destructor always invokes the destructors of its member objects (not for member variables that are pointers to objects). If we allocate memory dynamically it should be handled by us, otherwise default destructor clears the local variables.
If we do not write our own destructor in class, the compiler creates a default destructor for us. The default destructor works fine unless we have dynamically allocated memory or pointer in class.
When a class contains a pointer to memory allocated in class, we should write a destructor to release memory before the class instance is destroyed. This must be done to avoid memory leak.


text:
Q: How can $|x|= -x$, when $x<0$? Why is the following true?
$$
|x|=
\begin{cases}
x,&x\ge 0\\
-x,&x<0
\end{cases}
$$
Isn't the modulus of a number always positive? According to the above formula $|-4|=-4$ because $4<0$, which is incorrect.
Please explain this to me. Thank you.

A: According to the above formula, $|-4| = -(-4)$, which is perfectly fine.

A: You may prefer $|x|:=\sqrt{x^2}$, hence $|-4|=\sqrt{16}=4$.

A: According to your sentence : "Isn`t the modulus of a number always positive? According to the above formula |-4|=-4 because 4<0, which is incorrect." . You have said , "4<0" ? Is it right ? infact -4 < 0 . Infact , $ |-4| = -(-4) $ which is perfectly fine.

A: No, the formula says that $|-4|=-(-4)=4$. The $x$ in this case is $-4$, and $-(-4)=4$, not $-4$. When you get the value $-4$, you're not applying the definition correctly: you're taking the negative of $4$, not of $-4$, but the number inside the absolute value is not $4$.

A: $\vert x\rvert\ge0$ for any $x \in \mathbb{R}$. The piecewise-defined function for $\lvert x\rvert$ is
$$
\vert x\rvert=
\begin{cases}
x& x>0\\
0& x=0\\
-x& x<0
\end{cases}
$$
We read it literally as
$$
\vert x\rvert=
\begin{cases}
x& \text{if $x$ is a positive real number}\\
0& x=0\\
-x& \text{if $x$ is a negative real number}
\end{cases}
$$
If $x$ is a negative real number then $-x$ is a positive real number. I think it is obvious!

A: The prefix unary operand - changes the sign of its operand.  So a negative number's sign is changed to positive by this operation.


text:
Q: What is the command line statement for changing the System clock? Is there such command for changing the System clock's date and time?
For example:
The current date and time is January 1, 1970 22:30:59:980 where 59 and 980 refers to the seconds and millisecods respectively
And I want to change it to January 2, 1971 23:31:59:990
Is there a command for this?

A: To set the time in Ubuntu from the terminal, you can use the following command:
sudo date new_date_time_string
where new_date_time_string has to follow the format MMDDhhmmyyyy.ss which is described below:

*

*MM is a two digit month, between 01 to 12

*DD is a two digit day, between 01 and 31, with the regular rules for days according to month and year applying

*hh is two digit hour, using the 24-hour period so it is between 00 and 23

*mm is two digit minute, between 00 and 59

*yyyy is the year; it can be two digit or four digit

*ss is two digit seconds. Notice the period . before the ss.

Source: Manage Time in Ubuntu Through Command Line.
So, in your particular case, you can use:
sudo date 010224311971.59

Or, you can use:
sudo date --set="1971-01-02 23:31:59.990"  && date --rfc-3339=ns

which is exactly what you asked.
Source:

*

*How do I set current Unix time in milliseconds?

A: You can use the date command to change the time and you'll need sudo permission to do it; an example to set the date to 27 June 2014 and the time to 1:17 AM is:
sudo date --set "27 Jun 2014 1:17:00"

A: Since systemd was introducted in Ubuntu, the correct way is:
# timedatectl set-time "RFC 3339-compliant string"

e.g.
# timedatectl set-time "2002-10-02T10:00:00-05:00"
# timedatectl set-time "10:35"
# timedatectl set-time "+2 hours"

A: The easy way:
ntpdate -s ntp.ubuntu.com

To change the timezone:
dpkg-reconfigure tzdata

Probably you need sudo.

A: Short versions for setting date or time only:
To set the date (will set the time to 0:0:0):
date +%Y%m%d -s "19710102"

To set the time only:
date +%T -s "23:31:59"

You could add the desired ".990" to the seconds.
Read the man page for more options and formats regarding the date command:
man date

Note: you may also want to check or set the hardware clock. Read about it here.

A: sudo date --set="Mon Feb 16 08:49:56 IST 2015"

That would be correct statement in UBUNTU 14.04.


text:
Q: Re-issue SysTick interrupt I have a SysTick interrupt to trigger task switch 4 times per second, as shown below.
void SysTick_Handler(void) {
  SCB->ICSR |= SCB_ICSR_PENDSVSET_Msk; // Set PendSV
}

The tasks in the main are occasionally outputting some messages via one of the UART, and to ensure that they have exclusive I/O access, the output routines are protected with a mutex that is set with LDREX and STREX.  Code works perfectly well over 90% of the time.
However, one side effect of that protection appears to be that when SysTick happens during the period when the mutex is set, the task switch will not happen, and the task that was running at that time will continue to run until the next task switch.
Is there a way to trigger SysTick again, say, 10 ms later, and do that until the mutex is cleared by the currently running task?   For example:
void SysTick_Handler(void) {
  if (mutex) {
    // set SysTick to trigger again in 10 ms
  } else {
    SCB->ICSR |= SCB_ICSR_PENDSVSET_Msk; // Set PendSV
  }
}

If yes, how.
TIA

A: Set the SysTick, PendSV, SVCall or some other interrupt pending in your mutex release function.
If you want to avoid the cost of an unnecessary interrupt you can set an atomic flag in the systick handler and check it in the mutex release function so that you only trigger the interrupt if you missed your scheduled run.

A: I implemented a solution as per Tom V's suggestion, and it works like a charm!!   Thanks!!
The crucial portions:
void SysTick_Handler(void)
{
    if (mutex > 0) {
        sigint++;
    } else {
        sigint = 0;
        SCB->ICSR |= SCB_ICSR_PENDSVSET_Msk; // Set PendSV to pending
    }
}

and:
// in mutex release
if (sigint) {
    __asm(" CPSID i");
    sigint = 0;
    (*systick_ptr)();
    __asm(" CPSIE i");
}

However, be aware that this solution does have at least one 'feature': if this code misses more than 1 interrupt it will make up only one, but missing more than one interrupt is exceedingly unlikely in my case.


text:
Q: Laravel (OOP), model specfic array of values (for example titles of users) I have model User and inside there is a field named title.
Now I want to define all possible titles. For example an array of
['0' => 'Mr.', '1' => 'Ms.']
What is the correct way to define these.
My idea is to create the public function titles() { return ['0' => 'Mr.', '1' => 'Ms.']; inside the User.php model and call for the array as $user->titles() whenever I need it. However this makes me twitch a bit because I'm calling the function on the model instance.
I really don't think creating a relation here is needed as there aren't more than ten possible titles.
Is there a better/right way to do these kind of things. I'm not that new to Laravel but I'm self thought so I'm trying to check my ways of doing stuff here.
I need to get into these oop basics a bit so any pointers here are helpfull.
Thanks in advance.

A: If you want dynamic select box write this code
$titles = User::lists('title', 'id'); // controller

{!! Form::select('title', $titles, null, ['class' => 'form-control']) !!}  // view

A: One way to do this is to keep titles in config file, like:
'titles' => [
    1 => 'Mr.',
    2 => 'Mrs.'
    ....
],

Benefits are:

*

*you can edit this info at any time (keeping data hardcoded into model class is a bad practice)

*you can use this list as is for select list building

*you can keep data as TINYINT by keeping title IDs, sometimes it's a benefit

To build select list, do something like this:
{!! Form::select('titles', config('custom_config.titles'), 1) !!}

A: You can use config files as @Alexey Mezenin suggested, but in this cases I prefer to use the database to store that kind of options (I mean in a different table, not in same users table), so I can add or delete options without touching the code and use the same form template/partial across different pages or projects if needed.
If you just need to retrieve the array it would be as easy as make a query in your controller and return it, but if you need it for form options I suggest you to use something like a form builder helper in which you get the form options from database and build your form using laravelcollective package, then you can pass the helper object to your view to show your fields and show whatever info you need.


text:
Q: Angular 2.0 Routing Issue In my main.ts the code is like this.
import {provide, enableProdMode} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
import {ROUTER_PROVIDERS} from 'angular2/router';
import {HTTP_PROVIDERS} from 'angular2/http';
import {APP_BASE_HREF} from 'angular2/platform/common';
import {AppComponent} from './app/components/app.component';

enableProdMode();

bootstrap(AppComponent, [
  ROUTER_PROVIDERS, HTTP_PROVIDERS,
  provide(APP_BASE_HREF, { useValue: '<%= APP_BASE %>' })
]);

In my app.component.ts file I have the follwing code.
import {Component} from 'angular2/core';
import {enableProdMode} from 'angular2/core';
import {Router, ROUTER_DIRECTIVES, ROUTER_PROVIDERS, RouteConfig, RouteParams} from 'angular2/router';
import {SportsLiveFeedService} from '../shared/index';
import {MainComponent} from '../main/index';
import {ResultsComponent} from '../results/index';

@Component({
  selector: 'sd-app',
  viewProviders: [SportsLiveFeedService],
  templateUrl: 'app/components/app.component.html',
  styleUrls: ['css/bootstrap.min.css', 'css/main.css'],
  directives: [ROUTER_DIRECTIVES]
})
@RouteConfig([
  {
    path: '/',
    name: 'Main',
    component: MainComponent
  },
  {
    path: '/results/:id',
    name: 'Results',
    component: ResultsComponent
  }
])
export class AppComponent {
  constructor(private router: Router) {}
}

And in the ResultsComponent my code is like this.
import {Component} from 'angular2/core';
import {Inject} from 'angular2/di';
import {CORE_DIRECTIVES, FORM_DIRECTIVES} from 'angular2/common';
import {SportsLiveFeedService} from '../../shared/index';

@Component({
  selector: 'sd-about',
  templateUrl: 'app/results/components/results.component.html',
  styleUrls: ['css/bootstrap.min.css', 'css/main.css'],
  directives: [FORM_DIRECTIVES, CORE_DIRECTIVES],
  providers: [SportsLiveFeedService]
})

export class ResultsComponent implements OnInit {

  eventsDetails: [];

  constructor(private _sportsLiveFeedService: SportsLiveFeedService){
    this._sportsLiveFeedService = _sportsLiveFeedService;
  }

  ngOnInit(){
      this._sportsLiveFeedService
        .getEachEventInDetailByMeetingId()
        .subscribe(p => this.eventsDetails = p)
    }

}

The issue is when I first screen is loading just fine. But when I navigate to http://localhost:5555/results/121212 like this, The second screen UI is not showing. Please help me to fix this issue. I am new to Angular 2.0


text:
Q: ExtJs 4.1.1 Tree Panel node selection logic I am using tree panel is ExtJS.

Consider the above image as the tree panel. If user selects node 1.1.1.2, I should check if all its sibling are also checked/selected, if yes, system should select 1.1.1 node and deselect 1.1.1.1, 1.1.1.2, 1.1.1.3 nodes.
Similarly, At this point I should check the siblings of 1.1.1 node (1.1.2 & 1.1.3) & if they previously selected/checked, then I should deselect 1.1.1, 1.1.2, 1.1.3 and I should select 1.1 node.
This kind of check continues until I reach root node or one the siblings of selected node is not checked/selected.
What is the best way to achieve this. When I say best way, I am looking for some in-build property or method which will help me achieve this.
Thank you

A: I would start with the bubble method:
http://docs.sencha.com/extjs/4.1.1/#!/api/Ext.data.NodeInterface-method-bubble


text:
Q: Error while playing captured Video using OpenCV + Python I'm using Opencv 3.2 + Python on Ubuntu 16.04 LTS OS. I'm trying to undistort the fisheye video which is collected from web cam.
Below is my code where I'm undistorting the fisheye video by undistorting frame by frame. The program is executing fine and its undistorting fisheye video correctly but when I try to play the stored undistorted video (undistortedop.avi) it gives a error message saying "Could not demultiplex stream".
Could anyone please help me to solve this problem?

import cv2

import numpy as np

import os

import glob

import sys

assert float(cv2.__version__.rsplit('.', 1)[0]) >= 3, 'OpenCV version 3 or newer required.'

DIM=(1280, 720)

K=np.array([[517.7167401534203, 0.0, 641.312338873659], [0.0, 518.0410707880329, 361.1273127787553], [0.0, 0.0, 1.0]])

D=np.array([[-0.00428080929837007], [-0.14786471866085527], [0.07941291495275071], [-0.025649243686649097]])

balance=0.95

dim2=None

dim3=None

cap = cv2.VideoCapture(0)

# Define the codec and create VideoWriter object

fourcc = cv2.VideoWriter_fourcc(*'DIVX')

out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))

out1 = cv2.VideoWriter('undistortedop.avi',fourcc, 20.0, (640,480))

while True:

   ret, frame = cap.read()

   gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

   # img = cv2.imread(img_path)

   # dim1 = img.shape[:2][::-1]  #dim1 is the dimension of input image to un-distort

   dim1=(1280, 720)

   assert dim1[0]/dim1[1] == DIM[0]/DIM[1], "Image to undistort needs to have same aspect ratio as the ones used in calibration"

   if not dim2:

       dim2 = dim1

   if not dim3:

       dim3 = dim1

   dim3=(630, 480)

   scaled_K = K * dim1[0] / DIM[0]  # The values of K is to scale with image dimension.

   scaled_K[2][2] = 1.0  # Except that K[2][2] is always 1.0

   # This is how scaled_K, dim2 and balance are used to determine the final K used to un-distort image. OpenCV document failed to make this clear!

   new_K = cv2.fisheye.estimateNewCameraMatrixForUndistortRectify(scaled_K, D, dim2, np.eye(3), balance=balance)

   map1, map2 = cv2.fisheye.initUndistortRectifyMap(scaled_K, D, np.eye(3), new_K, dim3, cv2.CV_16SC2)

   undistorted_img = cv2.remap(frame, map1, map2, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT)

   # cv2.imwrite('Testpic3_undistorted.jpg', undistorted_img)

   out1.write(undistorted_img)

   cv2.imshow("undistorted", undistorted_img)

   # Write the frame

   out.write(frame)

   cv2.imshow('frame',frame)

   # cv2.imshow('gray', gray)

   if cv2.waitKey(1) & 0xFF == ord('q'):

       break

cap.release()

out.release()

out1.release()

cv2.destroyAllWindows()

A: This error might occurs due to mismatched frame size in the VideoWriter.
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))


text:
Q: require_once won't read variables from third script I'm working on some web application, learning PHP OOP. I have 3 scripts: index.php, database.php and config.php.
In config.php are the constants for accessing the DB.
In the database.php is a class for opening and closing the connection to the DB and so on. This file includes the config.php file.
Now on the index file I include the database.php file and I'm testing if $database exists. The files database.php and config.php are in different folder than the index.php.
When I run the index.php file it says: Use of undefined constant DB_SERVER - assumed 'DB_SERVER'
Everything works fine if they are in the same folder. It also works if I include the config.php file separately in the index file, but it won't work if only the database file is included
config.php
<?php constants ?>

database.php
<?php
require_once("config.php");
...

?>

index.php
<?php
require_once("../includes/database.php");
...
?>

Why won't the index.php file recognize the variables from config.php?

A: I believe the problem lies with the directories. When you include the ../includes/database.php file, all paths defined in that file become relative to IT! This means that instead of looking for the configuration file in the directory that index.php is in (lets say /var/www/html/funfile/index.php), it's now looking for it in /var/www/html/includes/ (so the literal path of the include would be /var/www/html/includes/config.php). It's a pretty easy fix, just make the path to the config file literal.
Try:
require_once("/var/www/html/funfile/config.php");

And replace the path I made up, with the actual path to the config file. That should solve your problem.

A: Its probably some problem with the include path. Even though database.php and config.php are in the same folder, its index.php that is making the calls and therefore the include path is the index.php folder. When database.php attempts to include config.php it will be looking for it there.
There are a couple ways you can solve this:

*

*Make index.php call all the includes, including the database.php dependencies;

*Make database.php aware that its path relative to the site root is ../includes and it too will refer to config.php as ../includes/config.php even though its right there in the same folder with it (not recommended specially if you need database.php in subfolders of your site);

*Use set_include_path(). Example:
index.php:
set_include_path('../includes');
require_once 'database.php';

A: You should give DB_SERVER in quotes like this:
define('DB_SERVER',$db_host);
define('DB_USER',$db_user);
define('DB_PASS',$db_pass);
define('DB_NAME',$db_name);


text:
Q: How to determine actual Signal-R message size I have a component library, one of its functionalyty is to pass large file from JS to c# code. I split the file into chunks, but I need to know what chunk size should be used.
Default message size is 32 kb, but user can change it in theirs app:
services.AddSignalR(o => {
   o.MaximumReceiveMessageSize = long.MaxValue;
});

How can I determine the message size in my library code?

A: On the Server, Inject IOptions<HubOptions> options into a service or controller.
var maximumReceiveMessageSize = options.Value.MaximumReceiveMessageSize;


text:
Q: Restrict height of the 'Watched Tags' sidebar widget (same as Ignored) I favourite/watch a lot of tags on Arqade, mainly due to the nature of tags on that site; every game has it's own tag.
I've noticed however, as I 'watch' more and more tags, that the widget on the sidebar is kinda getting a bit out of hand:

I've started using the wildcard character to combine tags and subsequently reduce it's height, but I can't deny it's just getting unwieldy. Can the Watched Tags widget have the same/similar sort of 'max height' added that the Ignored widget does, with a 'click to view more' or something? E.g.


text:
Q: Converting unix date-timestamp to time for a particular timezone in javascript I want to convert unix timestamp to time for a particular timezone.
say for example unix time stamp is - 1446960600
I want to convert this timestamp to America/Los Angeles ?

A: You can convert a unix timestamp integer into a Javascript date like this
var date = new Date(1446960600 * 1000);

Unix timestamps are in the UTC timezone, but there isn't an easy way to do timezone changes in Javascript.
I recommend you use a time library like momentjs. It handles edge cases like daylight savings that you would have to take into account if you do it yourself.
Here's some sample code from another answer:
function toTimeZone(time, zone) {
     var format = 'YYYY/MM/DD HH:mm:ss ZZ';
     return moment(time, format).tz(zone).format(format);
}

https://stackoverflow.com/a/18612568/1031569
You can use the getTimezoneOffset() method of a DateTime to calculate the timezone change, but understand this won't take into account daylights saving or leap year changes.

A: Use momentjs. You can choose your format  and you just set the country you need
http://momentjs.com/


text:
Q: Ant task to filter JARs for zip file and manifest I have an Ant file where I am creating a zip file and a manifest for several JAR files.  Both the zip and the manifest reference the same libraries, but in slightly different ways.  If possible I would like to combine the references to the files instead of explicitly writing them twice and hoping the references in both tasks sync up.  Below is an example of what I am currently doing.
<target name="zip" depends="default">
  <zip destfile="${dist.dir}/${project.name}_v${project.version}.zip">
    <zipfileset prefix="lib" dir="lib/Dom4J" includes="*.jar"/>
    <zipfileset prefix="lib" dir="lib/GSON" includes="*.jar"/>
    <zipfileset prefix="lib" dir="lib/Guava" includes="*.jar"/>
    <!-- ... A bunch more (Note I don't want everything
             in the lib directory, just certain subfolders
             within the lib directory which are explicitly
             listed here like GSON. -->
    </zip>
</target>

<target name="createManifest">
   <!-- Hard code the classpath by hand and hope
        they sync up with the zip task -->
   <property name="mfClasspath"
             value="dom4j-1.6.1.jar gson-2.1.jar guava-11.0.2.jar" />
   <!-- Code to use the mfClasspath when creating the manifest
        omitted for brevity -->
</target>

What I would ideally like to have is a fileset of some sort that I could reference in both tasks.  Note that the manifest does not contain any folders/paths.  The manifest only contains the JAR files found within the directories mentioned in the zip task.

A: You are right. You can accomplish this with a common fileset shared by both the zip and createManifest tasks. For the zip task, copy the files to a temporary location and then zip them up.
For the createManifest task, use character replacement to remove the folders from the paths. Character-replacement strategies are discussed in "Replacing characters in Ant property." If you have Ant-Contrib, you can simplify the character-replacement algorithm below by using the PropertyRegex Ant task.
<project default="all">
    <fileset id="jars" dir=".">
        <include name="lib/Dom4J/dom4j-1.6.1.jar" />
        <include name="lib/GSON/gson-2.1.jar" />
        <include name="lib/Guava/guava-11.0.2.jar" />
    </fileset>

    <target name="zip">
        <copy todir="tmp.dir" flatten="true">
            <fileset refid="jars" />
        </copy>
        <zip destfile="example.zip">
            <zipfileset dir="tmp.dir" prefix="lib" />
        </zip>
        <delete dir="tmp.dir" />
    </target>

    <target name="createManifest">
        <property name="jars.property" refid="jars" />
        <echo message="${jars.property}" file="some.tmp.file" />
        <loadfile property="mfClasspath" srcFile="some.tmp.file">
            <filterchain>
                <tokenfilter>
                    <replaceregex pattern="(?:[^;/]+/)+?([^;/]+\.jar)"
                        replace="\1" flags="g" />
                    <replacestring from=";" to=" " />
                </tokenfilter>
            </filterchain>
        </loadfile>
        <delete file="some.tmp.file" />
    </target>

    <target name="all" depends="zip, createManifest">
        <echo message="$${jars.property} = "${jars.property}"" />
        <echo message="$${mfClasspath} = "${mfClasspath}"" />
    </target>
</project>

When I executed the above Ant buildfile, the following was output to the console:
Buildfile: /workspace/StackOverflow/build.xml
zip:
      [zip] Building zip: /workspace/StackOverflow/example.zip
   [delete] Deleting directory /workspace/StackOverflow/tmp.dir
createManifest:
   [delete] Deleting: /workspace/StackOverflow/some.tmp.file
all:
     [echo] ${jars.property} = "lib/Dom4J/dom4j-1.6.1.jar;lib/GSON/gson-2.1.jar;lib/Guava/guava-11.0.2.jar"
     [echo] ${mfClasspath} = "dom4j-1.6.1.jar gson-2.1.jar guava-11.0.2.jar"
BUILD SUCCESSFUL
Total time: 675 milliseconds

Also, example.zip contained the following entries:

*

*lib/dom4j-1.6.1.jar

*lib/gson-2.1.jar

*lib/guava-11.0.2.jar


text:
Q: C++ protected function not visible from derived class I'm trying to call initCapture() that's declared pure virtual in LexContext. I'm trying to call it indirectly in ArduinoLexContext by way of StaticLexContext which overrides it.
I get
LexContext.hpp:316:25: error: there are no arguments to 'initCapture' that depend on a template parameter, so a declaration of 'initCapture' must be available [-fpermissive]

Here's the code. I've omitted most of LexContext since it isn't relevant here. I've been at this all morning and I know the answer is staring me right in the face but I need another set of eyes on this.
Thanks in advance.
#include <cstdint>
#include <ctype.h>
#include <stdlib.h>
namespace lex {
  // represents a cursor and capture buffer over an input source
  class LexContext {
      int16_t _current;
      unsigned long int _line;
      unsigned long int _column;
      unsigned long long _position;
    protected:
      // reads a character from the underlying device
      // read() should return EndOfInput if no more data is available,
      // and Closed if the underlying source has been closed, where
      // applicable
      virtual int16_t read()=0;
      // called to initialize the capture buffer
      virtual void initCapture()=0;
    public:
      ...

  };
// represents a LexContext with a fixed size buffer
  template<const size_t S> class StaticLexContext : virtual public LexContext {
    char _capture[S];
    size_t _captureCount;
    protected:
      // initializes the capture buffer
      void initCapture() override {
        *_capture=0;
        _captureCount=0;

      }
    public:
      StaticLexContext() {

      }
      // the capacity of the capture buffer (not including the trailing NULL)
      size_t captureCapacity() override { return S-1; }
      // the count of characters in the capture buffer
      size_t captureCount() const override {return _captureCount;}
      // returns a pointer to the capture buffer
      char* captureBuffer() override {return _capture;}
      // clears the capture buffer
      void clearCapture() override {
        _captureCount = 0;
        *_capture=0;
      }
      // captures the character under the cursor if any
      // returns true if a character was captured.
      bool capture() override {
        if (Closed!=current() && EndOfInput != current() && BeforeInput != current() && (S - 1) > _captureCount)
        {
          _capture[_captureCount++] = (uint8_t)current();
          _capture[_captureCount] = 0;
          return true;
        }
        return false;
      }

  };
#ifdef ARDUINO
  // represents a fixed length LexContext for the Arduino built on the Arduino SDK's Stream class
  template<const size_t S> class ArduinoLexContext : public StaticLexContext<S> {
        Stream* _pstream;
    protected:
        // reads a character from the stream
        int16_t read() override {
            if(!_pstream)
              return LexContext::Closed;
            return _pstream->read();
        }
    public:
      ArduinoLexContext() {

      }
        // initializes the lexcontext with a stream
        bool begin(Stream& stream) {
            _pstream = &stream;
            initCapture(); // compile error!
            return true;
        }
    };
#endif
}

A: Raymond Chen in the comments, folks. He's a hero.

The problem isn't the protected-ness. The problem is that
ArduinoLexContext derives from a template class. The compiler sees
initCapture(); and says, "Is this a member function derived from a
base class? Or is it a global function? I'm going to assume it's a
global function. Error: No global function called initCapture." (There
might be a specialization template<> StaticLexContext<0> { /* doesn't
derive from LexContext, no initCapture method */ }.) You need to help
out the compiler and write this->initCapture() to say "The initCapture
method is coming from my base class, trust me."

– Raymond Chen


text:
Q: How do I use converters in Xamarin.Forms to convert text to color? I want to have fixed enumeration of my app colors, i.e color for text, color for separators, and color for backgrounds, I don't want to type the same color every time I use it, so I thought that I may pass the object name (separator for example), and in the converter I convert it to the desired color:
here's my implementation of the IValueConverter class:
class AppColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is string)
        {
            var color = (string)value;
            switch (color)
            {
                case "separator":
                    return Color.FromHex("c2bca8");
                case "text":
                    return Color.FromHex("96907e");
                default:
                    return Color.Default;
            }
        }
        else
            return null;

    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

But I used this from my knowledge with data binding, but I simply want to pass a string to the color property, and the converter handle it , I added a ResourceDictionary:
  <Controls:CustomPage.Resources>
        <ResourceDictionary>
            <Converters:AppColorConverter x:Key="colorConverter"/>
        </ResourceDictionary>
    </Controls:CustomPage.Resources>

But how I use it , this doesn't work:
<Label Text="English"
       VerticalOptions="CenterAndExpand"
       HorizontalOptions="EndAndExpand"
       TextColor="{separator, Converter=colorConverter}"/>

A: You can also store your color values in a ResourceDictionary, like this:
<Color x:Key="ThemeBlue">#2499CE</Color>

Then in your switch statement, use this syntax:
return Application.Current.Resources["ThemeBlue"];

That way you can reuse your color values across all of the converters on your site, and manage them in a single place, your ResourceDictionary.
EDIT
You can bind as you are attempting, but you need to update your syntax. Try this:
<Label Text="English" VerticalOptions="CenterAndExpand" HorizontalOptions="EndAndExpand" TextColor="{Binding ., Converter={StaticResource colorConverter}, ConverterParameter='separator'}" />

And in your value converter, use the parameter object instead of the value object - we are passing "separator" as the parameter in this example. However, I wouldn't recommend this approach.
if (parameter is string)
        {
            var color = (string)parameter;
            ... etc ...

I think Diego's idea of just using a style is the way to go, but this answers your question and works in my test.

A: It's just a detail you've forgoten: the static resource declaration to use the converter.
Here is how you must set the use of the converter:
<Label Text="English"
       VerticalOptions="CenterAndExpand"
       HorizontalOptions="EndAndExpand"
       TextColor="{separator, Converter={StaticResource colorConverter}}"/>

Despite this, in your scenario, won't you think that a style it's a better approach?

A: Basically you can't use that syntax {separator, Converter=colorConverter}, because curly braces indicate that you are using a markup extension (in this case it would mean that there is a separatorExtension somewhere in your codebase that inherits from MarkupExtension, and it has a property named Converter, but this won't work either because UWP doesn't support custom markup extensions).  In case you tried to use the Binding markup extension(with its Converter, it should be something like this {Binding separator, C....), you can't do that either because it'll try to search for a 'separator' property in the DataContext of the containing element (but in WPF, you could bind to a static property, so you could create instances of your strings somewhere in your XAML and statically bind to it to use through the converter. We can't achieve this either in UWP).  So your only option is to go with the resources approach as in David's answer and reference them via the {StaticResource MyColor} syntax.


text:
Q: Move div block to another position I have an div block which contains text. In the index page it is too close to the middle, in other page it is too close to the top. I want to make it move, so you start on index page, and when you chose one of the other pages (for example the gallery), the block for the second must be in same place as in the index page, and then start moving to top. To jump from other pages to the index page it must move to the middle. How can I can make this?

A: Do you replace the content of the div via e.g. ajax, or do you load the whole page every time?
If you replace the content dynamically, you can try to animate the div to move via the callback function.
Link gets clicked -> Div loads new content -> New content is ready -> Callback-function moves the div up/down.


text:
Q: Recalculate sheet excel in VBA when getting numbers from cells with Cells.Value Here is a simple example to explain what I want to do:
Function fun(X As Double)

    Worksheets("Sheet1").Activate

    Y = Cells(2, "C").Value

    fun = X + Y

End Function

So, if I am changing the value of X inside the excel sheet, result of fun will change as expected, but if I change the value of Y, nothing happens. I must change X again so the function will get the new value of Y and calculate the proper value.
Is there a way to add code in this VBA function so the result of fun will automatically update with a change of value for Y?

A: Add Application.Volatile to your function as the first line.
Function fun(X As Double)
    Application.Volatile
    'Worksheets("Sheet1").Activate
    Dim Y As Long

    Y = Worksheets("Sheet1").Cells(2, "C").Value

    fun = X + Y

End Function

The assignment to Y should be done directly, not by activating a worksheet.


text:
Q: Typescript: Regex as enum value I am making API calls from an API in typescript and I would like to clearify how the response looks like using an interface. One of its values is an string which can only have a (defined) number of values. In my opinion that is the what enums are for, right?
These are the possible values:
"Normal Goal", "Own Goal", "Penalty", "Missed Penalty",
"Yellow Card", "Second Yellow Card", "Red Card",
"Substitution x"

where x can be any positive integer. And this x is the problem...
To implement it I tried using Regex. This is what it looks like:
enum Event {
  "Normal Goal", "Own Goal", "Penalty", "Missed Penalty",
  "Yellow Card", "Second Yellow Card", "Red Card",
  "Substitution [1-9]\d*$"
}

But it does not seem to work. If it isn't possible I'll just have to change the enum to type string but do you have any other idea how one could do this?

A: I would suggest using one regular expression for all values instead of an enum and check the value in runtime :
const event : RegExp = /(?:^|(?<= ))(Normal Goal|Own Goal|Penalty|Missed Penalty|Yellow Card|Second Yellow Card|Red Card|Substitution [1-9]\d*$)(?:(?= )|$)/

If you absolutely want it as a type you need to expand the regex to literals in your type:
type MatchEvent =
        "Normal Goal"|
        "Own Goal"|
        "Penalty"|
        "Missed Penalty"|
        "Yellow Card"|
        "Second Yellow Card"|
        "Red Card"|
        "Substitution 1"|
        "Substitution 2"|
        "Substitution 3"|
        "Substitution 4"|
        "Substitution 5"|
        "Substitution 6"|
        "Substitution 7"|
        "Substitution 8"|
        "Substitution 9"|
        "Substitution 10"|
        "Substitution 11"|
        "Substitution 12"|
        "Substitution 13"|
        "Substitution 14"|
        "Substitution 15"|
        "Substitution 16"|
        "Substitution 17"|
        "Substitution 18"|
        "Substitution 19"|
        "Substitution 20"|
        "Substitution 21"|
        "Substitution 22"|
        "Substitution 23"|
        "Substitution 24"|
        "Substitution 25"|
        "Substitution 26"|
        "Substitution 27"|
        "Substitution 28"|
        "Substitution 29"|
        "Substitution 30"|
        "Substitution 31"|
        "Substitution 32"|
        "Substitution 33"|
        "Substitution 34"|
        "Substitution 35"|
        "Substitution 36"|
        "Substitution 37"|
        "Substitution 38"|
        "Substitution 39"|
        "Substitution 40"|
        "Substitution 41"|
        "Substitution 42"|
        "Substitution 43"|
        "Substitution 44"|
        "Substitution 45"|
        "Substitution 46"|
        "Substitution 47"|
        "Substitution 48"|
        "Substitution 49"|
        "Substitution 50"|
        "Substitution 51"|
        "Substitution 52"|
        "Substitution 53"|
        "Substitution 54"|
        "Substitution 55"|
        "Substitution 56"|
        "Substitution 57"|
        "Substitution 58"|
        "Substitution 59"|
        "Substitution 60"|
        "Substitution 61"|
        "Substitution 62"|
        "Substitution 63"|
        "Substitution 64"|
        "Substitution 65"|
        "Substitution 66"|
        "Substitution 67"|
        "Substitution 68"|
        "Substitution 69"|
        "Substitution 70"|
        "Substitution 71"|
        "Substitution 72"|
        "Substitution 73"|
        "Substitution 74"|
        "Substitution 75"|
        "Substitution 76"|
        "Substitution 77"|
        "Substitution 78"|
        "Substitution 79"|
        "Substitution 80"|
        "Substitution 81"|
        "Substitution 82"|
        "Substitution 83"|
        "Substitution 84"|
        "Substitution 85"|
        "Substitution 86"|
        "Substitution 87"|
        "Substitution 88"|
        "Substitution 89"|
        "Substitution 90"|
        "Substitution 91"|
        "Substitution 92"|
        "Substitution 93"|
        "Substitution 94"|
        "Substitution 95"|
        "Substitution 96"|
        "Substitution 97"|
        "Substitution 98"|
        "Substitution 99";

A: Thanks to Christian for coming up with the idea of not using an enum. I created my own type which takes either one of the first several "enum strings" or a RegEx.
My code looks like this now:
type Event = ("Normal Goal"|"Own Goal"|"Penalty"|"Missed Penalty"|"Yellow Card"|"Second Yellow Card"|"Red Card"|"Substitution [1-9]\d*$)(?:(?= )|$");

interface I {
  test: Event
}


text:
Q: How to resolve a Promise within a loop function I am trying to to make several requests that are asynchronous, then push the data obtained into an array by using for loop. However, I encountered a problem that forloop itself doesnt return value which is required to resolve promise.. Also, I would like to use the array for rendering for GET method.
So How do I complete promise within for loop and make sure that the array is filled before I render it for GET method. Sorry for my bad English. I am still new to the asynchronous concept, please teach me in easy words if possible. Also, if there are any better ways to solve the problem I would like to know.

const currencyName = ["btc", "eth", "xrp"];
let dataCollections = [];
for (i = 0; i < currencyName.length; i ++) {
  dataCollections.push(new Promise(function(resolve, reject) {
    request.get(`https://apiv2.bitcoinaverage.com/indices/global/ticker/${currencyName[i]}jpy`, function(error, response, body) {
      if (error) {
        reject(error);
      } if (dataCollections.length === 3) {
        dataColletions = [];
      }  else {
        resolve(JSON.parse(body));
      }
    });
  }));
}

//Promise.all(??).then(??)

//For rendering dataCollections
  app.get("/", function(req, res) {
    res.render("home", {dataCollections: dataCollections});
}

A: 1) consider naming your array currencyNames plural so that you can name your iterator currencyName.
2) Your for loop is reinventing the array.map function. Consider using array.map instead.
3) Your for loop has an impossible if clause (if (dataCollections.length === 3)) which also means the else clause is on the wrong if statement. I assume this is a typo.
Now to the core of your question, yes Proimse.all(Array<Promise>) is what you want; it resolves when all elements in its param resolve.
const currencyNames = ["btc", "eth", "xrp"];

let dataCollections = currencyNames.map(currencyName => new Promise((resolve, reject) =>
    request.get(`https://apiv2.bitcoinaverage.com/indices/global/ticker/${currencyName}jpy`, (error, response, body) => {
      if (error)
        reject(error);
      else
        resolve(JSON.parse(body));
    })));

//For rendering dataCollections
app.get("/", async (req, res) =>
    res.render("home", {dataCollections: await Promise.all(dataCollections)}));

A: Make the endpoint async:
 app.get("/", async function(req, res) {
   res.render("home", {dataCollections: await Promise.all(dataCollections) });
 });


text:
Q: Let G be a finite group, $|G| = 1575$ and suppose $n_3 =1$. Prove $G$ is abelian This is the full question:

Let G be a finite group, $|G| = 1575$ and suppose $n_3 =1$,then $n_5=1$ and $n_7=1$. Prove $G$ is Abelian. $n_p$ denotes the number of sylow $p$-subgroups in $G$

$1575=3^2\cdot5^2\cdot7$, I was able to prove that if $n_3=1$ then $n_5=1$ and $n_7=1$. But how do i show from here that $G$ is Abelian ? I was considering using the thm : $ G/Z(G)$ is cylic iff $G$ is abelian. But then there are many cases to consider. Any hints ?

A: There is an extra property of Sylow subgroups, namely: if $H$ and $K$ are Sylow-subgroups (not necessarily of the same order and not with respect to the same prime number) that are normal (and thus unique), then $$\forall x \in H \text{ and } \forall y \in K, xy = yx. (1)$$ In particular, the above relation holds also for arbitrary normal subgroups whose intersection is only the neutral element.
In your question, the Sylow-subgroups are of order $3^2, 5^2$ and $7$. It is know that a group of order $p$ or $p^2$ where $p$ is a prime is abelian.
Equation $(1)$ also gives you an isomorphism between groups. If we let $S_3, S_5$ and $S_7$ be the respective Sylow subgruops from your question, then each of them is abelian, and the function $$g:S_3 \times S_5 \times S_7 \to G, g(x,y,z) = xyz $$ is an isomorphism, and since a direct product of abelian groups is abelian, then $G$ is abelian.


text:
Q: How do you merge two arrays of u8 and u16 elements into an array of u8 elements? So I have an array I've just created of u8 (a) and a slice of u16 (b). How can I get an array that is the result of concatenating the elements of a with the elements of b after turning these into u8?
I've tried a lot of modifications of the following code, but there is always some error.
fn main() {
    let a: [u8; 3] = [0x01, 0x02, 0x03];
    let b: &[u16] = &[0x0405, 0x0607, 0x0809];
    let result = [a,
                  b.iter().flat_map(|s| &s.to_be_bytes()).collect()]
                 .iter().flat_map(|e| e.iter()).collect();
    assert_eq!(result, [1, 2, 3, 4, 5, 6, 7, 8, 9]);
}

I understand the error in that piece of code but I don't know how to fix it without creating another.
Like, I can create a as a Vec<u8> so that collect() can collect into something that implements std::iter::FromIterator. But it collects into Vec<&u8>.
I also have the feeling that it should be way more simple than my example. As if I'm missing a specific function.

A: The following works:
fn main() {
    let a: [u8; 3] = [0x01, 0x02, 0x03];
    let b: &[u16] = &[0x0405, 0x0607, 0x0809];
    let result: Vec<u8> = a.iter().copied()
        .chain(
            b.iter()
                .flat_map(|s| std::array::IntoIter::new(s.to_be_bytes()))
        )
        .collect();
    assert_eq!(result, [1, 2, 3, 4, 5, 6, 7, 8, 9]);
}

This uses the newly added std::array::IntoIter, which converts an array [T; N] into an iterator of type T, as opposed to the .iter() which produces &T. This solves the issue of combining a u8 with a &u8.
Afterwards it uses .chain to attach both iterators together, which allows us to use different types of iterators that produce the same item, as opposed to using [a, b].iter(), which requires a and b to be the same type, as opposed to simply being iterators which produce the same type.
As a.iter().copied() and b.iter().flat_map(...) aren't the same type, you must use .chain instead of an array.


text:
Q: Is placeholder supports IE 8? I think IE 8 doesn't support placeholder, but when i load www.skydrive.com it comes with placeholder text as "someone@example.com & password"
Is there any way to access placeholder without jQuery etc in IE 8?

A: According to can I use the placeholder attribute came in IE10.
Modernizr is a good library for doing feature detection such as this and they also have a great list of polyfils you can use.

A: Just add this in your header. Hope it helps
<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE" />


text:
Q: AzureSearchSDK returning diffrent results than portal test While using SearchAsync function from AzureSearch .NET SDK putting in query encoded string containing UTF8 signs I got null response, no records are found. After investigation on Fiedler, I know that POST request is sent to azure search service:
url:
    /indexes('[INDEX_NAME]'/docs/search.post.search?api-version=2017-11-11 HTTP/1.1
body:
{
"count": false,
 "facets": [],
 "filter": "search.ismatch('6','CataloguesIds')",
 "queryType": "full",
 "scoringParameters": [],
 "search": "pier%C5%9Bcionek*",
 "searchMode": "any",
 "select": "Id,Name"
 }

The same request sent by Azure Portal returns proper results. Although Fiedler shows that method used in portal is GET
url: /indexes/products-index/docs?api-version=2017-11-11&search=pier%C5%9Bcionek*.
What should I do to get the same response from AzureSearch SDK as in portal for queries containing UTF8 signs? For request without UTF8 signs SearchAsync method returns proper results.

A: You should expect results to be the same between the query explorer in the Azure Portal and using the API directly.
In this case, the two queries you included above are different. The POST query includes both a search clause and a filter clause, while the GET request only has search clause. Perhaps there are no documents in the index that satisfy both conditions formulated in the POST query, resulting in empty results?
Additionally, for the body of the POST request you should not URL-encode values. The body needs to be a proper JSON document (including accounting for the right character encoding) with no additional encoding.


text:
Q: Splunk Fields - Broken I was going to ask this on the Splunk forums, but for some reason I haven't got a validation email after a few hours and multiple attempts, so I thought I would try here.
I create a search from a .csv data source and save a report from this search. I then selected the fields I want. Screenshot:

This works great. Then I send this report over to a dashboard so I can make some nice graphs and all the fields are gone and I have no option to map the fields.

(redacted some data)
As you can see there's no option to use the fields I selected in the report even though this is an import of that report. I tried manually mapping a field, and even that only shows up in the Reports view and not in any dashboards/panels. Is there something I'm missing here?

A: I suggest that you go to the report and choose the "Add to dashboard" option. Keep both the report and the dashboard in the same app. "Permanent" fields are defined within the context of an app. "Temporary" fields (created by the rex command, for example) exist only within the context of a report.


text:
Q: Variables and Pointers in an Isolated Environment like Virtual Machines I'm wondering how a programming language like Java can handle Variables and/or Pointers in an isolated environment like Java Virtual Machine and its own Byte-Code.
Examples in Assembly or binary equivalents are highly appreciated.

A: I suggest you read a little of how Java actually works.
Java doesn't have pointers, it has references which you cannot examine in pure Java.  An important distinction about references in Java is that they

*

*can change at any time without notice

*don't have to be a direct address in memory.  It can be encoded. e.g. to allow 32-bit references to access up to 32 GB of memory.

It has variables like any other language but you can't get a reference to them.
The byte code is a literal translation of the Java code and read it is unlikely to be more useful than reading the Java code unles syou have a deep understanding of Java.  Note: the JVM compiles this to native code, so it is not the code actually run much of the time.


text:
Q: Smooth transfer of service IP to backup system I'm trying to research the best way to find a HA solution plus (little) load balancing for our TCP services.
All solutions I found (e.g. HAProxy, LVS) use a master machine which holds the TCP service IP and when the master crashes a backup system (by keepalived, VRRP) becomes available by using that service IP. That's nice.
But I didn't found a solution for making the backup system the active one by a smooth transfer (without loosing a packet): Sometimes I need to update/change/reboot the current master machine so I want new connections going to the backup system while old/current connections are still handled by the old master until they are done so I am able to reboot the old master.
Is that possible or can't this be done?
And while dreaming: The optimal solution would be a transfer of the current connections (plus the service IP) to the backup machine. Is there a solution for this dream?

A: I'm not entirely sure what you're after, but if it's "smooth transfer without loosing a packet":
I've never used keepalived or VRRP implementations, because most (all?) of them lack STONITH, AFAIK.
But: The industry standard for setting up high availability clusters in the open source world, the corosync / pacemaker stack, provides this.


text:
Q: Margin from one element obscuring hover state of another I have a Flexbox based nav menu with a logo aligned in the horizontal center of inline links. Every pen or fiddle I tried making of this doesn't replicate what I'm getting for some reason, but you can go to this Flexbox test here which is almost exactly what I'm working from and if you go into an inspector and add an anchor to the main logo image you'll see what I mean.
The way this is set up is the third link has a left margin of auto applied to fill in the extra gap for the logo to fit in. The logo area is separate from the nav menu in the markup but flexbox layout puts them all in line with each other (at lower breakpoints the nav menu moves down).
Now this all works fine and good until you decide to make the logo a clickable link. When you do that, the margin from that third link obscures the hover state of the logo.
Here's a visual example:

So if you tried hovering over the logo where the margin area intersects it, you would not be able to click the logo, nor get a pointer cursor or any hover states (like a background change). Outside of the margin while over the logo, it works fine, but to a user, they're going to think something strange is going on. This happens if the logo is an img (as it is in the original example) or an SVG (as I'm trying to use).
Trying to see if there's a way around this without having to completely nuke my Flexbox layout. My markup is very similar to what is being used in that example. I've tried toying with a higher z-index for the logo compared to the nav, which didn't work. Giving the nav a negative z-index lets you click the logo but then you can't click the nav items.

A: You can add a relative position to the logo and then play around with the z-index to make the logo the first element.
.logo {
    position: relative;
    z-index: 1;
}


text:
Q: Find $\lim\limits_{n \to \infty}\frac{\ln^3 n}{\sqrt{n}}\sum_{k=2}^{n-2}\frac{1}{\ln k\ln(n-k)\ln(n+k)\sqrt{n+k}}$ On a Chinese website, someone has posted a solution as follows:
Notice
\begin{align*} s_n&:=\frac{\ln^3 n}{\sqrt{n}}\sum_{k=2}^{n-2}\frac{1}{\ln k\ln(n-k)\ln(n+k)\sqrt{n+k}}\\ &=\frac{1}{n}\sum_{k=2}^{n-2}\frac{1}{\left(1+\frac{1}{\ln n}\ln\frac{k}{n}\right)\left(1+\frac{1}{\ln n}\ln\left(1-\frac{k}{n}\right)\right)\left(1+\frac{1}{\ln n}\ln\left(1+\frac{k}{n}\right)\right)\sqrt{1+\frac{k}{n}}}, \end{align*}
and define
$$a_n(k):=\frac{1}{\left(1+\frac{1}{\ln n}\ln\frac{k}{n}\right)\left(1+\frac{1}{\ln n}\ln\left(1-\frac{k}{n}\right)\right)\left(1+\frac{1}{\ln n}\ln\left(1+\frac{k}{n}\right)\right)}.$$
It's obvious that $\lim\limits_{n \to \infty} a_n(k)=1$, independent of $k$.
Hence, $\forall \varepsilon\in(0,1), \exists N>0~ s.t.~1-\varepsilon\le a_n(k)\le1+\varepsilon$ holding for all $n>N,$ which implies
$$
\frac{1}{n}\sum_{k=2}^{N}\frac{a_n(k)}{\sqrt{1+\frac{k}{n}}}+\frac{1-\varepsilon}{n}\sum_{k=N+1}^{n-2}\frac{1}{\sqrt{1+\frac{k}{n}}}\le s_n \le \frac{1}{n}\sum_{k=2}^{N}\frac{a_n(k)}{\sqrt{1+\frac{k}{n}}}+\frac{1+\varepsilon}{n}\sum_{k=N+1}^{n-2}\frac{1}{\sqrt{1+\frac{k}{n}}}.$$
Let $n \to \infty$, then
$$(1-\varepsilon)\int_0^1 \frac{{\rm d}x}{\sqrt{1+x}}\le \liminf_{n \to \infty} s_n \le\limsup_{n \to \infty} s_n\le (1+\varepsilon)\int_0^1 \frac{{\rm d}x}{\sqrt{1+x}}.$$
As per the arbitariness of $\varepsilon>0$, we can conclude $$\lim_{n \to \infty} s_n= \int_0^1 \frac{{\rm d}x}{\sqrt{1+x}}=2\sqrt{2}-2.$$
Is it correct? Does there exist any other solution?


text:
Q: There are $6$ types of cookies. How many different packs of $3$ cookies can the baker package?
A cookie baker packages cookies $3$ to a pack. The type of cookies she can choose from include chocolate chip, oatmeal, sugar-coated, sugar-free, peanut butter, and hazelnut. How many different packs of $3$ cookies can she package?

When I approached the problem, I assumed that you had as many of each cookies as you wanted. So the first way to choose the first cookie is $6$, the second is $6$, and the third is $6$ as well.
So the total number of possible permutations is $216$. To resolve the order, divide by $3!$ which then yields a total of $36$.
The answer is however $56$ possible packages. I would appreciate that you not only give you provide the correct analysis and solution, but also where I made a mistake.

A: We assume the order of cookies in the package doesn't matter.
There are $\binom{6}{3}$ three-flavour packages. To count the two-flavour packages, the majority cookie can be chosen in $6$ ways, and for each of these ways the minority cookie can be chosen in $5$ ways. Finally, there are $6$ one-flavour packages, for a total of $56$.
Remark: Dividing $216$ by $3!$ is not right. The division  by $3!$ is correct for three-flavour packages, but two-flavour ordered packages only come in $3$ orders, not $3!$, and one-flavour packages come in only one order.


text:
Q: Extending home partition capacity on ubuntu 20.04 I have Ubuntu 20.04 virtually installed on vmware workstation 12 with windows 10 as the host.
I made a mistake on installation process and allocate just 5GB to home partition.
After installing several packages it reached its limit and ran out of capacity.
Here is a screenshot of what I have on my disk:

Could you please guide me how to increase the capacity of home directory to have 25GB more?
I did some research but couldn't find anything that suits my problem since I have unallocated space on a non-adjacent partition.
I am a beginner Linux user, any guidance would be appreciated.

A: To fix this you need to boot your VM with live media that contains the GParted application. The Ubuntu install media is perfect. Here are the steps:

*

*Backup any data you cannot afford to lose.

*Boot the live media, choose "Try Ubuntu" if using the Ubuntu install media.

*Start GParted. I recommend you reduce the size  of sda1 first. You can recover about 5GB there. Complete that operation.

*Next you need to resize sda2 so that it extends from sda1 to the end of the drive. Complete that operation.

*You now need to decide how much space to give to sda5 and sda6. Move sda6 all the way to the right and sda5 all the way to the left. Share out the space according to your decision. You might want to complete this as several steps completing each as you go.

*Shut down and reboot. Should be fine. Good luck!


text:
Q: Relative difficulty between leading zero counting and addition Consider a 32-bit or 64-bit ALU that must implement both count leading zeros and integer addition, with low latency (say a few cycles), implemented on a modern high frequency logic process.
Which is generally more complex, a fast adder or a fast leading zero count?

A: For a 64-bit leading zero counter, what you'd need is at most a 6-NOR-deep combinatorial chain plus one XOR (or equivalent) ("is the first bit zero, and the second bit one", "are the previous bits zero, using the result from the previous step") and 6 bit LUT.
That's very little.
A trivial ripple-block carry lookahead adder with 64 bit operands needs six stages, so it might be minimally faster, which is also very little.
In other words: I can't give you a definite answer; actual fast implementations will depend on the standard blocks that the hardware designer can employ: for example, on a modern high-performance FPGA, you'd either just use an arithmetic block (and not care about the design), or build it from 6-LUTs; so, these combinatorial considerations have no relevance to FPGA design. On an ASIC of an actual silicon CPU, neither components will be close to being the most complex things to do during a single clock cycle, and thus, more combinatorial steps in favor of e.g. lower routing overhead or lower switching probability might be favored.