text:
Q: Too Early to create image Whenever I run the following code I get this error. I am using Python 3 might be me using code for Python 2.
Traceback (most recent call last):
  File "Python Fun", line 238, in <module>
    platform1 = PlatformSprite(g, tk.PhotoImage(file="platform1.gif"), 0, 480,100, 10)
  File "C:\Users\ ------ Com\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 3394, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)
  File "C:\Users\ ------ Com\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 3335, in __init__
    raise RuntimeError('Too early to create image')
RuntimeError: Too early to create image
Press any key to continue . . .

What do I do?
import tkinter as tk
import random
import time

class Game:
    def _init_(self):
        self.tk = Tk()
        self.tk.title("Juniors Climb")
        self.tk.resizable(0,0)
        self.tk.wm_attributes("-topmost",1)
        self.canvas = Canvas(self.tk, width=1000, height=1000, highlightthickness = 0)
        self.canvas .pack()
        self.tk.update()
        self.canvas_height = 1000
        self.canvas_width = 1000
        self.bg = Photoimage(file="background.gif")
        w = self.bg.width()
        h = self.bg.height()
        for x in range(0,5):
            for y in range (0,5):
                self.canvas.create_image(xer*w, yer*h, image=self.bg, anchor='nw')
        self.sprites = []
        self.running = True

    def mainloop(self):
        while 1:
            if self.running == True:
                for sprite in self.sprites:
                    sprites.move()
            self.tk.update_idletasks()
            self.tk.update()
            time.sleeping(0.01)

class Coords:
    def _init_(self, x1=0, y1=0, x2=0, y2=0):
        self.x1 = x1
        self.y1 = y1
        self.x2 = x2
        self.y2 = y2

def within_x(co1, co2):
    if (co1.x1 > co2.x1 and co1.x1 < co2.x2) \
            or (co1.x2 > co2.x1 and co1.x2 < co2.x2) \
            or (co2.x1 > co1.x1 and co2.x1 < co1.x2) \
            or (co2.x2 > co1.x1 and co2.x2 < co1.x1):
        return True
    else:
        return False

def within_y(co1, co2):
    if (co1.y1 > co2.y1 and co1.y1 < co2.y2) \
            or (co1.y2 > co2.y1 and co1.y2 < co2.y2) \
            or (co2.y1 > co1.y1 and co2.y1 < co1.y2) \
            or (co2.y2 > co1.y1 and co2.y2 < co1.y1):
        return True
    else:
        return False

def collided_left(co1, co2):
    if within_y(co1, co2):
        if co1.x1 <= co2.x2 and co1.x1 >= co2.x1:
            return True
    return False

def collided_right(co1, co2):
    if within_y(co1, co2):
        if co1.x2 >= co2.x1 and co1.x2 <= co2.x2:
            return True
    return False

def collided_top(co1, co2):
    if within_x(co1, co2):
        if co1.y1 <= co2.y2 and co1.y1 >= co2.y1:
            return True
    return False

def collided_bottom(y, co1, co2):
    if within_x(co1, co2):
        y_calc = co1.y2 + y
        if y_calc >= co2.y1 and y_calc <= co2.y2:
            return True
    return False

class Sprite:
    def __init__(self, game):
        self.game = game
        self.endgame = False
        self.coordinates = None

    def move(self):
        pass

    def coords(self):
        return self.coordinates

class PlatformSprite(Sprite):
    def __init__(self, game, photo_image, x, y, width, height):
        Sprite.__init__(self, game)
        self.photo_image = photo_image
        self.image = game.canvas.create_image(x, y, \
        image=self.photo_image, anchor='nw')
        self.coordinates = Coords(x, y, x + width, y + height)

class StickFigureSprite(Sprite):
    def __init__(self, game):
        Sprite.__init__(self, game)
        self.images_left = [
            PhotoImage(file="figure_L1.gif"),
            PhotoImage(file="figure_L2.gif"),
            PhotoImage(file="figure_L3.gif")
 ]
        self.images_right = [
            PhotoImage(file="figure_R1.gif"),
            PhotoImage(file="figure_R2.gif"),
            PhotoImage(file="figure_R3.gif")
 ]
        self.image = game.canvas.create_image(200, 470, \
        image=self.images_left[0], anchor='nw')
        self.x = -2
        self.y = 0
        self.current_image = 0
        self.current_image_add = 1
        self.jump_count = 0
        self.last_time = time.time()
        self.coordinates = Coords()
        game.canvas.bind_all('<KeyPress-Left>', self.turn_left)
        game.canvas.bind_all('<KeyPress-Right>', self.turn_right)
        game.canvas.bind_all('<space>', self.jump)
    def turn_left(self, evt):
        if self.y == 0:
            self.x = -2
    def turn_right(self, evt):
        if self.y == 0:
            self.x = 2
    def jump(self, evt):
        if self.y == 0:
            self.y = -4
            self.jump_count = 0
    def animate(self):
        if self.x != 0 and self.y == 0:
            if time.time() - self.last_time > 0.1:
                self.last_time= time.time()
                self.current_image += self.current_image_add
                if self.current_image >= 2:
                    self.current_image_add = -1
                if self.current_image <= 0:
                    self.current_image_add = 1
        if self.x < 0:
            if self.y != 0:
                self.game.canvas.itemconfig(self.image, \
                    image=self.images_left[2])
            else:
                self.game.canvas.itemconfig(self.image, \
                    image=self.images_left[self.current_image])
        elif self.x > 0:
            if self.y != 0:
                self.game.canvas.itemconfig(self.image, \
                    image=self.images_right[2])
            else:
                self.game.canvas.itemconfig(self.image, \
                    image=self.images_right[self.current_image])
    def coords(self):
        xy = self.game.canvas.coords(self.image)
        self.coordinates.x1 = xy[0]
        self.coordinates.y1 = xy[1]
        self.coordinates.x2 = xy[0] + 27
        self.coordinates.y2 = xy[1] + 30
        return self.coordinates

    def move(self):
        self.animate()
        if self.y < 0:
            self.jump_count += 1
            if self.jump_count > 20:
                self.y = 4
        if self.y > 0:
            self.jump_count -= 1
        co = self.coords()
        left = True
        right = True
        top = True
        bottom = True
        falling = True
        if self.y > 0 and co.y2 >= self.game.canvas_height:
            self.y = 0
            bottom = False
        elif self.y < 0 and co.y1 <= 0:
            self.y = 0
            top = False
        if self.x > 0 and co.x2 >= self.game.canvas_width:
            self.x = 0
            right = False
        elif self.x < 0 and co.x1 <= 0:
            self.x = 0
            left = False
        for sprite in self.game.sprites:
            if sprite == self:
                continue
            sprite_co = sprite.coords()
            if top and self.y < 0 and collided_top(co, sprite_co):
                self.y = -self.y
                top = False
            if bottom and self.y > 0 and collided_bottom(self.y, co, sprite_co):
                self.y = sprite_co.y1 - co.y2
                if self.y < 0:
                    self.y = 0
                bottom = False
                top = False
            if bottom and falling and self.y == 0 \
                    and co.y2 < self.game.canvas_height \
                    and collided_bottom(1, co, sprite_co):
                falling = False
            if left and self.x < 0 and collided_left(co, sprite_co):
                self.x = 0
                left = False
                if sprite.endgame:
                    self.game.running = False
            if right and self.x > 0 and collided_right(co, sprite_co):
                self.x = 0
                right = False
                if sprite.endgame:
                    self.game.running = False
        if falling and bottom and self.y == 0 \
                and co.y2 < self.game.canvas_height:
            self.y = 4
        self.game.canvas.move(self.image, self.x, self.y)

class DoorSprite(Sprite):
    def __init__(self, game, photo_image, x, y, width, height):
        Sprite.__init__(self, game)
        self.photo_image = photo_image
        self.image = game.canvas.create_image(x, y, \
        image=self.photo_image, anchor='nw')
        self.coordinates = Coords(x, y, x + (width / 2), y + height)
        self.endgame = True

g = Game()
platform1 = PlatformSprite(g, tk.PhotoImage(file="platform1.gif"), 0, 480, 100, 10)
platform2 = PlatformSprite(g, tk.PhotoImage(file="platform1.gif"), 150, 440, 100, 10)
platform3 = PlatformSprite(g, tk.PhotoImage(file="platform1.gif"), 300, 400, 100, 10)
platform4 = PlatformSprite(g, tk.PhotoImage(file="platform1.gif"), 300, 160, 100, 10)
platform5 = PlatformSprite(g, tk.PhotoImage(file="platform2.gif"), 175, 350, 66, 10)
platform6 = PlatformSprite(g, tk.PhotoImage(file="platform2.gif"), 50, 300, 66, 10)
platform7 = PlatformSprite(g, tk.PhotoImage(file="platform2.gif"), 170, 120, 66, 10)
platform8 = PlatformSprite(g, tk.PhotoImage(file="platform2.gif"), 45, 60, 66, 10)
platform9 = PlatformSprite(g, tk.PhotoImage(file="platform3.gif"), 170, 250, 32, 10)
platform10 = PlatformSprite(g, tk.PhotoImage(file="platform3.gif"), 230, 200, 32, 10)
g.sprites.append(platform1)
g.sprites.append(platform2)
g.sprites.append(platform3)
g.sprites.append(platform4)
g.sprites.append(platform5)
g.sprites.append(platform6)
g.sprites.append(platform7)
g.sprites.append(platform8)
g.sprites.append(platform9)
g.sprites.append(platform10)
door = DoorSprite(g, PhotoImage(file="door1.gif"), 45, 30, 40, 35)
g.sprites.append(door)
sf = StickFigureSprite(g)
g.sprites.append(sf)
g.mainloop()

A: I believe the problem is you have the Tk() object scoped specifically to the Game() class.  Try putting root = tk.Tk() at the very top of your python and use root/pass it around for the handle for your Tkinter work.  Also, you are using a variable called "tk" even after you imported Tkinter as tk. Consider using a different name for that variable or you could run into some problems.


text:
Q: Multiple params asp net mvc 4 I already have a city parameter which represent a cityname that I'll search on my DB, everything work well when I do mysite/List?city=mycityname, but what I'm trying to do is that I would also like to do a search by firstname combined with the cityname example
List?city=mycityname&firstName=myfirstname. How can I do this ? Here is my query for city, I also added the firstname parameter but I don't really know how to add it so it'll filter both.
public string CurrentFirstName { get; set; }
public ViewResult List(string city, string firstName, int page = 1)
    {
        UsersListViewModel model = new UsersListViewModel
        {
            Users = repository.Userss
            .Where(p =>city == null || p.CityName == city )
            .OrderBy(p => p.UsersId)
            .Skip((page - 1) * PageSize)
            .Take(PageSize),
            PagingInfo = new PagingInfo
            {
                CurrentPage = page,
                UsersPerPage = PageSize,
                TotalUsers = repository.Userss.Count()
            },
            CurrentCity = city
            // CurrentFirstName = firstName
        };
        return View(model);
    }

A: You can write something like this
Users = repository.Userss
        .Where(p =>city == null || p.CityName == city )
        .Where(p=> firstName == null || p.FirstName == firstName)
        .OrderBy(p => p.UsersId)
     // rest of your query

A: Have a look into the following code:
    public ViewResult List(string city, string firstName, int page = 1)
    {
        UsersListViewModel model = new UsersListViewModel
        {
            Users = repository.Userss
            .Where((p =>city == null || p.CityName == city ) &&
             (p =>firstname == null || p.FirstName == firstName))
            .OrderBy(p => p.UsersId)
            .Skip((page - 1) * PageSize)
            .Take(PageSize),
            PagingInfo = new PagingInfo
            {
                CurrentPage = page,
                UsersPerPage = PageSize,
                TotalUsers = repository.Userss.Count()
            },
            CurrentCity = city
            CurrentFirstName = firstName
        };
        return View(model);
    }

A: You can do some conditional query building like,
public ViewResult List(string city, string firstName, int page = 1)
{
    var query = repository.Userss.Where(p => city == null || p.CityName == city);
    if (firstName != null)
        query = query.Where(p => firstName == null || p.FirstName == firstName);

    var model = new UsersListViewModel
    {
        Users = query
        .OrderBy(p => p.UsersId)
        .Skip((page - 1) * PageSize)
        .Take(PageSize),
        PagingInfo = new PagingInfo
        {
            CurrentPage = page,
            UsersPerPage = PageSize,
            TotalUsers = repository.Userss.Count()
        },
        CurrentCity = city
        // CurrentFirstName = firstName
    };
    return View(model);
}

Note: i think you should also consider the search criteria on TotalUsers calculation
hope this helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Migrating Windows Sharepoint Services 3.0 from Windows 2003 x86 / MSEE to Windows 2008 R2 x64 / SQL Server 2008 I am having a helluva time with this one.
I am attempting to migrate a 5 year old VM running Windows 2003 Windows Sharepoint Services 3.0 that was deployed as a standalone (thus to MSEE) to a Windows 2008 R2 x64 WSS3 implementation with SQL Server Standard 2008R2.
I was successful in getting the 14GB content DB moved over so now the standalone Win2k3 farm has its content DB on the 2008 machine (yay!).
However trying to get the config db & admincontent DB over has been troublesome. I have looked and followed the technet articles but seem to have no luck in resolving issues.
Is it best just to roll out a new farm and hook the new configuration into the old content DB or do I continue to try to preserve the configuration in the config DB & admin content DB (there aren't many customizations in my opinion).

A: I'd just build a new farm on the new machine, add solutions and then add the content database.
You might need SPSolutionExtractor

A: I would strongly recomand you build your own MOSS 2007 server farm and go through a series of database attach/upgrade (i mean SharePoint 2007 attach to an existing farm, and it will force an upgrade).
Before that, make sure you identified all customizations, 3rd party developments, etc.


text:
Q: Can OPTIONS and STYLES both be used for FusionTableLayer in Google Maps? When displaying map data from a Google Fusion table onto Google Maps as a layer, there is a very rich set of options available to customize the appearance of map features and the contents of info window. It appears that you can either use your own Style/Info Window generated at run time (i.e. through code on client side), or use the ones that you created in Fusion Tables tool, but not both. It would make sense for the same class of behaviour you are trying to customize for a given map view because there would otherwise be two competing commands for same action. However, I was wondering if I could mix and match it so that Styles is generated on the fly on the client side (using Styles section/directives), but use the "default" Info Window which was set up using Fusion Tables tool.
The following sample code illustrates what I would ideally want to do. Note the presence of both Options and Styles blocks. Options to use the default Info Window. And Styles to customize the appearance of map features.
    layer = new google.maps.FusionTablesLayer({
  ...
  },
  options: {
    //styleID is removed from Options; using Styles below--styleId: 2,
     templateId: 2 //Info Window is left to be the default one.
  }

  //Styles section is used instead of default styleID in "options" above.
  styles: [{
      where: "filter condition",
      polylineOptions: {
          strokeColor: "#ffbf00",
          strokeWeight: "3"
      }
  }]
});

A: Yes you can.  The styled infowindow contents is available in the click event.
See the documentation:
FusionTablesMouseEvent object specification

The properties of a mouse event on a FusionTablesLayer.

infoWindowHtml | Type:  string | Pre-rendered HTML content, as placed in the infowindow by the default UI.

example fiddle from your previous question: "WHERE" clauses being ignored in Fusion Table Layer in Google Maps
code snippet:

var geocoder = new google.maps.Geocoder();
var map;

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  layer = new google.maps.FusionTablesLayer({
    map: map,
    options: {
      // styleId: 2,
      templateId: 2
    },
    heatmap: {
      enabled: false
    },
    query: {
      select: "geometry",
      from: "1D6d93-0iT2zUCw8IvkbpDPYDx2-jA0ZAWXi07mQD",
    },
    styles: [{
      polylineOptions: {
        strokeOpacity: 0.001,
        strokeWeight: 0
      }
    }, {
      where: "SHIFT_ID = 3",
      polylineOptions: {
        strokeOpacity: 1.0,
        strokeColor: "#FFFFFF",
        strokeWeight: 3
      }
    }, {
      where: "SHIFT_ID = 1",
      polylineOptions: {
        strokeOpacity: 1.0,
        strokeColor: "#FF0000",
        strokeWeight: 3
      }
    }, {
      where: "SHIFT_ID = 2",
      polylineOptions: {
        strokeOpacity: 1.0,
        strokeColor: "#ffbf00",
        strokeWeight: "3"
      }
    }]
  });
  geocoder.geocode({
    'address': "Winnipeg, Canada"
  }, function(results, status) {
    if (status === google.maps.GeocoderStatus.OK) {
      map.fitBounds(results[0].geometry.viewport);
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });

}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}


text:
Q: What service do i need for hosting django (backend) + postgresql (database) on GCP I want to know what service in Google cloud Platform that i need to deploy my backend django + postgresql? I'm developing a mobile app using flutter.

A: There are multiple ways to host a Django app with PostgreSQL on GCP. The documentation covers the following available options:

*

*App Engine standard environment

*App Engine flexible Environment

*Cloud Run

*Google Kubernetes Engine (GKE)

*Compute Engine
For the PostgreSQL database, you can use the Cloud SQL.
If you need a Django package that already includes PostgreSQL, you can use the Django in Google Cloud Marketplace and deploy your app on the Compute Engine.

A: Google Cloud's Flexible App Engine Service can definitely work in this case .
About App Engine
Google App Engine lets app developers build scalable web and mobile back ends in any programming language on a fully managed serverless platform.
For more detail please check the below link, on how you can achieve the same
https://codeburst.io/beginners-guide-to-deploying-a-django-postgresql-project-on-google-cloud-s-flexible-app-engine-e3357b601b91


text:
Q: Couchbase subdocument select only field needed I need to select only one field from the subdocument.
ex. original document
{
   "geo" : {
      "lat" : 37.700967,
      "alt" : 5622,
      "lon" : -113.098847
   },
   "tz" : "America/Denver",
   "id" : 3824,
   "type" : "airport",
   "city" : "Cedar City",
   "country" : "United States",
   "icao" : "KCDC",
   "faa" : "CDC",
   "airportname" : "Cedar City Rgnl"
}

I want it as
{
    "geo" : { "alt" : 5622 },
    "tz" : "America/Denver",
    "id" : 3824,
    "type" : "airport",
    "city" : "Cedar City",
    "country" : "United States",
    "icao" : "KCDC",
    "faa" : "CDC",
    "airportname" : "Cedar City Rgnl"
}

I need to select only "alt" field from the "geo" sub document however when I refer it as geo.alt in the query it returns as field of main document. I need to preserve the full document structure as it is.
SELECT airportname, city, country, geo.alt FROM `travel-sample` WHERE type="airport"

Any advise?


text:
Q: How to have a simpler constructor fo special cases I am wondering if what I am trying to achieve is actually possible at all, I do not know the exact name of what I am doing hence why I cannot really properly google for results and why this topic title is also kind of vague.
My classes:
AccountConstraint.java:
package dao.constraint;

public class AccountConstraint {
    private Range<Integer> accountId;
    private String username;
    private String password;
    private String email;

    public AccountConstraint(final Range<Integer> accountId, final String username, final String password, final String email) {
        this.accountId = accountId;
        this.username = username;
        this.password = password;
        this.email = email;
    }

    public Range<Integer> getAccountId() {
        return accountId;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    public String getEmail() {
        return email;
    }
}

Range.java:
package dao.constraint;

public class Range<T> {
    private T min;
    private T max;

    public Range(T min, T max) {
        this.min = min;
        this.max = max;
    }

    public T getMin() {
        return min;
    }

    public T getMax() {
        return max;
    }
}

A perfectly valid code example would be:
AccountConstraint ac = new AccountConstraint(new Range<Integer>(5, 10), null, null, null));

If you would want to get all accounts with id 5 to 10. A still valid, but weirder piece of code would be:
AccountConstraint ac = new AccountConstraint(new Range<Integer>(3, 3), null, null, null));

if you would want to get the account with id 3.
What I would like is:
AccountConstraint ac = new AccountConstraint(3, null, null, null);

as new Range<Integer>(3, 3) is theoretically equal to 3.
Is there a way to do this, possibly via adding code to the Range class, I kind of feel like this should be possible, but I got no clue how and/or where to start.

A: You don't need to do anything about your Range class, simply provide another AccountConstraint constructor which makes a Range out of one int:
public AccountConstraint(final int accountId, final String username, final String password, final String email) {
    this(new Range<Integer>(accountId, accountId), username, password, email);
}

A: Create more constructors:
public AccountConstraint(Integer accountId, final String username, final String password, final String email) {
    this.accountId = new Range<Integer>(accountId);
    this.username = username;
    this.password = password;
    this.email = email;
}

public Range(T num) {
    this.min = num;
    this.max = num;
}

A: Add a constructor taking an Integer as first argument and create a Range with it:
public AccountConstraint(Integer accountId, final String username, final String password, final String email) {
    this(new Range<Integer>(accountId, accountId), username, password, email);
}

A: You can try this (Creating a new overloaded constructor):
public AccountConstraint(final Range<Integer> accountId, final String username, final String password, final String email) {
      this.accountId = accountId;
      this.username = username;
      this.password = password;
      this.email = email;
}

//new overloaded constructor
public AccountConstraint(Integer value, final String username, final String password, final String email) {
      Range<Integer> accountId = new Range(value,value);
      super(accountId , username, password, email));
}

A: Create a constructor like this. Pass the value to the constructor
   public AccountConstraint(Integer i, final String username, final String password, final String email) {
            this.accountId = new Range<Integer>(i,i)
            this.username = username;
            this.password = password;
            this.email = email;
        }

A: You could change your Range class to add a single parameter constructor:
public Range(T t) {
    min = t;
    max = t;
}

And call that constructor in a separate AccountConstraint constructor.

Incidentally, your Range class could benefit from some type bounding:
public class Range<T extends Comparable<T>> {
    public boolean contains(T value) {
        return value.compareTo(min) >= 0
          && value.compareTo(max) <= 0;
    }
    // rest of class the same
}


text:
Q: Weierstrass Preparation Theorem and meromorphic function Suppose $f:D \to \mathbb{C}$ is holomorphic in a domain $D \subset \mathbb{C}^n$, all of its partials extend continuously to $\bar{D}$ and $f$ is meromorphic in a neighborhood of $\bar{D}$.  Suppose $0 \in \partial D$.  In a small neighborhood of 0, why is
$$
f(z) = q(z) + \frac{\sum_{j=0}^{m-1}b_j(z')z_n^j}{z_n^m + \sum_{j=0}^{m-1}a_j(z')z_n^j}
$$
where $q$ is holomorphic, and the $a_j$'s and $b_j$'s are holomorphic functions of $z' = (z_1, ... z_{n-1})$ which vanish at $0' \in C^{n-1}$.
This result reminds me of the Weierstrass Preparation Theorem because the numerator and denominator have coefficients in $z'$ and vanish at 0'.


text:
Q: C# NET Core EF data fetch from database and check the data So im trying to contact the MySQL database to check if a player account exist and if so to fetch that data. But i have no idea how the MySQL functions works in NET Core (using pomelo mysql)
So far i have this:
public PlayerData Account
    {
        get
        {
            using (var db = new DataDbContext())
            {
                return db.Players.Include(x => x.PlayerName == this.PlayerName).SingleOrDefault();
            }
        }
    }

But i have no idea how to make on this a check to see if the account exist or not, and if it does to fetch the data
PlayerData class
PlayerData.cs
DataDbContext class DataDbContext.cs
(Added github links as i had troubles putting the code here)

A: You could adapt your code a bit to make it works
var player = db.Players.First(x => x.PlayerName == this.PlayerName);

if (player is null) {
    // Player does not exist
}


text: Q: Reading a sequence of handwritten numbers using Deep Networks with MNIST Data in R - Part1 Is it possible to read a sequence of numbers using Deep Networks trained with MNIST Data? For example the following number that I have written in Windows Paint:


text:
Q: Looking up through multiple points of similarity I have a GroupBy statement that I would like to add to. I have two tables that I am pulling from like so:
MU_Reports Table
Date      | Shift | Machine | MU
1/12/2016 |   1   |   12    | 44%
1/12/2016 |   2   |   12    | 34%
1/12/2016 |   2   |   12    | 34%
1/12/2016 |   3   |   12    | 54%
1/12/2016 |   3   |   13    | 24%

DownTime_Reports Table
Date      | Shift | Machine | DT Code  |  DT_Hours
1/12/2016 |   1   |   12    | No Work  |    3
1/12/2016 |   2   |   12    | No Resin |    2
1/12/2016 |   2   |   12    | No Op.   |    4
1/12/2016 |   3   |   12    | No Work  |    1
1/12/2016 |   3   |   13    | No Work  |    5
1/12/2016 |   3   |   12    | No Work  |    5

Example output:
Date      | Shift | Machine | MU   |  No_Work_Hours
1/12/2016 |   1   |   12    | 44%  |     3
1/12/2016 |   2   |   12    | 68%  |     0
1/12/2016 |   3   |   12    | 54%  |     6
1/12/2016 |   3   |   13    | 24%  |     5

my current GroupBy statement adds all No Work together in one shift (no matter date or machine):
using (var db = new ProductionContext())
{
    var query2 = from b in db.MU_Reports
                 join downtime in db.Downtime_Reports on new { b.Shift, b.Date, b.Machine_Number } equals new { downtime.Shift, downtime.Date, downtime.Machine_Number }
                 where downtime.DT_Code.Equals("No Work")
                 group downtime by new { b.Date, b.Shift, b.Machine, b.MU } into g
                 select new
                 {
                       Date = g.Key.Date,
                       Shift = g.Key.Shift,
                       Machine = g.Key.Machine,
                       MU = g.Key.MU,
                       NWTotal = g.Sum(x => x.No_Work_Hours)
                 };
}

As you can see in my example output what I want to do is to add all the No Work in the specific date, shift, and machine at the same time. So in other words I have to look through the Down_Time table to get the correct date then look through those dates to get the right shift then to get the correct machine to then get the right DT reason to get the amount of hours.
EDIT: I updated the code because I attempted to do multiple joins, however, now I do not output anything at all.

A: There are several ways to produce the desired output. All they require to first group the MU_Reports table by Date, Shift and Machine. Then you can for instance do group join the grouped subquery to the DownTime_Reports table by Date, Shift and Machine and perform the aggregates:
var query =
    from rg in db.MU_Reports.GroupBy(r => new { r.Date, r.Shift, r.Machine })
    join dt in db.Downtime_Reports
    on new { rg.Key.Date, rg.Key.Shift, rg.Key.Machine }
    equals new { dt.Date, dt.Shift, dt.Machine }
    into dtGroup
    select new
    {
        rg.Key.Date, rg.Key.Shift, rg.Key.Machine,
        MU = rg.Sum(r => r.MU),
        NWTotal = dtGroup.Where(dt => dt.DT_Code == "No Work").Sum(dt => dt.DT_Hours)
    };


text:
Q: Getting the right i18n while having multiple instances I have a module which contains a simple i18n configuration, similar to the following one:
var i18n = require("i18n");
module.exports = function(){
    i18n.configure({
        locales:['en', 'de'],
        directory: __dirname + '/locales'
    });
    i18n.translate = function(w){
       return i18n._(w);
    }
    return i18n;
}

My main class successfully uses this instance to make internationalization, but when I import this module in a new project which also has it's own i18n instance and locales, I'm noticing sometimes it makes the right translations, while others it's trying to get the translation from the wrong i18n file, resulting in the key saved as a new key/value pair in the wrong file and getting no translation.
How could I solve this issue? I know both instances doesn't have any key in common, so it would be great if I could have a way to keep always both locales available (tried the register: global but didn't work)


text:
Q: How to send a POST XHR request with FormData in the same format than when using a Submit button? I have a <form> that I normally send with a submit button:
<form action='/doit' method='post'>
<input type='text' name='ex1_q1' value='AAA'>
<input type='text' name='ex2_q1' value='BVB'>
<input type='submit' value='Go'>
</form>

This is working.
Every 10 seconds, I also want to (silently, in the background) send this <form> content with AJAX. However I noticed that when doing this:
setInterval(function() {
    var fd = new FormData(document.querySelector('form'));
    fd.append("dt", +new Date);
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "/doit");
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.send(fd);
}, 10 * 1000);

the data is sent indeed, but the server does not receive it the same format that when sending with the "Submit button".
More precisely:

*

*when sent with Ajax/XHR, the body is something like:
b'------WebKitFormBoundaryQb7yIKHLZODhAjqI\r\nContent-Disposition: form-data; name="ex1_q1"\r\n\r\nAAA\r\n------WebK

*when sent with the Submit button, I get:
b'ex1_q1=AAA&ex2_q1=BVB&accept=on&numero=1'

which is what I want in all cases
Question: with an XHR request, how to have the data sent with the same format than with a Submit button (case 2.)?

A: Depending on the enctype attribute, form data is submitted as either "application/x-www-form-urlencoded" or "multipart/form-data".
A FormData object will always encode data as "multipart/form-data".
If you want "application/x-www-form-urlencoded" then you should use a URLSearchParams object.


text:
Q: undefined environment vmatrix I am an absolute beginner in LaTeX... I am trying to learn it so that I can use it to ask question in websites.
I have faced the following problem...
I have learned some syntax which is used to describe the cross product from a course in Coursera.
It is written as follows
$$\mathbf{A}\times\mathbf{B}=
\begin{vmatrix}
\mathbf{i}&mathbf{j}&\mathbf{k}\\
a_1&a_2&a_3\\
b_a&b_2&b_3
\end{vmatrix}$$

and when I typed it in my Latex editor, it didn't work. However, when I posted it in Coursera it worked!!!
I wonder if the problem is due to the difference in software.
They use MathJax (I use an interpreter named MiKTeX, and an editor named TeXMaker).
I will upload an image of what happens in the editor.
Thank you.

A: vmatrix is defined in amsmath so add \usepackage{amsmath} before \begin{document}


text:
Q: Get element by data attribute using label and add disabled class here is my code here i want to disable the selective checkbox using get element by data attribute which is that "data-wapf-label" which I had in my webpage once my web page loads so i applied the disabled class but did not worked

$('.wapf-input[data-wapf-label="haribo strawberry"]').addClass('disabled');

  <input type="hidden" class="wapf-tf-h" data-fid="5fd25d21855fd" value="0" name="wapf[field_5fd25d21855fd][]">
  <input type="checkbox" name="wapf[field_5fd25d21855fd][]" class="wapf-input" data-field-id="5fd25d21855fd" value="kd4ik" data-wapf-label="Haribo Strawberry" data-is-required="" data-maxc="">
  Strawberry

  <input type="hidden" class="wapf-tf-h" data-fid="5fd25d21855fd" value="0" name="wapf[field_5fd25d21855fd][]">
  <input type="checkbox" name="wapf[field_5fd25d21855fd][]" class="wapf-input" data-field-id="5fd25d21855fd" value="kd4ik" data-wapf-label="Haribo Strawberry" data-is-required="" data-maxc="">
   Strawberr1

  <input type="hidden" class="wapf-tf-h" data-fid="5fd25d21855fd" value="0" name="wapf[field_5fd25d21855fd][]">
  <input type="checkbox" name="wapf[field_5fd25d21855fd][]" class="wapf-input" data-field-id="5fd25d21855fd" value="kd4ik" data-wapf-label="Haribo Strawberry" data-is-required="" data-maxc="">
  Haribo11

  <input type="hidden" class="wapf-tf-h" data-fid="5fd25d21855fd" value="0" name="wapf[field_5fd25d21855fd][]">
  <input type="checkbox" name="wapf[field_5fd25d21855fd][]" class="wapf-input" data-field-id="5fd25d21855fd" value="kd4ik" data-wapf-label="Haribo Strawberry" data-is-required="" data-maxc="">
  Haribo111

  <input type="hidden" class="wapf-tf-h" data-fid="5fd25d21855fd" value="0" name="wapf[field_5fd25d21855fd][]">
  <input type="checkbox" name="wapf[field_5fd25d21855fd][]" class="wapf-input" data-field-id="5fd25d21855fd" value="kd4ik" data-wapf-label="Haribo Strawberry" data-is-required="" data-maxc="">
  Haribo12

A: just an error on your selector:

*

*the string in data-wapf-label is cas sensitive, so adapt like in your html.
 $('input[data-wapf-label="Haribo Strawberry"]').addClass('disabled').prop('disabled', true);

if you add i  you'll have case insensitive:
    $('input[data-wapf-label="haribo strawberry" i]').addClass('disabled').prop('disabled', true);

$('input[data-wapf-label="haribo strawberry" i]').prop('disabled', true).
parent().closest('div').addClass("disabled");

$('div').each(function(){
   console.log($(this).attr("class"));
});

  <input type="hidden" class="wapf-tf-h" data-fid="5fd25d21855fd" value="0" name="wapf[field_5fd25d21855fd][]">
  <input type="checkbox" name="wapf[field_5fd25d21855fd][]" class="wapf-input" data-field-id="5fd25d21855fd" value="kd4ik" data-wapf-label="Haribo Strawberry" data-is-required="" data-maxc="">
  Strawberry

  <input type="hidden" class="wapf-tf-h" data-fid="5fd25d21855fd" value="0" name="wapf[field_5fd25d21855fd][]">
  <input type="checkbox" name="wapf[field_5fd25d21855fd][]" class="wapf-input" data-field-id="5fd25d21855fd" value="kd4ik" data-wapf-label="Haribo Strawberry" data-is-required="" data-maxc="">
   Strawberr1

  <input type="hidden" class="wapf-tf-h" data-fid="5fd25d21855fd" value="0" name="wapf[field_5fd25d21855fd][]">
  <input type="checkbox" name="wapf[field_5fd25d21855fd][]" class="wapf-input" data-field-id="5fd25d21855fd" value="kd4ik" data-wapf-label="Haribo Strawberry" data-is-required="" data-maxc="">
  Haribo11

  <input type="hidden" class="wapf-tf-h" data-fid="5fd25d21855fd" value="0" name="wapf[field_5fd25d21855fd][]">
  <input type="checkbox" name="wapf[field_5fd25d21855fd][]" class="wapf-input" data-field-id="5fd25d21855fd" value="kd4ik" data-wapf-label="Haribo Strawberry" data-is-required="" data-maxc="">
  Haribo111

  <input type="hidden" class="wapf-tf-h" data-fid="5fd25d21855fd" value="0" name="wapf[field_5fd25d21855fd][]">
  <input type="checkbox" name="wapf[field_5fd25d21855fd][]" class="wapf-input" data-field-id="5fd25d21855fd" value="kd4ik" data-wapf-label="Haribo Strawberry" data-is-required="" data-maxc="">
  Haribo12

A: let $selector = $('.wapf-swatch');
let $item = '.wapf-input';
$selector.each(function() {
    $(this).find($item).attr("data-wapf-label","haribo strawberry").prop('disabled', true);
});


text:
Q: No consigo acceder a las filas de mi tabla que creo de forma dinámica Por cada dato que me devuelve consultaIncidencias creo un tr en la tabla . Necesito coger los atributos del tr cuando hace doble click en la fila
Al hacer document.querySelectorAll("tbody tr") no me devuelve los tr que creo en procesarDatos
Este es mi código:
$(document).ready(function(){
            //Llamamos para recoger todas las incidencias y mostrarlas en pantalla
            $.get("consultaIncidencias", {}, procesarDatos);

            //ponemos a la escucha del doble click
            var filasTabla = document.querySelectorAll("tbody tr");

            alert("longitud-->" + filasTabla.length);
            //cogemos el ENDF del doble click
            for(var i=0 ; i<filasTabla.length; i++)
            {
                alert("doble clck");
                filasTabla[i].addEventListener("dblclick", cogerEdnf, false);
            }
            return false;
        });

        function cogerEdnf(e){
            alert("valor--> " + e.html() );
        }
        function procesarDatos(respuesta){
            $.each(respuesta.incidencias, function( index, value ) {

                $("#contenedor tbody").append ("
  " + value.fechaAlta + "	 " + value.titulo + "	  " + value.descripcion + "	 " + value.observaciones + "	 " + value.descripcion2 + "	  " + value.idEstados + "
" );
            });
        }

A: Me parece que tienes un problema es que $.get es asíncrono. La solución es mover ese codigo dentro de la otra función:
$(document).ready(function(){
            //Llamamos para recoger todas las incidencias y mostrarlas en pantalla
            $.get("consultaIncidencias", {}, procesarDatos);

            return false;
        });

        function cogerEdnf(e){
            alert("valor--> " + e.html() );
        }
        function procesarDatos(respuesta){
            $.each(respuesta.incidencias, function( index, value ) {

                $("#contenedor tbody").append ("
  " + value.fechaAlta + "	 " + value.titulo + "	  " + value.descripcion + "	 " + value.observaciones + "	 " + value.descripcion2 + "	  " + value.idEstados + "
" );
            });

//ponemos a la escucha del doble click
            var filasTabla = document.querySelectorAll("tbody tr");

            alert("longitud-->" + filasTabla.length);
            //cogemos el ENDF del doble click
            for(var i=0 ; i<filasTabla.length; i++)
            {
                alert("doble clck");
                filasTabla[i].addEventListener("dblclick", cogerEdnf, false);
            }
        }

Es algo ineficiente, porque haces 2 iteraciones la primera para crear la fila y la segunda para añadir el evento.
Esto a comentario personal, y porque lo he visto bastante, es que no hay motivos para no usar los eventos de las propiedades . Usando este método te ahorras (una iteración que no es poca cosa) y los típicos problemas de cuando vuelves a agregar filas en forma dinamica, las nuevas filas pueden quedar sin evento. Tampoco habrías tenido este problema. En muchas publicaciones que he leído señalan que las ventajas de addEventListener vs ocupar las propiedades son 3

*

*Permite asignar múltiples funciones al mismo evento

*Puedes eliminar el EventListner, aunque esto no es tan fácil y en rigor también lo puedes hacer con el otro método

*y tienes el useCapture que te permite cambiar el orden de ejecución del tren de eventos (este quizás es el mejor motivo)

Ahora si se piensa bien el 90% de las veces o más, nunca necesitamos algunos de esos motivos. Como quedaría tu coódigo
$(document).ready(function(){
            //Llamamos para recoger todas las incidencias y mostrarlas en pantalla
            $.get("consultaIncidencias", {}, procesarDatos);
        });

        function cogerEdnf(e){
            alert("valor--> " + e.html() );
        }
        function procesarDatos(respuesta){
            $.each(respuesta.incidencias, function( index, value ) {

               $("#contenedor tbody").append(`

                 ${value.fechaAlta}
                 ${value.titulo}
                 ${value.descripcion}
                 ${value.observaciones}
                 ${value.descripcion2}
                 ${value.idEstados}

` );
            });
        }


text:
Q: Hide dates after maximum / before minimum in UIDatePicker I have a UIDatePicker with a minimumDate and maximumDate set. The default UI of the date picker shows all dates, including those before the minimum and after the maximum. If the user spins to an out-of-bounds date, the picker does spin back - but this is not a great user experience. Can I make it so that the picker simply doesn't display out-of-bounds dates?
In my case, this is particularly important because my app deals with historic events. The date picker starts at the current date and allows users to spin back in time. It's faintly ridiculous in this situation to show tomorrow's date below the current date.


text:
Q: Is implementing an array class using ctypes more efficient than using lists? Is implementing an array class using ctypes more efficient than using lists?
Implementation

A: As Ctypes are deterministic, you'll definitely meet some improvements.  But I think more than that, it highly depends on your application. What do you want to do with the List?
For example, if you are performing a simple search, then python's own functions and libraries will probably suffice (as they are written in C/C++).
For matrices and algebra-related types of work, you are better off using NumPy as it is highly efficient (comparable to C++ libraries such as Eigen).
Any other calculation-related work, implementing it with Ctype will definitely bring you some performance.


text:
Q: How to post Javascript array to C# list of tuples ? I was wondering if anyone knew how to pass a Javascript array of objects to a MVC action method accepting an array of tuples.
Example:
The Javascript:
var objectArray =
[
    { id: 1, value: "one" },
    { id: 2, value: "two" }
];

$.post('test',objectArray);

The MVC controller action:
public JsonResult Test((int id, string value)[] objectArray)
{
    return Json(objectArray != null);
}

Unfortunately the example I've given always returns false as the objectArray in the C# code is null.

A: You cannot do this because like the error says: a tuple has no parameterless constructor, so the model binder can't instantiate it.
Also, you can read more about Model Binding.
One of the phrases said this:

In order for binding to happen the class must have a public default
  constructor and member to be bound must be public writable properties.
  When model binding happens the class will only be instantiated using
  the public default constructor, then the properties can be set.

You can use another approach:
First of all, you have to send the given array using JSON.stringify method.
JSON.stringify() turns a javascript object to json text and stores it in a string.
AJAX
objectArray = JSON.stringify({ 'objectArray': objectArray });
$.ajax({
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    type: 'POST',
    url: 'test',
    data: objectArray ,
    success: function () {

    }
});

In your server-side method you have to pass a list of objects as parameter.
[HttpPost]
public void PassThings(List<Thing> objectArray )
{

}

public class Thing
{
    public int Id { get; set; }
    public string Value { get; set; }
}


text:
Q: How to check solver convergence with GEKKO and APOPT I am dealing with small MILP problems for which I have fixed the maximum number of iterations. I would like to determine the instances for which we are sure that we have reached the optimum.
When calling m.solve(disp=True), if the solver stops early, it displays the warning:

Warning: reached maximum MINLP iterations, returning best solution

I would like to check programmatically whether we are in such a situation. I tried
1) looking at the documentation but it says m.options.SOLVESTATUS is always 1 and m.options.APPINFO is always 0 from the moment the solver found a feasible solution.
2)
optimum = m.options.ITERATIONS < m.options.MAX_ITER
but it does not work because in fact m.options.ITERATIONS doesn't do what I thought (it is always much lower than m.options.MAX_ITER).
3) raise and then catch the warning:
import warnings
warnings.filterwarnings("error")

try:
    self.model.solve()
    optimum = True
except:
    optimum = False

But it doesn't work either (no error is raised).

So I have 2 questions:
1) How to check the number of iterations that have been used by the solver ?
2) How to determine whether the solver did check every candidate and thus found the best instanciation ?

A: Right now, there is no way to report the number of Mixed Integer iterations from APOPT. However, you can ensure that APOPT never stops prematurely by setting minlp_maximum_iterations to a large value such as 100000. The m.options.ITERATIONS reports the NLP iterations of the last branch evaluation.
You can ensure that all candidate solutions are evaluated by setting minlp_gap_tol to zero. The solver will terminate if the gap tolerance condition is met. Setting it to zero means that all options will be evaluated. However, this can take much longer to evaluate all options.
from gekko import GEKKO
m = GEKKO(remote=False) # Initialize gekko
m.options.SOLVER=1  # APOPT is an MINLP solver

# optional solver settings with APOPT
m.solver_options = ['minlp_maximum_iterations 100000', \
                    # minlp iterations with integer solution
                    'minlp_max_iter_with_int_sol 10', \
                    # nlp sub-problem max iterations
                    'nlp_maximum_iterations 50', \
                    # covergence tolerance
                    'minlp_gap_tol 0.00']

# Initialize variables
x1 = m.Var(value=1,lb=1,ub=5)
x2 = m.Var(value=5,lb=1,ub=5)
# Integer constraints for x3 and x4
x3 = m.Var(value=5,lb=1,ub=5,integer=True)
x4 = m.Var(value=1,lb=1,ub=5,integer=True)
# Equations
m.Equation(x1*x2*x3*x4>=25)
m.Equation(x1**2+x2**2+x3**2+x4**2==40)
m.Obj(x1*x4*(x1+x2+x3)+x3) # Objective
m.solve(disp=True) # Solve
print('Results')
print('Iterations: ' + str(m.options.ITERATIONS))
print('x1: ' + str(x1.value))
print('x2: ' + str(x2.value))
print('x3: ' + str(x3.value))
print('x4: ' + str(x4.value))
print('Objective: ' + str(m.options.objfcnval))

There is more information on solver options.

A: From John Hedengren's answer :
1) How to check the number of iterations that have been used by the solver ?

Right now, there is no way to report the number of Mixed Integer iterations from APOPT

2) How to determine whether the solver did check every candidate and thus found the best instanciation ?

I added this as a feature request on Github: github.com/BYU-PRISM/GEKKO/issues/81

For now I have implemented an ugly solution :
# redirect stdout
sys.stdout = open('tmp_output', 'w')

# solve and output to the tmp file
try:
    self.model.solve(disp=True)
except:
    pass #solution not found

# read the file
with open('tmp_output', 'r') as f:
    line = f.readline()

    # skip the first lines
    while line[:5] != "Iter:":
        line = f.readline()

    # skip the next lines (one line per iteration)
    while line[:5] in ["Iter:", "--Int"]:
        line = f.readline()

    # check the warning
    optimal = line != " Warning: reached maximum MINLP iterations, returning best solution\n"

return optimal


text:
Q: How to achieve simple OOP in Solidity? Code:
contract A
{
    uint public foo;

    function A(uint _foo)
    {
        foo = _foo;
    }
}

contract B
{
    uint bar;

    function B()
    {
        A a = new A(42);
        bar = a.foo;
    }
}

Compile Error
Test:18:15: Error: Type function () returns (uint256) is not implicitly convertible to expected type uint256.
        bar = a.foo;
              ^---^

How can I read public variables of a contract in another?

A: contract A
{
    uint public foo;

    function A(uint _foo)
    {
        foo = _foo;
    }
}

contract B
{
    uint bar;

    function B()
    {
        A a = new A(42);
        bar = a.foo();
    }
}

bar = a.foo(); instead of bar = a.foo; ...


text:
Q: Uploading gallery images using filesystem in Entity Framework I want to upload gallery images to ASP.NET MVC 5 application using filesystem upload. I added
public IEnumerable<string> GalleryImages { get; set; }

to my ProductModel, built solution and performed update-database in the package manager console. But, the property is not added to the Product table and when I try to add and then edit a product, I get this error:

System.ArgumentNullException: 'Value cannot be null.
  Parameter name: source'

Also, I added this piece of code to Edit.cshtl:
@if (!Model.GalleryImages.Any())
{

There are no gallery images for this product.

}

<form action="/AdminPanel/Product/SaveGalleryImages" method="post" enctype="multipart/form-data" class="dropzone" id="dropzoneForm">

        <input type="file" name="file" multiple />
        <input type="submit" value="Upload" />

</form>

@foreach (var image in Model.GalleryImages)
{

        @Html.ActionLink("delete", "DeleteImage", "Product", new { @class = "deleteimage", data_name = image })

}
<link href="~/Scripts/dropzone/basic.css" rel="stylesheet" />
<link href="~/Scripts/dropzone/dropzone.css" rel="stylesheet" />

@section Scripts{

}

A: UPDATE:
What exactly do you expect as a column datatype when you model it as List<string>? SQL Server doesn't have any column data type to handle an arbitrary list of strings....
If you have an 1:n relationship between ProductModel and gallery images, you should really have a separate model class that holds the image information - e.g. MyImages. Then you could add a collection-style property
public virtual ICollection<MyImages> GalleryImages

to your ProductModel class.
SQL Server can't really handle List<string> as a column type .....

The steps needed to get this done are:

*

*Change your C# model class (you've done this already)

*Run add-migration migration-name so that an EF migration is added to your project (you seem to have skipped this step)

*Run update-database to actually apply that migration to the database.

Only if you've completed ALL 3 steps in exactly this order are changes from your C# model class actually applied to the database - you CANNOT simply skip step #2 ....


text:
Q: C++ How to create a std::unique_ptr from a class that takes parameters on constructor I need to create a std::unique_ptr from a class that has a constructor that takes one parameter. I can´t find references on how to do it. Here is the code example that cannot compile:
#include <iostream>
#include <string>
#include <sstream>
#include <memory>

class MyClass {

    public:
        MyClass(std::string name);
        virtual ~MyClass();

    private:
        std::string myName;
};

MyClass::MyClass(std::string name) : myName(name) {}
MyClass::~MyClass() {}

class OtherClass {

    public:
        OtherClass();
        virtual ~OtherClass();

        void MyFunction(std::string data);

        std::unique_ptr<MyClass> theClassPtr;
};

OtherClass::OtherClass() {}
OtherClass::~OtherClass() {}

void OtherClass::MyFunction(std::string data)
{
    std::unique_ptr<MyClass> test(data); <---------- PROBLEM HERE!
    theClassPtr = std::move(test);
}

int main()
{
    OtherClass test;
    test.MyFunction("This is a test");
}

The errors are related to the way I´m initializing the std::unique_ptr, pointed out in my code.
The original code and the errors can be found here.
Thanks for helping me to solve that.

A: You can do:
std::unique_ptr<MyClass> test(new MyClass(data));

Or if you have C++14
auto test = std::make_unique<MyClass>(data);

But:
In the provided example there is no need to create a temporary variable, you can just use the reset method of the class member:
theClassPtr.reset(new MyClass(data));

A: #include <memory>
...

int main()
{
    std::string testString{ "Testing 1...2....3" };
    auto test = std::make_unique<MyClass>( testString );
    return 0;
}

A: It's basically an oversight. You need this:
#include <memory>

namespace std
{

    template <class T, class... Args>
    std::unique_ptr <T> make_unique (Args&&... args)
    {
        return std::unique_ptr <T> (new T (std::forward <Args> (args)...));
    }
}

A: C++14 comes with std::make_unique.  It was omitted from C++11.
Writing it yourself is easy:
namespace notstd{
  template<class T,class...Args>
  std::unique_ptr<T> make_unique(Args&&...args){
    return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  }
}

now use it like this:
auto foo = notstd::make_unique<MyClass>(string);

will make your unique ptr for you.
This pattern has a few advantages.  First, it removes a new that is not paired with a delete from "user code", which makes me happy.
Second, if you call a function that takes 2 unque ptrs, ths above can avoid leaks in case of exceptions being thrown.
We put this in notstd as injecting new functions into std is illegal inder the standard (no diagnostic required).


text: Q: Запаковка программы в исполняемый файл exe У меня есть cmd скрипт для работы моего php кода из консоли.В этой же папке находится файл конфига и папка с php интерпретатором для, собственно, работы самого скрипта в винде из консоли без установки php на машину.Как мне можно все это добро запаковать в единый exe файл, чтобы его можно было вызывать из консоли с заданием параметров и они бы пересылались на скрипт?


text:
Q: CSS/JS Slider issue with loop I have an issue with CSS/JS slider.
I've used simple method to make it work - bigger element (container) inside smaller (area) with hidden overflow.
I have buttons above slider btn & btn2 to control movement of bigger element (containter)
The issue is that it only work until the "first slide" (blue) is reached, then its not possible to slide to second one (red).
Fiddle: https://jsfiddle.net/26r32hb6

var button = document.querySelector('.btn');
var button2 = document.querySelector('.btn2');
var container = document.querySelector('.container');

button.style.background = 'blue';
button2.style.background = 'blue';
container.style.backgroundColor = 'blue';

button.onclick = function() {
   if (container.style.left == 0) {
     container.style.left = '-100.5%';
     container.style.backgroundColor = 'red';
     button.style.backgroundColor = 'red';
     button2.style.backgroundColor = 'red';}
else if (container.style.left == '-100.5%') {
  container.style.left = '-200.5%';
  container.style.backgroundColor = 'purple';
  button.style.backgroundColor = 'purple';
  button2.style.backgroundColor = 'purple';
}
};
button2.onclick = function() {
  if (container.style.left == '-100.5%') {
    container.style.left = 0;
    container.style.backgroundColor = 'blue';
    button.style.backgroundColor = 'blue';
    button2.style.backgroundColor = 'blue';}
  else if (container.style.left == '-200.5%') {
    container.style.left = '-100.5%';
    container.style.backgroundColor = 'red';
    button.style.backgroundColor = 'red';
    button2.style.backgroundColor = 'red';
}
};
.wrapbtns {
  width: 365px;
  height: 50px;
  background: yellow;
}
.btn {
  width: 50px;
  height: 50px;
   float: right;
}
.btn2 {
  width: 50px;
  height: 50px;
  float: left;
  margin-right: 5px;
}
.btn, .btn2 {
  transition-duration: 1s;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  cursor: pointer;

}
.area {
  width: 365px;
  height: 250px;
  overflow: hidden; /* This */
  position: relative;
}
.container {
  background: blue;
  width: 1100px;
  height: 250px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: left;
  align-items: center;
  left: 0;
  position: absolute;
  transition-duration: 1s;
}
.box {
  background: yellow;
  min-width: 100px;
  height: 100px;
  margin: 1%;
  display: flex;
  justify-content: center;
  align-items: center;
  color: black;
  font-size: 48px;
  transition-duration: 500ms;
}

-X

X

a

b

c

d

e

f

g

h

i

j

k

l

m

n

o

p

q

r

A: First of all, all this can be much easier if you use something like jQuery.
but assuming that you only want to do this using javascript, here is my solution:
(Note: even if you use jQuery, the technique is quite similar to the one explained below)
FIDDLE: https://jsfiddle.net/Bintang/kvowcj6w/
var button = document.querySelector('.btn');
var button2 = document.querySelector('.btn2');
var container = document.querySelector('.container');
var area = document.querySelector('.area');

button.style.background = 'blue';
button2.style.background = 'blue';
container.style.backgroundColor = 'blue';

var slideCurrent = 0;
var slideTotal = Math.floor(container.offsetWidth / area.offsetWidth);
var slideWidth = area.offsetWidth;
var slideColors = ['blue', 'red', 'purple'];

button.onclick = function() {

  if (slideCurrent < slideTotal - 1) {
    var left = container.style.left;
    var leftInInteger = parseInt(left.replace("px", "")) || 0;
    container.style.left = (leftInInteger - slideWidth) + "px"
    slideCurrent += 1;

    //STYLING
    container.style.backgroundColor = slideColors[slideCurrent];
    button.style.backgroundColor = slideColors[slideCurrent];
    button2.style.backgroundColor = slideColors[slideCurrent];
  }

};
button2.onclick = function() {

  if (slideCurrent > 0) {
    var left = container.style.left;
    var leftInInteger = parseInt(left.replace("px", "")) || 0;
    container.style.left = (leftInInteger + slideWidth) + "px";
    slideCurrent -= 1;

    //STYLING
    container.style.backgroundColor = slideColors[slideCurrent];
    button.style.backgroundColor = slideColors[slideCurrent];
    button2.style.backgroundColor = slideColors[slideCurrent];
  }

};

Explanation:
instead of using if & else to set the specific value of "left" every single time you want to slide, what you want to do is increment the value of "left" every time you want to slide to the left & decrement the value every time you want to slide to the right. (look at the code below)
var slideCurrent = 0;
var slideTotal = Math.floor(container.offsetWidth / area.offsetWidth);
var slideWidth = area.offsetWidth;
var slideColors = ['blue', 'red', 'purple'];

button.onclick = function() {

  if (slideCurrent < slideTotal - 1) {
    var left = container.style.left;
    var leftInInteger = parseInt(left.replace("px", "")) || 0;
    container.style.left = (leftInInteger - slideWidth) + "px"
    slideCurrent += 1;

    //STYLING
    container.style.backgroundColor = slideColors[slideCurrent];
    button.style.backgroundColor = slideColors[slideCurrent];
    button2.style.backgroundColor = slideColors[slideCurrent];
  }

};

What the code above do is:
1.Every time the button is clicked it will check if the current slide is the last slide
if (slideCurrent < slideTotal - 1) {

2.if it's not the last slide it will get the current "left" value of the       "container" then it will remove the "px" and turn it from string into an
integer(using the parseInt() function), but if the "left" property hasn't been defined it will be replaced with the value of "0"
var left = container.style.left;
var leftInInteger = parseInt(left.replace("px", "")) || 0;

3.Now that it had the current value of "left" in integer it can decrement the value by the width of the "area"(the smaller element on top) so it will slide to the right and increment the slideCurrent variable by one
container.style.left = (leftInInteger - slideWidth) + "px"
slideCurrent += 1;

4.Lastly, it will set the color of the "container" to the specified color
//STYLING
container.style.backgroundColor = slideColors[slideCurrent];
button.style.backgroundColor = slideColors[slideCurrent];
button2.style.backgroundColor = slideColors[slideCurrent];

Then you can do the opposite to slide to the other direction.


text:
Q: Which lambda is cv.glmnet solving for? This is my understanding of glmnet:
if OLS is minimizing RSS, where
$ RSS = \sum(y-\beta x)^2 $
I believe glmnet is minimizing:
$ RSS - \sum(\alpha |\beta_j| + (1-\alpha) \beta_j^2) $
where $\alpha=\lambda_1/(\lambda_1+\lambda_2) $
$\lambda_1$ and $\lambda_2$ come from lasso and ridge regression, but I'm confused if $\lambda_1 = \lambda_2 $ such that cv.glmnet in glmnet package of R is solving for a single variable (along the whole path) $\lambda$? But then $\alpha = 0.5$ always.
If $\lambda_1 = \lambda_2 $, is the glmnet penalty equivalent to $RSS - \lambda |\beta| - \lambda \beta^2 $
I've read through Hastie et al. 2009 Elements of Statistical Learning and Zou and Hastie 2005 so now I'm trying to get some clarification on the lambdas and alpha. Thanks
EDIT:
I found this to be a useful formulation in Friedman et al (2010) Regularization Paths for Generalized Linear Models via Coordinate Descent.
$$
1/2N * \sum (y_i - \beta_0 - X\beta)^2 + \lambda P_\alpha (\beta)
$$
where
$$
P_\alpha (\beta) = \sum (1/2 (1-\alpha) \beta_j^2 + \alpha |\beta_j|)
$$
I thought it provided some intuition how lambda and alpha exist together.

A: $\alpha=\frac{\lambda_1}{\lambda_1+\lambda_2} \text{and } 1-\alpha=\frac{\lambda_2}{\lambda_1+\lambda_2}$. And  because $\lambda_i\ge0,$ it should be clear that $\alpha\in[0,1].$ So in glmnet, $\lambda=\lambda_1+\lambda_2$, and each penalty has a coefficient that is either $\alpha(\lambda_1+\lambda_2)$ or $(1-\alpha)(\lambda_1+\lambda_2)$.
But treating $\alpha$ independently of $\lambda_1, \lambda_2$ is convenient as a conceptual model because it controls how much of a ridge and lasso penalty is applied, with either extreme arising as a special case. And you can make a model "more lasso" or "more ridge" by adjusting $\alpha$ without having to worry about how to adjust $\lambda_i$ relative to the size of $\lambda_j, j\neq i$. That is, treated separately, $\alpha$ controls the range of elastic net compositions on a continuum of ridge to lasso, while $\lambda$ controls the overall magnitude of the penalty. The two can be thought of as distinct model hyper-parameters. The method with two lambdas links the two penalties.
And if both $\lambda_1$ and $\lambda_2$ are 0, that should correspond to no penalty, but the fraction $\frac{\lambda_1}{\lambda_1+\lambda_2}=\frac{0}{0}$ is unsightly and indeterminate.

A: Just to add: From the help file of glmnet, we read:
Note that cv.glmnet does NOT search for values for alpha. A specific value should be supplied, else alpha=1 is assumed by default. If users would like to cross-validate alpha as well, they should call cv.glmnet with a pre-computed vector foldid, and then use this same fold vector in separate calls to cv.glmnet with different values of alpha
This shows that glmnet doesn't cross validate over $\alpha$, so that the cross validation is just one-dimensional, as I think you suspect.


text:
Q: Disable certain records while fetching records from a database table in Android Im working with SQLite db in android and am stuck making a particular query:
I have a Table 1 with some email ids and I have another Table 2 with email ids and the usernames corresponding to those ids. From Table 2 I need to send only those emailid/usernames which are not present in Table 1. I want to do this using Cursor in android, something like:
Cursor cursor = getReadableDatabase().query(
                MY_TABLE,
                new String[] {ID},
                EMAIL_ID +" = ?",
                new String[]{email_id},
                null,
                null,
                null);

The prerequisites are:
I don't want to use delete from Table 2
I don't want to create extra column in Table 2.

A: Use NOT IN with a subselect to filter out results in your query. For example:
SELECT emailid,username FROM table2 WHERE emailid NOT IN (SELECT emailid FROM table1)

Use rawQuery() for performing such raw SQL queries instead of query() which builds the SQL for you.
Example:
sqlite> create table table2(emailid,username);
sqlite> create table table1(emailid);
sqlite> insert into table1 select 'a@b.c';
sqlite> insert into table1 select 'a@b.c.d';
sqlite> insert into table2 select 'a@b.c.d','abcd';
sqlite> insert into table2 select 'a@b.c.d.e','abcde';
sqlite> SELECT emailid,username FROM table2 WHERE emailid NOT IN (SELECT emailid FROM table1);
a@b.c.d.e|abcde

Since @m0skit0 is insistent in his comments, let's demonstrate his query with the same data:
sqlite> SELECT t2.emailid, t2.username FROM table1 t1, table2 t2 WHERE t1.emailid <> t2.emailid;
a@b.c.d|abcd
a@b.c.d.e|abcde
a@b.c.d.e|abcde

A: You just need to join both tables over emailid and username field.
SELECT t2.emailid, t2.username FROM table1 t1, table1 t1a, table2 t2 WHERE t1.emailid <> t2.emailid AND t1a.username <> t2.username

This will get you all rows in table2 whose emailid or username does not exist in table1.
Also you need to use rawQuery method instead if more than one table in your SQL query:
private static final String QUERY = "SELECT t2.emailid, t2.username FROM table1 t1, table2 t2 WHERE t1.emailid <> t2.emailid AND t1.username <> t2.usernam";
final Cursor cursor = getReadableDatabase().rawQuery(QUERY, new String[0]);


text:
Q: Should Grad-Cam attributions be greater than 1? I'm using the captum library to calculate LayerGradCam.
layer_gc = LayerGradCam(model, model.layer4)
attr = layer_gc.attribute(x, class_idx, relu_attributions=True)

Some values in attr have values greater than 1. Is this supposed to be the case?
If it is, then is it valid to minmax normalize the attributions in a batch?
I'm using these attributions to calculate Dice loss using pixel maps where the max value is 1. So when the attributions are greater than 1, Dice loss becomes negative, which is not valid.
So,
Question 1: Are the attributions supposed to be going over 1 or am I doing something wrong?
Question 2: If they're supposed to go over 1, is it valid to normalize the them per batch?


text:
Q: Show that $\lim_{z\to\infty}|\sum_{k=1}^n p_k(z)e^{\lambda_k z}|=0$ iff $\Re(\lambda_k)<0$
I want to show that that $$\lim_{z\to\infty}|\sum_{k=1}^n p_k(z)e^{\lambda_k z}|=0$$ iff $\Re(\lambda_k)<0$ for all $k=1,\dots,n$ where $p_k\in\mathbb C[z]\backslash \{0\}$ and $\lambda_k\in\mathbb C$ with pairwise different real parts.

My thoughts so far:
At first I considered the individual summands: For $z=x+iy$ we have $$|p(z)e^{\lambda z}|=|p(z)||e^{\Re(\lambda)\cdot x-\Im(\lambda)\cdot y}|\cdot\underbrace{|e^{i(\Re(\lambda)\cdot y+\Im(\lambda)\cdot x)}|}_{=1},$$so $$|p(z)e^{\lambda z}|=|p(z)|\frac{e^{\Re(\lambda)\cdot x}}{e^{\Im(\lambda)\cdot y}}.$$ Now, is there a way I can finish this argument to obtain that $\lim_{z\to 0}|p(z)e^{\lambda z}|=0$ iff $\Re(\lambda)<0$? And if so, can I then say that $$|\sum_{k=1}^n p_k(z)e^{\lambda_k z}|\leq\sum_{k=1}^n|p(z)e^{\lambda_k z}|\to 0$$ iff $\lambda_k <0$ for all $k=1,\dots,n$? What confuses me is that for some reason it is necessary that the $\lambda_k$ must have pairwise different real parts.

A: This is not true. Take $n=1 , p_1 (z) =1 , \lambda_1 = -1 .$ Let $z_m = im , m\in \mathbb{N} .$
Then $z_m \to \infty$ but $$\left|\sum_{k=1}^1 p_1 (z_m ) e^{\lambda_k z_k} \right| = |e^{-ik} | =1$$


text:
Q: I'm having trouble structuring data from a calendar The data is an array which contains the days and events alternating by week, so:
[1,2,3,4,5,'','','','green event','blue event','red event',8,9,10,11,12,'red event','white event','','','']
As you can see, sometimes there are more events per day, the events in the array wrap back to the first event
Which means day 1,2 and 3 have no events, day 4 has green and red, day five has blue.
I've been going at this for 8 hours straight.
here's my current code:

// holds the current event in the loop
let eventCount = 0;
// a count that resets every time the event count is longer than the amount of days in a week
// the idea was to combine the same realevents as they have the same number if they're on the    // same day
let realEventCount = 0;
// array to contain all the dates
let trashdays = [];
// array to contain all the events
let trashEvents = [];
// chunks are meant to split the events by week
let newChunk = true;
let chunk = 0;

let data = [1, 2, 3, 4, 5, '', '', '', 'green event', 'blue event', 'red event', 8, 9, 10, 11, 12, 'red event', 'white event', '', '', '']

for (let i = 0; i < data.length; i++) {

  // if the data is a date
  if (!isNaN(data[i]) && data[i] !== '') {
    trashdays.push(data[i]);

    if (newChunk) {
      chunk++;
      // reset reid when new chunk
      realEventCount = 0;
      newChunk = false;
    }
  } else {
    // every time data alternates from events to date numbers it becomes a new chunk
    newChunk = true;
  }

  // if data is an event or what passes as an empty event
  if (isNaN(data[i]) || data[i] === '') {
    trashEvents[eventCount] = {
      id: undefined,
      chunk: undefined,
      data: '',
      reid: undefined,
      day: undefined,
    };
    trashEvents[eventCount].id = eventCount;
    trashEvents[eventCount].data = data[i];
    trashEvents[eventCount].chunk = chunk;

    // this thing was for when it isn't an empty event, i'm probably wrong with the math
    // stuff, but it's trying to figure out how to know when the events wrap back
    if (isNaN(data[i])) {
      if (Math.floor(trashEvents[eventCount].id / trashEvents[eventCount].chunk) > 4) {
        // reset reid when the event is offset
        realEventCount = 0;
      }
      trashEvents[eventCount].reid = realEventCount;
      realEventCount++;
    }

    eventCount++;
  }
}

console.log(trashEvents)


text:
Q: Prestashop 1.7 show category only to admin I'm trying to find a way to preview a category page on PS 1.7 only to admin. I want to hide it from users in the menu and via the URL but be able to preview it as I'm connected as an admin.
Any idea ? Thank you

A: The best is to create a customer group "TEST" and assign you a customer account in this group, as well as assign the customer group to the category.
So only you will see the category.


text:
Q: I can only hear my xbox 360 audio not see the picture Whenever I turn my Xbox 360 on I can hear everything, but I can't see anything. I've tried adjusting the AV cables and I've tried everything everyone says, but it still doesn't work. Is it completely broken?

A: Turn on the Xbox using a plug & play while holding "Left trigger + Y" This resets your display settings.
Also check the hdmi switch on the display cable, set it to tv not hdmi.


text:
Q: Register in Constructor (over inheritance), after copy-constructor no longer accessible I'm supposed to program a game in C++ and OpenGL. I tried to structure it after Unity, so I have Gameobjects that inherit the Components they need. My problem is my renderer. This component contains a shape, Vao, Vbo and a Color. In this constructor I am trying to register the object in my GameView
LineRenderer::LineRenderer(){
    shape = { 1.0,1.0,0.0,
        1.0,0.0,0.0,
        0.0,0.0,0.0,
        0.0,1.0,0.0 };
    InitializeVertexArrayObject(&VAO, &VBO, shape);
    GameView::add(this);
}

The GameView has a static vector as member:
static std::vector<LineRenderer*> items;

And the add function just adds the pointer to the vector:
void GameView::add(LineRenderer* item){
    items.push_back(item);
}

Now, obviously, this is not working because every time I want to render the objects in the GameView they no longer exists. Google says this has something to do with the Copy Constructor and it seems the way I want to do this is not possible.
The Question is, is it even possible to inherit from a class that registers itself somewhere else (if the Object is always copied into the variable it's assigned to)? And, if not, what would be the best way to implement behaviour similar to this?

A: Unless your copying the object itself, copying pointers wont affect the constructor after you create it. The vector will just copy/ move it in. Lets say that your creating the LineRenderer like below,
void SomeFunction()
{
    ...
    LineRenderer* pRenderer = new LineRenderer();    // The constructor will be called here.
    ...
    delete pRenderer;    // The destructor will be called here.
}

Now, obviously this is not working because every time I want to render the objects in the GameView they no longer exists.

Yes, if your allocating them in the stack. Use heap allocation as I said before and things will work out.
Note: If you allocate something in the heap, make sure to delete it!

is it even possible to inherit from a Class that registers itself somewhere else (If the Object is always copied into the variable its assigned to)?

In your case, yes, you can. And your working with pointers here, so your not copying the object itself, your just copying the address of it.

And if not what would be the best way to implement behavior similar to this?

As you stated before, if you want your game to work like unity, your approach is somewhat different. Unity uses Entity Component System while you use the same thing which unity tries to work around. But looking at your implementation, what you need is to avoid static allocating those objects, rather than that allocate them in the heap. Remember, you'll have to manage its life time then!


text:
Q: git fails to add files that have root only permissions I am sitting on a cross development chair and created a JFFS2 file system to be used on the target.
Inside that tree are several directories and files that have root permissions only.
When I git add this tree I get
error: Unable to index file [file with problem]
fatal: adding files failed
I don't want to run git commands as root
And I don't want root priviledge needed on checkouts
How can I add this tree?
Thanx

A: Git is good, but git is not capable of reading files it is not allowed to read.  You have conflicting requirements - root-only access to the files but not running git as root.
You will have to change one of the two requirements.  I recommend changing the permissions on the files.


text:
Q: Vim function to sort by lines by tags I'm trying to create a custom function in gVim to sort lines based on a tag and I'm a bit out of my depth. The goal is for me to create a custom function in my _gvimrc so I can resort like this quickly and as necessary. I need some pointers as to where to study.
My goal is to group lines by a tag at the start of the line
file contents 1
:a some text
:b some other text
:a more text
:b more other text
:c final text
file contents 2

will become
:a
some text
more text
:b
some other text
more other text
:c
final text

file contents 1
file contents 2

The challenge is largely that I don't want to mess with the other lines in the file - those which have no tags. the :sort function will reorder all of those.
I have a feeling I will need to:
1. yank all the lines with tags into a register, and delete them (some kind of :g/pattern/yank register ?)
2. put them all at the beginning of the file (some kind of :g/pattern/put register ?)
3. sort the block by the tags (some kind of :sort r /pattern/ ?)
4. iterate over each tag to reformat from
:a text
:a text
:a text

to
:a
text
text
text

I'm not proficient enough in gVim to know where to really start - if anyone here is expert enough to assist with one of these sub-problems, so to speak, or has a better idea for the methodology, I'd really appreciate it. I'm particularly stymied on number 4.
If this isn't the kind of thing gVim is capable of, please let me know, but I have a feeling this is quite possible and just out of my pay grade.

A: I think awk or some higher language would fit this better. Example using awk and Vim's filter, %!:
:%!awk '$1 ~ /^:/ { a[$1] = a[$1] substr($0, 3) "\n"; next} {r = r $0 "\n"} END { asorti(a, keys); for (k in keys) { print keys[k]; print a[keys[k]] } print ""; print r}'

Prettier version:
$1 ~ /^:/ {
    a[$1] = a[$1] substr($0, 3) "\n";
    next
}

{
    r = r $0 "\n"
}

END {
    asorti(a, keys);
    for (k in keys) {
        print keys[k];
        print a[keys[k]]
    }
    print "";
    print r
}

Note: I use gawk


text:
Q: Unhandled error TypeError: snapshot.val is not a function when using forEach Firebase Cloud Functions I'm writing a Firebase Cloud Function, with an HTTPS trigger, and I am starting more that one read operation at once using Promise.all(arrayOfPromises), when all of the promises are fulfilled the then(snapshotContainsArrayOfSnapshots) method gets triggered, and I try to iterate the snapshotContainsArrayOfSnapshots with forEach(snapshot) method, but I get this Error:
Unhandled error TypeError: snapshot.val is not a function

Here is the code:
    f
let promisesArray = []
for(let i = 0; i < 10; i++){
    const promise = db.ref(`/questions/en/${i}`)
    promisesArray.push(promise)
}
return Promise.all(promisesArray)
    .then((snapshotContainsArrayOfSnapshots) => {
        let data = []
        snapshotContainsArrayOfSnapshots.forEach((snapshot) => {
            data.push(snapshot.val())
        })
        return JSON.stringify(data)
    })

Remember: This ISN'T an onWrite trigger so I dont need to call change.after.

A: What you are adding to the promisesArray are References, see doc here
For each of your references, you should query the data at the reference with the once() method (doc here) and it is the promise returned by this method that you need to add to your promisesArray.
So do as follows:
let promisesArray = []
for(let i = 0; i < 10; i++){
    const promise = db.ref(`/questions/en/${i}`).once('value');
    promisesArray.push(promise)
}
return Promise.all(promisesArray)
    .then((snapshotContainsArrayOfSnapshots) => {
        let data = []
        snapshotContainsArrayOfSnapshots.forEach((snapshot) => {
            data.push(snapshot.val())
        })
        return JSON.stringify(data)
    })


text:
Q: Sufficient condition for a subset to be compact in a Hausdorff topological space I know that if $X$ is a Hausdorff topological space and $A$ is compact in $X$, then $A$ is closed in $X$. My question is that if $A$ is a closed set in $X$ (where $X$ is Hausdorff), what extra condition is needed to ensure that $A$ is compact in $X$?

A: There's really not much that can be said in general: it depends very much on the Hausdorff space $X$. Some examples:

*

*If $X$ is compact, then every closed subset of $X$ is compact.

*If $X$ is $\mathbb{R}^n$ for some $n$, a closed subset of $X$ is compact if and only if it's bounded in the usual metric.

*If $X$ is an infinite space with the discrete topology, a closed subset of $X$ is compact if and only if it's finite.

*If $X$ is the space $\omega_1$ of countable ordinals with the order topology, a closed subset of $X$ is compact if and only if it's countable.

*If $X$ is the Sorgenfrey line, every compact subset of $X$ is countable, but $X$ has closed subsets, even bounded ones, that are not compact, e.g., $A=\{1\}\cup\{1-2^{-n}:n\in\omega\}$: $\{[1-2^{-n},1-2^{1-n}):n\in\omega\}\cup\{[1,2)\}$ is an open cover of $A$ with no finite subcover.

A: Brian has already given you many examples explaining that compactness of $A$ strongly depends on properties of the Hausdorff space $X$. It is worth to add to his list the following one:

Let $(X,\rho)$ be a metric space (thus Hausdorff) and $A\subseteq X$. Then $A$ is compact if and only if $A$ is complete and totally bounded.

This is one of the most important characterisations of compact subsets of metric spaces.
Many interesting properties and other characterisations you can find in the Wikipedia article: http://en.wikipedia.org/wiki/Compact_space


text:
Q: Finding the intersection of the Circle and Infinite Cylinder in 3D space Finding the intersection of the Circle and Infinite Cylinder. (all in 3D)
•   Circle is defined by center, plane in which it lies and radius.
•   Cylinder is defined by axis and radius.
how can i get the intersection of these two?

A: Let's some base point of cylinder is A0, unit axis direction vector is AD, radius AR. Circle center is B0, circle plane unit normal is BN, radius BR.
Circle intersects cylinder, if distance from B0 to cyl. axis is smaller than sum of cylinder radius plus projection of circle radius onto normal to axis
Dist <= AR + BR * Abs(Cos(AD, BN)).

Cos(AD, BN) = DotProduct(AD, BN)
Distance(B0, cyl.axis) = Abs(VectorProduct(AD, B0-A0))

A: WLOG the cylinder has equation X² + Y² = 1 (if not, you can make it so by translation, rotation and scaling).
Then the parametric equation of the circle is
P = C + U cos t + V sin t

where C is the center point and U, V two orthogonal vectors in the circle plane, of length R.
You can rationalize with the substitution cos t = (1 - u²) / (1 + u²), sin t = 2u / (1 + u²).
Combining these equations,
(Cx (1 + u²) + Ux (1 - u²) + Vx 2u)² + (Cy (1 + u²) + Uy (1 - u²) + Vy 2u)² = (1 + u²)²

which is a quartic one. There is no particular simplification of the coefficients.
You can solve numerically or by the closed-form formulas. There can be up to four solutions.

I guess that this is strictly equivalent to finding the intersections between the torus formed by inflating the circle circumference and the straight line obtained by deflating the cylinder to its axis. This is well addressed in the ray-tracing literature.
You can also sse it as a circle/ellipse intersection problem in 2D.


text:
Q: How to replace value of array in javascript with another value of array? I'm trying to replace values from an array which are present in a string with another array. What is the best way to do this in Javascript?
here is my code :
var string = "I've to but the Item1 along with Item2 and Item3. From the Item4."
var array1 = ['Item1', 'Item2', 'Item3', 'Item4']
var array2 = ['Product1', 'Product2', 'Product3', 'Product4']

and output should be like this
var replaced = "I've to but the Product1 along with Product2 and Product3. From the Product4."

every value in both arrays is completely different from each other.

A: You can replace the string using String.prototype.replaceAll

const input = "I've to but the Item1 along with Item2 and Item3. From the Item4.";
const original = ['Item1', 'Item2', 'Item3', 'Item4'];
const target = ['Product1', 'Product2', 'Product3', 'Product4'];

let result = input;
original.forEach((item, index) => {
  result = result.replaceAll(item, target[index]);
});

console.log(result);

A: I hope I have been helpful.

var array1 = ['Item1', 'Item2', 'Item3', 'Item4'];
var array2 = ['Product1', 'Product2', 'Product3', 'Product4'];
var string = "I've to but the Item1 along with Item2 and Item3. From the Item4.";

for (var i = 0; i < array1.length; i++) {
    var string = string.replace(array1[i], array2[i]);
}

console.log(string);

A: You can use template literal for e.g.
var array1 = [Item1, Item2, Item3, Item4];
var array2 = [Product1, Product2, Product3, Product4]
var string = `I've to but the ${array1[0]} along with ${array1[1]} and ${array1[2]}. From the
${array1[3]}.`
var replaced = `I've to but the ${array2[0]} along with ${array2[1]} and ${array2[2]}.
From the ${array2[3]}.`


text:
Q: Converting time (hh:mm:ss) to decimal values in R there.
I know this might be a silly question but really appreciated an answer.
I have two columns naming "start time" and "end time" in the format as "HH:MM:SS", what I need to do is converting them into decimal values and join them together.
More specifically,here is an example:
column "start time": 09:00:00
column "end time": 10:00:00
final result: 9-10
I know how to do that in mysql, but any solutions how to get it done in R? Thanks very much.

A: Here's a function to convert time to decimal, assuming you want decimal hour:
# fake data
asdf <- c("12:34:56","12:00:00","06:01:49","1:30:00")

hhmmss2dec <- function(x) {
  xlist <- strsplit(x,split=":")
  h <- as.numeric(sapply(xlist,"[",1))
  m <- as.numeric(sapply(xlist,"[",2))
  s <- as.numeric(sapply(xlist,"[",3))
  xdec <- h+(m/60)+(s/60/60)
  return(xdec)
}

hhmmss2dec(asdf)
12.582222 12.000000  6.030278  1.500000

Or this, which could work for what you're looking for...
starts <- c("10:00:00","12:34:56")
ends <- c("12:00:00","14:20:00")

hourthing <- function(start,end) {
  startlist <- strsplit(start,split=":")
  endlist <- strsplit(end,split=":")
  hstart <- sapply(startlist,"[",1)
  hend <- sapply(endlist,"[",1)
  out <- paste(hstart,hend,sep="-")
  return(out)
}

hourthing(starts,ends)
"10-12" "12-14"


text:
Q: Refactor nested Observable + Promise + Observable I usually end up with nested structures while working asynchronously. When the subscriptions gives me the responses, then I do something, when the promise gives me the response, then I do something and so on. An example is this:
  loadHacks(hackService, hacksStorageService) {
    firebase.auth().onIdTokenChanged(
      (user) => {
        if (user) {
          const uid = user.uid;
          const hacks = hackService.getHacks();
          if (hacks.length === 0) {
            user.getIdToken()
              .then(
                token => {
                  hacksStorageService.fetchHacks(token, uid)
                    .subscribe(
                      (hacks: Hack[]) => {
                        hackService.setHacks(hacks);
                      }
                    )
                }
              )
          }
        }
      }
    );
  }

onIdTokenChanged places an Observer to the token, getIdToken is a Promise, fetchHacks is an Observable.
How could I refactor the code? I have read about the do, but I don't really grasp it. If someone could tell me how to refactor such nested codes, I would be very grateful


text:
Q: Maven site warning: The repository url 'https://maven-repository.dev.java.net/nonav/repository' is invalid I'm using Maven 3.2.3 on a multi-module project.  I want to generate a checkstyle and findbugs report, so I have configured the following:
    <reporting>
            <plugins>
                    <plugin>
                            <groupId>org.apache.maven.plugins</groupId>
                            <artifactId>maven-checkstyle-plugin</artifactId>
                            <version>2.13</version>
                            <reportSets>
                                    <reportSet>
                                            <reports>
                                                    <report>checkstyle</report>
                                            </reports>
                                    </reportSet>
                            </reportSets>
                    </plugin>
                    <plugin>
                            <groupId>org.codehaus.mojo</groupId>
                            <artifactId>findbugs-maven-plugin</artifactId>
                            <version>2.5.5</version>
                    </plugin>
                    <plugin>
                            <groupId>org.apache.maven.plugins</groupId>
                            <artifactId>maven-jxr-plugin</artifactId>
                            <version>2.3</version>
                    </plugin>
            </plugins>
    </reporting>

However, when I run
mvn site:site site:deploy

I repeatedly get the following warning …
[WARNING] The repository url 'https://maven-repository.dev.java.net/nonav/repository' is invalid - Repository 'java.net' will be blacklisted.

I have no reference to this repo in either my pom.xml files or my ~/.m2/settings.xml file.  How can I track this down and ultimately resolve the warning?

A: I have maven project, where aggregation separate from inheritance:
maven module inheritance vs aggregation. In order
mvn project-info-reports:dependencies

works, aggregate pom must inherit parent.
To avoid blacklisted repository warnings, parent reporting must be configured as below mentioned, or it could be simple:
<properties>
    ...
    <dependency.locations.enabled>false</dependency.locations.enabled>
</properties>

A: You have to configure the reporting plugin, so that it does not look for repositories, as it builts the report.
in you pom add the following:
<reporting>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-project-info-reports-plugin</artifactId>
            <version>2.8</version>
            <configuration>
                <dependencyLocationsEnabled>false</dependencyLocationsEnabled>
            </configuration>
        </plugin>
    </plugins>
</reporting>

The reporting plugin throws the Warning even if you do not have set in your private or global maven settings or in any parent pom the "invalid" repositories. Maybe the plugin looks also for repository definitions in the dependencies of the project.
[WARNING] The repository url 'https://maven-repository.dev.java.net/nonav/repository' is invalid - Repository 'java.net' will be blacklisted.
[WARNING] The repository url 'http://maven.glassfish.org/content/groups/glassfish' is invalid - Repository 'glassfish-repo-archive' will be blacklisted.
[WARNING] The repository url 'https://maven.java.net/content/repositories/releases/' is invalid - Repository 'jvnet-nexus-releases' will be blacklisted.
[WARNING] The repository url 'https://maven.java.net/content/groups/public' is invalid - Repository 'release.maven.java.net' will be blacklisted.
[WARNING] The repository url 'http://repository.springsource.com/maven/bundles/external' is invalid - Repository 'spring-external' will be blacklisted.


text:
Q: Is data transmitted over 3G secure? When data is transferred from my iPhone via 3G, is it encrypted, or is it relatively simple for a hacker to read the data that's transferred to AT&T's cell tower? What about after it reaches the tower?

A: If you are operating over https, it doesn't matter through what type of connection you are communicating over. All data is going to be encrypted from your browser to the server program. The only way to brake this is to the eavesdrop mediate the communication between you and the your final destination. To solve this, identity certificate were created. This certifies that you are talking to your final destination and not through some mediator. So as long as identity certificate match, you are safe. If the identity certificate does not match the browser will show you a security warning, saying that the certificate does not match, generally they will leave an option for you to go on with the communication, just in case in the operation you are doing you don't care about security.

A: Not in the least. Even HTTPS is secure only from non government or ISP level actors.  Check EFF.org for more, but I warn you, it's damned depressing.
EDIT: The past is a country that is very hard to visit:
Bruce Schneier's analysis on SSL:
http://www.schneier.com/blog/archives/2010/09/uae_man-in-the-.html
Mozilla's discussion:
https://groups.google.com/forum/#!topic/mozilla.dev.security.policy/OBrPLsoMAR8
The open letter in august detailing the problem from the EFF:
https://www.eff.org/deeplinks/2010/08/open-letter-verizon
It's not that they decrypt it, you see.  Encryption we are all on equal footing until the quantum key or lock.  But people who don't code are not stupid.  SSL you can guarantee security to the server, but the certs themselves come from a chain of trust.
The phrase "I got that government gig!  Homeland Security!  Mary Anne's new boyfriend... F**k You!" , or similar must have been said at some point.
Amazon was not the only place after Wikileaks to have a group of sedans pull up. The FBI is screaming right now for backdoors in fact, or rather, to legitimize the backdoors they must have.  Since government, or industrial actors are not 'actors' but 'people' it is not FUD to question it.
An example of FUD, would be to highlight say, the complexity of the mathematics and try to use that to prove an answer wrong, and restore faith in a system that worked in the past, while ignoring the forced trust in humans, and the successful exploit in the wild.
Make sense?

A: A man-in-the-middle attack or snooping from someone sitting in the same coffee shop is far less likely over 3G.  The equipment to do such is far less commonly available, and the expertise required is higher.
Neither is guaranteed to be secure from say, a government intelligence organization or other large sophisticated operation, as the 3G encryption is not of that grade.  But HTTPS and SSH should protect you from the average snoop over either.

A: 3G can be secure or insecure, it's really down to the particular implementation.  If you are worried about your data while tethering or using a 3G iPad/iPhone then look at it this way, it's more secure than using free/unsecured WiFi hotspots/networks.
Really the answer to your question is that 3G is pretty secure, but it has its flaws.
3G is encrypted, the most common encryption algorithms have been cracked, with the right equipment somebody could intercept your information wirelessly.  However, they would need some knowledge, some money and some motivation to do it.  Then in addition to that, they would need your device to send unencrypted data (non https) so it could be deciphered.  All in all it's pretty unlikely but certainly possible that your information could be intercepted.  However, this is a risk for anyone transmitting data anywhere and is not isolated to 3G/WiFi or other mobile device communication methods.
Try a google search on 3G security and you'll find plenty of information on the flaws and security holes and how they might be exploited.
Just as an example, here are a couple of presentations:
3G Security Overview
blackhat.com powerpoint

A: A man in the middle attack can also be performed using sslstrip which can easily strip the ssl from https, making it an http connection, intercept all the data and use a fake certificate to re-enable the ssl before sending it out to the destination. In simple words that's the idea.
The user will never know what even happened to him/her. This was showcased in Blackhat in 2009 if I'm not mistaken. If Moxie Marlinspike was able to this in 2009, imagine what other pro hackers are capable of doing these days. He was one of the few revealing this for good purposes. A lot of them won't publish the vulnerabilities that they have at their disposal.
Don't want to scare you but if you think ssl is secure think twice. It's really up to the browsers to maintain the security of the users. Your faith is really in their hand. A lot of vulnerabilities exist for many years just like the heartbleed before they do something about it.


text:
Q: What's wrong with this code to determine if odd numbers are in a number list? def is_odd(number):
    """The function returns True if the number is odd,
    False otherwise.
    """
    if number %  2 == 1:
        return True
    return False

def contains_odd_number(number_list):
    """The function returns True if number_list contains
    at least one odd number, False otherwise.
    """
    for num in number_list:
        if is_odd(num) != True:
            return False
        return True

A: This seems overcomplex & broken. One big issue is the indentation inside your loop.
Well, scratch that and write the function as follows using any:
def contains_odd_number(number_list):
    return any(x % 2 for x in number_list)

that's way more pythonic & performant. any stops as soon as an odd number is found in the list.

A: Reverse the logic. You know there is an odd number when you find the first, but you don't know that there isn't an odd one when you find the first even one:
for num in number_list:
    if is_odd(num):
        return True
return False  # only return False after you checked all

A: You can simplify a lot your issue, don't be afraid to the boolean values, just return them:
in is_odd you can directly return the result
def is_odd(number):
    """The function returns True if the number is odd,
    False otherwise.
    """
    return number %  2 != 0

And here, with a little of comprehension, and a good use of any:
def contains_odd_number(number_list):
    """The function returns True if number_list contains
    at least one odd number, False otherwise.
    """
    return(any(is_odd(x) for x in number_list))

print(contains_odd_number([2,2,2,1]))

-> True

A: this is a logical error in
for num in number_list:
        if is_odd(num) != True:
            return False
        return True

you can solve this using a flag that you set to 1 if there is an odd number found in the list else it stays 0 if there is no odd number found in the iteration through the list
when the iteration through all list elements is finished you query the flag, if it is 1 the list contains an od number
        flag = 0
for num in number_list:
        if is_odd(num) == True:
            flag = 1

if flag == 1

    print ...

A: contains_odd_number() is returning after the first iteration of the for loop.
In order to have it loop through the whole list, you'll need to move your default return out of the loop.
Resulting in the following:
def contains_odd_number(number_list):
    """The function returns True if number_list contains
    at least one odd number, False otherwise.
    """
    for num in number_list:
        if is_odd(num) != True:
            return False
    return True


text:
Q: Retrieving an AppSettings value from a nested element in web.config How can I do if a want a nested element in web.config to have one of its values retrieved from AppSettings?
<element>
  <element2>
    <add virtualPath="[MyAppSettingsValue]" />
  </element2>
</element>

Thanks!